aws-cloudformationamazon-iamaws-cdkaws-rolesaws-permissions

Add permission boundaries to the stack


When I deploy a CDK stack - it creates several roles, both explicitly e.g. via iam.Role construct, and implicitly e.g. when roles are created internally by Level 2 constructs.

Is there a way to attach an existing permission boundary to all the roles being created by the stack - both explicit and implicit?


Solution

  • Yes, through aspects.

    You can add the following in bin/app.ts (the file might be named differently):

    class ConfigurePermissionBoundary implements IAspect {
      visit(node: IConstruct): void {
        if (node instanceof CfnRole) {
          const stack1 = Stack.of(node);
          let policy = stack1.node.tryFindChild('GlobalPermissionBoundaryPolicy') as ManagedPolicy | undefined
    
          if (!policy) {
            policy = new ManagedPolicy(stack1, 'GlobalPermissionBoundaryPolicy', {
              statements: [new PolicyStatement({
                effect: Effect.DENY,
                actions: ['sts:*'],
                resources: ['*']
              })]
            })
          }
    
          node.permissionsBoundary = policy.managedPolicyArn
        }
      }
    }
    
    Aspects.of(app).add(new ConfigurePermissionBoundary())
    

    Please note that we're adding a managed policy GlobalPermissionBoundaryPolicy that defines the permission boundary once. Also, the aspect handles both new iam.Role() as well as any new CfnRole() defined by your or library code.