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(iam): validate roleName #28509

Merged
merged 10 commits into from
Jan 2, 2024
4 changes: 4 additions & 0 deletions packages/aws-cdk-lib/aws-iam/lib/role.ts
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,10 @@ export class Role extends Resource implements IRole {
physicalName: props.roleName,
});

if (props.roleName && !/^[\w+=,.@-]{1,64}$/.test(props.roleName)) {
throw new Error('Invalid roleName. The name must be a string of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of the following characters: _+=,.@-. The role name must be unique within the account. Role names are not distinguished by case. For example, you cannot create roles named both "Role1" and "role1". Length must be between 1 and 64 characters.');
}

const externalIds = props.externalIds || [];
if (props.externalId) {
externalIds.push(props.externalId);
Expand Down
35 changes: 35 additions & 0 deletions packages/aws-cdk-lib/aws-iam/test/role.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1325,3 +1325,38 @@ test('cross-env role ARNs include path', () => {
},
});
});

test('throws with empty role name', () => {
const app = new App();
const stack = new Stack(app, 'MyStack');
expect(() => {
new Role(stack, 'Test', {
assumedBy: new ServicePrincipal('sns.amazonaws.com'),
roleName: '',
});
}).toThrow('/Invalid roleName/');
});

test('throws with name over 64 chars', () => {
const app = new App();
const stack = new Stack(app, 'MyStack');
const longName = 'a'.repeat(65);

expect(() => {
new Role(stack, 'Test', {
assumedBy: new ServicePrincipal('sns.amazonaws.com'),
roleName: longName,
});
}).toThrow('Invalid roleName');
});

test('throws with invalid chars', () => {
const app = new App();
const stack = new Stack(app, 'MyStack');
expect(() => {
new Role(stack, 'Test', {
assumedBy: new ServicePrincipal('sns.amazonaws.com'),
roleName: 'invalid!name',
});
}).toThrow('Invalid roleName');
});