2

My web app uses Node.js and Express in the backend. When there is violation of the content security policies (CSP), the report URI reports an empty object. The codes in my backend are as the following:

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      // some policies here
      reportUri: ["/my_amazing_csp_report_parser"],
    },
  },
}));

app.use('/my_amazing_csp_report_parser', (req, res, next) => {
  console.log(req.body);
  next();
})

I read on the Doc from MDN that the report URI should report a whole JSON object. But my console.log(req.body); returns an empty object. I am wondering if I am parsing my JSON object wrong with app.use(bodyParser.urlencoded({ extended: true })); and app.use(bodyParser.json());?

gshow8 shac
  • 391
  • 2
  • 15

1 Answers1

3

I do not work with React, so I acnt give you explicit code. But I can explain whatc going on.

CSP reports is differ from data sent from <form method='POST'>. The <form> datas has Content-type 'application/x-www-form-urlencoded' or 'multipart/form-data' which use to send list of name/value pairs to the server. Those data could be binary(files) or urlencoded, so you need to use bodyParser.urlencoded().

CSP report sends with 'application/json' MIME-type and there is no name/value pairs, just body. Therefore bodyParser.urlencoded({ extended: true }) will give you empty body, and you you need to use something like that:

app.use('/report-violation', bodyParser.json({ type: 'application/json' }));  # for old browsers
app.use('/report-violation', bodyParser.json({ type: 'application/reports+json' })); # for report-to directive
app.use('/report-violation', bodyParser.json({ type: 'application/csp-report' }));  # for report-uri directive
app.use('/report-violation', (req, res) => {
  // handle req.body
  res.status(204).end()
});

* I do never meet 'application/csp-report' Content-type and never used it, it's up to you. At least it is not IANA registered MIME type. It's a MIME type for reports from the CSP spec, sorry.

Do not forget to return "204 No content" status code

Here is some example how to get reports using winston logger, but I do not know is it work or not.

granty
  • 7,234
  • 1
  • 14
  • 21
  • Hi @granty, worked like a charm. Thank you. I am trying to understand why I have to return `"204 No content"`? Since it is a report URI, I thought that I would not need to end it since there is no client waiting for a response. – gshow8 shac Oct 23 '20 at 13:26
  • 2
    HTTP is a request-reply protocol, each request should have reply. Without reply within timeout browser think that something goes wrong and will resend request. 204 code means server have got request successfully but have no intention to send any data in response. – granty Oct 23 '20 at 16:14