Skip to content

Commit

Permalink
Revert "Lambda auth minor fixes (#8741)" (#8762)
Browse files Browse the repository at this point in the history
This reverts commit 8ff558b.
  • Loading branch information
ammarkarachi committed Nov 10, 2021
1 parent e86cbb9 commit aa1096c
Show file tree
Hide file tree
Showing 14 changed files with 246 additions and 76 deletions.
@@ -0,0 +1,208 @@
{
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "Lambda resource stack creation using Amplify CLI",
"Parameters": {
"env": {
"Type": "String"
}<%if (props.dependsOn && props.dependsOn.length > 0) { %>,<% } %>
<% if (props.dependsOn) { %>
<% for(var i=0; i < props.dependsOn.length; i++) { %>
<% for(var j=0; j < props.dependsOn[i].attributes.length; j++) { %>
"<%= props.dependsOn[i].category %><%= props.dependsOn[i].resourceName %><%= props.dependsOn[i].attributes[j] %>": {
"Type": "String",
"Default": "<%= props.dependsOn[i].category %><%= props.dependsOn[i].resourceName %><%= props.dependsOn[i].attributes[j] %>"
}<%if (i !== props.dependsOn.length - 1 || j !== props.dependsOn[i].attributes.length - 1) { %>,<% } %>
<% } %>
<% } %>
<% } %>
},
"Conditions": {
"ShouldNotCreateEnvResources": {
"Fn::Equals": [
{
"Ref": "env"
},
"NONE"
]
}
},
"Resources": {
"LambdaFunction": {
"Type": "AWS::Lambda::Function",
"Metadata": {
"aws:asset:path": "./src",
"aws:asset:property": "Code"
},
"Properties": {
"Handler": "index.handler",
"FunctionName": {
"Fn::If": [
"ShouldNotCreateEnvResources",
"<%= props.functionName %>",
{

"Fn::Join": [
"",
[
"<%= props.functionName %>",
"-",
{
"Ref": "env"
}
]
]
}
]
},
"Environment": {
"Variables" : {
"ENV": {
"Ref": "env"
},
"REGION": {
"Ref": "AWS::Region"
}
<% if (props.resourceProperties && props.resourceProperties.length > 0) { %>,<%- props.resourceProperties%> <% } %>
}
},
"Role": { "Fn::GetAtt" : ["LambdaExecutionRole", "Arn"] },
"Runtime": "nodejs14.x",
"Timeout": 25
}
},
"LambdaExecutionRole": {
"Type": "AWS::IAM::Role",
"Properties": {
"RoleName": {
"Fn::If": [
"ShouldNotCreateEnvResources",
"<%=props.roleName %>",
{

"Fn::Join": [
"",
[
"<%=props.roleName %>",
"-",
{
"Ref": "env"
}
]
]
}
]
},
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": [
"lambda.amazonaws.com"
]
},
"Action": [
"sts:AssumeRole"
]
}
]
}
}
}
,"lambdaexecutionpolicy": {
"DependsOn": ["LambdaExecutionRole"],
"Type": "AWS::IAM::Policy",
"Properties": {
"PolicyName": "lambda-execution-policy",
"Roles": [{ "Ref": "LambdaExecutionRole" }],
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action":["logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"],
"Resource": { "Fn::Sub" : [ "arn:aws:logs:${region}:${account}:log-group:/aws/lambda/${lambda}:log-stream:*", { "region": {"Ref": "AWS::Region"}, "account": {"Ref": "AWS::AccountId"}, "lambda": {"Ref": "LambdaFunction"}} ]}
}<% if (props.database && props.database.resourceName) { %>,
{
"Effect": "Allow",
"Action": ["dynamodb:GetItem","dynamodb:Query","dynamodb:Scan","dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:DeleteItem"],
"Resource": [
<% if (props.database && props.database.Arn) { %>
"<%= props.database.Arn %>",
{
"Fn::Join": [
"/",
[
"<%= props.database.Arn %>",
"index/*"
]
]
}
<% } else { %>
{ "Ref": "storage<%= props.database.resourceName %>Arn" },
{
"Fn::Join": [
"/",
[
{ "Ref": "storage<%= props.database.resourceName %>Arn" },
"index/*"
]
]
}
<% } %>
]
}
<% } %>
]
}
}
}
,"PermissionForAppSyncToInvokeLambda": {
"Type": "AWS::Lambda::Permission",
"Properties": {
"FunctionName": {
"Ref": "LambdaFunction"
},
"Action": "lambda:InvokeFunction",
"Principal": "appsync.amazonaws.com"
}
}
<% if (props.categoryPolicies && props.categoryPolicies.length > 0 ) { %>
,"AmplifyResourcesPolicy": {
"DependsOn": ["LambdaExecutionRole"],
"Type": "AWS::IAM::Policy",
"Properties": {
"PolicyName": "amplify-lambda-execution-policy",
"Roles": [{ "Ref": "LambdaExecutionRole" }],
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": <%- JSON.stringify(props.categoryPolicies) %>
}
}
}
<% } %>
},
"Outputs": {
"Name": {
"Value": {
"Ref": "LambdaFunction"
}
},
"Arn": {
"Value": {"Fn::GetAtt": ["LambdaFunction", "Arn"]}
},
"Region": {
"Value": {
"Ref": "AWS::Region"
}
},
"LambdaExecutionRole": {
"Value": {
"Ref": "LambdaExecutionRole"
}
}
}
}
Expand Up @@ -1143,25 +1143,46 @@ async function askLambdaFromProject(context: $TSContext) {
}

