Debugging with local instance and authentication cookies - cookies

So, I've recently taken over the front-end of a project in which the previous front-end developer always did his debugging with a localhost instance connecting to a remote staging back-end.
Right now we are improving some security issues and are using CSRF tokens.
For each POST,PUT,DELETE request, I'm first GETting a csrf endpoint, which sets a JSESSIONID HttpOnly cookie and returns a CSRF token in the response body. For the subsequent request the CSRF token goes into the request header and the cookie of course gets sent automatically of course.
Now,.. my code works fine deployed on the remote staging front-end. But, this new functionality has totally prevented me from debugging with a local instance, because the cookie wont work when I GET the CSRF token from localhost, because this is a different domain of course.
This requires me to deploy every single change of code to the staging front end. Very uncomfortable workflow when performing the usual trial-and-error fix.
Adding the remote as a localhost alias to my hosts file also doesn't work, because this routes all my requests to the remote to my own machine, which doesn't run a local instance of the remote.
I would've thought there would be a Chrome extension or something like that for problems like these, but since I couldn't find any I wondered if I'm missing a very obvious point here.

Okay, it seems that this was a really general issue:
set withCredentials to true for the request to the remote and use a chrome plugin to overwrite the response headers to:
Access-Control-Allow-Origin: http://localhost
Access-Control-Allow-Credentials: true

Related

cypress browser sends all cookies in all requests

I am using cypress for e2e testing with the session storage feature enabled.
Until recently the only two cookies in the project were "access_token" and "refresh_token". Now I added 2 more cookies which store some data which will automatically be written and read while you're using the website.
When browsing the website with any native browser (chrome, firefox, edge), no cookies get sent by the frontend to the backend in the request. Only the "access_token"s content will be used as the Authentication bearer.
When browsing in any browser inside cypress or letting cypress automatically browse, all cookies which exist will be added to every sent request. Not only requests sent by cy.request() but also the requests which the frontend natively sends.
This is a problem since the header size gets to large and the backend wont accept it. The quickfix was to increase the accepted header size in the backend but I'd prefer not sending the cookies at all.
Is there a way to tell cypress which cookies to send or prevent sending cookies at all? I don't really care which cookies will be stored in the cypress session. Only which cookies get sent.
EDIT:
All cookies use "strict" same site settings.
When testing against a deployed system https is used but with an invalid certificate.
When testing against a locally running system http is used.
The cookies only get sent when running cypress against a local system (localhost).
Using samesite=strict means that the cookie will never be included in requests to other sites, so I guess that is your core problem here. You need to use samesite=none to get cookies included in HTTP POST Request across sites.

Keystone session cookie only working on localhost

