Skip to content

(aws-lambda): addRoleToPolicy() breaks when feature flag createNewPoliciesWithAddToRolePolicy set to true #34894

@aws-solutions-constructs-team

Description

Describe the bug

(this might be aws-iam - while the flag is implemented in aws-lambda, it affects what routines are called in aws-iam)

When we run cdk deploy or cdk synth with the code shown below (in Reproduction Steps), it fails when @aws-cdk/aws-lambda:createNewPoliciesWithAddToRolePolicy is set to false (the default setting since PR 34010).

Regression Issue

  • Select this option if this issue appears to be a regression.

Last Known Working CDK Library Version

No response

Expected Behavior

When we run npm run build && cdk synth, we expect to get this template:

Mappings:
  testmapping:
    us:
      regionalModels: arn:aws:bedrock:us-west-2::foundation-model/amazon.nova-lite-v1:0
Resources:
  testfunctionServiceRoleFB85AD63:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Action: sts:AssumeRole
            Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
        Version: "2012-10-17"
      ManagedPolicyArns:
        - Fn::Join:
            - ""
            - - "arn:"
              - Ref: AWS::Partition
              - :iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
    Metadata:
      aws:cdk:path: TestPolicyFlagStack/test-function/ServiceRole/Resource
  testfunction5B23D3B0:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        ZipFile: "exports.handler = async (event) => { console.log(event); return {'statusCode': 200, 'body': ''}; }"
      Handler: index.handler
      Role:
        Fn::GetAtt:
          - testfunctionServiceRoleFB85AD63
          - Arn
      Runtime: nodejs20.x
    DependsOn:
      - testfunctionServiceRoleFB85AD63
    Metadata:
      aws:cdk:path: TestPolicyFlagStack/test-function/Resource
  testfunctioninlinePolicyAddedToExecutionRole08C3F09DE:
    Type: AWS::IAM::Policy
    Properties:
      PolicyDocument:
        Statement:
          - Action: bedrock:Invoke*
            Effect: Allow
            Resource: "*"
        Version: "2012-10-17"
      PolicyName: testfunctioninlinePolicyAddedToExecutionRole08C3F09DE
      Roles:
        - Ref: testfunctionServiceRoleFB85AD63
    Metadata:
      aws:cdk:path: TestPolicyFlagStack/test-function/inlinePolicyAddedToExecutionRole-0/Resource
  testfunctioninlinePolicyAddedToExecutionRole184A2127B:
    Type: AWS::IAM::Policy
    Properties:
      PolicyDocument:
        Statement:
          - Action: bedrock:Invoke*
            Effect: Allow
            Resource:
              Fn::Split:
                - ","
                - Fn::FindInMap:
                    - testmapping
                    - us
                    - regionalModels
        Version: "2012-10-17"
      PolicyName: testfunctioninlinePolicyAddedToExecutionRole184A2127B
      Roles:
        - Ref: testfunctionServiceRoleFB85AD63
    Metadata:
      aws:cdk:path: TestPolicyFlagStack/test-function/inlinePolicyAddedToExecutionRole-1/Resource
  CDKMetadata:
    Type: AWS::CDK::Metadata
    Properties:
      Analytics: v2:deflate64:H4sIAAAAAAAA/7VSwWrDMAz9lvk4HC/tacutGwx2GIx0t1KGarutWlsOsbNRTP59TpxCoOeejN7Te3rCWorFcynKB/jzhVTnwuBOxHUAeeZve/qEpkE68MT+RAN2p0DE945kQEebyKRTmlXskXHWdhTQXqsjkDK6Hat+O1hdVT1HsCLWzuhkAN53VqvXC6sia1okiQ2YlZQu2U1euWcQrEaHbMqZBYKDVl/OoETtWZX85thl1U69256nUSFtdfwgg6QznxSJvRs5rj3E5hlP8XyAoK2m4Kclkl6p9QzdxHnabzfob6bdwHfxHfPn6H3Pa+1d10o9SSj9vDj5p99lKRYv6YBOHrGYjkDU+f0Hdf53Cl0CAAA=
    Metadata:
      aws:cdk:path: TestPolicyFlagStack/CDKMetadata/Default
    Condition: CDKMetadataAvailable