async function createLambdaAuthorizerFunction(context: $TSContext) {
const targetDir = context.amplify.pathManager.getBackendDirPath();
const assetDir = path.normalize(path.join(rootAssetDir, 'graphql-lambda-authorizer'));
const [shortId] = uuid().split('-');

const functionName = `graphQlLambdaAuthorizer${shortId}`;
const resourceName = await context.amplify.invokePluginMethod(context, 'function', undefined, 'add', [
context,
'awscloudformation',
FunctionServiceNameLambdaFunction,

const functionProps = {
functionName: `${functionName}`,
roleName: `${functionName}LambdaRole`,
};

const copyJobs = [
{
functionName,
defaultRuntime: 'nodejs',
providerContext: {
provider: 'awscloudformation',
},
template: 'lambda-auth',
skipAdvancedSection: true,
skipNextSteps: true,
dir: assetDir,
template: 'graphql-lambda-authorizer-index.js',
target: `${targetDir}/function/${functionName}/src/index.js`,
},
{
dir: assetDir,
template: 'graphql-lambda-authorizer-package.json.ejs',
target: `${targetDir}/function/${functionName}/src/package.json`,
},
]);
{
dir: assetDir,
template: 'graphql-lambda-authorizer-template.json.ejs',
target: `${targetDir}/function/${functionName}/${functionName}-cloudformation-template.json`,
},
];

context.print.success(`Successfully added ${resourceName} function locally`);
await context.amplify.invokePluginMethod(context, 'function', undefined, 'addAppSyncInvokeMethodPermission', [resourceName]);
return resourceName;
// copy over the files
await context.amplify.copyBatch(context, copyJobs, functionProps, true);

const backendConfigs = {
service: FunctionServiceNameLambdaFunction,
providerPlugin: provider,
build: true,
};

await context.amplify.updateamplifyMetaAfterResourceAdd('function', functionName, backendConfigs);
context.print.success(`Successfully added ${functionName} function locally`);

return functionName;
}
Expand Up @@ -119,9 +119,6 @@ export async function addFunctionResource(
await openEditor(context, category, completeParams.resourceName, completeParams.functionTemplate);
}

if (completeParams.skipNextSteps) {
return completeParams.resourceName;
}
const { print } = context;

const customPoliciesPath = pathManager.getCustomPoliciesPath(category, completeParams.resourceName);
Expand All @@ -137,7 +134,6 @@ export async function addFunctionResource(
print.info(
'"amplify publish" builds all of your local backend and front-end resources (if you added hosting category) and provisions them in the cloud',
);

return completeParams.resourceName;
}

