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(cli): credentials system uses AWS SDK v3 #31572

Closed
wants to merge 10 commits into from
Closed
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
"packages/cdk",
"packages/@aws-cdk/*",
"packages/awslint",
"packages/cdk-credential-provider",
"packages/@aws-cdk-testing/*",
"packages/@aws-cdk/*/lambda-packages/*",
"tools/@aws-cdk/cdk-build-tools",
Expand Down
2 changes: 1 addition & 1 deletion packages/aws-cdk-lib/cx-api/FEATURE_FLAGS.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ The following json shows the current recommended set of flags, as `cdk init` wou
"@aws-cdk/aws-s3:keepNotificationInImportedBucket": false,
"@aws-cdk/aws-ecs:reduceEc2FargateCloudWatchPermissions": true,
"@aws-cdk/aws-ec2:ec2SumTImeoutEnabled": true,
"@aws-cdk/aws-appsync:appSyncGraphQLAPIScopeLambdaPermission": true
"@aws-cdk/aws-appsync:appSyncGraphQLAPIScopeLambdaPermission": true,
"@aws-cdk/aws-rds:setCorrectValueForDatabaseInstanceReadReplicaInstanceResourceId": true
}
}
Expand Down
11,388 changes: 11,377 additions & 11 deletions packages/aws-cdk/THIRD_PARTY_LICENSES

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion packages/aws-cdk/lib/api/aws-auth/_env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
* break dependencies and replace these functions.
*/

export { debug, warning, trace } from '../../logging';
export { debug, warning, trace, error, print } from '../../logging';

import { cdkCacheDir } from '../../util/directories';

Expand Down
175 changes: 0 additions & 175 deletions packages/aws-cdk/lib/api/aws-auth/aws-sdk-inifile.ts

This file was deleted.

72 changes: 44 additions & 28 deletions packages/aws-cdk/lib/api/aws-auth/awscli-compatible.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,21 @@ import * as child_process from 'child_process';
import * as os from 'os';
import * as path from 'path';
import * as util from 'util';
import {
createCredentialChain,
fromContainerMetadata,
fromIni,
fromInstanceMetadata,
fromProcess,
fromSSO,
fromTokenFile,
} from '@aws-sdk/credential-providers';
import * as AWS from 'aws-sdk';
import * as fs from 'fs-extra';
import * as promptly from 'promptly';
import { debug } from './_env';
import { PatchedSharedIniFileCredentials } from './aws-sdk-inifile';
import { fromPrefixedEnv } from './from-prefixed-env';
import { SdkRequestHandler } from './sdk-provider';
import { SharedIniFile } from './sdk_ini_file';

