Socket
Socket
Sign inDemoInstall

@aws-cdk/aws-kms

Package Overview
Dependencies
4
Maintainers
5
Versions
288
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

@aws-cdk/aws-kms


Version published
Weekly downloads
128K
decreased by-7.61%
Maintainers
5
Created
Weekly downloads
 

Package description

What is @aws-cdk/aws-kms?

@aws-cdk/aws-kms is an AWS CDK library that allows you to define and manage AWS Key Management Service (KMS) resources in your AWS infrastructure as code. It provides constructs for creating and managing KMS keys, aliases, and grants, enabling secure encryption and decryption of data.

What are @aws-cdk/aws-kms's main functionalities?

Create a KMS Key

This code sample demonstrates how to create a new KMS key with key rotation enabled and an alias using the AWS CDK.

const cdk = require('@aws-cdk/core');
const kms = require('@aws-cdk/aws-kms');

const app = new cdk.App();
const stack = new cdk.Stack(app, 'MyStack');

const key = new kms.Key(stack, 'MyKey', {
  enableKeyRotation: true,
  alias: 'alias/my-key'
});

app.synth();

Create a KMS Alias

This code sample demonstrates how to create a new KMS alias that points to an existing KMS key using the AWS CDK.

const cdk = require('@aws-cdk/core');
const kms = require('@aws-cdk/aws-kms');

const app = new cdk.App();
const stack = new cdk.Stack(app, 'MyStack');

const key = new kms.Key(stack, 'MyKey');

const alias = new kms.Alias(stack, 'MyAlias', {
  aliasName: 'alias/my-alias',
  targetKey: key
});

app.synth();

Grant Permissions to a KMS Key

This code sample demonstrates how to grant encrypt and decrypt permissions to an IAM user for a KMS key using the AWS CDK.

const cdk = require('@aws-cdk/core');
const kms = require('@aws-cdk/aws-kms');
const iam = require('@aws-cdk/aws-iam');

const app = new cdk.App();
const stack = new cdk.Stack(app, 'MyStack');

const key = new kms.Key(stack, 'MyKey');

const user = new iam.User(stack, 'MyUser');

key.grantEncryptDecrypt(user);

app.synth();

Other packages similar to @aws-cdk/aws-kms

Changelog

Source

1.78.0 (2020-12-11)

⚠ BREAKING CHANGES TO EXPERIMENTAL FEATURES

  • cloudfront-origins: Default minimum origin SSL protocol for HttpOrigin and LoadBalancerOrigin changed from SSLv3 to TLSv1.2.
  • apigatewayv2: domainName property under DomainName has been renamed to name.
  • appmesh: the properties dnsHostName and awsCloudMap of VirtualNodeProps have been replaced with the property serviceDiscovery
  • kms: change the default value of trustAccountIdentities to true, which will result in the key getting the KMS-recommended default key policy. This is enabled through the '@aws-cdk/aws-kms:defaultKeyPolicies' feature flag.

Features

  • appmesh: add ClientPolicy to VirtualNode, VirtualGateway and VirtualService (#11563) (bfee58c)
  • appmesh: change Virtual Node service discovery to a union-like class (#11926) (f75c264)
  • appsync: support appsync functions for pipelineConfig (#10111) (cb703c7), closes #9092
  • batch: Log configuration for job definitions (#11771) (84c959c), closes #11218
  • cloudfront: responseHttpStatus defaults to httpStatus in errorResponses (#11879) (c6052ae)
  • cloudfront: the Distribution construct is now Generally Available (stable) (#11919) (442bf7e)
  • cloudfront-origins: ability to specify minimum origin SSL protocol (#11997) (a0aa61d), closes #11994
  • cloudfront-origins: CloudFront Origins is now Generally Available (#12011) (daace16), closes #11919
  • codeguruprofiler: the CodeGuru Profiler Construct Library is now Generally Available (stable) (#11924) (cbe7a10)
  • ecs: introduce a new Image type, TagParameterContainerImage, to be used in CodePipeline (#11795) (4182c40), closes #1237 #7746
  • eks: kubernetes resource pruning (#11932) (1fdd549), closes #10495
  • kms: change default key policy to align with KMS best practices (under feature flag) (#11918) (ff695da), closes #5575 #8977 #10575 #11309
  • s3: add support to set bucket OwnershipControls (#11834) (0d289cc), closes #11591

Bug Fixes

  • apigateway: base path url cannot contain upper case characters (#11799) (8069a7e)
  • cfn-include: cfn-include fails in monocdk (#11595) (45e43f2), closes #11342
  • cli: cross-account deployment no longer works (#11966) (6fb3448), closes #11350 #11792 #11792
  • codebuild: incorrect SSM Parameter ARN in Project's IAM permissions (#11917) (7a09c18), closes #9980
  • core: autogenerated exports do not account for stack name length (#11909) (0df79a2), closes #9733
  • ecs: cannot disable container insights of an ECS cluster (#9151) (e328f22), closes #9149
  • eks: kubectl provider out-of-memory for large manifests/charts (now 1GiB) (#11957) (2ec2948), closes #11787
  • synthetics: metricFailed uses Average instead of Sum by default (#11941) (3530e8c)
  • apigatewayv2: rename 'domainName' to 'name' in the DomainName construct (#11989) (1be831a)

Readme

Source

AWS Key Management Service Construct Library


cfn-resources: Stable

cdk-constructs: Stable


Define a KMS key:

import * as kms from '@aws-cdk/aws-kms';

new kms.Key(this, 'MyKey', {
    enableKeyRotation: true
});

Add a couple of aliases:

const key = new kms.Key(this, 'MyKey');
key.addAlias('alias/foo');
key.addAlias('alias/bar');

Sharing keys between stacks

To use a KMS key in a different stack in the same CDK application, pass the construct to the other stack:

sharing key between stacks

Importing existing keys

To use a KMS key that is not defined in this CDK app, but is created through other means, use Key.fromKeyArn(parent, name, ref):

const myKeyImported = kms.Key.fromKeyArn(this, 'MyImportedKey', 'arn:aws:...');

// you can do stuff with this imported key.
myKeyImported.addAlias('alias/foo');

Note that a call to .addToPolicy(statement) on myKeyImported will not have an affect on the key's policy because it is not owned by your stack. The call will be a no-op.

If a Key has an associated Alias, the Alias can be imported by name and used in place of the Key as a reference. A common scenario for this is in referencing AWS managed keys.

const myKeyAlias = kms.Alias.fromAliasName(this, 'myKey', 'alias/aws/s3');
const trail = new cloudtrail.Trail(this, 'myCloudTrail', {
    sendToCloudWatchLogs: true,
    kmsKey: myKeyAlias
});

Note that calls to addToResourcePolicy and grant* methods on myKeyAlias will be no-ops, and addAlias and aliasTargetKey will fail, as the imported alias does not have a reference to the underlying KMS Key.

Key Policies

Controlling access and usage of KMS Keys requires the use of key policies (resource-based policies attached to the key); this is in contrast to most other AWS resources where access can be entirely controlled with IAM policies, and optionally complemented with resource policies. For more in-depth understanding of KMS key access and policies, see

KMS keys can be created to trust IAM policies. This is the default behavior for both the KMS APIs and in the console. This behavior is enabled by the '@aws-cdk/aws-kms:defaultKeyPolicies' feature flag, which is set for all new projects; for existing projects, this same behavior can be enabled by passing the trustAccountIdentities property as true when creating the key:

new kms.Key(stack, 'MyKey', { trustAccountIdentities: true });

With either the @aws-cdk/aws-kms:defaultKeyPolicies feature flag set, or the trustAccountIdentities prop set, the Key will be given the following default key policy:

{
  "Effect": "Allow",
  "Principal": {"AWS": "arn:aws:iam::111122223333:root"},
  "Action": "kms:*",
  "Resource": "*"
}

This policy grants full access to the key to the root account user. This enables the root account user -- via IAM policies -- to grant access to other IAM principals. With the above default policy, future permissions can be added to either the key policy or IAM principal policy.

const key = new kms.Key(stack, 'MyKey');
const user = new iam.User(stack, 'MyUser');
key.grantEncrypt(user); // Adds encrypt permissions to user policy; key policy is unmodified.

Adopting the default KMS key policy (and so trusting account identities) solves many issues around cyclic dependencies between stacks. Without this default key policy, future permissions must be added to both the key policy and IAM principal policy, which can cause cyclic dependencies if the permissions cross stack boundaries. (For example, an encrypted bucket in one stack, and Lambda function that accesses it in another.)

Appending to or replacing the default key policy

The default key policy can be amended or replaced entirely, depending on your use case and requirements. A common addition to the key policy would be to add other key admins that are allowed to administer the key (e.g., change permissions, revoke, delete). Additional key admins can be specified at key creation or after via the grantAdmin method.

const myTrustedAdminRole = iam.Role.fromRoleArn(stack, 'TrustedRole', 'arn:aws:iam:....');
const key = new kms.Key(stack, 'MyKey', {
  admins: [myTrustedAdminRole],
});

const secondKey = new kms.Key(stack, 'MyKey2');
secondKey.grantAdmin(myTrustedAdminRole);

Alternatively, a custom key policy can be specified, which will replace the default key policy.

Note: In applications without the '@aws-cdk/aws-kms:defaultKeyPolicies' feature flag set and with trustedAccountIdentities set to false (the default), specifying a policy at key creation appends the provided policy to the default key policy, rather than replacing the default policy.

const myTrustedAdminRole = iam.Role.fromRoleArn(stack, 'TrustedRole', 'arn:aws:iam:....');
// Creates a limited admin policy and assigns to the account root.
const myCustomPolicy = new iam.PolicyDocument({
  statements: [new iam.PolicyStatement({
    actions: [
      'kms:Create*',
      'kms:Describe*',
      'kms:Enable*',
      'kms:List*',
      'kms:Put*',
    ],
    principals: [new iam.AccountRootPrincipal()],
    resources: ['*'],
  })],
});
const key = new kms.Key(stack, 'MyKey', {
  policy: myCustomPolicy,
});

Warning: Replacing the default key policy with one that only grants access to a specific user or role runs the risk of the key becoming unmanageable if that user or role is deleted. It is highly recommended that the key policy grants access to the account root, rather than specific principals. See https://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html for more information.

Keywords

FAQs

Last updated on 12 Dec 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc