Skip to content

Instantly share code, notes, and snippets.

@revmischa
Created October 7, 2022 02:52
Show Gist options
  • Save revmischa/9a27af84b3c18e6f6084f55c48546fce to your computer and use it in GitHub Desktop.
Save revmischa/9a27af84b3c18e6f6084f55c48546fce to your computer and use it in GitHub Desktop.
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import * as sst from '@serverless-stack/resources';
import { Function, getStack } from '@serverless-stack/resources';
import { Match, Template } from 'aws-cdk-lib/assertions';
import { useBaseInfra } from 'stacks';
import { test } from 'vitest';
import { Functions } from './functions';
function TestStack({ stack }: sst.StackContext) {
const placeholderFn = new Function(stack, 'Default', {
handler: 'api/internalFunctions/empty.handler',
});
return { placeholderFn, role: placeholderFn.role };
}
test('Default lambda role created with permissions', () => {
const app = new sst.App();
// build the base stack
const baseApp = useBaseInfra(app);
// add some more default permissions
app.addDefaultFunctionPermissions(['snowball']); // should exist in policy
// build the rest of the stack
baseApp.stack(TestStack).stack(Functions);
// get synthesized template
const testTemplate = Template.fromStack(getStack(TestStack));
const funcTemplate = Template.fromStack(getStack(Functions));
// find role our test stack generated
// it should contain all default permissions
const testTemplateRoles = testTemplate.findResources('AWS::IAM::Policy');
const testTemplateRole = getServiceRole(testTemplateRoles)!;
expect(testTemplateRole).toBeDefined();
// funcStack default lambda role's policy should have the same permissions
// as the testStack placeholder lambda role
funcTemplate.hasResourceProperties('AWS::IAM::Policy', {
// same policy
PolicyDocument: testTemplateRole.Properties.PolicyDocument,
});
funcTemplate.hasResourceProperties('AWS::IAM::Policy', {
// has policy statement for snowball:*
PolicyDocument: {
Statement: Match.arrayWith([
{
Action: 'snowball:*',
Effect: 'Allow',
Resource: '*',
},
]),
},
});
});
function getServiceRole(roles: { [key: string]: any }): any | undefined {
const entry = Object.entries(roles).find(([k]) => {
return k.startsWith('ServiceRole');
});
return entry ? entry[1] : undefined;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment