Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(aws-route53): cross account DNS delegations #12680

Merged
merged 9 commits into from
Jan 27, 2021
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/@aws-cdk/aws-route53/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ nyc.config.js
*.snk
!.eslintrc.js

junit.xml
junit.xml
!jest.config.js
3 changes: 2 additions & 1 deletion packages/@aws-cdk/aws-route53/.npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,5 @@ tsconfig.json
# exclude cdk artifacts
**/cdk.out
junit.xml
test/
test/
jest.config.js
24 changes: 24 additions & 0 deletions packages/@aws-cdk/aws-route53/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,30 @@ Constructs are available for A, AAAA, CAA, CNAME, MX, NS, SRV and TXT records.
Use the `CaaAmazonRecord` construct to easily restrict certificate authorities
allowed to issue certificates for a domain to Amazon only.

To add a NS record to a HostedZone in different account

```ts
import * as route53 from '@aws-cdk/aws-route53';

// In the HostedZone containing a account
ayush987goyal marked this conversation as resolved.
Show resolved Hide resolved
const parentZone = new route53.PublicHostedZone(this, 'HostedZone', {
zoneName: 'someexample.com',
crossAccountZoneDelegationPrinciple: new iam.AccountPrincipal('12345678901')
});

// In this account
const subZone = new route53.PublicHostedZone(this, 'SubZone', {
zoneName: 'sub.someexample.com'
});

new route53.CrossAccountZoneDelegationRecord(this, 'delegate', {
recordName: 'sub.someexample.com',
nameServers: subZone.hostedZoneNameServers!,
zoneName: 'someexample.com',
delegationRole: parentZone.crossAccountDelegationRole
});
ayush987goyal marked this conversation as resolved.
Show resolved Hide resolved
```

## Imports

If you don't know the ID of the Hosted Zone to import, you can use the
Expand Down
2 changes: 2 additions & 0 deletions packages/@aws-cdk/aws-route53/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
const baseConfig = require('cdk-build-tools/config/jest.config');
module.exports = baseConfig;
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// eslint-disable-next-line import/no-extraneous-dependencies
import { Credentials, Route53, STS } from 'aws-sdk';

interface ResourceProperties {
AssumeRoleArn: string,
ParentZoneName: string,
RecordName: string,
NameServers: string[],
TTL: number,
}

export async function handler(event: AWSLambda.CloudFormationCustomResourceEvent) {
const resourceProps = event.ResourceProperties as unknown as ResourceProperties;

switch (event.RequestType) {
case 'Create':
case 'Update':
return cfnEventHandler(resourceProps, false);
case 'Delete':
return cfnEventHandler(resourceProps, true);
}
}

async function cfnEventHandler(props: ResourceProperties, isDeleteEvent: boolean) {
const { AssumeRoleArn, ParentZoneName, RecordName, NameServers, TTL } = props;

const credentials = await getCrossAccountCredentials(AssumeRoleArn);
const route53 = new Route53({ credentials });

const { HostedZones } = await route53.listHostedZonesByName({ DNSName: ParentZoneName }).promise();
if (HostedZones.length < 1) {
ayush987goyal marked this conversation as resolved.
Show resolved Hide resolved
throw Error('No hosted zones found with the provided name.');
}

const { Id: hostedZoneId, Name: hostedZoneName } = HostedZones[0];
if (!hostedZoneName.startsWith(ParentZoneName)) {
ayush987goyal marked this conversation as resolved.
Show resolved Hide resolved
throw Error('No hosted zones found with the provided name.');
}

await route53.changeResourceRecordSets({
HostedZoneId: hostedZoneId,
ChangeBatch: {
Changes: [{
Action: isDeleteEvent ? 'DELETE' : 'UPSERT',
ResourceRecordSet: {
Name: RecordName,
Type: 'NS',
TTL,
ResourceRecords: NameServers.map(ns => ({ Value: ns })),
},
}],
},
}).promise();
}

async function getCrossAccountCredentials(roleArn: string): Promise<Credentials> {
const sts = new STS();
const timestamp = (new Date()).getTime();

const { Credentials: assumedCredentials } = await sts
.assumeRole({
RoleArn: roleArn,
RoleSessionName: `cross-account-zone-delegation-${timestamp}`,
ayush987goyal marked this conversation as resolved.
Show resolved Hide resolved
})
.promise();

if (!assumedCredentials) {
njlynch marked this conversation as resolved.
Show resolved Hide resolved
throw Error('Error getting assume role credentials');
}

return new Credentials({
accessKeyId: assumedCredentials.AccessKeyId,
secretAccessKey: assumedCredentials.SecretAccessKey,
sessionToken: assumedCredentials.SessionToken,
});
}
34 changes: 34 additions & 0 deletions packages/@aws-cdk/aws-route53/lib/hosted-zone.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as ec2 from '@aws-cdk/aws-ec2';
import * as iam from '@aws-cdk/aws-iam';
import * as cxschema from '@aws-cdk/cloud-assembly-schema';
import { ContextProvider, Duration, Lazy, Resource, Stack } from '@aws-cdk/core';
import { Construct } from 'constructs';
Expand Down Expand Up @@ -190,6 +191,14 @@ export interface PublicHostedZoneProps extends CommonHostedZoneProps {
* @default false
*/
readonly caaAmazon?: boolean;

/**
* The principle for which a assumed by role is created
ayush987goyal marked this conversation as resolved.
Show resolved Hide resolved
* for record set updation
*
* @default - No delegation configuration
*/
readonly crossAccountZoneDelegationPrinciple?: iam.IPrincipal;
njlynch marked this conversation as resolved.
Show resolved Hide resolved
}

