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

[PoC] Proxy Mode #223

Draft
wants to merge 7 commits into
base: v2
Choose a base branch
from
Draft
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
1 change: 1 addition & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
const modules = {
server: "./lib/server",
sslUtil: "./lib/sslUtil",
proxyConfiguration: "./lib/proxyConfiguration",
middlewareRepository: "./lib/middleware/middlewareRepository"
};

Expand Down
82 changes: 69 additions & 13 deletions lib/middleware/MiddlewareManager.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const middlewareRepository = require("./middlewareRepository");
const MiddlewareUtil = require("./MiddlewareUtil");
const proxyConfiguration = require("../proxyConfiguration");

/**
*
Expand All @@ -8,7 +9,8 @@ const MiddlewareUtil = require("./MiddlewareUtil");
*/
class MiddlewareManager {
constructor({tree, resources, options = {
sendSAPTargetCSP: false
sendSAPTargetCSP: false,
useProxy: false
}}) {
if (!tree || !resources || !resources.all || !resources.rootProject || !resources.dependencies) {
throw new Error("[MiddlewareManager]: One or more mandatory parameters not provided");
Expand Down Expand Up @@ -84,6 +86,13 @@ class MiddlewareManager {
}

async addStandardMiddleware() {
const useProxy = this.options.useProxy;

let proxyConfig;
if (useProxy) {
proxyConfig = await proxyConfiguration.getConfigurationForProject(this.tree);
}

await this.addMiddleware("csp", {
wrapperCallback: ({middleware: cspModule}) => {
const oCspConfig = {
Expand Down Expand Up @@ -125,6 +134,22 @@ class MiddlewareManager {
});
await this.addMiddleware("compression");
await this.addMiddleware("cors");

if (useProxy) {
await this.addMiddleware("proxyRewrite", {
wrapperCallback: ({middleware: proxyRewriteModule}) => {
return ({resources, middlewareUtil}) => {
return proxyRewriteModule({
resources,
middlewareUtil,
configuration: proxyConfig,
cdnUrl: this.options.cdnUrl
});
};
}
});
}

await this.addMiddleware("discovery", {
mountPath: "/discovery"
});
Expand All @@ -143,21 +168,52 @@ class MiddlewareManager {
};
}
});
await this.addMiddleware("connectUi5Proxy", {
mountPath: "/proxy"
});

if (this.options.cdnUrl) {
await this.addMiddleware("cdn", {
wrapperCallback: (cdn) => {
return ({resources}) => {
return cdn({
resources,
cdnUrl: this.options.cdnUrl
});
};
}
});
}

if (useProxy) {
await this.addMiddleware("proxy", {
wrapperCallback: ({middleware: proxyModule}) => {
return ({resources}) => {
return proxyModule({
resources,
configuration: proxyConfig
});
};
}
});
} else {
await this.addMiddleware("connectUi5Proxy", {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is now removed officially from UI5 Tooling since version 3: #550

mountPath: "/proxy"
});
}

// 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
await this.addMiddleware("nonReadRequests");
await this.addMiddleware("serveIndex", {
wrapperCallback: ({middleware: middleware}) => {
return ({resources, middlewareUtil}) => middleware({
resources,
middlewareUtil,
simpleIndex: this.options.simpleIndex
});
}
});
if (!useProxy) {
// Don't do directory listing when using a proxy. High potential for confusion
await this.addMiddleware("serveIndex", {
wrapperCallback: ({middleware: middleware}) => {
return ({resources, middlewareUtil}) => middleware({
resources,
middlewareUtil,
simpleIndex: this.options.simpleIndex
});
}
});
}
}

async addCustomMiddleware() {
Expand Down
99 changes: 99 additions & 0 deletions lib/middleware/cdn.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
const log = require("@ui5/logger").getLogger("server:middleware:cdn");
const http = require("http");
const https = require("https");

function createMiddleware({cdnUrl}) {
if (!cdnUrl) {
throw new Error(`Missing parameter "cdnUrl"`);
}
if (cdnUrl.endsWith("/")) {
throw new Error(`Parameter "cdnUrl" must not end with a slash`);
}

return function proxy(req, res, next) {
if (req.method !== "GET" && req.method !== "HEAD" && req.method !== "OPTIONS") {
// Cannot be fulfilled by CDN
next();
return;
}

log.verbose(`Requesting ${req.url} from CDN ${cdnUrl}...`);
log.verbose(`Orig. URL: ${req.originalUrl}`);

getResource({
cdnUrl,
resourcePath: req.url,
resolveOnOddStatusCode: true,
headers: req.headers
}).then(({data, headers, statusCode}) => {
if (statusCode !== 200) {
// odd status code
log.verbose(`CDN replied with status code ${statusCode} for request ${req.url}`);
next();
return;
}
if (headers) {
for (const headerKey in headers) {
if (headers.hasOwnProperty(headerKey)) {
res.setHeader(headerKey, headers[headerKey]);
}
}
}

res.setHeader("x-ui5-tooling-proxied-from-cdn", cdnUrl);
res.setHeader("x-ui5-tooling-proxied-as", req.url);

res.send(data);
}).catch((err) => {
log.error(`CDN request error: ${err.message}`);
next(err);
});
};
}

const cache = {};

function getResource({cdnUrl, resourcePath, resolveOnOddStatusCode, headers}) {
return new Promise((resolve, reject) => {
const reqUrl = cdnUrl + resourcePath;
if (cache[reqUrl]) {
resolve(cache[reqUrl]);
}
if (!cdnUrl.startsWith("http")) {
throw new Error(`CDN URL must start with protocol "http" or "https": ${cdnUrl}`);
}
let client = http;
if (cdnUrl.startsWith("https")) {
client = https;
}
client.get(reqUrl, (cdnResponse) => {
const {statusCode} = cdnResponse;

const data = [];
cdnResponse.on("data", (chunk) => {
data.push(chunk);
});
cdnResponse.on("end", () => {
try {
const result = {
data: Buffer.concat(data),
statusCode,
headers: cdnResponse.headers
};
cache[reqUrl] = result;
if (Object.keys(cache).length % 10 === 0) {
log.verbose(`Cache size: ${Object.keys(cache).length} entries`);
}
resolve(result);
} catch (err) {
reject(err);
}
});
}).on("error", (err) => {
reject(err);
});
});
}

module.exports = createMiddleware;
module.exports.getResource = getResource;
4 changes: 3 additions & 1 deletion lib/middleware/middlewareRepository.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ const middlewareInfos = {
connectUi5Proxy: {path: "./connectUi5Proxy"},
serveThemes: {path: "./serveThemes"},
testRunner: {path: "./testRunner"},
nonReadRequests: {path: "./nonReadRequests"}
nonReadRequests: {path: "./nonReadRequests"},
proxy: {path: "./proxy"},
proxyRewrite: {path: "./proxyRewrite"}
};

function getMiddleware(middlewareName) {
Expand Down
55 changes: 55 additions & 0 deletions lib/middleware/proxy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
const log = require("@ui5/logger").getLogger("server:middleware:proxy");
const httpProxy = require("http-proxy");

function createMiddleware({configuration}) {
let agent;

if (configuration.forwardProxy) {
let username = configuration.forwardProxy.username;
let password = configuration.forwardProxy.password;
if (!username) {
// TODO prompt user for credentials
username = "";
}
if (!password) {
// TODO prompt user for credentials
password = "";
}
const HttpsProxyAgent = require("https-proxy-agent");
agent = new HttpsProxyAgent({
host: configuration.forwardProxy.hostname,
port: configuration.forwardProxy.port,
secureProxy: configuration.forwardProxy.useSsl,
auth: username + ":" + password
});
}

const proxyServer = httpProxy.createProxyServer({
agent: agent,
secure: !configuration.insecure,
prependPath: false,
xfwd: true,
target: configuration.destination.origin,
changeOrigin: true
});

proxyServer.on("proxyRes", function(proxyRes, req, res) {
res.setHeader("x-ui5-tooling-proxied-from", configuration.destination.origin);
});

return function proxy(req, res, next) {
if (req.url !== req.originalUrl) {
log.verbose(`Proxying "${req.url}"`); // normalized URL - used for local resolution
log.verbose(` as "${req.originalUrl}"`); // original URL - used for reverse proxy requests
} else {
log.verbose(`Proxying "${req.url}"`);
}
req.url = req.originalUrl; // Always use the original (non-rewritten) URL
proxyServer.web(req, res, (err) => {
log.error(`Proxy error: ${err.message}`);
next(err);
});
};
}

module.exports = createMiddleware;
Loading