chai-http icon indicating copy to clipboard operation
chai-http copied to clipboard

Response - testing for XSSI prevention and then strip it before proceeding.

Open workin-bob opened this issue 7 years ago • 1 comments

It seems that a best practice to prevent cross-site script injection is to return the following string at the top of any Content-Type: application/json. The string is to force a JSON parse error. Angular knows to strip this string before conversion. ")]}',\n"

I need 2 things 1 - A flag on the response indicating the XSSI prevention string is in place (for unit tests) 2 - strip the prefix before returning the response in the .end - and any anywhere else it is appropriate

If this capability already exists, please let me know.

workin-bob avatar Feb 20 '18 23:02 workin-bob

Hi @workin-bob, this doesn't exist in chai-http, but seems like an easy utility function that could be written. Note this issue for getting application/javascript as text.



const fs = require('fs');
const express = require('express');
const chai = require('chai');
const chaiHttp = require('chai-http');

const { expect } = chai;
chai.use(chaiHttp);
const app = express();

const XSSI_PREFIX = ")]}',\n"

const file = fs.readFileSync(__dirname + '/index.js').toString('utf8');
app.get('/js', function(req, res) {
  res.set('content-type', 'application/javascript');
  res.send(XSSI_PREFIX + file);
});

function validateXSSIPrevention(text) {
  expect(text).to.be.a('string');
  expect(text.indexOf(XSSI_PREFIX)).to.equal(0);
}

function stripXSSI(text) {
  return text.slice(XSSI_PREFIX.length);
}

describe('xssi', () => {
  it('should have the appropriate prefix', async () => {
    const res = await chai.request(app)
              .get('/js')
              .set('Accept', 'application/javascript')
              .buffer(true);
    const content = res.text.trim();
    validateXSSIPrevention(content);
    const validContent = stripXSSI(content);
  });
});

austince avatar May 27 '19 18:05 austince