/**
Expand Down Expand Up @@ -222,6 +231,11 @@ export class PublicHostedZone extends HostedZone implements IPublicHostedZone {
return new Import(scope, id);
}

/**
* Role for cross account delegation
*/
public readonly crossAccountDelegationRole?: iam.Role;

constructor(scope: Construct, id: string, props: PublicHostedZoneProps) {
super(scope, id, props);

Expand All @@ -230,6 +244,26 @@ export class PublicHostedZone extends HostedZone implements IPublicHostedZone {
zone: this,
});
}

if (props.crossAccountZoneDelegationPrinciple) {
this.crossAccountDelegationRole = new iam.Role(this, 'CrossAccountZoneDelegationRole', {
assumedBy: props.crossAccountZoneDelegationPrinciple,
inlinePolicies: {
delegation: new iam.PolicyDocument({
statements: [
new iam.PolicyStatement({
actions: ['route53:ListHostedZonesByName'],
resources: ['*'],
}),
new iam.PolicyStatement({
actions: ['route53:ChangeResourceRecordSets'],
resources: [this.hostedZoneArn],
}),
],
}),
},
});
}
}

public addVpc(_vpc: ec2.IVpc) {
Expand Down
69 changes: 68 additions & 1 deletion packages/@aws-cdk/aws-route53/lib/record-set.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
import { Duration, IResource, Resource, Token } from '@aws-cdk/core';
import * as path from 'path';
import * as iam from '@aws-cdk/aws-iam';
import { CustomResource, CustomResourceProvider, CustomResourceProviderRuntime, Duration, IResource, Resource, Token } from '@aws-cdk/core';
import { Construct } from 'constructs';
import { IAliasRecordTarget } from './alias-record-target';
import { IHostedZone } from './hosted-zone-ref';
import { CfnRecordSet } from './route53.generated';
import { determineFullyQualifiedDomainName } from './util';

const CROSS_ACCOUNT_ZONE_DELEGATION_RESOURCE_TYPE = 'Custom::CrossAccountZoneDelegation';

// v2 - keep this import as a separate section to reduce merge conflict when forward merging with the v2 branch.
// eslint-disable-next-line
import { Construct as CoreConstruct } from '@aws-cdk/core';

/**
* A record set
*/
Expand Down Expand Up @@ -559,3 +567,62 @@ export class ZoneDelegationRecord extends RecordSet {
});
}
}

/**
* Construction properties for a CrossAccountZoneDelegationRecord
*/
export interface CrossAccountZoneDelegationRecordProps {
/**
* The name of the record to be made
*/
readonly recordName: string;

/**
* The name servers to report in the delegation records.
*/
readonly nameServers: string[];

/**
* The hosted zone name in the parent account
*/
readonly zoneName: string;

/**
* The delegation role in the parent account
*/
readonly delegationRole: iam.IRole;

/**
* The resource record cache time to live (TTL).
*
* @default Duration.days(2)
*/
readonly ttl?: Duration;
}

/**
* A Cross Account Zone Delegation record
*/
export class CrossAccountZoneDelegationRecord extends CoreConstruct {
constructor(scope: Construct, id: string, props: CrossAccountZoneDelegationRecordProps) {
super(scope, id);

const serviceToken = CustomResourceProvider.getOrCreate(this, CROSS_ACCOUNT_ZONE_DELEGATION_RESOURCE_TYPE, {
codeDirectory: path.join(__dirname, 'cross-account-zone-delegation-handler'),
runtime: CustomResourceProviderRuntime.NODEJS_12,
policyStatements: [{ Effect: 'Allow', Action: 'sts:AssumeRole', Resource: props.delegationRole.roleArn }],
});

new CustomResource(this, 'CrossAccountZoneDelegationCustomResource', {
resourceType: CROSS_ACCOUNT_ZONE_DELEGATION_RESOURCE_TYPE,
serviceToken,
properties: {
AssumeRoleArn: props.delegationRole.roleArn,
ParentZoneName: props.zoneName,
RecordName: props.recordName,
NameServers: props.nameServers,
TTL: (props.ttl || Duration.days(2)).toSeconds(),
},
});
}
}
7 changes: 5 additions & 2 deletions packages/@aws-cdk/aws-route53/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@
"cloudformation": "AWS::Route53",
"env": {
"AWSLINT_BASE_CONSTRUCT": true
}
},
"jest": true
},
"keywords": [
"aws",
Expand All @@ -77,11 +78,12 @@
"cdk-integ-tools": "0.0.0",
"cfn2ts": "0.0.0",
"jest": "^26.6.0",
"nodeunit": "^0.11.3",
"nodeunit-shim": "0.0.0",
"pkglint": "0.0.0"
},
"dependencies": {
"@aws-cdk/aws-ec2": "0.0.0",
"@aws-cdk/aws-iam": "0.0.0",
"@aws-cdk/aws-logs": "0.0.0",
"@aws-cdk/core": "0.0.0",
"@aws-cdk/cloud-assembly-schema": "0.0.0",
Expand All @@ -91,6 +93,7 @@
"homepage": "https://github.com/aws/aws-cdk",
"peerDependencies": {
"@aws-cdk/aws-ec2": "0.0.0",
"@aws-cdk/aws-iam": "0.0.0",
"@aws-cdk/aws-logs": "0.0.0",
"@aws-cdk/core": "0.0.0",
"@aws-cdk/cloud-assembly-schema": "0.0.0",
Expand Down
Loading