vendredi 24 août 2018

How can I test the Sails.js v1.0 login controller with CSRF security enabled (using mocha, supertest)?

I have an almost-new Sails.js 1.0.2 app and I'm able to log in with both a browser and with Postman. However, I can't seem to make the same process work in my test runner.

The test below should result in a successful login, where a cookie is returned with a new session ID. If I change the security configuration to disable CSRF protection, it runs perfectly. But with security enabled, the request is forbidden (403). The only difference between what I'm sending in Postman seems to be that mocha runs the app on a different port (Postman sends to localhost:1337, express' res variable says PUT /api/v1/entrance/login HTTP/1.1 Host: 127.0.0.1:56002

Anyone see something I'm missing?

Here's the test file:

/**
 * /test/integration/controllers/entrance/login.test.js
 */

'use strict';

const supertest = require('supertest');  // also tried supertest-session

describe('Entrance controllers', () => {

  describe('/api/v1/entrance/login', () => {

    before(() => {
      return supertest(sails.hooks.http.app)
      .get('/login')
      .then(res => {
        const reTokenCapture = /_csrf:\s*unescape\('([^']+)'\)/;
        const found = reTokenCapture.exec(res.text);
        this._csrf = sails.config.security.csrf ? found[1] : '';
        this.url = '/api/v1/entrance/login';
      });
    });

    it('should return a session cookie in response headers', () => {
      return supertest(sails.hooks.http.app)
      .put(this.url)
      .set('X-CSRF-Token', this._csrf)
      .send({
        emailAddress: 'admin@example.com',
        password: 'abc123',
        // _csrf: this._csrf,  // I tried this too; no luck
      })
      .expect(200)  // if sails.config.security.csrf is enabled, status is 403
      .then(res => {
        // console.log('res:', res);  // this shows the correct header
        res.headers['set-cookie'].should.be.an('array');
        const hasSid = res.headers['set-cookie'].map(cookie => {
          const reSid = /^sails\.sid=[^;]+;\sPath=\/;(?:\sExpires=[^;]+GMT;)?\sHttpOnly$/;
          return reSid.test(cookie);
        });
        hasSid.should.include.members([true]);
      });
    });

  });

});

I'm running node v8.11.3, sails v1.0.2, mocha v5.2.0, supertest v3.1.0, chai v4.1.2

Aucun commentaire:

Enregistrer un commentaire