-
Notifications
You must be signed in to change notification settings - Fork 822
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Known issue with Lambda Auth to Graphql API #13235
Comments
Hey @qwikag 👋 thanks for raising this, and thanks for bringing this to our attention! We'll get those samples updated now that Lambda supports Node 18, removing the Please note there is also an active issue we are tracking where Function access is not applied to your GraphQL API. This happens when the API is already deployed and you grant your Function access to the API to query/mutate, and the corresponding resolvers are not updated to include your Function's information for authorization, thus giving you a 401. To workaround this you can add an empty space to the GraphQL Schema to trigger an update and push with
As a quick callout, it is not recommended to modify records on DynamoDB directly and rather query/mutate through GraphQL. This will ensure any DataStore-connected clients are notified of subscribed updates, and ensure the tables DataStore uses are updated.
Functions created with Amplify CLI >12.2.x are created using the Node 18 runtime, and therefore can be built without the use of
Unfortunately the
IAM is our recommendation, however this can also be used with API Key with little updates needed for the code as outlined in the linked doc. For Cognito you will need to configure a REST API to use Cognito to authorize requests, which you can then send along to the GraphQL API request.
AWS SDK v3 is now included in Lambda's Node 18 runtime, superseding AWS SDK v2 that was available in previous runtime versions.
There is currently an active issue for debugging Lambda Functions with
IAM Policies for access are generated for you automatically when stepping through the |
Hi @josefaidt, Fantastic response, Thank you. I just want to clarify on this point:
But the docs do say to do it that way:
So can you please advise the best order of setting up a new function.
or
As a side I think this is the problem with most of the guides/turorials, there is very little step by step process. very little "why do we do this" and very little scenario based options (e.g. IAM(SSO), and App Router vs Pages. The menu structure of the docs is not easy to find stuff. Anyway, I hope to oneday be proficient enough to be more helpful/hands on. |
Hey @qwikag
This is a great callout! And I see how the callout in the docs shown after the example causes confusion. In the docs this is a callout specifically for the "AppSync - GraphQL API request (with IAM)" Function template you are prompted for on
The second option here is fine. For the active issue I linked the only thing you'll want to ensure is that your API is updated after adding/updating a Function to have access to that API. You can inspect the
This and the following comments are also great callouts, and highlight a gap in our suggested workflows when considering both Amplify Hosting and the CLI. Let's continue this conversation in a docs issue. I see you have one regarding Next.js app router vs pages, but would you mind filing a new issue there with these thoughts? |
@josefaidt This workaround doesn't work. I just created a new function and added the permissions through the CLI, added a space in my graphQL file and made the deployment with push and I'm still getting this error. The Amplify team should prioritize this type of bugs which have been reported since at least 1 year and 4 months ago, this basically makes all the documentation around 'using GraphQL on lambda' useless as if you follow it up it just doesn't work. I would also asume by seeing the number of devs with issues on this matter that this affects a great deal of users, so why not prioritize this bugs which affect basic functionality for any type of app instead of adding shiny new things like passkeys? And I actually have a long list of things that the team could prioritize and that the devs have been asking for years like:
These are all things that could improve the developer experience greatly, and things that probably affect or could improve +80% of all projects done in Amplify. |
have you tried that? Adding permission: what exactly did you do? Did you give IAM access to GraphQL API? |
@qwikag I've tried almost everything found on Github/Stackoverflow by now, this bug has been messing with me now for 2 weeks, I decided to just query the database directly as there's no issues with getting permissions directly from the db, but once more I tried doing it from scratch and again got the same result, here are my detailed step-by-step:
/* Amplify Params - DO NOT EDIT
API_XXXX_GRAPHQLAPIENDPOINTOUTPUT
API_XXXX_GRAPHQLAPIIDOUTPUT
API_XXXX_GRAPHQLAPIKEYOUTPUT
ENV
REGION
Amplify Params - DO NOT EDIT */
import crypto from '@aws-crypto/sha256-js';
import { defaultProvider } from '@aws-sdk/credential-provider-node';
import { SignatureV4 } from '@aws-sdk/signature-v4';
import { HttpRequest } from '@aws-sdk/protocol-http';
import { default as fetch, Request } from 'node-fetch';
const GRAPHQL_ENDPOINT = process.env.API_XXXX_GRAPHQLAPIENDPOINTOUTPUT;
const AWS_REGION = process.env.AWS_REGION || 'us-east-1';
const { Sha256 } = crypto;
export const query = /* GraphQL */ `
query ListItems($filter: ModelItemFilterInput, $limit: Int, $nextToken: String) {
listItems(filter: $filter, limit: $limit, nextToken: $nextToken) {
items {
id
owner
public
}
nextToken
}
}
`;
/**
* @type {import('@types/aws-lambda').APIGatewayProxyHandler}
*/
export const handler = async (event) => {
console.log(`EVENT: ${JSON.stringify(event)}`);
const endpoint = new URL(GRAPHQL_ENDPOINT);
const signer = new SignatureV4({
credentials: defaultProvider(),
region: AWS_REGION,
service: 'appsync',
sha256: Sha256
});
const requestToBeSigned = new HttpRequest({
method: 'POST',
headers: {
'Content-Type': 'application/json',
host: endpoint.host
},
hostname: endpoint.host,
body: JSON.stringify({ query }),
path: endpoint.pathname
});
const signed = await signer.sign(requestToBeSigned);
const request = new Request(endpoint, signed);
let statusCode = 200;
let body;
let response;
try {
response = await fetch(request);
body = await response.json();
if (body.errors) statusCode = 400;
} catch (error) {
statusCode = 500;
body = {
errors: [
{
message: error.message
}
]
};
}
return {
statusCode,
// Uncomment below to enable CORS requests
// headers: {
// "Access-Control-Allow-Origin": "*",
// "Access-Control-Allow-Headers": "*"
// },
body: JSON.stringify(body)
};
};
type Item
@model(subscriptions: null)
@auth(rules: [{ allow: private, provider: iam }, { allow: owner }]) {
id: ID!
owner: String @auth(rules: [{ allow: owner, operations: [read, delete] }])
public: String @default(value: "false")
}
{
"statusCode": 400,
"body": "{\"data\":{\"listItems\":null},\"errors\":[{\"path\":[\"listItems\"],\"data\":null,\"errorType\":\"Unauthorized\",\"errorInfo\":null,\"locations\":[{\"line\":3,\"column\":5,\"sourceName\":null}],\"message\":\"Not Authorized to access listItems on type Query\"}]}"
} If I go into the details of the lambda I can even see that the role is created and it has the necessary permissions or it looks like it but doesn't work: Any suggestion greatly appreciated. |
@jerocosio But... You kinda ignored my questions... I will reiterate: I also have used But I think they are included in the push. (very little documentation) Here is my setup:
|
@jerocosio Your code looks exactly like mine and mine is now working due to the a space & |
Thank you so much @qwikag for looking into this I really appreciate it, I continued following the steps you shared by doing:
But still got the same error: {
"statusCode": 400,
"body": "{\"data\":{\"listItems\":null},\"errors\":[{\"path\":[\"listItems\"],\"data\":null,\"errorType\":\"Unauthorized\",\"errorInfo\":null,\"locations\":[{\"line\":3,\"column\":5,\"sourceName\":null}],\"message\":\"Not Authorized to access listItems on type Query\"}]}"
} I also just found something odd on my resolvers, on all of them in the auth I have this:
But I actually deleted that function 'xxxxPostConfirmation' a long time ago, but I don't see the actual function that I'm trying to give access to anywhere in the resolvers. |
@jerocosio I am on Lets discuss alternative platforms shall we. I have just raised 2 very serious bugs occurring in the schema: there is no way to get proper attention here, or quick support. So again what is a better platform outside AWS? |
@qwikag I really like Amplify ad have used it in a number of projects, but it's true that support is basically non-existent and you have to find 'hacks' around making it work the way you want definately supabase or firebase are great alternatives to it, but I haven't really used them for a project lately. I believe the issue with Amplify is the way they prioritize stuff, focusing on creating flashy stuff like their Figma integration, the Amplify Studio, etc... which are cool to have, but not really useful for more than 5% of their users vs things such as simple improvements to their transforms, functions, etc... (as mentioned above) which no one really sees but would improve 99% of their users. |
Hey @jerocosio 👋 the error in the issue you're experiencing seems related to a missing For example I've created a sample project using the following steps:
A few notes:
|
@qwikag thank you for helping out here! Would you be open to hopping on a quick call to gather additional feedback? If so would you mind sending me a message at [email protected]? |
@jerocosio apologies, just noticed the schema snippet a few comments above, type Item
@model(subscriptions: null)
@auth(rules: [{ allow: private, provider: iam }, { allow: owner }]) {
id: ID!
owner: String @auth(rules: [{ allow: owner, operations: [read, delete] }])
public: String @default(value: "false")
} which looks good. The auth resolver you noted does look a bit odd. Is this an overridden resolver by chance? If you run |
Hi @josefaidt, |
@josefaidt thank you for looking into this, I just ran |
@josefaidt I looked a little deeper into the files and they haven't been updated since at least a couple of weeks ago, I tracked down those dates and it looks like they match to when I created a new env for my project, not sure if it's 100% correlated, but looks like so. |
@jerocosio can you try deleting the build directory and pushing? |
@josefaidt I finally got it working, for some reason there was a resolver directory on the root of the api directory which had all the resolvers that I had in the past, so on the new build they were being picked as if they were made to override the new resolvers that were created. Thanks for digging into this and for the help, I hope that the overal bug around having to make edits on the schema every time a user wants to add/remove the permissions gets solved soon. |
Hey @jerocosio glad to hear it!! That sounds like a side effect of an older bug where some mock issue would leave the |
Any auth change I make is not reflected until I delete the resolvers folder and re mock. Huge hinderance to dev/debugging workflow. |
Closing in favor of tracking existing item |
|
How did you install the Amplify CLI?
Who Knows, because the process is all over the shop.
If applicable, what version of Node.js are you using?
20.3.1
Amplify CLI Version
12.4.0
What operating system are you using?
WIN 10
Did you make any manual changes to the cloud resources managed by Amplify? Please describe the changes made.
No manual changes
Describe the bug
This document is not helpful in any way. And this is a BUG!
https://docs.amplify.aws/guides/functions/graphql-from-lambda/q/platform/js/
Because presently the process and commands to deliver on it do not work.
So in rewriting this document and testing the process, the bugs should get removed in the process.
Could we please get it rewritten to accurately describe how to set up a lambda's access to GraphQL API or via node-fetch or direct dynamo or something?
So that we can actually get our apps running!!!
The document needs to provide accurate steps, and actually work.
Also update the page with a date so we know when it was last updated/reviewed.
Expected behavior
the documented process takes the user through setting up and provides a few various common situations like Cognito triggers etc.
Reproduction steps
follow the current page:
https://docs.amplify.aws/guides/functions/graphql-from-lambda/q/platform/js/
Project Identifier
1aff16e72d6657e6251bd6a212fd28ac
Log output
No response
Additional information
Points of interest and questions:
What Amplify Version?
What libraries are available (node-fetch only), can API.GraphQL be used?
Can it be setup with IAM/API-key/Cognito, and how?, and why?
AWS SDK v3 - WHAT?
Proper debugging???
Policies to give access - WHAT?
Before submitting, please confirm:
The text was updated successfully, but these errors were encountered: