cors-middleware icon indicating copy to clipboard operation
cors-middleware copied to clipboard

Improve CORS error debugging by populating cors headers that did not fail the check

Open dakujem opened this issue 3 years ago • 0 comments

Scenario

  1. User agent sends preflight request with requested methods and headers.
  2. One of the headers fails the check, but the origin is correct, the methods are correct too
  3. CORS middleware returns 401
  4. User agent fails with message like Reason: CORS header ‘Access-Control-Allow-Origin’ missing

So it's rather hard to tell what the problem is. It's not that the origin check failed, but that the header check failed.

The person trying to discover the issue should instead be directed to the missing header error 👉 https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSMissingAllowHeaderFromPreflight.

Workaround

Browsers do not display the response's content, so sending the information as the response's data is mostly useless.

The only way of propagating the error message to the browser that I can think of is using a header, like this:

// CORS middleware error handler example
function (Request $request, Response $response, array $arguments): Response {
    return $response
        ->withAddedHeader('X-CORS-Error-Message', $arguments['message'] ?? 'Generic CORS error.');
},

Future

I am writing this down to let others know about this possibility of conveying the message,
and to ask if it was possible to implement partial response decoration, with headers that did not fail, so that the browser could generate a correct error message.

dakujem avatar Jul 21 '22 12:07 dakujem