Expand Down
Expand Up @@ -50,9 +50,7 @@ export async function createWalkthrough(
templateParameters = merge(templateParameters, autogeneratedParameters(context));

// ask generic function questions and merge in results
if(!templateParameters.functionName) {
templateParameters = merge(templateParameters, await generalQuestionsWalkthrough(context));
}
templateParameters = merge(templateParameters, await generalQuestionsWalkthrough(context));
if (templateParameters.functionName) {
templateParameters.resourceName = templateParameters.functionName;
}
Expand All @@ -66,10 +64,6 @@ export async function createWalkthrough(
// ask template selection questions and merge in results
templateParameters = merge(templateParameters, await templateWalkthrough(context, templateParameters));

if(templateParameters.skipAdvancedSection) {
return templateParameters;
}

// list out the advanced settings before asking whether to configure them
context.print.info('');
context.print.success('Available advanced settings:');
Expand Down
Expand Up @@ -37,7 +37,6 @@ export async function templateWalkthrough(context: $TSContext, params: Partial<F
selectionPrompt: 'Choose the function template that you want to use:',
notFoundMessage: `No ${params.runtime.name} ${params.providerContext.service} templates found`,
service,
defaultSelection: params.template,
};
const selections = await getSelectionsFromContributors<FunctionTemplateCondition>(context, selectionOptions);
const selection = selections[0];
Expand Down Expand Up @@ -77,7 +76,6 @@ export async function runtimeWalkthrough(
notFoundMessage: `No runtimes found for provider ${params.providerContext.provider} and service ${params.providerContext.service}`,
service,
runtimeState: runtimeLayers,
defaultSelection: params.defaultRuntime,
};
// runtime selections
const selections = await getSelectionsFromContributors<FunctionRuntimeCondition>(context, selectionOptions);
Expand Down Expand Up @@ -167,8 +165,6 @@ async function getSelectionsFromContributors<T>(
}
context.print.info(singleOptionMsg);
selection = selections[0].value;
} else if(isDefaultDefined(selectionOptions)) {
selection = selectionOptions.defaultSelection;
} else {
// ask which template to use
let answer = await inquirer.prompt([
Expand Down Expand Up @@ -196,11 +192,6 @@ async function getSelectionsFromContributors<T>(
});
}

function isDefaultDefined(selectionOptions: PluginSelectionOptions<FunctionRuntimeCondition>) {
return selectionOptions.defaultSelection &&
(selectionOptions.pluginType == 'functionTemplate' || selectionOptions.pluginType == 'functionRuntime');
}

export async function loadPluginFromFactory(pluginPath: string, expectedFactoryFunction: string, context: $TSContext): Promise<$TSAny> {
let plugin;
try {
Expand Down Expand Up @@ -235,7 +226,6 @@ interface PluginSelectionOptions<T extends FunctionRuntimeCondition | FunctionTe
selectionPrompt: string;
service: string;
runtimeState?: string[];
defaultSelection?: string;
}

interface PluginSelection {
Expand Down
Expand Up @@ -14,7 +14,6 @@ export type LayerParameters = {
build: boolean;
description?: string;
versionHash?: string;
defaultRuntime?: string;
};

export enum PermissionEnum {
Expand Down
2 changes: 0 additions & 2 deletions packages/amplify-e2e-core/src/categories/api.ts
Expand Up @@ -231,8 +231,6 @@ export function addApiWithAllAuthModesV2(cwd: string, opts: Partial<AddApiOption
// Lambda
.wait(/.*Choose a Lambda authorization function*/)
.sendCarriageReturn()
.wait(/.*Do you want to edit the local lambda function now*/)
.sendConfirmNo()
.wait(/.*How long should the authorization response be cached in seconds.*/)
.sendLine('600')
.wait(/.*Here is the GraphQL API that we will create. Select a setting to edit or continue.*/)
Expand Down
5 changes: 0 additions & 5 deletions packages/amplify-function-plugin-interface/src/index.ts
Expand Up @@ -137,10 +137,6 @@ export type FunctionParameters = {
lambdaLayers: LambdaLayer[];
environmentVariables?: Record<string, string>;
secretDeltas?: SecretDeltas;
template?: string;
defaultRuntime?: string;
skipAdvancedSection?: boolean;
skipNextSteps?: boolean;
};

/**
Expand Down Expand Up @@ -168,7 +164,6 @@ export interface FunctionTriggerParameters {
functionTemplate?: FunctionTemplate;
cloudResourceTemplatePath?: string;
environmentVariables?: Record<string, string>;
skipNextSteps?: boolean;
}

export interface ProviderContext {
Expand Down

0 comments on commit aa1096c

Please sign in to comment.