diff --git a/packages/aws-cdk/lib/api/aws-auth/sdk-provider.ts b/packages/aws-cdk/lib/api/aws-auth/sdk-provider.ts index 39f7cd2f2a1b1..200f6548c6554 100644 --- a/packages/aws-cdk/lib/api/aws-auth/sdk-provider.ts +++ b/packages/aws-cdk/lib/api/aws-auth/sdk-provider.ts @@ -459,7 +459,11 @@ function readIfPossible(filename: string): string | undefined { * @see https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html#API_AssumeRole_RequestParameters */ function safeUsername() { - return os.userInfo().username.replace(/[^\w+=,.@-]/g, '@'); + try { + return os.userInfo().username.replace(/[^\w+=,.@-]/g, '@'); + } catch (e) { + return 'noname'; + } } /** diff --git a/packages/aws-cdk/test/api/sdk-provider.test.ts b/packages/aws-cdk/test/api/sdk-provider.test.ts index c2e3d311af647..9c03a7be0beed 100644 --- a/packages/aws-cdk/test/api/sdk-provider.test.ts +++ b/packages/aws-cdk/test/api/sdk-provider.test.ts @@ -341,6 +341,34 @@ describe('with intercepted network calls', () => { }); }); + test('assuming a role does not fail when OS username cannot be read', async () => { + // GIVEN + prepareCreds({ + fakeSts, + config: { + default: { aws_access_key_id: 'foo', $account: '11111' }, + }, + }); + + await withMocked(os, 'userInfo', async (userInfo) => { + userInfo.mockImplementation(() => { + // SystemError thrown as documented: https://nodejs.org/docs/latest-v16.x/api/os.html#osuserinfooptions + throw new Error('SystemError on Linux: uv_os_get_passwd returned ENOENT. See #19401 issue.'); + }); + + // WHEN + const provider = await providerFromProfile(undefined); + + const sdk = (await provider.forEnvironment(env(uniq('88888')), Mode.ForReading, { assumeRoleArn: 'arn:aws:role' })).sdk as SDK; + await sdk.currentAccount(); + + // THEN + expect(fakeSts.assumedRoles[0]).toEqual(expect.objectContaining({ + roleSessionName: 'aws-cdk-noname', + })); + }); + }); + test('even if current credentials are for the wrong account, we will still use them to AssumeRole', async () => { // GIVEN prepareCreds({ diff --git a/packages/cdk-assets/lib/aws.ts b/packages/cdk-assets/lib/aws.ts index c35dedb38bbe2..4f79ead780227 100644 --- a/packages/cdk-assets/lib/aws.ts +++ b/packages/cdk-assets/lib/aws.ts @@ -150,6 +150,10 @@ export class DefaultAwsClient implements IAws { * @see https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html#API_AssumeRole_RequestParameters */ function safeUsername() { - return os.userInfo().username.replace(/[^\w+=,.@-]/g, '@'); + try { + return os.userInfo().username.replace(/[^\w+=,.@-]/g, '@'); + } catch (e) { + return 'noname'; + } }