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

fix(cognito-identitypool): providerUrl causes error when mappingKey is not provided and it is a token #21191

Merged
merged 8 commits into from
Jul 30, 2022
Merged
Show file tree
Hide file tree
Changes from 5 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
21 changes: 20 additions & 1 deletion packages/@aws-cdk/aws-cognito-identitypool/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ new IdentityPool(this, 'myidentitypool', {
});
```

Using a rule-based approach to role mapping allows roles to be assigned based on custom claims passed from the identity provider:
Using a rule-based approach to role mapping allows roles to be assigned based on custom claims passed from the identity provider:

```ts
import { IdentityPoolProviderUrl, RoleMappingMatchType } from '@aws-cdk/aws-cognito-identitypool';
Expand Down Expand Up @@ -349,6 +349,25 @@ new IdentityPool(this, 'myidentitypool', {
});
```

If a provider URL is a CDK Token, as it will be if you are trying to use a previously defined Cognito User Pool, you will need to also provide a mappingKey.
This is because by default, the key in the Cloudformation role mapping hash is the providerUrl, and Cloudformation map keys must be concrete strings, they
cannot be references. For example:

```ts
import { UserPool } from '@aws-cdk/aws-cognito';
import { IdentityPoolProviderUrl } from '@aws-cdk/aws-cognito-identitypool';

