How to test for CORS in Kitura?

252 views Asked by At

Task

To enable CORS on a Kitura server hosted on Bluemix.

Development machine
OS X 10.12.1, Swift version 3.0.2.

Deployed to
Ubuntu 14.04, Swift 3.0.1.

Code

I am using Kitura-CORS middleware from IBM to enable CORS.

.Package(url: "https://github.com/IBM-Swift/Kitura-CORS", majorVersion: 1, minor: 4)

Here's how I've configured the app:

let options = Options(allowedOrigin: .all, credentials: true, exposedHeaders: ["X-Access-Token"])
let cors = CORS(options: options)
self.router.all(middleware: cors)

Findings

  1. A OPTIONS request to https://adeptness.eu-gb.mybluemix.net from Postman returns the following headers:

    • Connection → Keep-Alive
    • Content-Type → text/html
    • Date → Wed, 21 Dec 2016 19:12:04 GMT
    • Transfer-Encoding → chunked
    • X-Backside-Transport → OK OK
    • X-Global-Transaction-ID → 4203875359
  2. The app passes the test at Test CORS for a GET request to https://adeptness.eu-gb.mybluemix.net and reports the following exposed response headers:

    • Content-Type → text/html

Issue

I'm not entirely sure if CORS is setup properly. Why is there no X-Access-Token header in the OPTIONS response in Finding #1?

I've read Mozilla's documentation on CORS, and although I do understand that browsers pre-flight requests and block all CORS request unless explicitly allowed by the server. What I couldn't find was any resource on how to go about testing CORS server-side without having to mock up a "test" front-end.

How should one go about testing CORS?

1

There are 1 answers

1
skallner On BEST ANSWER

As you said, in general CORS is about telling the browser which Cross Origin requests are allowed, enabling the developer to break out of the old JavaScript sandbox that limited XHR requests to the same server the HTML page was loaded from.

Not all cross origin requests are allowed. The Kitura-CORS package lets the server developer provide information to browsers as to what kind of requests are allowed. Again this is all about the requests being sent to the server and not about the responses.

The exposedHeaders parameter enables the server developer to control what HTTP headers are allowed to be in the request being sent to the server.

To test you need to have a pair of servers with a simple web page loaded from one, that has JavaScript that makes an XHR request to the second server. The two servers need to be in different domains (i.e. one locally on your laptop and the second one on Bluemix). You will be able to see what is passed, if the second server passes in its responses the headers it received with the request.