aws-cdk-lib
Version:
Version 2 of the AWS Cloud Development Kit library
3 lines (2 loc) • 12.5 kB
JavaScript
"use strict";var _a;Object.defineProperty(exports,"__esModule",{value:!0}),exports.Effect=exports.PolicyStatement=void 0,exports.deriveEstimateSizeOptions=deriveEstimateSizeOptions;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");var group_1=()=>{var tmp=require("./group");return group_1=()=>tmp,tmp},principals_1=()=>{var tmp=require("./principals");return principals_1=()=>tmp,tmp},postprocess_policy_document_1=()=>{var tmp=require("./private/postprocess-policy-document");return postprocess_policy_document_1=()=>tmp,tmp},util_1=()=>{var tmp=require("./private/util");return util_1=()=>tmp,tmp},cdk=()=>{var tmp=require("../../core");return cdk=()=>tmp,tmp};const ensureArrayOrUndefined=field=>{if(field!==void 0){if(typeof field!="string"&&!Array.isArray(field))throw new Error("Fields must be either a string or an array of strings");if(Array.isArray(field)&&field.find(f=>typeof f!="string"))throw new Error("Fields must be either a string or an array of strings");return Array.isArray(field)?field:[field]}},DEFAULT_ARN_SIZE_ESTIMATE=150,ARN_SIZE_ESTIMATE_CONTEXT_KEY="@aws-cdk/aws-iam.arnSizeEstimate";class PolicyStatement{static fromJson(obj){const ret=new PolicyStatement({sid:obj.Sid,actions:ensureArrayOrUndefined(obj.Action),resources:ensureArrayOrUndefined(obj.Resource),conditions:obj.Condition,effect:obj.Effect,notActions:ensureArrayOrUndefined(obj.NotAction),notResources:ensureArrayOrUndefined(obj.NotResource),principals:obj.Principal?[new JsonPrincipal(obj.Principal)]:void 0,notPrincipals:obj.NotPrincipal?[new JsonPrincipal(obj.NotPrincipal)]:void 0}),errors=ret.validateForAnyPolicy();if(errors.length>0)throw new Error("Incorrect Policy Statement: "+errors.join(`
`));return ret}constructor(props={}){this._action=new OrderedSet,this._notAction=new OrderedSet,this._principal={},this._notPrincipal={},this._resource=new OrderedSet,this._notResource=new OrderedSet,this._condition={},this._principals=new OrderedSet,this._notPrincipals=new OrderedSet,this._frozen=!1;try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_PolicyStatementProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,PolicyStatement),error}this._sid=props.sid,this._effect=props.effect||Effect.ALLOW,this.addActions(...props.actions||[]),this.addNotActions(...props.notActions||[]),this.addPrincipals(...props.principals||[]),this.addNotPrincipals(...props.notPrincipals||[]),this.addResources(...props.resources||[]),this.addNotResources(...props.notResources||[]),props.conditions!==void 0&&this.addConditions(props.conditions)}get sid(){return this._sid}set sid(sid){this.assertNotFrozen("sid"),this._sid=sid}get effect(){return this._effect}set effect(effect){this.assertNotFrozen("effect"),this._effect=effect}addActions(...actions){if(this.assertNotFrozen("addActions"),actions.length>0&&this._notAction.length>0)throw new Error("Cannot add 'Actions' to policy statement if 'NotActions' have been added");this.validatePolicyActions(actions),this._action.push(...actions)}addNotActions(...notActions){if(this.assertNotFrozen("addNotActions"),notActions.length>0&&this._action.length>0)throw new Error("Cannot add 'NotActions' to policy statement if 'Actions' have been added");this.validatePolicyActions(notActions),this._notAction.push(...notActions)}get hasPrincipal(){return this._principals.length+this._notPrincipals.length>0}addPrincipals(...principals){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IPrincipal(principals)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addPrincipals),error}if(this.assertNotFrozen("addPrincipals"),principals.length>0&&this._notPrincipals.length>0)throw new Error("Cannot add 'Principals' to policy statement if 'NotPrincipals' have been added");for(const principal of principals)this.validatePolicyPrincipal(principal);const added=this._principals.push(...principals);for(const principal of added){const fragment=principal.policyFragment;(0,util_1().mergePrincipal)(this._principal,fragment.principalJson),this.addPrincipalConditions(fragment.conditions)}}addNotPrincipals(...notPrincipals){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IPrincipal(notPrincipals)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addNotPrincipals),error}if(this.assertNotFrozen("addNotPrincipals"),notPrincipals.length>0&&this._principals.length>0)throw new Error("Cannot add 'NotPrincipals' to policy statement if 'Principals' have been added");for(const notPrincipal of notPrincipals)this.validatePolicyPrincipal(notPrincipal);const added=this._notPrincipals.push(...notPrincipals);for(const notPrincipal of added){const fragment=notPrincipal.policyFragment;(0,util_1().mergePrincipal)(this._notPrincipal,fragment.principalJson),this.addPrincipalConditions(fragment.conditions)}}validatePolicyActions(actions){if(!cdk().Token.isUnresolved(actions)){for(const action of actions||[])if(!cdk().Token.isUnresolved(action)&&!/^(\*|[a-zA-Z0-9-]+:[a-zA-Z0-9*]+)$/.test(action))throw new Error(`Action '${action}' is invalid. An action string consists of a service namespace, a colon, and the name of an action. Action names can include wildcards.`)}}validatePolicyPrincipal(principal){if(principal instanceof group_1().Group)throw new Error("Cannot use an IAM Group as the 'Principal' or 'NotPrincipal' in an IAM Policy")}addAwsAccountPrincipal(accountId){this.addPrincipals(new(principals_1()).AccountPrincipal(accountId))}addArnPrincipal(arn){this.addPrincipals(new(principals_1()).ArnPrincipal(arn))}addServicePrincipal(service,opts){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_ServicePrincipalOpts(opts)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addServicePrincipal),error}this.addPrincipals(new(principals_1()).ServicePrincipal(service,opts))}addFederatedPrincipal(federated,conditions){this.addPrincipals(new(principals_1()).FederatedPrincipal(federated,conditions))}addAccountRootPrincipal(){this.addPrincipals(new(principals_1()).AccountRootPrincipal)}addCanonicalUserPrincipal(canonicalUserId){this.addPrincipals(new(principals_1()).CanonicalUserPrincipal(canonicalUserId))}addAnyPrincipal(){this.addPrincipals(new(principals_1()).AnyPrincipal)}addResources(...arns){if(this.assertNotFrozen("addResources"),arns.length>0&&this._notResource.length>0)throw new Error("Cannot add 'Resources' to policy statement if 'NotResources' have been added");this._resource.push(...arns)}addNotResources(...arns){if(this.assertNotFrozen("addNotResources"),arns.length>0&&this._resource.length>0)throw new Error("Cannot add 'NotResources' to policy statement if 'Resources' have been added");this._notResource.push(...arns)}addAllResources(){this.addResources("*")}get hasResource(){return this._resource&&this._resource.length>0}addCondition(key,value){this.assertNotFrozen("addCondition"),(0,principals_1().validateConditionObject)(value);const existingValue=this._condition[key];this._condition[key]=existingValue?{...existingValue,...value}:value}addConditions(conditions){Object.keys(conditions).map(key=>{this.addCondition(key,conditions[key])})}addAccountCondition(accountId){this.addCondition("StringEquals",{"sts:ExternalId":accountId})}addSourceAccountCondition(accountId){this.addCondition("StringEquals",{"aws:SourceAccount":accountId})}addSourceArnCondition(arn){this.addCondition("ArnEquals",{"aws:SourceArn":arn})}copy(overrides={}){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_PolicyStatementProps(overrides)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.copy),error}return new PolicyStatement({sid:overrides.sid??this.sid,effect:overrides.effect??this.effect,actions:overrides.actions??this.actions,notActions:overrides.notActions??this.notActions,principals:overrides.principals??this.principals,notPrincipals:overrides.notPrincipals??this.notPrincipals,resources:overrides.resources??this.resources,notResources:overrides.notResources??this.notResources,conditions:overrides.conditions??this.conditions})}toStatementJson(){return(0,postprocess_policy_document_1().normalizeStatement)({Action:this._action.direct(),NotAction:this._notAction.direct(),Condition:this._condition,Effect:this.effect,Principal:this._principal,NotPrincipal:this._notPrincipal,Resource:this._resource.direct(),NotResource:this._notResource.direct(),Sid:this.sid})}toString(){return cdk().Token.asString(this,{displayHint:"PolicyStatement"})}toJSON(){return this.toStatementJson()}addPrincipalConditions(conditions){const theseConditions=JSON.stringify(conditions);if(this.principalConditionsJson===void 0)this.principalConditionsJson=theseConditions;else if(this.principalConditionsJson!==theseConditions)throw new Error(`All principals in a PolicyStatement must have the same Conditions (got '${this.principalConditionsJson}' and '${theseConditions}'). Use multiple statements instead.`);this.addConditions(conditions)}validateForAnyPolicy(){const errors=new Array;return this._action.length===0&&this._notAction.length===0&&errors.push("A PolicyStatement must specify at least one 'action' or 'notAction'."),errors}validateForResourcePolicy(){const errors=this.validateForAnyPolicy();return this._principals.length===0&&this._notPrincipals.length===0&&errors.push("A PolicyStatement used in a resource-based policy must specify at least one IAM principal."),errors}validateForIdentityPolicy(){const errors=this.validateForAnyPolicy();return(this._principals.length>0||this._notPrincipals.length>0)&&errors.push("A PolicyStatement used in an identity-based policy cannot specify any IAM principals."),this._resource.length===0&&this._notResource.length===0&&errors.push("A PolicyStatement used in an identity-based policy must specify at least one resource."),errors}get actions(){return this._action.copy()}get notActions(){return this._notAction.copy()}get principals(){return this._principals.copy()}get notPrincipals(){return this._notPrincipals.copy()}get resources(){return this._resource.copy()}get notResources(){return this._notResource.copy()}get conditions(){return{...this._condition}}freeze(){return this._frozen=!0,this}get frozen(){return this._frozen}_estimateSize(options){let ret=0;const{actionEstimate,arnEstimate}=options;return ret+=`"Effect": "${this.effect}",`.length,count("Action",this.actions,actionEstimate),count("NotAction",this.notActions,actionEstimate),count("Resource",this.resources,arnEstimate),count("NotResource",this.notResources,arnEstimate),ret+=this.principals.length*arnEstimate,ret+=this.notPrincipals.length*arnEstimate,ret+=JSON.stringify(this.conditions).length,ret;function count(key,values,tokenSize){values.length>0&&(ret+=key.length+5+(0,util_1().sum)(values.map(v=>(cdk().Token.isUnresolved(v)?tokenSize:v.length)+3)))}}assertNotFrozen(method){if(this._frozen)throw new Error(`${method}: freeze() has been called on this PolicyStatement previously, so it can no longer be modified`)}}exports.PolicyStatement=PolicyStatement,_a=JSII_RTTI_SYMBOL_1,PolicyStatement[_a]={fqn:"aws-cdk-lib.aws_iam.PolicyStatement",version:"2.185.0"};var Effect;(function(Effect2){Effect2.ALLOW="Allow",Effect2.DENY="Deny"})(Effect||(exports.Effect=Effect={}));class JsonPrincipal extends principals_1().PrincipalBase{constructor(json={}){if(super(),typeof json=="string"&&(json={[util_1().LITERAL_STRING_KEY]:[json]}),typeof json!="object")throw new Error(`JSON IAM principal should be an object, got ${JSON.stringify(json)}`);this.policyFragment={principalJson:json,conditions:{}}}dedupeString(){return JSON.stringify(this.policyFragment)}}function deriveEstimateSizeOptions(scope){const arnEstimate=scope.node.tryGetContext(ARN_SIZE_ESTIMATE_CONTEXT_KEY)??DEFAULT_ARN_SIZE_ESTIMATE;if(typeof arnEstimate!="number")throw new Error(`Context value ${ARN_SIZE_ESTIMATE_CONTEXT_KEY} should be a number, got ${JSON.stringify(arnEstimate)}`);return{actionEstimate:20,arnEstimate}}class OrderedSet{constructor(){this.set=new Set,this.array=new Array}push(...xs){const ret=new Array;for(const x of xs)this.set.has(x)||(this.set.add(x),this.array.push(x),ret.push(x));return ret}get length(){return this.array.length}copy(){return[...this.array]}direct(){return this.array}}