Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FEATURE] Proxy Backend Services #38

Closed
wants to merge 14 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

A list of unreleased changes can be found [here](https://github.com/SAP/ui5-server/compare/v0.2.0...HEAD).
A list of unreleased changes can be found [here](https://github.com/SAP/ui5-server/compare/v0.2.1...HEAD).

<a name="v0.2.1"></a>
## [v0.2.1] - 2018-07-13

<a name="v0.2.0"></a>
## [v0.2.0] - 2018-07-12
Expand Down Expand Up @@ -53,6 +56,7 @@ A list of unreleased changes can be found [here](https://github.com/SAP/ui5-serv
- **Travis:** Add node.js 10 to test matrix [`2881261`](https://github.com/SAP/ui5-server/commit/2881261a05afd737af7c8874b91819a52b8f88df)


[v0.2.1]: https://github.com/SAP/ui5-server/compare/v0.2.0...v0.2.1
[v0.2.0]: https://github.com/SAP/ui5-server/compare/v0.1.2...v0.2.0
[v0.1.2]: https://github.com/SAP/ui5-server/compare/v0.1.1...v0.1.2
[v0.1.1]: https://github.com/SAP/ui5-server/compare/v0.1.0...v0.1.1
Expand Down
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,22 @@ If there is none, a new certificate is created and used.

**Hint:** If Chrome unintentionally redirects a HTTP-URL to HTTPS, you need to delete the HSTS mapping in [chrome://net-internals/#hsts](chrome://net-internals/#hsts) by entering the domain name (e.g. localhost) and pressing "delete".

## Proxy

You can proxy existing (OData) backend services to get around Access-Control-Allow-Origin (CORS) errors.
To do so, you can add a hash of proxied paths in your `ui5.yml`. Example (auth is optional):
```
# ui5.yml
specVersion: '0.1'
metadata:
name: my-awesome-app
type: application
resources:
proxies:
/api/v1: "http://api.of.external.service/v1"
auth: "myproxyusername:myproxypassword"
```

## Contributing
Please check our [Contribution Guidelines](https://github.com/SAP/ui5-tooling/blob/master/CONTRIBUTING.md).

Expand Down
133 changes: 133 additions & 0 deletions lib/middleware/serveProxies.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
// heavily inspired by https://github.com/SAP/connect-openui5/blob/master/lib/proxy.js
const url = require("url");
const httpProxy = require("http-proxy");

const env = {
noProxy: process.env.NO_PROXY || process.env.no_proxy,
httpProxy: process.env.HTTP_PROXY || process.env.http_proxy,
httpsProxy: process.env.HTTPS_PROXY || process.env.https_proxy
};

function getProxyUri(uri) {
if (uri.protocol === "https:" && env.httpsProxy || uri.protocol === "http:" && env.httpProxy) {
if (env.noProxy) {
const canonicalHost = uri.host.replace(/^\.*/, ".");
const port = uri.port || (uri.protocol === "https:" ? "443" : "80");

const patterns = env.noProxy.split(",");
for (let i = patterns.length - 1; i >= 0; i--) {
let pattern = patterns[i].trim().toLowerCase();

// don"t use a proxy at all
if (pattern === "*") {
return null;
}

// Remove leading * and make sure to have exact one leading dot (.)
pattern = pattern.replace(/^[*]+/, "").replace(/^\.*/, ".");

// if host ends with pattern, no proxy should be used
if (canonicalHost.indexOf(pattern) === canonicalHost.length - pattern.length) {
return null;
}
}
}

if (uri.protocol === "https:" && env.httpsProxy) {
return env.httpsProxy;
} else if (uri.protocol === "http:" && env.httpProxy) {
return env.httpProxy;
}
}

return null;
}

function buildRequestUrl(uri) {
let ret = uri.pathname;
if (uri.query) {
ret += "?" + uri.query;
}
return ret;
}

function createUri(uriParam, proxyDefinitions) {
for (let path in proxyDefinitions) {
if (uriParam.startsWith(path)) {
return url.parse(proxyDefinitions[path] + uriParam.substring(path.length));
}
}
return null;
}

/**
* Creates and returns the middleware to serve proxied servers.
*
* @module server/middleware/serveProxies
* @param {Object} proxyDefinitions Contains proxy definitions
* @returns {function} Returns a server middleware closure.
*/
function createMiddleware(proxyDefinitions) {
let proxyServerParameters = {};
if (proxyDefinitions.auth)
{
proxyServerParameters.auth = proxyDefinitions.auth;
}
let proxy = httpProxy.createProxyServer(proxyServerParameters);

return function serveResources(req, res, next) {
if (proxyDefinitions == undefined) {
return next();
}
let uri = createUri(req.url, proxyDefinitions);
if (!uri || !uri.host) {
next();
return;
}

// change original request url to target url
req.url = buildRequestUrl(uri);

// change original host to target host
req.headers.host = uri.host;

// overwrite response headers
res.orgWriteHead = res.writeHead;
res.writeHead = function(...args) {
// We always filter the secure header to avoid the cookie from
// "not" beeing included in follow up requests in case of the
// proxy is running on HTTP and not HTTPS
let cookies = res.getHeader("set-cookie");
// array == multiple cookies
if (Array.isArray(cookies)) {
for (let i = 0; i < cookies.length; i++) {
cookies[i] = cookies[i].replace("secure;", "");
}
} else if (typeof cookies === "string" || cookies instanceof String) {
// single cookie
cookies = cookies.replace("secure;", "");
}

if (cookies) {
res.setHeader("set-cookie", cookies);
}

// call original writeHead function
res.orgWriteHead(args);
};

// get proxy for uri (if defined in env vars)
let targetUri = getProxyUri(uri) || uri.protocol + "//" + uri.host;

// proxy the request
proxy.proxyRequest(req, res, {
target: targetUri
}, function(err) {
if (err) {
next(err);
}
});
};
}

module.exports = createMiddleware;
2 changes: 2 additions & 0 deletions lib/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const serveIndex = require("./middleware/serveIndex");
const discovery = require("./middleware/discovery");
const versionInfo = require("./middleware/versionInfo");
const serveThemes = require("./middleware/serveThemes");
const serveProxies = require("./middleware/serveProxies");
const csp = require("./middleware/csp");
const ui5connect = require("connect-openui5");
const nonReadRequests = require("./middleware/nonReadRequests");
Expand Down Expand Up @@ -90,6 +91,7 @@ function serve(tree, {port, changePortIfInUse = false, h2 = false, key, cert, ac
app.use("/proxy", ui5connect.proxy({
secure: false
}));
app.use(serveProxies(tree.resources.proxies));

// Handle anything but read operations *before* the serveIndex middleware
// as it will reject them with a 405 (Method not allowed) instead of 404 like our old tooling
Expand Down
97 changes: 59 additions & 38 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading