Skip to content

Commit

Permalink
feat: change default template of custom policies
Browse files Browse the repository at this point in the history
  • Loading branch information
luhanamz committed Sep 8, 2021
1 parent 8a8268c commit 453b8b2
Show file tree
Hide file tree
Showing 7 changed files with 40 additions and 42 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,12 @@ describe('Custom policies util test', () => {

const data = JSONUtilities.readJson(expectedFilePath);

expect(data).toMatchObject({
policies: [
expect(data).toMatchObject([
{
Action: [],
Resource: []
}
]
});
]);

})
})
37 changes: 21 additions & 16 deletions packages/amplify-cli-core/src/customPoliciesUtils.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { Fn, IAM } from "cloudform-types";
import * as iam from '@aws-cdk/aws-iam';
import { JSONUtilities, pathManager } from ".";
import * as fs from 'fs-extra';

export type CustomIAMPolicies = {
policies: CustomIAMPolicy[];
}
export type CustomIAMPolicies = CustomIAMPolicy[];

export type CustomIAMPolicy = {
Action: string[];
Expand All @@ -14,11 +13,9 @@ export type CustomIAMPolicy = {


export const CustomIAMPoliciesSchema = {
type : "object",
properties: {
policies: {type: "array", minItems: 1, items: {type: "object"}}
},
required: ["policies"],
type : "array",
minItems: 1,
items: {type: "object"},
additionalProperties: false
}

Expand Down Expand Up @@ -57,16 +54,24 @@ export const customExecutionPolicyForContainer = new IAM.Policy({

export function addCustomPoliciesFile(categoryName: string, resourceName: string) {
const customPoliciesPath = pathManager.getCustomPoliciesPath(categoryName, resourceName);
const defaultCustomPolicies = {
policies: [
{
Action: [],
Resource: []
}
]
}
const defaultCustomPolicies = [
{
Action: [],
Resource: []
}
]
JSONUtilities.writeJson(customPoliciesPath, defaultCustomPolicies);
}

export function isCustomPoliciesFile(filePath: string) {
try{
const fileString = fs.readFileSync(filePath, 'utf-8');
JSON.parse(fileString);
return true;
} catch(err) {
return false;
}
}



5 changes: 2 additions & 3 deletions packages/amplify-cli-core/src/state-manager/stateManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ import { $TSMeta, $TSTeamProviderInfo, $TSAny, DeploymentSecrets, HooksConfig }
import { JSONUtilities } from '../jsonUtilities';
import { SecretFileMode } from '../cliConstants';
import { HydrateTags, ReadTags, Tag } from '../tags';
import { CustomIAMPolicies } from '../customPoliciesUtils';
import { isJsonFileContent} from '../cfnUtilities'
import { CustomIAMPolicies, isCustomPoliciesFile } from '../customPoliciesUtils';
import path from 'path';

export type GetOptions<T> = {
Expand Down Expand Up @@ -80,7 +79,7 @@ export class StateManager {

getCustomPolicies = (categoryName: string, resourceName: string): CustomIAMPolicies | undefined => {
const filePath = pathManager.getCustomPoliciesPath(categoryName, resourceName);
if (!(fs.existsSync(filePath)) || !isJsonFileContent(fs.readFileSync(filePath, 'utf8'))) {
if (!(fs.existsSync(filePath)) || !isCustomPoliciesFile(filePath)) {
return undefined;
}
return JSONUtilities.readJson<CustomIAMPolicies>(filePath);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,7 @@ const customIAMPolicy: CustomIAMPolicy = {
],
Resource: []
};
const customIAMPolicies = {
policies: []
}
const customIAMPolicies: CustomIAMPolicy[] = [];

async function setupAmplifyProject(cwd: string) {
await amplifyConfigureProject({
Expand Down Expand Up @@ -71,7 +69,7 @@ it(`should init and deploy a api container, attach custom policies to the Fargat

customIAMPolicy.Resource.push(ssmParameterArn);
const customPoliciesPath = getCustomPoliciesPath(projRoot, 'api', name);
customIAMPolicies.policies.push(customIAMPolicy);
customIAMPolicies.push(customIAMPolicy);
JSONUtilities.writeJson(customPoliciesPath, customIAMPolicies);

await amplifyPushWithoutCodegen(projRoot);
Expand All @@ -80,7 +78,7 @@ it(`should init and deploy a api container, attach custom policies to the Fargat
);

expect(containerCFN.Resources.CustomExecutionPolicyForContainer.Properties.PolicyDocument.Statement[0])
.toEqual(customIAMPolicies.policies[0]);
.toEqual(customIAMPolicies[0]);
});

type CustomIAMPolicy = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@ const customIAMPolicy: CustomIAMPolicy = {
],
Resource: []
};
const customIAMPolicies = {
policies: []
}
const customIAMPolicies: CustomIAMPolicy[] = [];

let projRoot: string;

Expand Down Expand Up @@ -75,7 +73,7 @@ it(`should init and deploy storage DynamoDB + Lambda trigger, attach custom poli

customIAMPolicy.Resource.push(ssmParameterArn);
const customPoliciesPath = getCustomPoliciesPath(projRoot, 'function', funcName);
customIAMPolicies.policies.push(customIAMPolicy);
customIAMPolicies.push(customIAMPolicy);
JSONUtilities.writeJson(customPoliciesPath, customIAMPolicies);

overrideFunctionCodeNode(projRoot, funcName, 'get-ssm-parameter.js');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@ const cfnTemplate = ({
} as unknown) as Template;
const templateFormat = CFNTemplateFormat.JSON;

const customPolicies = {
policies : [{
const customPolicies: CustomIAMPolicies = [
{
Action : ['test:test'],
Effect : 'Allow',
Resource : ['arn:aws:s3:us-east-2:012345678910:testResource']
}]
} as CustomIAMPolicies;
}
];

readCFNTemplate_mock.mockResolvedValue({
templateFormat,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export async function writeCustomPoliciesToCFNTemplate(
}
await validateCustomPoliciesSchema(customPolicies, category, resourceName);

await addCustomPoliciesToCFNTemplate(service, category, customPolicies.policies, cfnTemplate, filePath, resourceName, {templateFormat} );
await addCustomPoliciesToCFNTemplate(service, category, customPolicies, cfnTemplate, filePath, resourceName, {templateFormat} );

}

Expand All @@ -76,7 +76,7 @@ export async function writeCustomPoliciesToCFNTemplate(
async function addCustomPoliciesToCFNTemplate(
service: string,
category: string,
customPolicies: CustomIAMPolicy[],
customPolicies: CustomIAMPolicies,
cfnTemplate: Template,
filePath: string,
resourceName: string,
Expand Down Expand Up @@ -159,9 +159,9 @@ function validateExistCustomPolicies(customPolicies: CustomIAMPolicies) : Boolea
return false;
}

if (customPolicies.policies.length === 1
&& customPolicies.policies[0].Action?.length === 0
&& customPolicies.policies[0].Resource?.length === 0) {
if (customPolicies.length === 1
&& customPolicies[0].Action?.length === 0
&& customPolicies[0].Resource?.length === 0) {
return false;
}

Expand Down Expand Up @@ -196,7 +196,7 @@ async function validateCustomPoliciesSchema(data: CustomIAMPolicies, categoryNam
//validate if the policies match the custom IAM policies schema, if not, then not write into the CFN template
const validatePolicy = ajv.compile(CustomIAMPolicySchema);

for(const policy of data.policies) {
for(const policy of data) {
if(!validatePolicy(policy)) {
let errorMessage = `Invalid custom IAM policies in the ${resourceName} ${categoryName} is invalid.\n
Edit <project-dir>/amplify/backend/function/socialmediademoea2a770a/custom-policies.json to fix
Expand Down

0 comments on commit 453b8b2

Please sign in to comment.