-
Notifications
You must be signed in to change notification settings - Fork 207
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
7 changed files
with
372 additions
and
37 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,130 @@ | ||
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
// SPDX-License-Identifier: MIT | ||
|
||
package main | ||
|
||
import ( | ||
"context" | ||
"errors" | ||
"fmt" | ||
"log" | ||
"strings" | ||
"time" | ||
|
||
"github.com/aws/aws-sdk-go-v2/config" | ||
"github.com/aws/aws-sdk-go-v2/service/iam" | ||
"github.com/aws/aws-sdk-go-v2/service/iam/types" | ||
|
||
"github.com/aws/amazon-cloudwatch-agent/tool/clean" | ||
) | ||
|
||
const retentionPeriod = clean.KeepDurationOneWeek | ||
|
||
var ( | ||
roleNamePrefixes = []string{ | ||
"cwa-integ-assume-role", | ||
"cwagent-eks-Worker-Role", | ||
"cwagent-integ-test-task-role", | ||
"cwagent-operator-eks-Worker-Role", | ||
"cwagent-operator-helm-integ-Worker-Role", | ||
} | ||
) | ||
|
||
type iamClient interface { | ||
ListRoles(ctx context.Context, input *iam.ListRolesInput, optFns ...func(*iam.Options)) (*iam.ListRolesOutput, error) | ||
GetRole(ctx context.Context, input *iam.GetRoleInput, optFns ...func(*iam.Options)) (*iam.GetRoleOutput, error) | ||
DeleteRole(ctx context.Context, input *iam.DeleteRoleInput, optFns ...func(*iam.Options)) (*iam.DeleteRoleOutput, error) | ||
ListAttachedRolePolicies(ctx context.Context, input *iam.ListAttachedRolePoliciesInput, optFns ...func(*iam.Options)) (*iam.ListAttachedRolePoliciesOutput, error) | ||
DetachRolePolicy(ctx context.Context, input *iam.DetachRolePolicyInput, optFns ...func(*iam.Options)) (*iam.DetachRolePolicyOutput, error) | ||
} | ||
|
||
func main() { | ||
log.Print("Begin to clean IAM Roles") | ||
ctx := context.Background() | ||
cfg, err := config.LoadDefaultConfig(ctx) | ||
if err != nil { | ||
log.Fatalf("unable to load AWS config: %v", err) | ||
} | ||
client := iam.NewFromConfig(cfg) | ||
if err = deleteRoles(ctx, client, getExpirationDate()); err != nil { | ||
log.Fatalf("errors cleaning: %v", err) | ||
} | ||
} | ||
|
||
func getExpirationDate() time.Time { | ||
return time.Now().UTC().Add(retentionPeriod) | ||
} | ||
|
||
func deleteRoles(ctx context.Context, client iamClient, expirationDate time.Time) error { | ||
var errs error | ||
var marker *string | ||
for { | ||
output, err := client.ListRoles(ctx, &iam.ListRolesInput{Marker: marker}) | ||
if err != nil { | ||
return err | ||
} | ||
for _, role := range output.Roles { | ||
if hasPrefix(*role.RoleName) && expirationDate.After(*role.CreateDate) { | ||
var getRoleOutput *iam.GetRoleOutput | ||
getRoleOutput, err = client.GetRole(ctx, &iam.GetRoleInput{RoleName: role.RoleName}) | ||
if err != nil { | ||
return err | ||
} | ||
role = *getRoleOutput.Role | ||
if role.RoleLastUsed == nil || role.RoleLastUsed.LastUsedDate == nil || expirationDate.After(*role.RoleLastUsed.LastUsedDate) { | ||
errs = errors.Join(errs, deleteRole(ctx, client, role)) | ||
} | ||
} | ||
} | ||
if output.Marker == nil { | ||
break | ||
} | ||
marker = output.Marker | ||
} | ||
return errs | ||
} | ||
|
||
func deleteRole(ctx context.Context, client iamClient, role types.Role) error { | ||
lastUsed := "never" | ||
if role.RoleLastUsed != nil && role.RoleLastUsed.LastUsedDate != nil { | ||
lastUsed = fmt.Sprintf("%d days ago", int(time.Since(*role.RoleLastUsed.LastUsedDate).Hours()/24)) | ||
} | ||
log.Printf("Trying to delete role (%q) last used %s", *role.RoleName, lastUsed) | ||
if err := detachPolicies(ctx, client, role); err != nil { | ||
return err | ||
} | ||
if _, err := client.DeleteRole(ctx, &iam.DeleteRoleInput{RoleName: role.RoleName}); err != nil { | ||
return err | ||
} | ||
log.Printf("Deleted role (%q) successfully", *role.RoleName) | ||
return nil | ||
} | ||
|
||
func detachPolicies(ctx context.Context, client iamClient, role types.Role) error { | ||
var marker *string | ||
for { | ||
output, err := client.ListAttachedRolePolicies(ctx, &iam.ListAttachedRolePoliciesInput{RoleName: role.RoleName, Marker: marker}) | ||
if err != nil { | ||
return err | ||
} | ||
for _, policy := range output.AttachedPolicies { | ||
if _, err = client.DetachRolePolicy(ctx, &iam.DetachRolePolicyInput{PolicyArn: policy.PolicyArn, RoleName: role.RoleName}); err != nil { | ||
return fmt.Errorf("unable to detach policy (%q) from role (%q): %w", *policy.PolicyName, *role.RoleName, err) | ||
} | ||
} | ||
if output.Marker == nil { | ||
break | ||
} | ||
marker = output.Marker | ||
} | ||
return nil | ||
} | ||
|
||
func hasPrefix(roleName string) bool { | ||
for _, prefix := range roleNamePrefixes { | ||
if strings.HasPrefix(roleName, prefix) { | ||
return true | ||
} | ||
} | ||
return false | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
// SPDX-License-Identifier: MIT | ||
|
||
package main | ||
|
||
import ( | ||
"context" | ||
"testing" | ||
"time" | ||
|
||
"github.com/aws/aws-sdk-go-v2/aws" | ||
"github.com/aws/aws-sdk-go-v2/service/iam" | ||
"github.com/aws/aws-sdk-go-v2/service/iam/types" | ||
"github.com/stretchr/testify/assert" | ||
"github.com/stretchr/testify/mock" | ||
) | ||
|
||
const ( | ||
expiredTestRoleName = "cwa-integ-assume-role-expired" | ||
activeTestRoleName = "cwagent-integ-test-task-role-active" | ||
) | ||
|
||
type mockIamClient struct { | ||
mock.Mock | ||
} | ||
|
||
var _ iamClient = (*mockIamClient)(nil) | ||
|
||
func (m *mockIamClient) ListRoles(ctx context.Context, input *iam.ListRolesInput, optFns ...func(*iam.Options)) (*iam.ListRolesOutput, error) { | ||
args := m.Called(ctx, input, optFns) | ||
return args.Get(0).(*iam.ListRolesOutput), args.Error(1) | ||
} | ||
|
||
func (m *mockIamClient) GetRole(ctx context.Context, input *iam.GetRoleInput, optFns ...func(*iam.Options)) (*iam.GetRoleOutput, error) { | ||
args := m.Called(ctx, input, optFns) | ||
return args.Get(0).(*iam.GetRoleOutput), args.Error(1) | ||
} | ||
|
||
func (m *mockIamClient) DeleteRole(ctx context.Context, input *iam.DeleteRoleInput, optFns ...func(*iam.Options)) (*iam.DeleteRoleOutput, error) { | ||
args := m.Called(ctx, input, optFns) | ||
return args.Get(0).(*iam.DeleteRoleOutput), args.Error(1) | ||
} | ||
|
||
func (m *mockIamClient) ListAttachedRolePolicies(ctx context.Context, input *iam.ListAttachedRolePoliciesInput, optFns ...func(*iam.Options)) (*iam.ListAttachedRolePoliciesOutput, error) { | ||
args := m.Called(ctx, input, optFns) | ||
return args.Get(0).(*iam.ListAttachedRolePoliciesOutput), args.Error(1) | ||
} | ||
|
||
func (m *mockIamClient) DetachRolePolicy(ctx context.Context, input *iam.DetachRolePolicyInput, optFns ...func(*iam.Options)) (*iam.DetachRolePolicyOutput, error) { | ||
args := m.Called(ctx, input, optFns) | ||
return args.Get(0).(*iam.DetachRolePolicyOutput), args.Error(1) | ||
} | ||
|
||
func TestDeleteRoles(t *testing.T) { | ||
expirationDate := getExpirationDate() | ||
|
||
ctx := context.Background() | ||
ignoredRole := types.Role{ | ||
CreateDate: aws.Time(expirationDate.Add(-2 * time.Hour)), | ||
RoleName: aws.String("does-not-match-any-prefix"), | ||
RoleLastUsed: &types.RoleLastUsed{ | ||
LastUsedDate: aws.Time(expirationDate.Add(-1 * time.Hour)), | ||
}, | ||
} | ||
expiredRole := types.Role{ | ||
CreateDate: aws.Time(expirationDate.Add(-2 * time.Hour)), | ||
RoleName: aws.String(expiredTestRoleName), | ||
RoleLastUsed: &types.RoleLastUsed{ | ||
LastUsedDate: aws.Time(expirationDate.Add(-1 * time.Hour)), | ||
}, | ||
} | ||
activeRole := types.Role{ | ||
CreateDate: aws.Time(expirationDate.Add(-2 * time.Hour)), | ||
RoleName: aws.String(activeTestRoleName), | ||
RoleLastUsed: &types.RoleLastUsed{ | ||
LastUsedDate: aws.Time(expirationDate.Add(time.Hour)), | ||
}, | ||
} | ||
testRoles := []types.Role{ignoredRole, expiredRole, activeRole} | ||
testPolicies := []types.AttachedPolicy{ | ||
{ | ||
PolicyArn: aws.String("policy-arn"), | ||
PolicyName: aws.String("policy-name"), | ||
}, | ||
} | ||
|
||
client := &mockIamClient{} | ||
client.On("ListRoles", ctx, &iam.ListRolesInput{}, mock.Anything).Return(&iam.ListRolesOutput{Roles: testRoles}, nil) | ||
client.On("GetRole", ctx, &iam.GetRoleInput{RoleName: aws.String(expiredTestRoleName)}, mock.Anything).Return(&iam.GetRoleOutput{Role: &expiredRole}, nil) | ||
client.On("GetRole", ctx, &iam.GetRoleInput{RoleName: aws.String(activeTestRoleName)}, mock.Anything).Return(&iam.GetRoleOutput{Role: &activeRole}, nil) | ||
client.On("DeleteRole", ctx, mock.Anything, mock.Anything).Return(&iam.DeleteRoleOutput{}, nil) | ||
client.On("ListAttachedRolePolicies", ctx, mock.Anything, mock.Anything).Return(&iam.ListAttachedRolePoliciesOutput{AttachedPolicies: testPolicies}, nil) | ||
client.On("DetachRolePolicy", ctx, mock.Anything, mock.Anything).Return(&iam.DetachRolePolicyOutput{}, nil) | ||
assert.NoError(t, deleteRoles(ctx, client, expirationDate)) | ||
assert.Len(t, client.Calls, 6) | ||
for _, call := range client.Calls { | ||
switch call.Method { | ||
case "DeleteRole": | ||
input := call.Arguments.Get(1).(*iam.DeleteRoleInput) | ||
assert.Equal(t, expiredTestRoleName, *input.RoleName) | ||
case "ListAttachedRolePolicies": | ||
input := call.Arguments.Get(1).(*iam.ListAttachedRolePoliciesInput) | ||
assert.Equal(t, expiredTestRoleName, *input.RoleName) | ||
case "DetachRolePolicy": | ||
input := call.Arguments.Get(1).(*iam.DetachRolePolicyInput) | ||
assert.Equal(t, expiredTestRoleName, *input.RoleName) | ||
assert.Equal(t, "policy-arn", *input.PolicyArn) | ||
} | ||
} | ||
} |
Oops, something went wrong.