Invalid state with Github provider (err 500)
Prerequisites
- [X] I have written a descriptive issue title
- [X] I have searched existing issues to ensure the bug has not already been reported
Fastify version
4.26.2
Plugin version
7.8.0
Node.js version
20.5.1
Operating system
macOS
Operating system version (i.e. 20.04, 11.3, 10)
14.4.1
Description
Hello,
While using the Github provider, I noticed something strange.
When setting the startRedirectPath, if you put a / in the path, it breaks the Github provider.
So, for example, if you set the startRedirectPath to /login/github and try to connect, you will get a result from the callback that looks like this
{
"statusCode": 500,
"error": "Internal Server Error",
"message": "Invalid state"
}
But, setting the startRedirectPath to something like /github instantly works, so I think there's a bug somewhere.
Maybe worth to know, I use the autoload to load all my routes like that :
fastify.register(autoLoad, {
dir: path.join(__dirname, "src/routes"),
options: { prefix: "/api" },
});
From what I can see, it looks like the state and stateCookie variables are not equal in the defaultCheckStateFunction function in the index.js of the package. But I have no idea why.
Steps to Reproduce
fastify.register(oAuthPlugin, {
name: "oauthName",
credentials: {
client: {
id: "xxx",
secret: "xxx",
},
auth: oAuthPlugin.GITHUB_CONFIGURATION,
},
startRedirectPath: "/login/github",
callbackUri: "http://localhost:3000/api/auth/providers/github/callback",
});
Expected Behavior
No response
I'm pretty sure this is the issue I was facing here.
The module's cookie (oauth2-redirect-state) path set by startRedirectPath is set to /login, and your callbackUri is at /api/auth/[...] which is outside of /login.
When changing startRedirectPath to /github, the cookie path is /, so the cookie is available everywhere
@FlawTECH you are right, one solution is make sure startRedirectPath and callbackUri has same prefix path
or another solution is pass a cookie params without change startRedirectPath or callbackUri:
fastify.register(fastifyOauth2, {
// The documentation says the default `path` is / , but it's not actually ~
cookie: {
path: "/",
}
}
certainly, you can custom checkStateFunction and generateStateFunction without use cookie. eg: maybe store state in redis
When I was planning to submit a documentation fix for the cookie.path annotation in @fastify/fastify-cookie today, I found that it had already been addressed in version 9.4.0.
more details please see here: https://github.com/fastify/fastify-cookie/pull/284
also,
https://stackoverflow.com/questions/43324480/how-does-a-browser-handle-cookie-with-no-path-and-no-domain