UNPKG

aws-cdk-lib

Version:

Version 2 of the AWS Cloud Development Kit library

3 lines (2 loc) 15.5 kB
"use strict";var __decorate=exports&&exports.__decorate||function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r},_a,_b;Object.defineProperty(exports,"__esModule",{value:!0}),exports.QualifiedFunctionBase=exports.FunctionBase=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");var crypto_1=()=>{var tmp=require("crypto");return crypto_1=()=>tmp,tmp},event_invoke_config_1=()=>{var tmp=require("./event-invoke-config");return event_invoke_config_1=()=>tmp,tmp},event_source_mapping_1=()=>{var tmp=require("./event-source-mapping");return event_source_mapping_1=()=>tmp,tmp},function_url_1=()=>{var tmp=require("./function-url");return function_url_1=()=>tmp,tmp},lambda_generated_1=()=>{var tmp=require("./lambda.generated");return lambda_generated_1=()=>tmp,tmp},util_1=()=>{var tmp=require("./util");return util_1=()=>tmp,tmp},iam=()=>{var tmp=require("../../aws-iam");return iam=()=>tmp,tmp},core_1=()=>{var tmp=require("../../core");return core_1=()=>tmp,tmp},errors_1=()=>{var tmp=require("../../core/lib/errors");return errors_1=()=>tmp,tmp},metadata_resource_1=()=>{var tmp=require("../../core/lib/metadata-resource");return metadata_resource_1=()=>tmp,tmp},cxapi=()=>{var tmp=require("../../cx-api");return cxapi=()=>tmp,tmp};class FunctionBase extends core_1().Resource{constructor(){super(...arguments),this._warnIfCurrentVersionCalled=!1,this._invocationGrants={},this._functionUrlInvocationGrants={},this._policyCounter=0}considerWarningOnInvokeFunctionPermissions(scope,action){["lambda:InvokeFunction","lambda:*","lambda:Invoke*"].includes(action)&&(scope.node.tryFindChild("CurrentVersion")?this.warnInvokeFunctionPermissions(scope):this._warnIfCurrentVersionCalled=!0)}warnInvokeFunctionPermissions(scope){core_1().Annotations.of(scope).addWarningV2("@aws-cdk/aws-lambda:addPermissionsToVersionOrAlias",["AWS Lambda has changed their authorization strategy, which may cause client invocations using the 'Qualifier' parameter of the lambda function to fail with Access Denied errors.","If you are using a lambda Version or Alias, make sure to call 'grantInvoke' or 'addPermission' on the Version or Alias, not the underlying Function","See: https://github.com/aws/aws-cdk/issues/19273"].join(` `))}addPermission(id,permission){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_Permission(permission)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addPermission),error}if(!this.canCreatePermissions){this._skipPermissions||core_1().Annotations.of(this).addWarningV2("UnclearLambdaEnvironment",`addPermission() has no effect on a Lambda Function with region=${this.env.region}, account=${this.env.account}, in a Stack with region=${core_1().Stack.of(this).region}, account=${core_1().Stack.of(this).account}. Suppress this warning if this is is intentional, or pass sameEnvironment=true to fromFunctionAttributes() if you would like to add the permissions.`);return}let principal=this.parsePermissionPrincipal(permission.principal),{sourceArn,sourceAccount,principalOrgID}=this.validateConditionCombinations(permission.principal)??{};const action=permission.action??"lambda:InvokeFunction",scope=permission.scope??this;this.considerWarningOnInvokeFunctionPermissions(scope,action),new(lambda_generated_1()).CfnPermission(scope,id,{action,principal,functionName:this.functionArn,eventSourceToken:permission.eventSourceToken,sourceAccount:permission.sourceAccount??sourceAccount,sourceArn:permission.sourceArn??sourceArn,principalOrgId:permission.organizationId??principalOrgID,functionUrlAuthType:permission.functionUrlAuthType})}addToRolePolicy(statement){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_PolicyStatement(statement)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addToRolePolicy),error}const useCreateNewPolicies=core_1().FeatureFlags.of(this).isEnabled(cxapi().LAMBDA_CREATE_NEW_POLICIES_WITH_ADDTOROLEPOLICY);if(this.role)if(useCreateNewPolicies){const policyToAdd=new(iam()).Policy(this,`inlinePolicyAddedToExecutionRole-${this._policyCounter++}`,{statements:[statement]});this.role.attachInlinePolicy(policyToAdd)}else this.role.addToPrincipalPolicy(statement)}get connections(){if(!this._connections)throw new(errors_1()).ValidationError('Only VPC-associated Lambda Functions have security groups to manage. Supply the "vpc" parameter when creating the Lambda, or "securityGroupId" when importing it.',this);return this._connections}get latestVersion(){return this._latestVersion||(this._latestVersion=new LatestVersion(this)),this._latestVersion}get isBoundToVpc(){return!!this._connections}addEventSourceMapping(id,options){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_EventSourceMappingOptions(options)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addEventSourceMapping),error}return new(event_source_mapping_1()).EventSourceMapping(this,id,{target:this,...options})}grantInvoke(grantee){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IGrantable(grantee)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.grantInvoke),error}const identifier=`Invoke${(0,crypto_1().createHash)("sha256").update(JSON.stringify({principal:grantee.grantPrincipal.toString(),conditions:grantee.grantPrincipal.policyFragment.conditions}),"utf8").digest("base64")}`;let grant=this._invocationGrants[identifier];return grant||(grant=this.grant(grantee,identifier,"lambda:InvokeFunction",this.resourceArnsForGrantInvoke),this._invocationGrants[identifier]=grant),grant}grantInvokeLatestVersion(grantee){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IGrantable(grantee)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.grantInvokeLatestVersion),error}return this.grantInvokeVersion(grantee,this.latestVersion)}grantInvokeVersion(grantee,version){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IGrantable(grantee),jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_IVersion(version)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.grantInvokeVersion),error}const identifier=`Invoke${(0,crypto_1().createHash)("sha256").update(JSON.stringify({principal:grantee.grantPrincipal.toString(),conditions:grantee.grantPrincipal.policyFragment.conditions,version:version.version}),"utf8").digest("base64")}`;let grant=this._invocationGrants[identifier];if(!grant){let resouceArns=[`${this.functionArn}:${version.version}`];version==this.latestVersion&&resouceArns.push(this.functionArn),grant=this.grant(grantee,identifier,"lambda:InvokeFunction",resouceArns),this._invocationGrants[identifier]=grant}return grant}grantInvokeUrl(grantee){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IGrantable(grantee)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.grantInvokeUrl),error}const identifier=`InvokeFunctionUrl${grantee.grantPrincipal}`;let grant=this._functionUrlInvocationGrants[identifier];return grant||(grant=this.grant(grantee,identifier,"lambda:InvokeFunctionUrl",[this.functionArn],{functionUrlAuthType:function_url_1().FunctionUrlAuthType.AWS_IAM}),this._functionUrlInvocationGrants[identifier]=grant),grant}grantInvokeCompositePrincipal(compositePrincipal){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_CompositePrincipal(compositePrincipal)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.grantInvokeCompositePrincipal),error}return compositePrincipal.principals.map(principal=>this.grantInvoke(principal))}addEventSource(source){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_IEventSource(source)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addEventSource),error}source.bind(this)}configureAsyncInvoke(options){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_EventInvokeConfigOptions(options)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.configureAsyncInvoke),error}if(this.node.tryFindChild("EventInvokeConfig")!==void 0)throw new(errors_1()).ValidationError(`An EventInvokeConfig has already been configured for the function at ${this.node.path}`,this);new(event_invoke_config_1()).EventInvokeConfig(this,"EventInvokeConfig",{function:this,...options})}addFunctionUrl(options){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_FunctionUrlOptions(options)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addFunctionUrl),error}return new(function_url_1()).FunctionUrl(this,"FunctionUrl",{function:this,...options})}_functionNode(){return this.node}_isStackAccount(){return core_1().Token.isUnresolved(this.stack.account)||core_1().Token.isUnresolved(this.functionArn)?!1:this.stack.splitArn(this.functionArn,core_1().ArnFormat.SLASH_RESOURCE_NAME).account===this.stack.account}grant(grantee,identifier,action,resourceArns,permissionOverrides){return iam().Grant.addToPrincipalOrResource({grantee,actions:[action],resourceArns,resource:{addToResourcePolicy:_statement=>{this.addPermission(identifier,{principal:grantee.grantPrincipal,action,...permissionOverrides});const permissionNode=this._functionNode().tryFindChild(identifier);if(!permissionNode&&!this._skipPermissions)throw new(errors_1()).ValidationError("Cannot modify permission to lambda function. Function is either imported or $LATEST version.\nIf the function is imported from the same account use `fromFunctionAttributes()` API with the `sameEnvironment` flag.\nIf the function is imported from a different account and already has the correct permissions use `fromFunctionAttributes()` API with the `skipPermissions` flag.",this);return{statementAdded:!0,policyDependable:permissionNode}},node:this.node,stack:this.stack,env:this.env,applyRemovalPolicy:x=>this.applyRemovalPolicy(x)}})}parsePermissionPrincipal(principal){if("wrapped"in principal&&(principal=principal.wrapped),"accountId"in principal)return principal.accountId;if("service"in principal)return principal.service;if("arn"in principal)return principal.arn;const stringEquals=matchSingleKey("StringEquals",principal.policyFragment.conditions);if(stringEquals&&matchSingleKey("aws:PrincipalOrgID",stringEquals))return"*";const json=principal.policyFragment.principalJson;if(Object.keys(principal.policyFragment.conditions).length===0&&json.AWS){if(typeof json.AWS=="string")return json.AWS;if(Array.isArray(json.AWS)&&json.AWS.length===1&&typeof json.AWS[0]=="string")return json.AWS[0]}throw new(errors_1()).ValidationError(`Invalid principal type for Lambda permission statement: ${principal.constructor.name}. Supported: AccountPrincipal, ArnPrincipal, ServicePrincipal, OrganizationPrincipal`,this);function matchSingleKey(key,obj){if(Object.keys(obj).length===1)return obj[key]}}validateConditionCombinations(principal){const conditions=this.validateConditions(principal);if(!conditions)return;const sourceArn=requireString(requireObject(conditions.ArnLike)?.["aws:SourceArn"]),sourceAccount=requireString(requireObject(conditions.StringEquals)?.["aws:SourceAccount"]),principalOrgID=requireString(requireObject(conditions.StringEquals)?.["aws:PrincipalOrgID"]);if(principalOrgID&&(sourceArn||sourceAccount))throw new(errors_1()).ValidationError("PrincipalWithConditions had unsupported condition combinations for Lambda permission statement: principalOrgID cannot be set with other conditions.",this);return{sourceArn,sourceAccount,principalOrgID}}validateConditions(principal){if(this.isPrincipalWithConditions(principal)){const conditions=principal.policyFragment.conditions,conditionPairs=(0,util_1().flatMap)(Object.entries(conditions),([operator,conditionObjs])=>Object.keys(conditionObjs).map(key=>({operator,key}))),supportedPrincipalConditions=[{operator:"ArnLike",key:"aws:SourceArn"},{operator:"StringEquals",key:"aws:SourceAccount"},{operator:"StringEquals",key:"aws:PrincipalOrgID"}],unsupportedConditions=conditionPairs.filter(condition=>!supportedPrincipalConditions.some(supportedCondition=>supportedCondition.operator===condition.operator&&supportedCondition.key===condition.key));if(unsupportedConditions.length==0)return conditions;throw new(errors_1()).ValidationError(`PrincipalWithConditions had unsupported conditions for Lambda permission statement: ${JSON.stringify(unsupportedConditions)}. Supported operator/condition pairs: ${JSON.stringify(supportedPrincipalConditions)}`,this)}}isPrincipalWithConditions(principal){return Object.keys(principal.policyFragment.conditions).length>0}}exports.FunctionBase=FunctionBase,_a=JSII_RTTI_SYMBOL_1,FunctionBase[_a]={fqn:"aws-cdk-lib.aws_lambda.FunctionBase",version:"2.185.0"};class QualifiedFunctionBase extends FunctionBase{constructor(){super(...arguments),this.permissionsNode=this.node}get latestVersion(){return this.lambda.latestVersion}get resourceArnsForGrantInvoke(){return[this.functionArn]}configureAsyncInvoke(options){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_lambda_EventInvokeConfigOptions(options)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.configureAsyncInvoke),error}if(this.node.tryFindChild("EventInvokeConfig")!==void 0)throw new(errors_1()).ValidationError(`An EventInvokeConfig has already been configured for the qualified function at ${this.node.path}`,this);new(event_invoke_config_1()).EventInvokeConfig(this,"EventInvokeConfig",{function:this.lambda,qualifier:this.qualifier,...options})}considerWarningOnInvokeFunctionPermissions(_scope,_action){}}exports.QualifiedFunctionBase=QualifiedFunctionBase,_b=JSII_RTTI_SYMBOL_1,QualifiedFunctionBase[_b]={fqn:"aws-cdk-lib.aws_lambda.QualifiedFunctionBase",version:"2.185.0"};class LatestVersion extends FunctionBase{constructor(lambda){super(lambda,"$LATEST"),this.version="$LATEST",this.permissionsNode=this.node,this.canCreatePermissions=!1,this.lambda=lambda}get functionArn(){return`${this.lambda.functionArn}:${this.version}`}get functionName(){return`${this.lambda.functionName}:${this.version}`}get architecture(){return this.lambda.architecture}get grantPrincipal(){return this.lambda.grantPrincipal}get latestVersion(){return this}get role(){return this.lambda.role}get edgeArn(){throw new(errors_1()).ValidationError("$LATEST function version cannot be used for Lambda@Edge",this)}get resourceArnsForGrantInvoke(){return[this.functionArn]}addAlias(aliasName,options={}){return(0,util_1().addAlias)(this,this,aliasName,options)}}__decorate([(0,metadata_resource_1().MethodMetadata)()],LatestVersion.prototype,"addAlias",null);function requireObject(x){return x&&typeof x=="object"&&!Array.isArray(x)?x:void 0}function requireString(x){return x&&typeof x=="string"?x:void 0}