Search code examples
aws-lambdaaws-amplifyaws-appsync

Lambda function can not access appsync


I have a lambda function create by amplify to get a list of donors from appsync but it will get UnauthorizedException every time I try to request. Here is my lambda function:

const axios = require('axios');
const gql = require('graphql-tag');
const graphql = require('graphql');
const { print } = graphql;

const listDonors = gql`
    query listDonors {
        listDonors {
            items {
                id
                firstName
                lastName
            }
        }
    }
`

exports.handler = async (event) => {
    console.log("--------------------------------->");
    try {
        const graphqlData = await axios({
            url: process.env.API_DOCBACKEND_GRAPHQLAPIENDPOINTOUTPUT,
            method: 'post',
            headers: {
                'x-api-key': process.env.API_DOCBACKEND_GRAPHQLAPIIDOUTPUT
            },
            data: {
                query: print(listDonors),
            }
        });
        const body = {
            graphqlData: graphqlData.data.data.listTodos
        }
        return {
            statusCode: 200,
            body: JSON.stringify(body),
            headers: {
                "Access-Control-Allow-Origin": "*",
            }
        }
    } catch (err) {
        console.log('error posting to appsync: ', err);
    }
}

Here is my IAM role:

{
"Version": "2012-10-17",
"Statement": [
    {
        "Action": [
            "appsync:Create*",
            "appsync:StartSchemaCreation",
            "appsync:GraphQL",
            "appsync:Get*",
            "appsync:List*",
            "appsync:Update*",
            "appsync:Delete*"
        ],
        "Resource": [
            "arn:aws:appsync:us-east-1:862148551361:apis/2i62fn5z4vhtxbik3jcm33tc6e/types/Query/*",
            "arn:aws:appsync:us-east-1:862148551361:apis/2i62fn5z4vhtxbik3jcm33tc6e/types/Mutation/*",
            "arn:aws:appsync:us-east-1:862148551361:apis/2i62fn5z4vhtxbik3jcm33tc6e/types/Subscription/*"
        ],
        "Effect": "Allow"
    }
]

}

I follow the aws amplify document but it does not help me anything at all.


Solution

  • The doc seems to indicate that you should pass a field or a graphqlapi to the GraphQL permission.

    • field should read arn:${Partition}:appsync:${Region}:${Account}:apis/${GraphQLAPIId}/types/${TypeName}/fields/${FieldName}
    • graphqlapi should read arn:${Partition}:appsync:${Region}:${Account}:apis/${GraphQLAPIId}

    It seems to me like arn:aws:appsync:us-east-1:xxx:apis/xxx/types/Query/* does not quite match the rule.

    Maybe you should replace it with arn:aws:appsync:us-east-1:xxx:apis/xxx" to use the graphqlapi format

    Or use the field format: arn:aws:appsync:us-east-1:xxx:apis/xxx/types/Query/fields/* (and do the same for other types, obviously) ?