Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
8 changes: 8 additions & 0 deletions src/credentials_rotators/aws-token-rotation/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
*.js
!jest.config.js
*.d.ts
node_modules

# CDK asset staging directory
.cdk.staging
cdk.out
6 changes: 6 additions & 0 deletions src/credentials_rotators/aws-token-rotation/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
*.ts
!*.d.ts

# CDK asset staging directory
.cdk.staging
cdk.out
14 changes: 14 additions & 0 deletions src/credentials_rotators/aws-token-rotation/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Welcome to your CDK TypeScript project!

This is a blank project for TypeScript development with CDK.

The `cdk.json` file tells the CDK Toolkit how to execute your app.

## Useful commands

* `npm run build` compile typescript to js
* `npm run watch` watch for changes and compile
* `npm run test` perform the jest unit tests
* `cdk deploy` deploy this stack to your default AWS account/region
* `cdk diff` compare deployed stack with current state
* `cdk synth` emits the synthesized CloudFormation template
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#!/usr/bin/env node
import 'source-map-support/register';
import * as cdk from '@aws-cdk/core';
import { AwsTokenRotationStack } from '../lib/aws-token-rotation-stack';

const app = new cdk.App();
new AwsTokenRotationStack(app, 'AwsTokenRotationStack', {
/* If you don't specify 'env', this stack will be environment-agnostic.
* Account/Region-dependent features and context lookups will not work,
* but a single synthesized template can be deployed anywhere. */

/* Uncomment the next line to specialize this stack for the AWS Account
* and Region that are implied by the current CLI configuration. */
// env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION },

/* Uncomment the next line if you know exactly what Account and Region you
* want to deploy the stack to. */
// env: { account: '123456789012', region: 'us-east-1' },

/* For more information, see https://docs.aws.amazon.com/cdk/latest/guide/environments.html */
});
18 changes: 18 additions & 0 deletions src/credentials_rotators/aws-token-rotation/cdk.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"app": "npx ts-node --prefer-ts-exts bin/aws-token-rotation.ts",
"context": {
"@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId": true,
"@aws-cdk/core:enableStackNameDuplicates": "true",
"aws-cdk:enableDiffNoFail": "true",
"@aws-cdk/core:stackRelativeExports": "true",
"@aws-cdk/aws-ecr-assets:dockerIgnoreSupport": true,
"@aws-cdk/aws-secretsmanager:parseOwnedSecretName": true,
"@aws-cdk/aws-kms:defaultKeyPolicies": true,
"@aws-cdk/aws-s3:grantWriteWithoutAcl": true,
"@aws-cdk/aws-ecs-patterns:removeDefaultDesiredCount": true,
"@aws-cdk/aws-rds:lowercaseDbIdentifier": true,
"@aws-cdk/aws-efs:defaultEncryptionAtRest": true,
"@aws-cdk/aws-lambda:recognizeVersionProps": true,
"@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021": true
}
}
8 changes: 8 additions & 0 deletions src/credentials_rotators/aws-token-rotation/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = {
testEnvironment: 'node',
roots: ['<rootDir>/test'],
testMatch: ['**/*.test.ts'],
transform: {
'^.+\\.tsx?$': 'ts-jest'
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import * as cdk from '@aws-cdk/core';
import * as path from 'path';
import * as nodejsLambda from '@aws-cdk/aws-lambda-nodejs';
import * as secretmanager from '@aws-cdk/aws-secretsmanager';
import * as iam from '@aws-cdk/aws-iam';
import * as events from '@aws-cdk/aws-events';
import * as target from '@aws-cdk/aws-events-targets';

export class AwsTokenRotationStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const role = new iam.Role(this, 'rotatorLambdaRole', {
assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
});
const githubSecretArnParam = new cdk.CfnParameter(this, "githubSecretArn", {
noEcho: true,
type: 'String',
});

const crossAccountRole = new cdk.CfnParameter(this, "crossAccountRoleArn", {
noEcho: true,
type: 'String',
})
const e2eTestRoleArn = new cdk.CfnParameter(this, "e2eTestRoleArn", {
noEcho: true,
type: 'String',
})

const secret = secretmanager.Secret.fromSecretCompleteArn(this, 'githubSecret', githubSecretArnParam.valueAsString);
secret.grantRead(role);

role.addToPolicy(new iam.PolicyStatement({
actions: ['sts:assumerole'],
resources: [crossAccountRole.valueAsString]
}));

role.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AWSLambdaBasicExecutionRole'))



const rotatorFunction = new nodejsLambda.NodejsFunction(this, 'RotatorLambda', {
entry: path.normalize(path.join(__dirname, 'lambda-handler', 'index.ts')),
environment: {
CROSS_ACCOUNT_ROLE_ARN: crossAccountRole.valueAsString,
GITHUB_TOKEN_ARN: secret.secretArn,
ROLE_ARN: e2eTestRoleArn.valueAsString,
},
role,
timeout: cdk.Duration.minutes(5)

})



const eventRule = new events.Rule(this, "FiveHourlySchedule", {
schedule: events.Schedule.expression("rate(5 hours)")
});

eventRule.addTarget(new target.LambdaFunction(rotatorFunction));

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import * as aws from "aws-sdk";
import { updateGithubEnvironmentSecret } from "../../../common-utils/github-helper";
export async function handler(_: any, context: any) {
const { CROSS_ACCOUNT_ROLE_ARN, ROLE_ARN, GITHUB_TOKEN_ARN } = process.env;
const sts = new aws.STS();
console.assert(CROSS_ACCOUNT_ROLE_ARN, "ROLE_ARN should have value");
// assuming role of the other account
const assumeRoleResult = await sts
.assumeRole({
RoleArn: CROSS_ACCOUNT_ROLE_ARN || "",
RoleSessionName: "export-test-role",
})
.promise();
const creds = assumeRoleResult.Credentials;


const iam = new aws.IAM({
credentials: {
accessKeyId: creds?.AccessKeyId || "",
secretAccessKey: creds?.SecretAccessKey || "",
sessionToken: creds?.SessionToken || "",
},
});

// getting the keys of the user
const accessKeys = await iam
.createAccessKey({
UserName: "amplify-cli-export-user",
})
.promise();

if (!assumeRoleResult.Credentials) {
throw new Error("Unable to get keys");
}
const { AccessKeyId, SecretAccessKey } = accessKeys.AccessKey;

await sleep(10000);

const crossSts = new aws.STS({
accessKeyId: AccessKeyId,
secretAccessKey: SecretAccessKey,
});

// using the keys of the other role
console.assert(ROLE_ARN, "ROLE_ARN should have value");
const crossAccountAssumeRoleResult = await crossSts
.assumeRole({
RoleArn: ROLE_ARN || "",
RoleSessionName: "export-test-role",
DurationSeconds: 6 * 60 * 60,
})
.promise();

// writing github keys
console.assert(GITHUB_TOKEN_ARN, "GITHUB_TOKEN_ARN should have value");

const sm = new aws.SecretsManager();

const val = await sm
.getSecretValue({ SecretId: GITHUB_TOKEN_ARN || "" })
.promise();

const githubConfig = {
owner: "aws-amplify",
repo: "amplify-cli-export-construct",
token: val.SecretString || "",
};

await updateGithubEnvironmentSecret(
githubConfig,
crossAccountAssumeRoleResult.Credentials?.AccessKeyId || "",
"AWS_ACCESS_KEY_ID"
);
await updateGithubEnvironmentSecret(
githubConfig,
crossAccountAssumeRoleResult.Credentials?.SecretAccessKey || "",
"AWS_SECRET_ACCESS_KEY"
);
await updateGithubEnvironmentSecret(
githubConfig,
crossAccountAssumeRoleResult.Credentials?.SessionToken || "",
"AWS_SESSION_TOKEN"
);

//delete keys

await iam
.deleteAccessKey({
AccessKeyId,
UserName: 'amplify-cli-export-user',
})
.promise();

return context;
}

function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
Loading