UNPKG

aws-cdk-lib

Version:

Version 2 of the AWS Cloud Development Kit library

2 lines (1 loc) 15.6 kB
"use strict";var __runInitializers=exports&&exports.__runInitializers||function(thisArg,initializers,value){for(var useValue=arguments.length>2,i=0;i<initializers.length;i++)value=useValue?initializers[i].call(thisArg,value):initializers[i].call(thisArg);return useValue?value:void 0},__esDecorate=exports&&exports.__esDecorate||function(ctor,descriptorIn,decorators,contextIn,initializers,extraInitializers){function accept(f){if(f!==void 0&&typeof f!="function")throw new TypeError("Function expected");return f}for(var kind=contextIn.kind,key=kind==="getter"?"get":kind==="setter"?"set":"value",target=!descriptorIn&&ctor?contextIn.static?ctor:ctor.prototype:null,descriptor=descriptorIn||(target?Object.getOwnPropertyDescriptor(target,contextIn.name):{}),_,done=!1,i=decorators.length-1;i>=0;i--){var context={};for(var p in contextIn)context[p]=p==="access"?{}:contextIn[p];for(var p in contextIn.access)context.access[p]=contextIn.access[p];context.addInitializer=function(f){if(done)throw new TypeError("Cannot add initializers after decoration has completed");extraInitializers.push(accept(f||null))};var result=(0,decorators[i])(kind==="accessor"?{get:descriptor.get,set:descriptor.set}:descriptor[key],context);if(kind==="accessor"){if(result===void 0)continue;if(result===null||typeof result!="object")throw new TypeError("Object expected");(_=accept(result.get))&&(descriptor.get=_),(_=accept(result.set))&&(descriptor.set=_),(_=accept(result.init))&&initializers.unshift(_)}else(_=accept(result))&&(kind==="field"?initializers.unshift(_):descriptor[key]=_)}target&&Object.defineProperty(target,contextIn.name,descriptor),done=!0};Object.defineProperty(exports,"__esModule",{value:!0}),exports.Key=exports.KeyUsage=exports.KeySpec=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");var alias_1=()=>{var tmp=require("./alias");return alias_1=()=>tmp,tmp},kms_generated_1=()=>{var tmp=require("./kms.generated");return kms_generated_1=()=>tmp,tmp},perms=()=>{var tmp=require("./private/perms");return perms=()=>tmp,tmp},iam=()=>{var tmp=require("../../aws-iam");return iam=()=>tmp,tmp},cxschema=()=>{var tmp=require("../../cloud-assembly-schema");return cxschema=()=>tmp,tmp},core_1=()=>{var tmp=require("../../core");return core_1=()=>tmp,tmp},metadata_resource_1=()=>{var tmp=require("../../core/lib/metadata-resource");return metadata_resource_1=()=>tmp,tmp},prop_injectable_1=()=>{var tmp=require("../../core/lib/prop-injectable");return prop_injectable_1=()=>tmp,tmp},cxapi=()=>{var tmp=require("../../cx-api");return cxapi=()=>tmp,tmp};class KeyBase extends core_1().Resource{aliases=[];constructor(scope,id,props={}){super(scope,id,props),this.node.addValidation({validate:()=>this.policy?.validateForResourcePolicy()??[]})}get keyRef(){return{keyArn:this.keyArn,keyId:this.keyId}}addAlias(aliasName){const aliasId=this.aliases.length>0?`Alias${aliasName}`:"Alias",alias=new(alias_1()).Alias(this,aliasId,{aliasName,targetKey:this});return this.aliases.push(alias),alias}addToResourcePolicy(statement,allowNoOp=!0){const stack=core_1().Stack.of(this);if(!this.policy){if(allowNoOp)return{statementAdded:!1};throw new(core_1()).ValidationError(`Unable to add statement to IAM resource policy for KMS key: ${JSON.stringify(stack.resolve(this.keyArn))}`,this)}return this.policy.addStatements(statement),{statementAdded:!0,policyDependable:this.policy}}grant(grantee,...actions){const granteeStackDependsOnKeyStack=this.granteeStackDependsOnKeyStack(grantee),principal=granteeStackDependsOnKeyStack?new(iam()).AccountPrincipal(granteeStackDependsOnKeyStack):grantee.grantPrincipal,crossAccountAccess=this.isGranteeFromAnotherAccount(grantee),crossRegionAccess=this.isGranteeFromAnotherRegion(grantee),crossEnvironment=crossAccountAccess||crossRegionAccess,grantOptions={grantee,actions,resource:this,resourceArns:[this.keyArn],resourceSelfArns:crossEnvironment?void 0:["*"]};return this.trustAccountIdentities&&!crossEnvironment?iam().Grant.addToPrincipalOrResource(grantOptions):iam().Grant.addToPrincipalAndResource({...grantOptions,resourceArns:crossEnvironment?["*"]:[this.keyArn],resourcePolicyPrincipal:principal})}grantDecrypt(grantee){return this.grant(grantee,...perms().DECRYPT_ACTIONS)}grantEncrypt(grantee){return this.grant(grantee,...perms().ENCRYPT_ACTIONS)}grantEncryptDecrypt(grantee){return this.grant(grantee,...perms().DECRYPT_ACTIONS,...perms().ENCRYPT_ACTIONS)}grantSign(grantee){return this.grant(grantee,...perms().SIGN_ACTIONS)}grantVerify(grantee){return this.grant(grantee,...perms().VERIFY_ACTIONS)}grantSignVerify(grantee){return this.grant(grantee,...perms().SIGN_ACTIONS,...perms().VERIFY_ACTIONS)}grantGenerateMac(grantee){return this.grant(grantee,...perms().GENERATE_HMAC_ACTIONS)}grantVerifyMac(grantee){return this.grant(grantee,...perms().VERIFY_HMAC_ACTIONS)}granteeStackDependsOnKeyStack(grantee){const grantPrincipal=grantee.grantPrincipal;if(!iam().principalIsOwnedResource(grantPrincipal))return;const keyStack=core_1().Stack.of(this),granteeStack=core_1().Stack.of(grantPrincipal);if(keyStack!==granteeStack)return granteeStack.dependencies.includes(keyStack)?granteeStack.account:void 0}isGranteeFromAnotherRegion(grantee){if(!iam().principalIsOwnedResource(grantee.grantPrincipal))return!1;const bucketStack=core_1().Stack.of(this),identityStack=core_1().Stack.of(grantee.grantPrincipal);return core_1().FeatureFlags.of(this).isEnabled(cxapi().KMS_REDUCE_CROSS_ACCOUNT_REGION_POLICY_SCOPE)?bucketStack.region!==identityStack.region&&this.env.region!==identityStack.region:bucketStack.region!==identityStack.region}isGranteeFromAnotherAccount(grantee){if(!iam().principalIsOwnedResource(grantee.grantPrincipal))return!1;const bucketStack=core_1().Stack.of(this),identityStack=core_1().Stack.of(grantee.grantPrincipal);return core_1().FeatureFlags.of(this).isEnabled(cxapi().KMS_REDUCE_CROSS_ACCOUNT_REGION_POLICY_SCOPE)?bucketStack.account!==identityStack.account&&this.env.account!==identityStack.account:bucketStack.account!==identityStack.account}}var KeySpec;(function(KeySpec2){KeySpec2.SYMMETRIC_DEFAULT="SYMMETRIC_DEFAULT",KeySpec2.RSA_2048="RSA_2048",KeySpec2.RSA_3072="RSA_3072",KeySpec2.RSA_4096="RSA_4096",KeySpec2.ECC_NIST_P256="ECC_NIST_P256",KeySpec2.ECC_NIST_P384="ECC_NIST_P384",KeySpec2.ECC_NIST_P521="ECC_NIST_P521",KeySpec2.ECC_SECG_P256K1="ECC_SECG_P256K1",KeySpec2.HMAC_224="HMAC_224",KeySpec2.HMAC_256="HMAC_256",KeySpec2.HMAC_384="HMAC_384",KeySpec2.HMAC_512="HMAC_512",KeySpec2.SM2="SM2",KeySpec2.ML_DSA_44="ML_DSA_44",KeySpec2.ML_DSA_65="ML_DSA_65",KeySpec2.ML_DSA_87="ML_DSA_87"})(KeySpec||(exports.KeySpec=KeySpec={}));var KeyUsage;(function(KeyUsage2){KeyUsage2.ENCRYPT_DECRYPT="ENCRYPT_DECRYPT",KeyUsage2.SIGN_VERIFY="SIGN_VERIFY",KeyUsage2.GENERATE_VERIFY_MAC="GENERATE_VERIFY_MAC",KeyUsage2.KEY_AGREEMENT="KEY_AGREEMENT"})(KeyUsage||(exports.KeyUsage=KeyUsage={}));let Key=(()=>{let _classDecorators=[prop_injectable_1().propertyInjectable],_classDescriptor,_classExtraInitializers=[],_classThis,_classSuper=KeyBase,_instanceExtraInitializers=[],_grantAdmin_decorators;var Key2=class extends _classSuper{static{_classThis=this}static{const _metadata=typeof Symbol=="function"&&Symbol.metadata?Object.create(_classSuper[Symbol.metadata]??null):void 0;_grantAdmin_decorators=[(0,metadata_resource_1().MethodMetadata)()],__esDecorate(this,null,_grantAdmin_decorators,{kind:"method",name:"grantAdmin",static:!1,private:!1,access:{has:obj=>"grantAdmin"in obj,get:obj=>obj.grantAdmin},metadata:_metadata},null,_instanceExtraInitializers),__esDecorate(null,_classDescriptor={value:_classThis},_classDecorators,{kind:"class",name:_classThis.name,metadata:_metadata},null,_classExtraInitializers),Key2=_classThis=_classDescriptor.value,_metadata&&Object.defineProperty(_classThis,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:_metadata})}static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_kms.Key",version:"2.233.0"};static PROPERTY_INJECTION_ID="aws-cdk-lib.aws-kms.Key";static DEFAULT_DUMMY_KEY_ID="1234abcd-12ab-34cd-56ef-1234567890ab";static fromKeyArn(scope,id,keyArn){class Import extends KeyBase{keyArn=keyArn;keyId;policy=void 0;trustAccountIdentities=!0;constructor(keyId,props={}){super(scope,id,props),this.keyId=keyId}}const keyResourceName=core_1().Stack.of(scope).splitArn(keyArn,core_1().ArnFormat.SLASH_RESOURCE_NAME).resourceName;if(!keyResourceName)throw new(core_1()).ValidationError(`KMS key ARN must be in the format 'arn:<partition>:kms:<region>:<account>:key/<keyId>', got: '${keyArn}'`,scope);return new Import(keyResourceName,{environmentFromArn:keyArn})}static fromCfnKey(cfnKey){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_kms_CfnKey(cfnKey)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.fromCfnKey),error}const id="@FromCfnKey",existing=cfnKey.node.tryFindChild(id);if(existing)return existing;let keyPolicy;try{keyPolicy=iam().PolicyDocument.fromJson(cfnKey.keyPolicy)}catch{throw new(core_1()).ValidationError("Could not parse the PolicyDocument of the passed AWS::KMS::Key resource because it contains CloudFormation functions. This makes it impossible to create a mutable IKey from that Policy. You have to use fromKeyArn instead, passing it the ARN attribute property of the low-level CfnKey",cfnKey)}return cfnKey.keyPolicy=core_1().Lazy.any({produce:()=>keyPolicy.toJSON()}),new class extends KeyBase{keyArn=cfnKey.attrArn;keyId=cfnKey.ref;policy=keyPolicy;trustAccountIdentities=!1}(cfnKey,id)}static fromLookup(scope,id,options){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_kms_KeyLookupOptions(options)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.fromLookup),error}class Import extends KeyBase{keyArn;keyId;policy=void 0;trustAccountIdentities=!0;constructor(keyId,keyArn){super(scope,id),this.keyId=keyId,this.keyArn=keyArn}}if(core_1().Token.isUnresolved(options.aliasName))throw new(core_1()).ValidationError("All arguments to Key.fromLookup() must be concrete (no Tokens)",scope);const attributes=core_1().ContextProvider.getValue(scope,{provider:cxschema().ContextProvider.KEY_PROVIDER,props:{aliasName:options.aliasName},dummyValue:{keyId:Key2.DEFAULT_DUMMY_KEY_ID},mustExist:!options.returnDummyKeyOnMissing}).value;return new Import(attributes.keyId,core_1().Arn.format({resource:"key",service:"kms",resourceName:attributes.keyId},core_1().Stack.of(scope)))}static isLookupDummy(key){try{jsiiDeprecationWarnings().aws_cdk_lib_interfaces_aws_kms_IKeyRef(key)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.isLookupDummy),error}return key.keyRef.keyId===Key2.DEFAULT_DUMMY_KEY_ID}keyArn=__runInitializers(this,_instanceExtraInitializers);keyId;policy;trustAccountIdentities;enableKeyRotation;constructor(scope,id,props={}){super(scope,id);try{jsiiDeprecationWarnings().aws_cdk_lib_aws_kms_KeyProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,Key2),error}(0,metadata_resource_1().addConstructMetadata)(this,props);const denyLists={[KeyUsage.ENCRYPT_DECRYPT]:[KeySpec.ECC_NIST_P256,KeySpec.ECC_NIST_P384,KeySpec.ECC_NIST_P521,KeySpec.ECC_SECG_P256K1,KeySpec.HMAC_224,KeySpec.HMAC_256,KeySpec.HMAC_384,KeySpec.HMAC_512,KeySpec.ML_DSA_44,KeySpec.ML_DSA_65,KeySpec.ML_DSA_87],[KeyUsage.SIGN_VERIFY]:[KeySpec.SYMMETRIC_DEFAULT,KeySpec.HMAC_224,KeySpec.HMAC_256,KeySpec.HMAC_384,KeySpec.HMAC_512],[KeyUsage.GENERATE_VERIFY_MAC]:[KeySpec.RSA_2048,KeySpec.RSA_3072,KeySpec.RSA_4096,KeySpec.ECC_NIST_P256,KeySpec.ECC_NIST_P384,KeySpec.ECC_NIST_P521,KeySpec.ECC_SECG_P256K1,KeySpec.SYMMETRIC_DEFAULT,KeySpec.SM2,KeySpec.ML_DSA_44,KeySpec.ML_DSA_65,KeySpec.ML_DSA_87],[KeyUsage.KEY_AGREEMENT]:[KeySpec.SYMMETRIC_DEFAULT,KeySpec.RSA_2048,KeySpec.RSA_3072,KeySpec.RSA_4096,KeySpec.ECC_SECG_P256K1,KeySpec.HMAC_224,KeySpec.HMAC_256,KeySpec.HMAC_384,KeySpec.HMAC_512,KeySpec.ML_DSA_44,KeySpec.ML_DSA_65,KeySpec.ML_DSA_87]},keySpec=props.keySpec??KeySpec.SYMMETRIC_DEFAULT,keyUsage=props.keyUsage??KeyUsage.ENCRYPT_DECRYPT;if(denyLists[keyUsage].includes(keySpec))throw new(core_1()).ValidationError(`key spec '${keySpec}' is not valid with usage '${keyUsage}'`,this);if(keySpec.startsWith("HMAC")&&props.enableKeyRotation)throw new(core_1()).ValidationError("key rotation cannot be enabled on HMAC keys",this);if(keySpec!==KeySpec.SYMMETRIC_DEFAULT&&props.enableKeyRotation)throw new(core_1()).ValidationError("key rotation cannot be enabled on asymmetric keys",this);if(this.enableKeyRotation=props.enableKeyRotation,props.rotationPeriod){if(props.enableKeyRotation===!1)throw new(core_1()).ValidationError("'rotationPeriod' cannot be specified when 'enableKeyRotation' is disabled",this);if(props.rotationPeriod.toDays()<90||props.rotationPeriod.toDays()>2560)throw new(core_1()).ValidationError(`'rotationPeriod' value must between 90 and 2650 days. Received: ${props.rotationPeriod.toDays()}`,this);props.enableKeyRotation===void 0&&(this.enableKeyRotation=!0)}const defaultKeyPoliciesFeatureEnabled=core_1().FeatureFlags.of(this).isEnabled(cxapi().KMS_DEFAULT_KEY_POLICIES);if(this.policy=props.policy??new(iam()).PolicyDocument,defaultKeyPoliciesFeatureEnabled){if(props.trustAccountIdentities===!1)throw new(core_1()).ValidationError("`trustAccountIdentities` cannot be false if the @aws-cdk/aws-kms:defaultKeyPolicies feature flag is set",this);this.trustAccountIdentities=!0,props.policy||this.addDefaultAdminPolicy()}else this.trustAccountIdentities=props.trustAccountIdentities??!1,this.trustAccountIdentities?this.addDefaultAdminPolicy():this.addLegacyAdminPolicy();let pendingWindowInDays;if(props.pendingWindow&&(pendingWindowInDays=props.pendingWindow.toDays(),pendingWindowInDays<7||pendingWindowInDays>30))throw new(core_1()).ValidationError(`'pendingWindow' value must between 7 and 30 days. Received: ${pendingWindowInDays}`,this);const resource=new(kms_generated_1()).CfnKey(this,"Resource",{description:props.description,enableKeyRotation:this.enableKeyRotation,rotationPeriodInDays:props.rotationPeriod?.toDays(),enabled:props.enabled,keySpec:props.keySpec,keyUsage:props.keyUsage,keyPolicy:this.policy,multiRegion:props.multiRegion,pendingWindowInDays});this.keyArn=resource.attrArn,this.keyId=resource.ref,resource.applyRemovalPolicy(props.removalPolicy),(props.admins??[]).forEach(p=>this.grantAdmin(p)),props.alias!==void 0&&this.addAlias(props.alias)}grantAdmin(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.grantAdmin),error}return this.grant(grantee,...perms().ADMIN_ACTIONS)}addDefaultAdminPolicy(){this.addToResourcePolicy(new(iam()).PolicyStatement({resources:["*"],actions:["kms:*"],principals:[new(iam()).AccountRootPrincipal]}))}addLegacyAdminPolicy(){const actions=["kms:Create*","kms:Describe*","kms:Enable*","kms:List*","kms:Put*","kms:Update*","kms:Revoke*","kms:Disable*","kms:Get*","kms:Delete*","kms:ScheduleKeyDeletion","kms:CancelKeyDeletion","kms:GenerateDataKey","kms:TagResource","kms:UntagResource"];this.addToResourcePolicy(new(iam()).PolicyStatement({resources:["*"],actions,principals:[new(iam()).AccountRootPrincipal]}))}static{__runInitializers(_classThis,_classExtraInitializers)}};return Key2=_classThis})();exports.Key=Key;