UNPKG

aws-cdk-lib

Version:

Version 2 of the AWS Cloud Development Kit library

2 lines (1 loc) 16.4 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;Object.defineProperty(exports,"__esModule",{value:!0}),exports.Role=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");var constructs_1=()=>{var tmp=require("constructs");return constructs_1=()=>tmp,tmp},grant_1=()=>{var tmp=require("./grant");return grant_1=()=>tmp,tmp},iam_generated_1=()=>{var tmp=require("./iam.generated");return iam_generated_1=()=>tmp,tmp},managed_policy_1=()=>{var tmp=require("./managed-policy");return managed_policy_1=()=>tmp,tmp},policy_1=()=>{var tmp=require("./policy");return policy_1=()=>tmp,tmp},policy_document_1=()=>{var tmp=require("./policy-document");return policy_document_1=()=>tmp,tmp},principals_1=()=>{var tmp=require("./principals");return principals_1=()=>tmp,tmp},assume_role_policy_1=()=>{var tmp=require("./private/assume-role-policy");return assume_role_policy_1=()=>tmp,tmp},immutable_role_1=()=>{var tmp=require("./private/immutable-role");return immutable_role_1=()=>tmp,tmp},imported_role_1=()=>{var tmp=require("./private/imported-role");return imported_role_1=()=>tmp,tmp},policydoc_adapter_1=()=>{var tmp=require("./private/policydoc-adapter");return policydoc_adapter_1=()=>tmp,tmp},precreated_role_1=()=>{var tmp=require("./private/precreated-role");return precreated_role_1=()=>tmp,tmp},util_1=()=>{var tmp=require("./private/util");return util_1=()=>tmp,tmp},core_1=()=>{var tmp=require("../../core");return core_1=()=>tmp,tmp},helpers_internal_1=()=>{var tmp=require("../../core/lib/helpers-internal");return helpers_internal_1=()=>tmp,tmp},metadata_resource_1=()=>{var tmp=require("../../core/lib/metadata-resource");return metadata_resource_1=()=>tmp,tmp};const MAX_INLINE_SIZE=1e4,MAX_MANAGEDPOL_SIZE=6e3,IAM_ROLE_SYMBOL=Symbol.for("@aws-cdk/packages/aws-iam/lib/role.Role");class Role extends core_1().Resource{static fromRoleArn(scope,id,roleArn,options={}){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_FromRoleArnOptions(options)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.fromRoleArn),error}const scopeStack=core_1().Stack.of(scope),parsedArn=scopeStack.splitArn(roleArn,core_1().ArnFormat.SLASH_RESOURCE_NAME),resourceName=parsedArn.resourceName,roleAccount=parsedArn.account,roleName=resourceName.split("/").pop();if((0,helpers_internal_1().getCustomizeRolesConfig)(scope).enabled)return new(precreated_role_1()).PrecreatedRole(scope,id,{rolePath:`${scope.node.path}/${id}`,role:new(imported_role_1()).ImportedRole(scope,`Import${id}`,{account:roleAccount,roleArn,roleName,...options})});if(options.addGrantsToResources!==void 0&&options.mutable!==!1)throw new Error("'addGrantsToResources' can only be passed if 'mutable: false'");const roleArnAndScopeStackAccountComparison=core_1().Token.compareStrings(roleAccount??"",scopeStack.account),equalOrAnyUnresolved=roleArnAndScopeStackAccountComparison===core_1().TokenComparison.SAME||roleArnAndScopeStackAccountComparison===core_1().TokenComparison.BOTH_UNRESOLVED||roleArnAndScopeStackAccountComparison===core_1().TokenComparison.ONE_UNRESOLVED,mutableRoleId=options.mutable!==!1&&equalOrAnyUnresolved?id:`MutableRole${id}`,importedRole=new(imported_role_1()).ImportedRole(scope,mutableRoleId,{roleArn,roleName,account:roleAccount,...options});return options.mutable!==!1&&equalOrAnyUnresolved?importedRole:new(immutable_role_1()).ImmutableRole(scope,id,importedRole,options.addGrantsToResources??!1)}static isRole(x){return x!==null&&typeof x=="object"&&IAM_ROLE_SYMBOL in x}static fromRoleName(scope,id,roleName,options={}){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_FromRoleNameOptions(options)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.fromRoleName),error}return Role.fromRoleArn(scope,id,core_1().Stack.of(scope).formatArn({region:"",service:"iam",resource:"role",resourceName:roleName}),options)}static customizeRoles(scope,options){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_CustomizeRolesOptions(options)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.customizeRoles),error}const preventSynthesis=options?.preventSynthesis??!0,useRoles={};for(const[constructPath,roleName]of Object.entries(options?.usePrecreatedRoles??{})){const absPath=constructPath.startsWith(scope.node.path)?constructPath:`${scope.node.path}/${constructPath}`;useRoles[absPath]=roleName}scope.node.setContext(helpers_internal_1().CUSTOMIZE_ROLES_CONTEXT_KEY,{preventSynthesis,usePrecreatedRoles:useRoles})}constructor(scope,id,props){super(scope,id,{physicalName:props.roleName}),this.grantPrincipal=this,this.principalAccount=this.env.account,this.assumeRoleAction="sts:AssumeRole",this.managedPolicies=[],this.attachedPolicies=new(util_1()).AttachedPolicies,this.dependables=new Map,this._didSplit=!1;try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_RoleProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,Role),error}if((0,metadata_resource_1().addConstructMetadata)(this,props),props.roleName&&!core_1().Token.isUnresolved(props.roleName)&&!/^[\w+=,.@-]{1,64}$/.test(props.roleName))throw new Error("Invalid roleName. The name must be a string of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of the following characters: _+=,.@-. Length must be between 1 and 64 characters.");const externalIds=props.externalIds||[];props.externalId&&externalIds.push(props.externalId),this.assumeRolePolicy=createAssumeRolePolicy(props.assumedBy,externalIds),this.managedPolicies.push(...props.managedPolicies||[]),this.inlinePolicies=props.inlinePolicies||{},this.permissionsBoundary=props.permissionsBoundary;const maxSessionDuration=props.maxSessionDuration&&props.maxSessionDuration.toSeconds();validateMaxSessionDuration(maxSessionDuration);const description=props.description&&props.description?.length>0?props.description:void 0;if(description&&description.length>1e3)throw new Error("Role description must be no longer than 1000 characters.");validateRolePath(props.path);const config=this.getPrecreatedRoleConfig(),roleArn=core_1().Stack.of(scope).formatArn({region:"",service:"iam",resource:"role",resourceName:config.precreatedRoleName}),importedRole=new(imported_role_1()).ImportedRole(this,"Import"+id,{roleArn,roleName:config.precreatedRoleName??id,account:core_1().Stack.of(this).account});if(this.roleName=importedRole.roleName,this.roleArn=importedRole.roleArn,config.enabled){const role=new(precreated_role_1()).PrecreatedRole(this,"PrecreatedRole"+id,{rolePath:this.node.path,role:importedRole,missing:!config.precreatedRoleName,assumeRolePolicy:this.assumeRolePolicy});this.managedPolicies.forEach(policy=>role.addManagedPolicy(policy)),Object.entries(this.inlinePolicies).forEach(([name,policy])=>{role.attachInlinePolicy(new(policy_1()).Policy(this,name,{document:policy}))}),this._precreatedRole=role}if(!config.preventSynthesis){const role=new(iam_generated_1()).CfnRole(this,"Resource",{assumeRolePolicyDocument:this.assumeRolePolicy,managedPolicyArns:util_1().UniqueStringSet.from(()=>this.managedPolicies.map(p=>p.managedPolicyArn)),policies:_flatten(this.inlinePolicies),path:props.path,permissionsBoundary:this.permissionsBoundary?this.permissionsBoundary.managedPolicyArn:void 0,roleName:this.physicalName,maxSessionDuration,description});this._roleId=role.attrRoleId,this.roleArn=this.getResourceArnAttribute(role.attrArn,{region:"",service:"iam",resource:"role",resourceName:`${props.path?props.path.substr(props.path.charAt(0)==="/"?1:0):""}${this.physicalName}`}),this.roleName=this.getResourceNameAttribute(role.ref),core_1().Aspects.of(this).add({visit:c=>{c===this&&this.splitLargePolicy()}},{priority:core_1().AspectPriority.MUTATING})}this.policyFragment=new(principals_1()).ArnPrincipal(this.roleArn).policyFragment;function _flatten(policies){if(policies==null||Object.keys(policies).length===0)return;const result=new Array;for(const policyName of Object.keys(policies)){const policyDocument=policies[policyName];result.push({policyName,policyDocument})}return result}this.node.addValidation({validate:()=>this.validateRole()})}addToPrincipalPolicy(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.addToPrincipalPolicy),error}if(this._precreatedRole)return this._precreatedRole.addToPrincipalPolicy(statement);{this.defaultPolicy||(this.defaultPolicy=new(policy_1()).Policy(this,"DefaultPolicy"),this.attachInlinePolicy(this.defaultPolicy)),this.defaultPolicy.addStatements(statement);const policyDependable=new(constructs_1()).DependencyGroup;return this.dependables.set(statement,policyDependable),{statementAdded:!0,policyDependable}}}addToPolicy(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.addToPolicy),error}return this._precreatedRole?this._precreatedRole.addToPolicy(statement):this.addToPrincipalPolicy(statement).statementAdded}addManagedPolicy(policy){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IManagedPolicy(policy)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addManagedPolicy),error}if(this._precreatedRole)return this._precreatedRole.addManagedPolicy(policy);if(this.managedPolicies.some(mp=>mp.managedPolicyArn===policy.managedPolicyArn))return;this.managedPolicies.push(policy)}attachInlinePolicy(policy){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_Policy(policy)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.attachInlinePolicy),error}this._precreatedRole?this._precreatedRole.attachInlinePolicy(policy):(this.attachedPolicies.attach(policy),policy.attachToRole(this))}grant(grantee,...actions){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IPrincipal(grantee)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.grant),error}return grant_1().Grant.addToPrincipal({grantee,actions,resourceArns:[this.roleArn],scope:this})}grantPassRole(identity){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IPrincipal(identity)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.grantPassRole),error}return this.grant(identity,"iam:PassRole")}grantAssumeRole(identity){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IPrincipal(identity)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.grantAssumeRole),error}if(identity instanceof principals_1().ServicePrincipal||identity instanceof principals_1().AccountPrincipal)throw new Error("Cannot use a service or account principal with grantAssumeRole, use assumeRolePolicy instead.");return this.grant(identity,"sts:AssumeRole")}get roleId(){if(!this._roleId)throw new Error('"roleId" is not available on precreated roles');return this._roleId}withoutPolicyUpdates(options={}){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_WithoutPolicyUpdatesOptions(options)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.withoutPolicyUpdates),error}return this.immutableRole||(this.immutableRole=new(immutable_role_1()).ImmutableRole(constructs_1().Node.of(this).scope,`ImmutableRole${this.node.id}`,this,options.addGrantsToResources??!1)),this.immutableRole}applyRemovalPolicy(policy){try{jsiiDeprecationWarnings().aws_cdk_lib_RemovalPolicy(policy)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.applyRemovalPolicy),error}this.getPrecreatedRoleConfig().preventSynthesis||super.applyRemovalPolicy(policy)}validateRole(){const errors=new Array;errors.push(...this.assumeRolePolicy?.validateForResourcePolicy()??[]);for(const policy of Object.values(this.inlinePolicies))errors.push(...policy.validateForIdentityPolicy());return errors}splitLargePolicy(){if(!this.defaultPolicy||this._didSplit)return;this._didSplit=!0;const self=this,originalDoc=this.defaultPolicy.document,splitOffDocs=originalDoc._splitDocument(this,MAX_INLINE_SIZE,MAX_MANAGEDPOL_SIZE),mpCount=this.managedPolicies.length+(splitOffDocs.size-1);mpCount>20?core_1().Annotations.of(this).addWarningV2("@aws-cdk/aws-iam:rolePolicyTooLarge",`Policy too large: ${mpCount} exceeds the maximum of 20 managed policies attached to a Role`):mpCount>10&&core_1().Annotations.of(this).addWarningV2("@aws-cdk/aws-iam:rolePolicyLarge",`Policy large: ${mpCount} exceeds 10 managed policies attached to a Role, this requires a quota increase`),markDeclaringConstruct(originalDoc,this.defaultPolicy);let i=1;for(const newDoc of splitOffDocs.keys()){if(newDoc===originalDoc)continue;const mp=new(managed_policy_1()).ManagedPolicy(this,`OverflowPolicy${i++}`,{description:`Part of the policies for ${this.node.path}`,document:newDoc,roles:[this]});markDeclaringConstruct(newDoc,mp)}function markDeclaringConstruct(doc,declaringConstruct){for(const original of splitOffDocs.get(doc)??[])self.dependables.get(original)?.add(declaringConstruct)}}getPrecreatedRoleConfig(){return(0,helpers_internal_1().getPrecreatedRoleConfig)(this)}}exports.Role=Role,_a=JSII_RTTI_SYMBOL_1,Role[_a]={fqn:"aws-cdk-lib.aws_iam.Role",version:"2.185.0"},__decorate([(0,metadata_resource_1().MethodMetadata)()],Role.prototype,"addToPrincipalPolicy",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Role.prototype,"addToPolicy",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Role.prototype,"addManagedPolicy",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Role.prototype,"attachInlinePolicy",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Role.prototype,"grant",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Role.prototype,"grantPassRole",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Role.prototype,"grantAssumeRole",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Role.prototype,"withoutPolicyUpdates",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Role.prototype,"applyRemovalPolicy",null);function createAssumeRolePolicy(principal,externalIds){const actualDoc=new(policy_document_1()).PolicyDocument,addDoc=externalIds.length===0?actualDoc:new(policydoc_adapter_1()).MutatingPolicyDocumentAdapter(actualDoc,statement=>(statement.addCondition("StringEquals",{"sts:ExternalId":externalIds.length===1?externalIds[0]:externalIds}),statement));return(0,assume_role_policy_1().defaultAddPrincipalToAssumeRole)(principal,addDoc),actualDoc}function validateRolePath(path){if(path===void 0||core_1().Token.isUnresolved(path))return;const validRolePath=/^(\/|\/[\u0021-\u007F]+\/)$/;if(path.length==0||path.length>512)throw new Error(`Role path must be between 1 and 512 characters. The provided role path is ${path.length} characters.`);if(!validRolePath.test(path))throw new Error(`Role path must be either a slash or valid characters (alphanumerics and symbols) surrounded by slashes. Valid characters are unicode characters in [\\u0021-\\u007F]. However, ${path} is provided.`)}function validateMaxSessionDuration(duration){if(duration!==void 0&&(duration<3600||duration>43200))throw new Error(`maxSessionDuration is set to ${duration}, but must be >= 3600sec (1hr) and <= 43200sec (12hrs)`)}Object.defineProperty(Role.prototype,IAM_ROLE_SYMBOL,{value:!0,enumerable:!1,writable:!1});