request.cookies is undefined when using Supertest - cookies

I'm passing my authentication token via an HTTP-Only cookie in my NestJS API.
As such, when writing some E2E tests for my Auth endpoints, I'm having an issue with cookies not being where I expect them.
Here's my pared-down test code:
describe('auth/logout', () => {
it('should log out a user', async (done) => {
// ... code to create user account
const loginResponse: Response = await request(app.getHttpServer())
.post('/auth/login')
.send({ username: newUser.email, password });
// get cookie manually from response.headers['set-cookie']
const cookie = getCookieFromHeaders(loginResponse);
// Log out the new user
const logoutResponse: Response = await request(app.getHttpServer())
.get('/auth/logout')
.set('Cookie', [cookie]);
});
});
In my JWT Strategy, I'm using a custom cookie parser. The problem I'm having is that request.cookies is always undefined when it gets to the parser. However, the cookie will be present in request.headers.
I'm following the manual cookie example from this Medium article: https://medium.com/#juha.a.hytonen/testing-authenticated-requests-with-supertest-325ccf47c2bb, and there don't appear to be any other methods available on the request object to set cookies.
If I test the same functionality from Postman, everything works as expected. What am I doing wrong?

I know this is an old thread but...
I also had req.cookies undefined, but for a different reason.
I'm testing my router independently, not the top level app. So I bootstrap the app in beforeEach and add the route to test.
I was getting req.cookies undefined because express 4 requires the cookieParser middleware to be present to parse the cookies from the headers.
E.g.
const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const request = require('supertest');
const {router} = require('./index');
describe('router', () => {
let app;
beforeAll(() => {
app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use('/', router);
});
beforeEach(() => jest.clearAllMocks());
it('GET to /', async () => {
const jwt = 'qwerty-1234567890';
const resp = await request(app)
.get('/')
.set('Cookie', `jwt=${jwt};`)
.set('Content-Type', 'application/json')
.send({});
});
});
Testing this way allows me to unit test a router in isolation of the app. The req.cookies turn up as expected.

Late but I hope I can help you. The problem is in the initialization of the app object. Probably in your main.ts file you have some middlewares configured as they are: cors and queryParse. You must also put them in your tests when you create the app.
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
const app = moduleFixture.createNestApplication();
// Add cors
app.enableCors({
credentials: true,
origin: ['http://localhost:4200'],
});
// Add cookie parser
app.use(cookieParser());
await app.init();

As per the article you're following, the code at https://medium.com/#juha.a.hytonen/testing-authenticated-requests-with-supertest-325ccf47c2bb :
1) has the 'cookie' value in .set('cookie', cookie) in lowercase and in your code it's in Pascal case ==> Have you tried with lowercase in your code instead ?
2) the cookie value assigned to the 'cookie' header is not an array, whereas in your code you're assigning an array ==> Have you tried with a non array value ?
So to resume, can you try with the following code:
describe('auth/logout', () => {
it('should log out a user', async (done) => {
// ... code to create user account
const loginResponse: Response = await request(app.getHttpServer())
.post('/auth/login')
.send({ username: newUser.email, password });
// get cookie manually from response.headers['set-cookie']
const cookie = getCookieFromHeaders(loginResponse);
// Log out the new user
const logoutResponse: Response = await request(app.getHttpServer())
.get('/auth/logout')
.set('cookie', cookie) // <== here goes the diff
.expect(200, done);
});
});
Let us know if that helps :)

Related

Unable to set cookies on server side with Sveltekit

the title speaks for itself: From one moment to another, I am unable to set cookies from the server page of my Sveltekit project.
In the +page.server.js of my page I have an action in which I am setting a cookie with the set function. After that, when reloading the page, I am trying to retrieve the cookie with the get function inside the load function, but the cookie is undefined. I am quite convinced that it is not set at all, but I don't know why.
export const load = async ({ cookies }) => {
const myCookie = cookies.get('myCookie');
}
export const actions = {
default: async ({ cookies }) => {
//stuff
cookies.set('myCookie', true);
throw redirect(303, '/');
}
}
I specify that this is a procedure I have already done in other projects and it has always worked. What could be the problem? Thank you for your help.
UPDATE:
I don't know if it helps, but I want to specify that I am using Pocketbase and that a cookie is set in the hook.server.js of the project, which I can see in the browser and works correctly:
export async function handle({ event, resolve }) {
event.locals.pb = new PocketBase('http://127.0.0.1:8090');
event.locals.pb.authStore.loadFromCookie(event.request.headers.get('cookie') || '');
if (event.locals.pb.authStore.isValid) {
event.locals.user = serializeNonPOJOs(event.locals.pb.authStore.model);
} else {
event.locals.user = undefined;
}
const response = await resolve(event, {
transformPageChunk: ({ html }) => minify(html, minification_options)
})
response.headers.set('set-cookie', event.locals.pb.authStore.exportToCookie({ secure: false }));
return response
}

Apify: Preserve headers in RequestQueue

I'm trying to crawl our local Confluence installation with the PuppeteerCrawler. My strategy is to login first, then extracting the session cookies and using them in the header of the start url. The code is as follows:
First, I login 'by foot' to extract the relevant credentials:
const Apify = require("apify");
const browser = await Apify.launchPuppeteer({sloMo: 500});
const page = await browser.newPage();
await page.goto('https://mycompany/confluence/login.action');
await page.focus('input#os_username');
await page.keyboard.type('myusername');
await page.focus('input#os_password');
await page.keyboard.type('mypasswd');
await page.keyboard.press('Enter');
await page.waitForNavigation();
// Get cookies and close the login session
const cookies = await page.cookies();
browser.close();
const cookie_jsession = cookies.filter( cookie => {
return cookie.name === "JSESSIONID"
})[0];
const cookie_crowdtoken = cookies.filter( cookie => {
return cookie.name === "crowd.token_key"
})[0];
Then I'm building up the crawler structure with the prepared request header:
const startURL = {
url: 'https://mycompany/confluence/index.action',
method: 'GET',
headers:
{
Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7',
Cookie: `${cookie_jsession.name}=${cookie_jsession.value}; ${cookie_crowdtoken.name}=${cookie_crowdtoken.value}`,
}
}
const requestQueue = await Apify.openRequestQueue();
await requestQueue.addRequest(new Apify.Request(startURL));
const pseudoUrls = [ new Apify.PseudoUrl('https://mycompany/confluence/[.*]')];
const crawler = new Apify.PuppeteerCrawler({
launchPuppeteerOptions: {headless: false, sloMo: 500 },
requestQueue,
handlePageFunction: async ({ request, page }) => {
const title = await page.title();
console.log(`Title of ${request.url}: ${title}`);
console.log(page.content());
await Apify.utils.enqueueLinks({
page,
selector: 'a:not(.like-button)',
pseudoUrls,
requestQueue
});
},
maxRequestsPerCrawl: 3,
maxConcurrency: 10,
});
await crawler.run();
The by-foot-login and cookie extraction seems to be ok (the "curlified" request works perfectly), but Confluence doesn't accept the login via puppeteer / headless chromium. It seems like the headers are getting lost somehow..
What am I doing wrong?
Without first going into the details of why the headers don't work, I would suggest defining a custom gotoFunction in the PuppeteerCrawler options, such as:
{
// ...
gotoFunction: async ({ request, page }) => {
await page.setCookie(...cookies); // From page.cookies() earlier.
return page.goto(request.url, { timeout: 60000 })
}
}
This way, you don't need to do the parsing and the cookies will automatically be injected into the browser before each page load.
As a note, modifying default request headers when using a headless browser is not a good practice, because it may lead to blocking on some sites that match received headers against a list of known browser fingerprints.
Update:
The below section is no longer relevant, because you can now use the Request class to override headers as expected.
The headers problem is a complex one involving request interception in Puppeteer. Here's the related GitHub issue in Apify SDK. Unfortunately, the method of overriding headers via a Request object currently does not work in PuppeteerCrawler, so that's why you were unsuccessful.