Conditions:
  CDKMetadataAvailable:
    Fn::Or:
      - Fn::Or:
          - Fn::Equals:
              - Ref: AWS::Region
              - af-south-1
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-east-1
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-northeast-1
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-northeast-2
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-northeast-3
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-south-1
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-south-2
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-southeast-1
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-southeast-2
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-southeast-3
      - Fn::Or:
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-southeast-4
          - Fn::Equals:
              - Ref: AWS::Region
              - ca-central-1
          - Fn::Equals:
              - Ref: AWS::Region
              - ca-west-1
          - Fn::Equals:
              - Ref: AWS::Region
              - cn-north-1
          - Fn::Equals:
              - Ref: AWS::Region
              - cn-northwest-1
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-central-1
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-central-2
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-north-1
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-south-1
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-south-2
      - Fn::Or:
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-west-1
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-west-2
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-west-3
          - Fn::Equals:
              - Ref: AWS::Region
              - il-central-1
          - Fn::Equals:
              - Ref: AWS::Region
              - me-central-1
          - Fn::Equals:
              - Ref: AWS::Region
              - me-south-1
          - Fn::Equals:
              - Ref: AWS::Region
              - sa-east-1
          - Fn::Equals:
              - Ref: AWS::Region
              - us-east-1
          - Fn::Equals:
              - Ref: AWS::Region
              - us-east-2
          - Fn::Equals:
              - Ref: AWS::Region
              - us-west-1
      - Fn::Equals:
          - Ref: AWS::Region
          - us-west-2
Parameters:
  BootstrapVersion:
    Type: AWS::SSM::Parameter::Value<String>
    Default: /cdk-bootstrap/hnb659fds/version
    Description: Version of the CDK Bootstrap resources in this environment, automatically retrieved from SSM Parameter Store. [cdk:skip]

Current Behavior

When we run the code with the feature flag set to false (default setting), we get:

/Users/biffgaut/Documents/Active/AWS/Constructs/clients/TestPolicyFlag/node_modules/aws-cdk-lib/core/lib/resolvable.js:4
  at `)}`),e.message=message,e}}resolveString(fragments,context){try{jsiiDeprecationWarnings().aws_cdk_lib_TokenizedStringFragments(fragments),jsiiDeprecationWarnings().aws_cdk_lib_IResolveContext(context)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.resolveString),error}return fragments.mapTokens({mapToken:context.resolve}).join(this.concat)}resolveList(xs,context){try{jsiiDeprecationWarnings().aws_cdk_lib_IResolveContext(context)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.resolveList),error}if(xs.length!==1)throw new Error(`Cannot add elements to list token, got: ${xs}`);const str=encoding_1().TokenString.forListToken(xs[0]),tokenMap=token_map_1().TokenMap.instance(),fragments=str.split(tokenMap.lookupToken.bind(tokenMap));if(fragments.length!==1)throw new Error(`Cannot concatenate strings in a tokenized string array, got: ${xs[0]}`);return fragments.mapTokens({mapToken:context.resolve}).firstValue}}exports.DefaultTokenResolver=DefaultTokenResolver,_b=JSII_RTTI_SYMBOL_1,DefaultTokenResolver[_b]={fqn:"aws-cdk-lib.DefaultTokenResolver",version:"2.180.0"};
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           ^
Error: Resolution error: Resolution error: Resolution error: Cannot add elements to list token, got: #{Token[TOKEN.35]},*.
Object creation stack:
  at stack traces disabled..
    at RememberingTokenResolver.resolveList (/Users/biffgaut/Documents/Active/AWS/Constructs/clients/TestPolicyFlag/node_modules/aws-cdk-lib/core/lib/resolvable.js:4:668)
    at resolve (/Users/biffgaut/Documents/Active/AWS/Constructs/clients/TestPolicyFlag/node_modules/aws-cdk-lib/core/lib/private/resolve.js:1:2434)
    at Object.resolve (/Users/biffgaut/Documents/Active/AWS/Constructs/clients/TestPolicyFlag/node_modules/aws-cdk-lib/core/lib/private/resolve.js:1:1115)
    at resolve (/Users/biffgaut/Documents/Active/AWS/Constructs/clients/TestPolicyFlag/node_modules/aws-cdk-lib/core/lib/private/resolve.js:1:3026)
    at Object.resolve (/Users/biffgaut/Documents/Active/AWS/Constructs/clients/TestPolicyFlag/node_modules/aws-cdk-lib/core/lib/private/resolve.js:1:1115)
    at /Users/biffgaut/Documents/Active/AWS/Constructs/clients/TestPolicyFlag/node_modules/aws-cdk-lib/core/lib/private/resolve.js:1:2553
    at Array.map (<anonymous>)
    at resolve (/Users/biffgaut/Documents/Active/AWS/Constructs/clients/TestPolicyFlag/node_modules/aws-cdk-lib/core/lib/private/resolve.js:1:2519)
    at Object.resolve (/Users/biffgaut/Documents/Active/AWS/Constructs/clients/TestPolicyFlag/node_modules/aws-cdk-lib/core/lib/private/resolve.js:1:1115)
    at resolve (/Users/biffgaut/Documents/Active/AWS/Constructs/clients/TestPolicyFlag/node_modules/aws-cdk-lib/core/lib/private/resolve.js:1:3026)
