amplify-cli icon indicating copy to clipboard operation
amplify-cli copied to clipboard

Unauthorization error when using custom resolver in lambda function

Open johnEthicalTechnology opened this issue 6 years ago • 7 comments

Note: If your question is regarding the AWS Amplify Console service, please log it in the official AWS Amplify Console forum

Which Category is your question related to? AppSync custom resolver and Lambda function triggered by DynamoDB Stream

Amplify CLI Version 4.32.0

You can use amplify -v to check the amplify cli version on your system

What AWS Services are you utilizing? AppSync, DynamoDB, Cognitio, IAM, Lambda

Provide additional details e.g. code snippets I created a custom resolver to do a batch update of the Lead model. I'm able to use it on the client side but when I try to use it in a Lambda I get this error: Not Authorized to access batchUpdateLeadsToActive on type Mutation"

I don't understand why I get the error. I've given the function access to all the CRUD operations and to the database, but I'm still getting unauthorized error.

In the AppSync console I'm getting the same error. When I try to use IAM authorization I get unauthorized error but when I use Cognito user I'm able to complete the mutation.

How do I set up a custom mutations so as to be able to be used in a function without being given the unauthorized error?

Relevant portion of schema

type Lead
  @model
  @key(
    name: "byMappingData"
    fields: ["mappingDataID", "createdTime"]
    queryField: "listLeadsByMappingDataId"
  )
  @key(
    name: "ByStatus"
    fields: ["status", "createdTime"]
    queryField: "listLeadsByStatus"
  )
  @auth(
    rules: [
      { allow: private, operations: [update, read] }
      { allow: private, provider: iam, operations: [create, read, update] }
    ]
  ) {
  id: ID!
  formId: String!
  pageId: String!
  processedLeadData: String
  status: Status!
  deliveryStatus: DeliveryStatus!
  zohoResponse: String
  createdTime: String
  fbLeadId: String
  rawLeadData: [FieldData]
  mappingDataID: ID!
  submitDataToZoho: Boolean
  testLead: Boolean
  mappingData: MappingData @connection(fields: ["mappingDataID"])
}


type Mutation {
  batchUpdateLeadsToActive(leads: [UpdateLeadInput]): [Lead]
}

Custom Resolver

#set($leadsdata = [])
#foreach($lead in ${ctx.args.leads})
    ## Automatically set the updatedAt timestamp. **
    $util.qr($lead.put("updatedAt", $util.defaultIfNull($ctx.args.input.updatedAt, $util.time.nowISO8601())))
    $util.qr($lead.put("__typename", "Lead"))
    $util.qr($lead.put("status", "ACTIVE"))
    $util.qr($leadsdata.add($util.dynamodb.toMapValues($lead)))
#end
{
    "version" : "2018-05-29",
    "operation" : "BatchPutItem",
    "tables" : {
        "Lead-kkbs55pjjrbltj2bi3zewybnfu-prod": $utils.toJson($leadsdata)
    }
}

johnEthicalTechnology avatar Nov 04 '20 06:11 johnEthicalTechnology

Hi @johnEthicalTechnology

You can try @function directive in your custom mutation , this will generate all the IAM roles and policies required for the operation. We have a documentation to configure lambda resolvers : https://docs.amplify.aws/cli/graphql-transformer/function.

Let me know if this works for you?

akshbhu avatar Nov 04 '20 19:11 akshbhu

Thanks for the quick reply!

This is what I changed in my schema:

type Mutation {
  batchUpdateLeadsToActive(leads: [UpdateLeadInput]): [Lead]
    @function(name: "batchUpdateLeadsToActive")
}

But it didn't work.

However, when I checked the schema in the AppSync console I discovered this:

type Mutation {
	batchUpdateLeadsToActive(leads: [UpdateLeadInput]): [Lead]
	deleteMappingData(input: DeleteMappingDataInput!, condition: ModelMappingDataConditionInput): MappingData
	deleteLead(input: DeleteLeadInput!, condition: ModelLeadConditionInput): Lead
	createMappingData(input: CreateMappingDataInput!, condition: ModelMappingDataConditionInput): MappingData
		@aws_iam
	updateMappingData(input: UpdateMappingDataInput!, condition: ModelMappingDataConditionInput): MappingData
		@aws_iam
@aws_cognito_user_pools
	createLead(input: CreateLeadInput!, condition: ModelLeadConditionInput): Lead
		@aws_iam
	updateLead(input: UpdateLeadInput!, condition: ModelLeadConditionInput): Lead
		@aws_iam
@aws_cognito_user_pools
}

I don't know what the @functions directive is meant to do, but it looks like it didn't do anything to the schema, at least with the mutations.

So I changed it by adding an @aws_iam directive to the batchUpdateLeadsToActive mutation like so:

batchUpdateLeadsToActive(leads: [UpdateLeadInput]): [Lead]
		@aws_iam

Now it is working. However, my question is if and when I update the schema next time will I have to re-add the @aws-iam directive to the schema through the AppSync console? I've got a suspicion that I will as it hasn't been adding it through the expected workflow.

It's not ideal, but at least it's a fix for now. But it sounds like this could be a bug, unless there's something that I've not done correctly?

johnEthicalTechnology avatar Nov 04 '20 23:11 johnEthicalTechnology

I just wanted to add another piece to this. I removed the @function directive from the mutation, thinking it isn't need, but when I ran the lambda and did the call to App Sync with that mutation the mutation return null. But when I put the @function directive back on the mutation it worked again.

johnEthicalTechnology avatar Nov 05 '20 00:11 johnEthicalTechnology

Hi @johnEthicalTechnology

Can you try amplify update api and select ```IAM`` as the additional authorization mode. After that you can add @auth to your custom mutation

batchUpdateLeadsToActive(leads: [UpdateLeadInput]): [Lead] @auth

Let me know if this works?

akshbhu avatar Nov 09 '20 23:11 akshbhu

I already have the IAM authorization as an additional mode, but I did that command again. I added the @auth to my custom mutation as directed, and then I ran amplify push. I got the following error:

Directive "@auth" argument "rules" of type "[AuthRule!]!" is required, but it was not provided.
An error occurred during the push operation: Directive "@auth" argument "rules" of type "[AuthRule!]!" is required, but it was not provided.

johnEthicalTechnology avatar Nov 10 '20 02:11 johnEthicalTechnology

@johnEthicalTechnology You'd need to add @aws_iam instead of @auth directive the the batchUpdateLeadsToActive mutation.

kaustavghosh06 avatar Jan 27 '21 00:01 kaustavghosh06

This issue has been automatically locked since there hasn't been any recent activity after it was closed. Please open a new issue for related bugs.

Looking for a help forum? We recommend joining the Amplify Community Discord server *-help channels for those types of questions.

github-actions[bot] avatar May 25 '21 07:05 github-actions[bot]