NodeJS Express应用程序测试 - 如何在使用Mocha和Chai进行测试时提交CSRF令牌?

时间:2016-09-30 09:00:10

标签: node.js express testing mocha chai

我尝试使用Mocha,Chai和ChaiHttp在我的Express应用程序中为POST路由编写测试,但由于我保留了这一点,我无法使其工作每当提交我的CSRF令牌时都会收到HTTP 403响应。下面是我到目前为止的代码:

express.js配置文件

...
  app.use(session(config.SESSION));
  // csrf is the 'csurf' module
  app.use(csrf());

  app.use((req, res, next) => {
    res.cookie('XSRF-TOKEN', req.csrfToken());
    return next();
  });
...

User.test.js

'use strict';
process.env.NODE_ENV = 'test';

const User = require('../server/models/User');
const chai = require('chai');
const chaiHttp = require('chai-http');
const server = require('../index');
const utils = require('../utils');

chai.use(chaiHttp);

describe('Users', () => {
  beforeEach((done) => {
    User.remove({}, (err) => {
      done();
    });
  });

  after((done) => {
    server.close();
    done();
  });
...
 /*
   * [POST] /user
   */
  describe('[POST] /user', () => {
    it('should return a JSON object with a "success" property equal to "true" when creating a new user', (done) => {
      const userObj = utils.generateUserObject();

      chai.request(server)
          .get('/api')
          .end((error, response) => {

            userObj._csrf = utils.extractCsrfToken(response.headers['set-cookie']);


            /*
             * Accurately logs the _csrf property with the correct CSRF token that was retrieved via the initial GET request
             * 
             * Example output:
             * 
             * { 
             * username: 'Stacey89',
             * first_name: 'Gregg',
             * last_name: 'King',
             * ...
             * _csrf: 'vBhDfXUq-jE86hOHadDyjgpQOu-uE8FyUp_M' 
             * }
             *
             */ 


            console.log(userObj);

            chai.request(server)
                .post('/api/user')
                .set('content-type', 'application/x-www-form-urlencoded')
                .send(userObj)
                .end((err, res) => {
                  res.should.have.status(200);
                  res.body.should.be.a('object');
                  res.body.should.have.property('success').eql('true');
                  done();
                });
          });
    });
...

utils.js

...
  extractCsrfToken(cookiesObj) {
    const cookiesArray = Array.prototype.join.call(cookiesObj, '').split(';');
    let csrfToken = 'NOT FOUND';

    cookiesArray.forEach((cookie) => {
      if (cookie.includes('XSRF-TOKEN')) {
        csrfToken = cookie.split('=').splice(1, 1).join('');
      }
    });

    return csrfToken;
  }
...

当我运行上述测试时,我收到以下错误:

ForbiddenError: invalid csrf token
...
POST /api/user 403

奇怪的是,如果我使用与前面描述的完全相同的配置从Postman发出POST请求,我成功获得了我正在寻找的响应并且表单提交成功。

似乎只有在我的测试套件中提交userObj时才能正常工作。

更新#1 我终于设法为我的问题找到了一个有效的解决方案。

我已将之前设置XSRF-TOKEN Cookie的中间件更新为以下内容:

  app.use((err, req, res, next) => {
    res.locals._csrf = req.csrfToken();
    return next();
  });

现在单元测试成功运行。

此外,我注意到发给服务器的第一个[GET]请求返回Set-Cookie标题:

Status Code: 200 OK
Content-Length: 264
Content-Type: application/json; charset=utf-8
Date: Tue, 18 Oct 2016 12:10:09 GMT
Etag: W/"108-NSQ2HIdRqiuMIf0F+7qwjw"
Set-Cookie: connect.sid=s%3Ap5io8_3iD7Wy0X0K77qWZLoYj-fD1ZbA.6uvcBiB%2B%2BSi1KOVOmJgvWe%2B5Mqpuc1rs9yUYxH0uNPY; Path=/; HttpOnly
X-Download-Options: noopen
X-XSS-Protection: 1; mode=block
x-content-type-options: nosniff
x-dns-prefetch-control: off
x-frame-options: SAMEORIGIN

任何后续[GET]请求都不会返回该标头:

Status Code: 200 OK
Content-Length: 264
Content-Type: application/json; charset=utf-8
Date: Tue, 18 Oct 2016 12:11:19 GMT
Etag: W/"108-NSQ2HIdRqiuMIf0F+7qwjw"
X-Download-Options: noopen
X-XSS-Protection: 1; mode=block
x-content-type-options: nosniff
x-dns-prefetch-control: off
x-frame-options: SAMEORIGIN

这在应用程序安全性方面是否正常?简单地在_csrf对象上设置res.locals标记是一种好习惯吗?

1 个答案:

答案 0 :(得分:0)

chai-http的send()方法用于发送json(通常需要使用json body解析器)。因此,您不应该将内容类型设置为chai.request(server) .post('/api/user') .field('_csrf', _csrf) .end((err, res) => { res.should.have.status(200); res.body.should.be.a('object'); res.body.should.have.property('success').eql('true'); done(); });

如果您没有使用json正文解析器并且您确实希望将其作为表单数据发送,那么field() method应该有效:

AND