npx ts-node --prefer-ts-exts bin/test_policy_flag.ts: Subprocess exited with error 1

Reproduction Steps

import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as iam from 'aws-cdk-lib/aws-iam';

export class TestPolicyFlagStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // PR #33291 introduces this feature flag, included in v2.180.0
    // CDK v2.180.0, flag set to true, no issues
    // CDK v2.180.0, flag set to false, breaks
    // PR #34010 changes default value for flag to false
    // CDK v2.188.0, flag set to true, no issues
    // CDK v2.188.0, flag set to false, breaks
    // behavior is unchanged in releases since then
    this.node.setContext("@aws-cdk/aws-lambda:createNewPoliciesWithAddToRolePolicy", false);

    const mappingName = `testmapping`;
    const mapping = new cdk.CfnMapping(this, `testmapping`, {
      mapping: {
        'us': {
          regionalModels:
            `arn:aws:bedrock:us-west-2::foundation-model/amazon.nova-lite-v1:0`
        },
      }
    });
    mapping.overrideLogicalId(mappingName);

    const func = new lambda.Function(this, 'test-function', {
      code: new lambda.InlineCode('exports.handler = async (event) => { console.log(event); return {\'statusCode\': 200, \'body\': \'\'}; }'),
      runtime: lambda.Runtime.NODEJS_20_X,
      handler: 'index.handler',
    });

    func.addToRolePolicy(new iam.PolicyStatement({
      actions: ['bedrock:Invoke*'],
      resources: [
        "*",
      ]
    }));

    func.addToRolePolicy(new iam.PolicyStatement({
      actions: ['bedrock:Invoke*'],
      resources: cdk.Fn.split(",", cdk.Fn.findInMap(mappingName, 'us', 'regionalModels'))
    }));

  }
}

Possible Solution

No response

Additional Information/Context

No response

AWS CDK Library version (aws-cdk-lib)

2.188.0

AWS CDK CLI version

2.1020.1

Node.js Version

v20.19.0

OS

Sequoia 15.5 (MacOS)

Language

TypeScript

Language Version

3.8.3

Other information

No response

Metadata

Metadata

Labels

@aws-cdk/aws-lambdaRelated to AWS LambdabugThis issue is a bug.effort/mediumMedium work item – several days of effortp0

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions