From a4179e454aaeed182de394284afca7cd86f3d175 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miroslav=20Bajto=C5=A1?= Date: Wed, 22 Oct 2014 11:10:15 +0200 Subject: [PATCH] swagger: honour X-Forwarded-Proto header Improve the algorithm building `baseUrl` to honour `X-Forwarded-Proto` header when it is present. --- lib/swagger.js | 4 ++-- test/swagger.test.js | 12 ++++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/lib/swagger.js b/lib/swagger.js index 32843b7..5da84ae 100644 --- a/lib/swagger.js +++ b/lib/swagger.js @@ -166,9 +166,9 @@ function addRoute(app, uri, doc, opts) { if (hasBasePath) { var headers = req.headers; // NOTE header names (keys) are always all-lowercase + var proto = headers['x-forwarded-proto'] || opts.protocol || req.protocol; var host = headers['x-forwarded-host'] || headers.host; - doc.basePath = (opts.protocol || req.protocol) + '://' + - host + initialPath; + doc.basePath = proto + '://' + host + initialPath; } res.status(200).send(doc); }); diff --git a/test/swagger.test.js b/test/swagger.test.js index 9a79082..f70c9b0 100644 --- a/test/swagger.test.js +++ b/test/swagger.test.js @@ -93,6 +93,18 @@ describe('swagger definition', function() { done(); }); }); + + it('respects X-Forwarded-Proto header (behind a proxy)', function(done) { + var app = givenAppWithSwagger(); + getAPIDeclaration(app, 'products') + .set('X-Forwarded-Proto', 'https') + .end(function(err, res) { + if (err) return done(err); + var baseUrl = url.parse(res.body.basePath); + expect(baseUrl.protocol).to.equal('https:'); + done(); + }); + }); }); describe('Model definition attributes', function() {