Skip to content

Commit

Permalink
feat(events): add static grantPutEvents() to EventBus (#5133)
Browse files Browse the repository at this point in the history
* feat(events): add static grantPutEvents() to EventBus

It's currently not possible to restrict `PutEvents` to specific resources.

See https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/permissions-reference-cwe.html

* Update event-bus.ts
  • Loading branch information
jogold authored and mergify[bot] committed Nov 25, 2019
1 parent 534ef00 commit 0823396
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
17 changes: 17 additions & 0 deletions packages/@aws-cdk/aws-events/lib/event-bus.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import iam = require('@aws-cdk/aws-iam');
import { Construct, IResource, Lazy, Resource, Stack } from '@aws-cdk/core';
import { CfnEventBus } from './events.generated';

Expand Down Expand Up @@ -136,6 +137,22 @@ export class EventBus extends Resource implements IEventBus {
return new Import(scope, id);
}

/**
* Permits an IAM Principal to send custom events to EventBridge
* so that they can be matched to rules.
*
* @param grantee The principal (no-op if undefined)
*/
public static grantPutEvents(grantee: iam.IGrantable): iam.Grant {
// It's currently not possible to restrict PutEvents to specific resources.
// See https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/permissions-reference-cwe.html
return iam.Grant.addToPrincipal({
grantee,
actions: ['events:PutEvents'],
resourceArns: ['*'],
});
}

private static eventBusProps(defaultEventBusName: string, props?: EventBusProps) {
if (props) {
const { eventBusName, eventSourceName } = props;
Expand Down
33 changes: 33 additions & 0 deletions packages/@aws-cdk/aws-events/test/test.event-bus.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { expect, haveResource } from '@aws-cdk/assert';
import iam = require('@aws-cdk/aws-iam');
import { CfnResource, Stack } from '@aws-cdk/core';
import { Test } from 'nodeunit';
import { EventBus } from '../lib';
Expand Down Expand Up @@ -200,6 +201,38 @@ export = {
createInvalidBus();
}, /'eventSourceName' must satisfy: /);

test.done();
},

'can grant PutEvents'(test: Test) {
// GIVEN
const stack = new Stack();
const role = new iam.Role(stack, 'Role', {
assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com')
});

// WHEN
EventBus.grantPutEvents(role);

// THEN
expect(stack).to(haveResource('AWS::IAM::Policy', {
PolicyDocument: {
Statement: [
{
Action: 'events:PutEvents',
Effect: 'Allow',
Resource: '*'
}
],
Version: '2012-10-17'
},
Roles: [
{
Ref: 'Role1ABCC5F0'
}
]
}));

test.done();
}
};

0 comments on commit 0823396

Please sign in to comment.