Skip to content

Commit

Permalink
Add integration tests for remaining resources
Browse files Browse the repository at this point in the history
This adds integration tests for the remaining construct libraries.

Also adds mapping for one missing CCAPI resource
(`AWS::Events::EventBusPolicy`)

re #183
  • Loading branch information
corymhall committed Nov 11, 2024
1 parent 0dfa36d commit 61cf3d5
Show file tree
Hide file tree
Showing 13 changed files with 404 additions and 58 deletions.
9 changes: 9 additions & 0 deletions integration/examples_nodejs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,15 @@ func TestLogs(t *testing.T) {
integration.ProgramTest(t, &test)
}

func TestMisc(t *testing.T) {
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "misc-services"),
})

integration.ProgramTest(t, &test)
}

func getJSBaseOptions(t *testing.T) integration.ProgramTestOptions {
base := getBaseOptions(t)
baseJS := base.With(integration.ProgramTestOptions{
Expand Down
3 changes: 3 additions & 0 deletions integration/misc-services/Pulumi.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
name: pulumi-aws-misc
runtime: nodejs
description: misc integration test
87 changes: 87 additions & 0 deletions integration/misc-services/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import * as events from 'aws-cdk-lib/aws-events';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as ssm from 'aws-cdk-lib/aws-ssm';
import * as ecr from 'aws-cdk-lib/aws-ecr';
import * as cloudwatch from 'aws-cdk-lib/aws-cloudwatch';
import * as pulumicdk from '@pulumi/cdk';
import { SecretValue } from 'aws-cdk-lib';
import { AwsCliLayer } from 'aws-cdk-lib/lambda-layer-awscli';

class MiscServicesStack extends pulumicdk.Stack {
constructor(app: pulumicdk.App, id: string, options?: pulumicdk.StackOptions) {
super(app, id, options);
const repo = new ecr.Repository(this, 'testrepo');
repo.grantPull(new iam.ServicePrincipal('lambda.amazonaws.com'));

new ssm.StringParameter(this, 'testparam', {
stringValue: 'testvalue',
});

const eventBus = new events.EventBus(this, 'testbus');
eventBus.addToResourcePolicy(
new iam.PolicyStatement({
sid: 'testsid',
actions: ['events:PutEvents'],
principals: [new iam.AccountRootPrincipal()],
resources: [eventBus.eventBusArn],
}),
);

// This type of event bus policy is created for cross account access
new events.CfnEventBusPolicy(this, 'bus-policy', {
action: 'events:PutEvents',
statementId: 'statement-id',
principal: new iam.AccountRootPrincipal().accountId,
});
const connection = new events.Connection(this, 'testconn', {
authorization: events.Authorization.basic('user', SecretValue.unsafePlainText('password')),
});
new events.ApiDestination(this, ' testdest', {
endpoint: 'https://example.com',
connection,
});

const fn = new lambda.Function(this, 'testfn', {
runtime: lambda.Runtime.PYTHON_3_12,
handler: 'index.handler',
code: lambda.Code.fromInline('def handler(event, context): return {}'),
});
fn.addLayers(new AwsCliLayer(this, 'testlayer'));

const errors = fn.metricErrors();
const throttles = fn.metricThrottles();
const throttleAlarm = throttles.createAlarm(this, 'alarm-throttles', { threshold: 1, evaluationPeriods: 1 });
const errorsAlarm = errors.createAlarm(this, 'alarm-errors', { threshold: 1, evaluationPeriods: 1 });
const alarmRule = cloudwatch.AlarmRule.anyOf(throttleAlarm, errorsAlarm);
new cloudwatch.CompositeAlarm(this, 'compositealarm', {
alarmRule,
});

const dashboard = new cloudwatch.Dashboard(this, 'testdash');
dashboard.addWidgets(
new cloudwatch.GraphWidget({
left: [errors],
}),
);

new iam.User(this, 'User', {
groups: [new iam.Group(this, 'Group')],
managedPolicies: [
new iam.ManagedPolicy(this, 'ManagedPolicy', {
statements: [
new iam.PolicyStatement({
actions: ['s3:*'],
resources: ['*'],
effect: iam.Effect.DENY,
}),
],
}),
],
});
}
}

new pulumicdk.App('app', (scope: pulumicdk.App) => {
new MiscServicesStack(scope, 'teststack');
});
15 changes: 15 additions & 0 deletions integration/misc-services/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "pulumi-aws-cdk",
"devDependencies": {
"@types/node": "^10.0.0"
},
"dependencies": {
"@pulumi/aws": "^6.0.0",
"@pulumi/aws-native": "^1.5.0",
"@pulumi/cdk": "^0.5.0",
"@pulumi/pulumi": "^3.0.0",
"aws-cdk-lib": "2.149.0",
"constructs": "10.3.0",
"esbuild": "^0.24.0"
}
}
18 changes: 18 additions & 0 deletions integration/misc-services/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"strict": true,
"outDir": "bin",
"target": "es2019",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"experimentalDecorators": true,
"pretty": true,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"forceConsistentCasingInFileNames": true
},
"include": [
"./*.ts"
]
}
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
}
},
"resolutions": {
"@pulumi/pulumi": "3.121.0",
"@pulumi/pulumi": "3.136.0",
"wrap-ansi": "7.0.0",
"string-width": "4.1.0"
},
Expand All @@ -30,7 +30,7 @@
"@pulumi/aws": "^6.32.0",
"@pulumi/aws-native": "^1.6.0",
"@pulumi/docker": "^4.5.0",
"@pulumi/pulumi": "3.121.0",
"@pulumi/pulumi": "3.136.0",
"@types/archiver": "^6.0.2",
"@types/fs-extra": "^11.0.4",
"@types/jest": "^29.5.2",
Expand Down
40 changes: 40 additions & 0 deletions src/aws-resource-mappings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,46 @@ export function mapToAwsResource(
);
}

case 'AWS::Events::EventBusPolicy': {
let props: aws.cloudwatch.EventBusPolicyArgs;
if (rawProps.Statement && (rawProps.Principal || rawProps.Action || rawProps.Condition)) {
throw new Error(
'EventBusPolicy args invalid. Only Statement or StatementId, Principal, Action, and Condition are allowed',
);
} else if (rawProps.Statement) {
props = {
policy: pulumi.jsonStringify({
Statement: [rawProps.Statement],
Version: '2012-10-17',
}),
eventBusName: rawProps.EventBusName,
};
} else {
const region = aws.getRegionOutput({}, options).name;
const partition = aws.getPartitionOutput({}, options).partition;
const busName = rawProps.EventBusName ?? 'default';
const arn = pulumi.interpolate`arn:${partition}:events:${region}:${rawProps.Principal}:event-bus/${busName}`;
props = {
policy: pulumi.jsonStringify({
Statement: [
{
Sid: rawProps.StatementId,
Principal: {
AWS: rawProps.Principal,
},
Action: rawProps.Action,
Effect: 'Allow',
Resource: arn,
Condition: rawProps.Condition,
},
],
Version: '2012-10-17',
}),
eventBusName: rawProps.EventBusName,
};
}
return new aws.cloudwatch.EventBusPolicy(logicalId, props, options);
}
default:
return undefined;
}
Expand Down
5 changes: 5 additions & 0 deletions src/cfn-resource-mappings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ export function mapToCfnResource(
// lowercase letters.
return new aws.s3.Bucket(logicalId.toLowerCase(), props, options);

case 'AWS::ECR::Repository':
// Lowercase the repository name to comply with the Repository resource's naming constraints, which only allow
// lowercase letters.
return new aws.ecr.Repository(logicalId.toLowerCase(), props, options);

// A couple of ApiGateway resources suffer from https://github.com/pulumi/pulumi-cdk/issues/173
// These are very popular resources so handling the workaround here since we can remove these
// manual mappings once the issue has been fixed without breaking users
Expand Down
70 changes: 67 additions & 3 deletions tests/aws-resource-mappings.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
import { mapToAwsResource } from '../src/aws-resource-mappings';
import * as route53 from 'aws-cdk-lib/aws-route53';
import * as aws from '@pulumi/aws';

jest.mock('@pulumi/aws', () => {
return {
getRegionOutput: jest.fn().mockImplementation(() => {
return {
name: 'us-east-1',
};
}),
getPartitionOutput: jest.fn().mockImplementation(() => {
return {
partition: 'aws',
};
}),
apigatewayv2: {
Integration: jest.fn().mockImplementation(() => {
return {};
Expand All @@ -19,6 +28,11 @@ jest.mock('@pulumi/aws', () => {
return {};
}),
},
cloudwatch: {
EventBusPolicy: jest.fn().mockImplementation(() => {
return {};
}),
},
iam: {
Policy: jest.fn().mockImplementation(() => {
return {};
Expand All @@ -41,11 +55,13 @@ jest.mock('@pulumi/aws', () => {
};
});

afterEach(() => {
afterAll(() => {
jest.resetAllMocks();
});

beforeAll(() => {});
beforeEach(() => {
jest.clearAllMocks();
});

describe('AWS Resource Mappings', () => {
test('maps iam.Policy', () => {
Expand Down Expand Up @@ -370,4 +386,52 @@ describe('AWS Resource Mappings', () => {
{},
);
});

test('successfully maps EventBusPolicy resource', () => {
// GIVEN
const cfnType = 'AWS::Events::EventBusPolicy';
const logicalId = 'my-resource';
const cfnProps = {
EventBusName: 'eventBus',
Action: 'events:PutEvents',
Principal: '123456789012',
StatementId: 'MyStatement',
};
// WHEN
mapToAwsResource(logicalId, cfnType, cfnProps, {});
// THEN
expect(aws.cloudwatch.EventBusPolicy).toHaveBeenCalledWith(
logicalId,
{
eventBusName: 'eventBus',
policy: expect.anything(),
},
{},
);
});

test('successfully maps EventBusPolicy resource when statement provided', () => {
// GIVEN
const cfnType = 'AWS::Events::EventBusPolicy';
const logicalId = 'my-resource';
const cfnProps = {
EventBusName: 'eventBus',
Statement: {
Effect: 'Allow',
Principal: '123456789012',
Action: 'events:PutEvents',
},
};
// WHEN
mapToAwsResource(logicalId, cfnType, cfnProps, {});
// THEN
expect(aws.cloudwatch.EventBusPolicy).toHaveBeenCalledWith(
logicalId,
{
eventBusName: 'eventBus',
policy: expect.anything(),
},
{},
);
});
});
61 changes: 61 additions & 0 deletions tests/cdk-resource.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import * as route53 from 'aws-cdk-lib/aws-route53';
import * as events from 'aws-cdk-lib/aws-events';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
import { TableArgs } from '@pulumi/aws-native/dynamodb';
import { Key } from 'aws-cdk-lib/aws-kms';
Expand Down Expand Up @@ -109,4 +111,63 @@ describe('CDK Construct tests', () => {
expect(txt).toBeDefined();
expect(txt?.inputs.records).toEqual(['hello'.repeat(51), 'hello']);
});

test('EventBusPolicy correctly maps statement', async () => {
await testApp((scope: Construct) => {
const eventBus = new events.EventBus(scope, 'testbus');
eventBus.addToResourcePolicy(
new iam.PolicyStatement({
sid: 'testsid',
actions: ['events:PutEvents'],
principals: [new iam.AccountRootPrincipal()],
resources: [eventBus.eventBusArn],
}),
);
});
const policy = resources.find((res) => res.type === 'aws:cloudwatch/eventBusPolicy:EventBusPolicy');
expect(policy).toBeDefined();
expect(policy?.inputs.policy).toEqual(
JSON.stringify({
Statement: [
{
Action: 'events:PutEvents',
Effect: 'Allow',
Principal: { AWS: 'arn:aws:iam::12345678912:root' },
Resource: 'testbus9BA9ECFC_arn',
Sid: 'cdk-testsid',
},
],
Version: '2012-10-17',
}),
);
});

test('EventBusPolicy correctly maps props', async () => {
await testApp((scope: Construct) => {
// This type of event bus policy is created for cross account access
new events.CfnEventBusPolicy(scope, 'buspolicy', {
action: 'events:PutEvents',
statementId: 'statement-id',
principal: '123456789012',
});
});
const policy = resources.find(
(res) => res.type === 'aws:cloudwatch/eventBusPolicy:EventBusPolicy' && res.name === 'buspolicy',
);
expect(policy).toBeDefined();
expect(policy?.inputs.policy).toEqual(
JSON.stringify({
Statement: [
{
Sid: 'statement-id',
Principal: { AWS: '123456789012' },
Action: 'events:PutEvents',
Effect: 'Allow',
Resource: 'arn:aws:events:us-east-2:123456789012:event-bus/default',
},
],
Version: '2012-10-17',
}),
);
});
});
Loading

0 comments on commit 61cf3d5

Please sign in to comment.