Chai-http doesn't seem to accept header always sends 401

I am trying to test my API routes that are protected by using jsonwebtoken.
I have tested my routes in postman and have gotten the correct results however running the same tests using mocha/chai/chai-http is not working.
Everytime I test a protected route I receive a 401 'unauthorized'
describe('user', () => {
let user, token
beforeEach(async () => {
await dropDb()
user = await new User({ email: 'testing#test.com', password: 'password' }).save()
const payload = { userid: user.id, role: user.roles.title, status: user.roles.status }
token = jwt.sign(payload, secret, { expiresIn: 3600 })
})
it('should return a list of users when logged in', async () => {
console.log(token)
const result = await chai.request(app)
.get('/api/user')
.set('Authorization', `Bearer ${token}`)
expect(result).to.have.status(200)
expect(result).to.be.json
})
})
My gut feeling was that there was somehow a race condition where the token being passed into the set wasn't finished being signed before the test ran. But inside the result it appears that my token has been set.
Additionally if I console.log the token after I can see that it matches the token created. Anybody run into a similar issue?

Jest how to check async response

I'm new to Jest and React so this should be a very simple question to answer... I have an api-endpoint I'd like to check that I can hit. I picked Axios as a client to try this and created the following test:
describe('Api Tests', () => {
it('can perform an axios request', () => {
console.log('Here goes!');
const resp = axios.get('api-endpoint');
console.log(resp);
expect(resp).toBeDefined();
console.log('Done...');
});
});
Thankfully, the test passes, but with the following output:
PASS src\api\api.test.js
Api Tests
√ can perform an axios request (39ms)
console.log src\api\api.test.js:15
Here goes!
console.log src\api\api.test.js:23
Promise { <pending> }
console.log src\api\api.test.js:25
Done...
How do I test a simple request (WITHOUT MOCKING) so that I can get back a response that I can then interrogate?
Since axios.get returns a promise you should instruct Jest to wait for the response to return.
it('can perform an axios request', async () => {
const resp = await axios.get('api-endpoint');
expect(resp).toBeDefined();
});
or without async functions:
it('can perform an axios request', () => {
return expect(axios.get('api-endpoint')).resolves.toBeDefined();
});
I have nice and easy method , maybe you will like it too. Just keep it simple.
`import axios from 'axios';
axios.get('url goes here')
.then(response =>{console.log(response)})`
Maybe find helpful to you.

Mock Firebase Admin Auth for Unit Testing Authenticated Routes

I'm using firebase-admin for authentication on my express backend. I have a middleware that checks if requests are authenticated.
public resolve(): (req, res, next) => void {
return async (req, res, next) => {
const header = req.header('Authorization');
if (!header || !header.split(' ')) {
throw new HttpException('Unauthorized', UNAUTHORIZED);
}
const token = header.split(' ')[1];
await admin.auth().verifyIdToken(token).then((decodedToken: any) => {
req.user = decodedToken;
next();
}).catch((error: any) => {
throw new HttpException(error, UNAUTHORIZED);
});
};
}
So far, I can only unit test my routes to make sure that they respond UNAUTHORIZED instead of NOT_FOUND.
it('GET /api/menu should return 401 ', done => {
const NOT_FOUND = 404;
const UNAUTHORIZED = 401;
supertest(instance)
.get('/api/menu')
.end((error, response: superagent.Response) => {
expect(response.status).not.toEqual(NOT_FOUND);
expect(response.status).toEqual(UNAUTHORIZED);
done();
});
});
But, I want to write more unit tests than this! I want to mock users so I can make AUTHORIZED requests! I want to use the type property I have on users to verify that users of a certain type can/cannot use certain routes. Does anyone have an idea of how I could do this with firebase-admin-node?
It looks like the firebase-admin-node repo generates tokens for unit tests here, but I'm not sure how I would apply that to my specific problem.