From aa1096ca504bdb7e6a2dca2963c546f957116f9d Mon Sep 17 00:00:00 2001 From: Ammar <56042290+ammarkarachi@users.noreply.github.com> Date: Tue, 9 Nov 2021 16:38:59 -0800 Subject: [PATCH] Revert "Lambda auth minor fixes (#8741)" (#8762) This reverts commit 8ff558b51d510934fe696e9b3e3b12d0ed4c8058. --- .../graphql-lambda-authorizer-index.js} | 0 ...raphql-lambda-authorizer-package.json.ejs} | 0 ...raphql-lambda-authorizer-template.json.ejs | 208 ++++++++++++++++++ .../appSync-walkthrough.ts | 53 +++-- .../provider-utils/awscloudformation/index.ts | 4 - .../lambda-walkthrough.ts | 8 +- .../utils/functionPluginLoader.ts | 10 - .../awscloudformation/utils/layerParams.ts | 1 - .../amplify-e2e-core/src/categories/api.ts | 2 - .../src/index.ts | 5 - .../amplify-plugin.json | 4 - .../resources/lambda/lambda-auth/event.json | 3 - .../src/index.ts | 4 - .../src/providers/lambdaAuthProvider.ts | 20 -- 14 files changed, 246 insertions(+), 76 deletions(-) rename packages/{amplify-nodejs-function-template-provider/resources/lambda/lambda-auth/index.js => amplify-category-api/resources/awscloudformation/graphql-lambda-authorizer/graphql-lambda-authorizer-index.js} (100%) rename packages/{amplify-nodejs-function-template-provider/resources/lambda/lambda-auth/package.json.ejs => amplify-category-api/resources/awscloudformation/graphql-lambda-authorizer/graphql-lambda-authorizer-package.json.ejs} (100%) create mode 100644 packages/amplify-category-api/resources/awscloudformation/graphql-lambda-authorizer/graphql-lambda-authorizer-template.json.ejs delete mode 100644 packages/amplify-nodejs-function-template-provider/resources/lambda/lambda-auth/event.json delete mode 100644 packages/amplify-nodejs-function-template-provider/src/providers/lambdaAuthProvider.ts diff --git a/packages/amplify-nodejs-function-template-provider/resources/lambda/lambda-auth/index.js b/packages/amplify-category-api/resources/awscloudformation/graphql-lambda-authorizer/graphql-lambda-authorizer-index.js similarity index 100% rename from packages/amplify-nodejs-function-template-provider/resources/lambda/lambda-auth/index.js rename to packages/amplify-category-api/resources/awscloudformation/graphql-lambda-authorizer/graphql-lambda-authorizer-index.js diff --git a/packages/amplify-nodejs-function-template-provider/resources/lambda/lambda-auth/package.json.ejs b/packages/amplify-category-api/resources/awscloudformation/graphql-lambda-authorizer/graphql-lambda-authorizer-package.json.ejs similarity index 100% rename from packages/amplify-nodejs-function-template-provider/resources/lambda/lambda-auth/package.json.ejs rename to packages/amplify-category-api/resources/awscloudformation/graphql-lambda-authorizer/graphql-lambda-authorizer-package.json.ejs diff --git a/packages/amplify-category-api/resources/awscloudformation/graphql-lambda-authorizer/graphql-lambda-authorizer-template.json.ejs b/packages/amplify-category-api/resources/awscloudformation/graphql-lambda-authorizer/graphql-lambda-authorizer-template.json.ejs new file mode 100644 index 00000000000..acd908246dc --- /dev/null +++ b/packages/amplify-category-api/resources/awscloudformation/graphql-lambda-authorizer/graphql-lambda-authorizer-template.json.ejs @@ -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" + } + } + } +} diff --git a/packages/amplify-category-api/src/provider-utils/awscloudformation/service-walkthroughs/appSync-walkthrough.ts b/packages/amplify-category-api/src/provider-utils/awscloudformation/service-walkthroughs/appSync-walkthrough.ts index 52de5b0701e..933134e813d 100644 --- a/packages/amplify-category-api/src/provider-utils/awscloudformation/service-walkthroughs/appSync-walkthrough.ts +++ b/packages/amplify-category-api/src/provider-utils/awscloudformation/service-walkthroughs/appSync-walkthrough.ts @@ -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; } diff --git a/packages/amplify-category-function/src/provider-utils/awscloudformation/index.ts b/packages/amplify-category-function/src/provider-utils/awscloudformation/index.ts index 97662918e28..a7df8555b4e 100644 --- a/packages/amplify-category-function/src/provider-utils/awscloudformation/index.ts +++ b/packages/amplify-category-function/src/provider-utils/awscloudformation/index.ts @@ -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); @@ -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; } diff --git a/packages/amplify-category-function/src/provider-utils/awscloudformation/service-walkthroughs/lambda-walkthrough.ts b/packages/amplify-category-function/src/provider-utils/awscloudformation/service-walkthroughs/lambda-walkthrough.ts index 74308773c55..64935d66c6d 100644 --- a/packages/amplify-category-function/src/provider-utils/awscloudformation/service-walkthroughs/lambda-walkthrough.ts +++ b/packages/amplify-category-function/src/provider-utils/awscloudformation/service-walkthroughs/lambda-walkthrough.ts @@ -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; } @@ -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:'); diff --git a/packages/amplify-category-function/src/provider-utils/awscloudformation/utils/functionPluginLoader.ts b/packages/amplify-category-function/src/provider-utils/awscloudformation/utils/functionPluginLoader.ts index 71119e214ba..7be7254def9 100644 --- a/packages/amplify-category-function/src/provider-utils/awscloudformation/utils/functionPluginLoader.ts +++ b/packages/amplify-category-function/src/provider-utils/awscloudformation/utils/functionPluginLoader.ts @@ -37,7 +37,6 @@ export async function templateWalkthrough(context: $TSContext, params: Partial(context, selectionOptions); const selection = selections[0]; @@ -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(context, selectionOptions); @@ -167,8 +165,6 @@ async function getSelectionsFromContributors( } 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([ @@ -196,11 +192,6 @@ async function getSelectionsFromContributors( }); } -function isDefaultDefined(selectionOptions: PluginSelectionOptions) { - return selectionOptions.defaultSelection && - (selectionOptions.pluginType == 'functionTemplate' || selectionOptions.pluginType == 'functionRuntime'); -} - export async function loadPluginFromFactory(pluginPath: string, expectedFactoryFunction: string, context: $TSContext): Promise<$TSAny> { let plugin; try { @@ -235,7 +226,6 @@ interface PluginSelectionOptions; secretDeltas?: SecretDeltas; - template?: string; - defaultRuntime?: string; - skipAdvancedSection?: boolean; - skipNextSteps?: boolean; }; /** @@ -168,7 +164,6 @@ export interface FunctionTriggerParameters { functionTemplate?: FunctionTemplate; cloudResourceTemplatePath?: string; environmentVariables?: Record; - skipNextSteps?: boolean; } export interface ProviderContext { diff --git a/packages/amplify-nodejs-function-template-provider/amplify-plugin.json b/packages/amplify-nodejs-function-template-provider/amplify-plugin.json index 3a5b9741453..7ed278e976b 100644 --- a/packages/amplify-nodejs-function-template-provider/amplify-plugin.json +++ b/packages/amplify-nodejs-function-template-provider/amplify-plugin.json @@ -25,10 +25,6 @@ { "name": "Lambda trigger", "value": "trigger" - }, - { - "name": "GraphQL Lambda Authorizer", - "value": "lambda-auth" } ] } diff --git a/packages/amplify-nodejs-function-template-provider/resources/lambda/lambda-auth/event.json b/packages/amplify-nodejs-function-template-provider/resources/lambda/lambda-auth/event.json deleted file mode 100644 index 16936b83271..00000000000 --- a/packages/amplify-nodejs-function-template-provider/resources/lambda/lambda-auth/event.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "authorizedToken": "custom-authorized" -} diff --git a/packages/amplify-nodejs-function-template-provider/src/index.ts b/packages/amplify-nodejs-function-template-provider/src/index.ts index 3457fc429d2..f8688a8e1f0 100644 --- a/packages/amplify-nodejs-function-template-provider/src/index.ts +++ b/packages/amplify-nodejs-function-template-provider/src/index.ts @@ -4,7 +4,6 @@ import { provideHelloWorld } from './providers/helloWorldProvider'; import { provideCrud } from './providers/crudProvider'; import { provideServerless } from './providers/serverlessProvider'; import { provideTrigger } from './providers/triggerProvider'; -import { provideLambdaAuth } from './providers/lambdaAuthProvider'; export const functionTemplateContributorFactory: FunctionTemplateContributorFactory = context => { return { @@ -22,9 +21,6 @@ export const functionTemplateContributorFactory: FunctionTemplateContributorFact case 'trigger': { return provideTrigger(context); } - case 'lambda-auth': { - return provideLambdaAuth(); - } default: { throw new Error(`Unknown template selection [${request.selection}]`); } diff --git a/packages/amplify-nodejs-function-template-provider/src/providers/lambdaAuthProvider.ts b/packages/amplify-nodejs-function-template-provider/src/providers/lambdaAuthProvider.ts deleted file mode 100644 index 40310af2638..00000000000 --- a/packages/amplify-nodejs-function-template-provider/src/providers/lambdaAuthProvider.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { FunctionTemplateParameters } from 'amplify-function-plugin-interface'; -import { templateRoot } from '../utils/constants'; -import fs from 'fs-extra'; -import path from 'path'; -import _ from 'lodash'; -import { getDstMap } from '../utils/destFileMapper'; - -const pathToTemplateFiles = path.join(templateRoot, 'lambda/lambda-auth'); - -export function provideLambdaAuth(): Promise { - const files = fs.readdirSync(pathToTemplateFiles); - return Promise.resolve({ - functionTemplate: { - sourceRoot: pathToTemplateFiles, - sourceFiles: files, - defaultEditorFile: path.join('src', 'index.js'), - destMap: getDstMap(files), - }, - }); -}