declare const userPool : UserPool;
new IdentityPool(this, 'myidentitypool', {
identityPoolName: 'myidentitypool',
roleMappings: [{
mappingKey: 'cognito',
providerUrl: IdentityPoolProviderUrl.userPool(userPool.userPoolProviderUrl),
useToken: true,
}],
});
```

See [here](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-identitypoolroleattachment-rolemapping.html#cfn-cognito-identitypoolroleattachment-rolemapping-identityprovider) for more information.

### Authentication Flow
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
import {
Resource,
IResource,
Token,
} from '@aws-cdk/core';
import {
Construct,
Expand Down Expand Up @@ -65,6 +66,12 @@ export interface IdentityPoolRoleMapping {
*/
readonly providerUrl: IdentityPoolProviderUrl;

/**
* The key used for the role mapping in the role mapping hash. Required if the providerUrl is a token.
* @default - the provided providerUrl
*/
readonly mappingKey?: string;

/**
* If true then mapped roles must be passed through the cognito:roles or cognito:preferred_role claims from identity provider.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/role-based-access-control.html#using-tokens-to-assign-roles-to-users
Expand Down Expand Up @@ -176,6 +183,17 @@ export class IdentityPoolRoleAttachment extends Resource implements IIdentityPoo
): { [name:string]: CfnIdentityPoolRoleAttachment.RoleMappingProperty } | undefined {
if (!props || !props.length) return undefined;
return props.reduce((acc, prop) => {
let mappingKey;
if (prop.mappingKey) {
mappingKey = prop.mappingKey;
} else {
const providerUrl = prop.providerUrl.value;
if (Token.isUnresolved(providerUrl)) {
throw new Error('mappingKey must be provided when providerUrl.value is an unresolved token');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
throw new Error('mappingKey must be provided when providerUrl.value is an unresolved token');
throw new Error('mappingKey must be provided when providerUrl.value is a token');

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm happy to make this change; that was wording I've copied from other parts of the CDK such as

throw new Error('Unable to determine ARN separator for SSM parameter since the parameter name is an unresolved token. Use "fromAttributes" and specify "simpleName" explicitly');
and
throw new Error(`multiple "${operator}" conditions cannot be merged if one of them contains an unresolved token`);
.

I couldn't decide if this was a fix or a feature; I fell on the side of this being a feature as it does actually provide new functionality, rather than altering existing functionality; it's just that the new feature addresses a gap that was previously present in the CDK's capabilities. Once again, I'm happy to defer to your judgment here.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, I've made the change manually, rather than applying your commit suggestion; that's Github functionality I hadn't seen before.

}
mappingKey = providerUrl;
}

let roleMapping: any = {
ambiguousRoleResolution: prop.resolveAmbiguousRoles ? 'AuthenticatedRole' : 'Deny',
type: prop.useToken ? 'Token' : 'Rules',
Expand All @@ -196,7 +214,7 @@ export class IdentityPoolRoleAttachment extends Resource implements IIdentityPoo
}),
};
};
acc[prop.providerUrl.value] = roleMapping;
acc[mappingKey] = roleMapping;
return acc;
}, {} as { [name:string]: CfnIdentityPoolRoleAttachment.RoleMappingProperty });
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,20 @@
"Arn"
]
}
},
"RoleMappings": {
"www.amazon.com": {
"AmbiguousRoleResolution": "Deny",
"IdentityProvider": "www.amazon.com",
"Type":"Token"
},
"theKey":{
"AmbiguousRoleResolution": "Deny",
"IdentityProvider": {
"Fn::ImportValue": "ProviderUrl"
},
"Type":"Token"
}
}
},
"DependsOn": [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
PolicyDocument,
} from '@aws-cdk/aws-iam';
import {
Fn,
Stack,
} from '@aws-cdk/core';
import {
Expand Down Expand Up @@ -397,6 +398,93 @@ describe('identity pool', () => {
});

describe('role mappings', () => {
test('mappingKey respected when identity provider is not a token', () => {
const stack = new Stack();
new IdentityPool(stack, 'TestIdentityPoolRoleMappingToken', {
roleMappings: [{
mappingKey: 'amazon',
providerUrl: IdentityPoolProviderUrl.AMAZON,
useToken: true,
}],
});
Template.fromStack(stack).hasResourceProperties('AWS::Cognito::IdentityPoolRoleAttachment', {
IdentityPoolId: {
Ref: 'TestIdentityPoolRoleMappingToken0B11D690',
},
RoleMappings: {
amazon: {
AmbiguousRoleResolution: 'Deny',
IdentityProvider: 'www.amazon.com',
Type: 'Token',
},
},
Roles: {
authenticated: {
'Fn::GetAtt': [
'TestIdentityPoolRoleMappingTokenAuthenticatedRoleD99CE043',
'Arn',
],
},
unauthenticated: {
'Fn::GetAtt': [
'TestIdentityPoolRoleMappingTokenUnauthenticatedRole1D86D800',
'Arn',
],
},
},
});
});

test('mappingKey required when identity provider is not a token', () => {
const stack = new Stack();
const providerUrl = Fn.importValue('ProviderUrl');
expect(() => new IdentityPool(stack, 'TestIdentityPoolRoleMappingErrors', {
roleMappings: [{
providerUrl: IdentityPoolProviderUrl.userPool(providerUrl),
useToken: true,
}],
})).toThrowError('mappingKey must be provided when providerUrl.value is an unresolved token');
});

test('mappingKey respected when identity provider is a token', () => {
const stack = new Stack();
const providerUrl = Fn.importValue('ProviderUrl');
new IdentityPool(stack, 'TestIdentityPoolRoleMappingToken', {
roleMappings: [{
mappingKey: 'theKey',
providerUrl: IdentityPoolProviderUrl.userPool(providerUrl),
useToken: true,
}],
});
Template.fromStack(stack).hasResourceProperties('AWS::Cognito::IdentityPoolRoleAttachment', {
IdentityPoolId: {
Ref: 'TestIdentityPoolRoleMappingToken0B11D690',
},
RoleMappings: {
theKey: {
AmbiguousRoleResolution: 'Deny',
IdentityProvider: {
'Fn::ImportValue': 'ProviderUrl',
},
Type: 'Token',
},
},
Roles: {
authenticated: {
'Fn::GetAtt': [
'TestIdentityPoolRoleMappingTokenAuthenticatedRoleD99CE043',
'Arn',
],
},
unauthenticated: {
'Fn::GetAtt': [
'TestIdentityPoolRoleMappingTokenUnauthenticatedRole1D86D800',
'Arn',
],
},
},
});
});
test('using token', () => {
const stack = new Stack();
new IdentityPool(stack, 'TestIdentityPoolRoleMappingToken', {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ import {
} from '@aws-cdk/aws-iam';
import {
App,
Fn,
Stack,
} from '@aws-cdk/core';
import {
IdentityPool,
IdentityPoolProviderUrl,
} from '../lib/identitypool';
import {
UserPoolAuthenticationProvider,
Expand Down Expand Up @@ -56,6 +58,17 @@ const idPool = new IdentityPool(stack, 'identitypool', {
amazon: { appId: 'amzn1.application.12312k3j234j13rjiwuenf' },
google: { clientId: '12345678012.apps.googleusercontent.com' },
},
roleMappings: [
{
providerUrl: IdentityPoolProviderUrl.AMAZON,
useToken: true,
},
{
mappingKey: 'theKey',
providerUrl: IdentityPoolProviderUrl.userPool(Fn.importValue('ProviderUrl')),
useToken: true,
},
],
allowClassicFlow: true,
identityPoolName: 'my-id-pool',
});
Expand Down