/**
Expand Down Expand Up @@ -41,48 +51,52 @@ export class AwsCliCompatible {
// we use that to the exclusion of everything else (note: this does not apply
// to AWS_PROFILE, environment credentials still take precedence over AWS_PROFILE)
if (options.profile) {
return new AWS.CredentialProviderChain(iniFileCredentialFactories(options.profile, options.httpOptions));
return createCredentialChain(...iniFileCredentialFactories(options.profile, options.requestHandler));
}

const implicitProfile = process.env.AWS_PROFILE || process.env.AWS_DEFAULT_PROFILE || 'default';

const sources = [
() => new AWS.EnvironmentCredentials('AWS'),
() => new AWS.EnvironmentCredentials('AMAZON'),
...iniFileCredentialFactories(implicitProfile, options.httpOptions),
fromPrefixedEnv('AWS'),
fromPrefixedEnv('AMAZON'),
...iniFileCredentialFactories(implicitProfile, options.requestHandler),
];

if (options.containerCreds ?? hasEcsCredentials()) {
sources.push(() => new AWS.ECSCredentials());
sources.push(fromContainerMetadata());
} else if (hasWebIdentityCredentials()) {
// else if: we have found WebIdentityCredentials as provided by EKS ServiceAccounts
sources.push(() => new AWS.TokenFileWebIdentityCredentials());
sources.push(fromTokenFile());
} else if (options.ec2instance ?? await isEc2Instance()) {
// else if: don't get EC2 creds if we should have gotten ECS or EKS creds
// ECS and EKS instances also run on EC2 boxes but the creds represent something different.
// Same behavior as upstream code.
sources.push(() => new AWS.EC2MetadataCredentials());
sources.push(fromInstanceMetadata());
}

return new AWS.CredentialProviderChain(sources);
return createCredentialChain(...sources);

function profileCredentials(profileName: string) {
return new PatchedSharedIniFileCredentials({
profile: profileName,
filename: credentialsFileName(),
httpOptions: options.httpOptions,
tokenCodeFn,
});
}

function iniFileCredentialFactories(theProfile: string, theHttpOptions?: AWS.HTTPOptions) {
function iniFileCredentialFactories(theProfile: string, requestHandler?: SdkRequestHandler) {
return [
() => profileCredentials(theProfile),
() => new AWS.SsoCredentials({
fromIni({
profile: theProfile,
filepath: credentialsFileName(),
configFilepath: configFileName(),
mfaCodeProvider: mfaCodeFn,
clientConfig: {
requestHandler: requestHandler,
},
ignoreCache: true,
}),
fromSSO({
profile: theProfile,
clientConfig: {
requestHandler: requestHandler,
},
}),
fromProcess({
profile: theProfile,
httpOptions: theHttpOptions,
}),
() => new AWS.ProcessCredentials({ profile: theProfile }),
];
}
}
Expand Down Expand Up @@ -308,7 +322,9 @@ function matchesRegex(re: RegExp, s: string | undefined) {
*/
function readIfPossible(filename: string): string | undefined {
try {
if (!fs.pathExistsSync(filename)) { return undefined; }
if (!fs.pathExistsSync(filename)) {
return undefined;
}
return fs.readFileSync(filename, { encoding: 'utf-8' });
} catch (e: any) {
debug(e);
Expand All @@ -320,7 +336,7 @@ export interface CredentialChainOptions {
readonly profile?: string;
readonly ec2instance?: boolean;
readonly containerCreds?: boolean;
readonly httpOptions?: AWS.HTTPOptions;
readonly requestHandler?: SdkRequestHandler;
}

export interface RegionOptions {
Expand All @@ -333,17 +349,17 @@ export interface RegionOptions {
*
* Result is send to callback function for SDK to authorize the request
*/
async function tokenCodeFn(serialArn: string, cb: (err?: Error, token?: string) => void): Promise<void> {
async function mfaCodeFn(serialArn: string): Promise<string> {
debug('Require MFA token for serial ARN', serialArn);
try {
const token: string = await promptly.prompt(`MFA token for ${serialArn}: `, {
trim: true,
default: '',
});
debug('Successfully got MFA token from user');
cb(undefined, token);
return token;
} catch (err: any) {
debug('Failed to get MFA token', err);
cb(err);
throw err;
}
}
5 changes: 3 additions & 2 deletions packages/aws-cdk/lib/api/aws-auth/credential-plugins.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { CdkCredentials, CredentialProviderSource } from 'cdk-credential-provider';
import { debug } from './_env';
import { Mode } from './credentials';
import { warning } from '../../logging';
import { CredentialProviderSource, PluginHost } from '../plugin';
import { PluginHost } from '../plugin';

/**
* Cache for credential providers.
Expand Down Expand Up @@ -71,6 +72,6 @@ export class CredentialPlugins {
}

export interface PluginCredentials {
readonly credentials: AWS.Credentials;
readonly credentials: CdkCredentials;
readonly pluginName: string;
}
2 changes: 1 addition & 1 deletion packages/aws-cdk/lib/api/aws-auth/credentials.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
// Re-export this here because it used to be here and I don't want
// to change imports too much.
export { Mode } from '../plugin';
export { Mode } from 'cdk-credential-provider';
Loading
Loading