Edit:
After investigating this further, it seems cookies are sent correctly on most API requests. However something happens in the specific request that checks if the user is logged in and it always returns null. When refreshing the browser a successful preflight request is sent and nothing else, even though there is a session and a valid session cookie.
Original question:
I have a NextJS frontend authenticating against a Keystone backend.
When running on localhost, I can log in and then refresh the browser without getting logged out, i.e. the browser reads the cookie correctly.
When the application is deployed on an external server, I can still log in, but when refreshing the browser it seems no cookie is found and it is as if I'm logged out. However if I then go to the Keystone admin UI, I am still logged in.
In the browser settings, I can see that for localhost there is a "keystonejs-session" cookie being created. This is not the case for the external server.
Here are the session settings from the Keystone config file.
The value of process.env.DOMAIN on the external server would be for example example.com when Keystone is deployed to admin.example.com. I have also tried .example.com, with a leading dot, with the same result. (I believe the leading dot is ignored in newer specifications.)
const sessionConfig = {
maxAge: 60 * 60 * 24 * 30,
secret: process.env.COOKIE_SECRET,
sameSite: 'lax',
secure: true,
domain: process.env.DOMAIN,
path: "/",
};
const session = statelessSessions(sessionConfig);
(The session object is then passed to the config function from #keystone-6/core.)
Current workaround:
I'm currently using a workaround which involves routing all API requests to '/api/graphql' and rewriting that request to the real URL using Next's own rewrites. Someone recommended this might work and it does, sort of. When refreshing the browser window the application is still in a logged-out state, but after a second or two the session is validated.
To use this workaround, add the following rewrite directive to next.config.js
rewrites: () => [
{
source: '/api/graphql',
destination:
process.env.NODE_ENV === 'development'
? `http://localhost:3000/api/graphql`
: process.env.NEXT_PUBLIC_BACKEND_ENDPOINT,
},
],
Then make sure you use this URL for queries. In my case that's the URL I feed to createUploadLink().
This workaround still means constant error messages in the logs since relative URLs are not supposed to work. I would love to see a proper solution!
It's hard to know what's happening for sure without knowing more about your setup. Inspecting the requests and responses your browser is making may help figure this out. Look in the "network" tab in your browser dev tools. When you make make the request to sign in, you should see the cookie being set in the headers of the response.
Some educated guesses:
Are you accessing your external server over HTTPS?
They Keystone docs for the session API mention that, when setting secure to true...
[...] the cookie is only sent to the server when a request is made with the https: scheme (except on localhost)
So, if you're running your deployed env over plain HTTP, the cookie is never set, creating the behaviour you're describing. Somewhat confusingly, in development the flag is ignored, allowing it to work.
A similar thing can happen if you're deploying behind a proxy, like nginx:
In this scenario, a lot of people choose to have the proxy terminate the TLS connection, so requests are forwarded to the backend over HTTP (but on a private network, so still relatively secure). In that case, you need to do two things:
Ensure the proxy is configured to forward the X-Forwarded-Proto header, which informs the backend which protocol was used originally request
Tell express to trust what the proxy is saying by configuring the trust proxy setting
I did a write up of this proxy issue a while back. It's for Keystone 5 (so some of the details are off) but, if you're using a reverse proxy, most of it's still relevant.
Update
From Simons comment, the above guesses missed the mark 😭 but I'll leave them here in case they help others.
Since posting about this issue a month ago I was actually able to work around it by routing API requests via a relative path like '/api/graphql' and then forwarding that request to the real API on a separate subdomain. For some mysterious reason it works this way.
This is starting to sound like a CORS or issue
If you want to serve your front end from a different origin (domain) than the API, the API needs to return a specific header to allow this. Read up on CORS and the Access-Control-Allow-Origin header. You can configure this setting the cors option in the Keystone server config which Keystone uses to configure the cors package.
Alternatively, the solution of proxying API requests via the Next app should also work. It's not obvious to me why your proxying "workaround" is experiencing problems.

Why can't I see my (localhost) cookie being stored in Electron app?

I have an Angular app using Electron as the desktop wrapper. And there's a separate Django backend which provides HTTP APIs to the Electron client.
So normally when I call the login API the response header will have a Set-Cookie field containing the sessionId. And I can clearly see that sessionId in Postman, however, I can't see this cookie in my Angular app (Dev tools of Electron).
After some further debugging I noticed a warning sign beside my Set-Cookie in dev tools. It said that the cookie is blocked due to the SameSite being set to Lax. So I found a way to modify the server code to return a None samesite (together with a Secure property; I'm using HTTP):
# settings.py
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_SAMESITE = 'None'
which did work (and the warning sign is gone) but the cookie is still not visible.
So what's the problem here? Why can't (and How can) I see that cookie so as to make sure that the login works in the actual client, not just Postman?
(btw, now both ends are being developed in localhost.)
There's no need to worry. A good way to check if it works is to actually make a request that requires login (after the API has been Postman tested) and see if the desired data are returned. If so, you are good to go (especially when the warning is gone).
If the sessionId cookie is saved it should automatically be included in the request. Unless there's something wrong with the cookie's path; but a / path would be fine.
Why is the cookie not visible: it's probably due to the separation of front and back ends. In Electron, the pages are typically some local HTML files, as one common step during configuration is to probably modify loadURL or something like that in main.js, for instance:
mainWindow.loadURL(`file://${__dirname}/dist/your-project/index.html`);
So the "site" you are accessing from Electron can be considered as local filesystem (which has no domain and hence no cookie at all), and you should see an empty file:// entry in dev tools -> application -> storage -> cookie. It doesn't mean a local path containing all cookies of the Electron app. Although your backend may be on the same local machine, you are accessing as http:// instead of file:// so the browser (Electron) will treat it as an actual web server.
Therefore, your cookies should be stored in another entry like http(s)://localhost and you can't see it in Electron. (Note that the same cookie will work in both HTTP and HTTPS)
If you use Chrome instead to test, you may be able to see it in all cookies. In some cases where the frontend and backend are deployed to the same host you may see the cookie in dev tools. But I guess there're always some reasons why you need Electron to create a desktop app (e.g. Python scripts).
Further reading
Using HTTPS
Although moving to HTTPS does not necessarily solve the original problem, it may be worth doing in order to prevent potential problems and get ready for the publish.
In your case, for the backend, you can use django-sslserver as a temporary solution before getting your SSL, but it uses a self-signed certificate and may make your frontend complain.
To fix this, consider adding the following code to the main process:
# const { app } = require('electron');
if (!app.isPackaged) {
app.commandLine.appendSwitch('ignore-certificate-errors');
}
Now it provides a good way to distinguish between development (unpacked) and production (packed) and only disables certificate check in development in order to make the code work.
Assuming that SESSION_COOKIE_SECURE in your config refers to cookie's secure flag, You ll have to set
SESSION_COOKIE_SECURE = False
because if this flag is set to True the browser will allow this cookie to be set only if you are using an https connection.
PS: This is just for your localhost. Hopefully you ll be using an Https connection in other environments.

Localhost frontend no longer sending cookie to development backend

I'm trying to connect my local frontend to our development backend hosted in aws.
Everything used to work, and I'm going crazy trying to figure out what happened.
The issue is that the request to the backend isn't passing along the cookie we use for authentication.
We have cors setup and it appears to be working correctly. The Options call returns everything I'd expect
.
but the request just doesn't contain the cookie.
I'm setting the cookie via javascript in the frontend code rather than having the server itself set it. This setup used to work idk why it doesn't anymore.
What are the reasons why a browser wouldn't pass a cookie along?
My checklist includes:
ensuring Access-Control-Allow-Credentials is passed back from the Options request
ensure withCredentials is set on the frontend making the request
ensuring the cookie domain is set to /
We recently added some CSRF protection but I disabled that and still can't get the cookie to be sent.
A soapui call to the backend works just fine.
The issue lied in the samesite cookie.
I deployed my development server to explicitly set samesite=none and things are working again.
axios({
method: "get",
withCredentials: true,
});
adding withCredentials:true worked for me

Cookie Manager of Apache JMeter doesn't add the cookie to POST request

I build up very simple test plan.
Login: POST, a session cookie is returned.
Get the state: GET, a user state is returned.
Create a resource: POST, JSON body is supplied for the resource.
So my 'Test Plan' looks like:
Test Plan
Thread Group
HTTP Request Defaults
HTTP Cookie Manager
Login (HTTP Request Sampler: POST)
Get State (HTTP Request Sampler: GET)
Create Resource (HTTP Request Sampler: POST)
The cookie generated by 'Login' is added to 'Get State' correctly.
But 'Create Resource' has NO cookie. I changed their order but it doesn't help.
I used the default options firstly and changed some options but it also doesn't help.
Is it a bug of JMeter? or just POST http request is not able to have cookie?
Please give me any advice.
[SOLVED]
I noticed that it is related to the path, not the method.
You'd like to look at the domain of the cookie as well as the path.
I mean, the path and the domain of a cookie could be defined in the server side through Set-Cookie header.
Another solution is to set CookieManager.check.cookies=false in jmeter.properties usually sitting besides the jmeter startup script in bin.
JMeter for some reasons thinks that you can't set the path=/something in a cookie if you are on http:/somesite/somethingelse. That is the path has to match the path your currently on.
I've never seen a browser enforce this limitation if it actually exists. I've seen and written several sites that use this technique to set a secure cookie and then forward someone say to /admin.
I wish this option was at least in the GUI so I didn't have to change the properties file. I think BlazeMeter is smart enough to turn off checking where flood.io is not. If it were up to me I'd just remove the code that checks this entirely. Why make the load tester any harder then it needs to be.
I had this turned on in my Spring Boot server which was causing the issue with CookieManager in jMeter:
server.servlet.session.cookie.secure=true
Removing this made the cookies flow ! Of course this is for localhost. For Production you may need this turned on.