From 683aed20a75a084d9b682d265b523957a6d94483 Mon Sep 17 00:00:00 2001 From: Jari Kolehmainen Date: Thu, 23 Sep 2021 07:34:50 +0300 Subject: [PATCH] fix Signed-off-by: Jari Kolehmainen --- src/common/k8s-api/index.ts | 2 +- src/common/k8s-api/json-api.ts | 5 ++++- src/main/lens-proxy.ts | 16 +++++++++++++--- 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/src/common/k8s-api/index.ts b/src/common/k8s-api/index.ts index e1865f3d52..5a07454732 100644 --- a/src/common/k8s-api/index.ts +++ b/src/common/k8s-api/index.ts @@ -48,7 +48,7 @@ if (typeof window === "undefined") { }); } else { apiBase = new JsonApi({ - serverAddress: `http://localhost:${window.location.port}`, + serverAddress: `http://${window.location.host}`, apiBase: apiPrefix, debug: isDevelopment || isDebugging, }); diff --git a/src/common/k8s-api/json-api.ts b/src/common/k8s-api/json-api.ts index 9f59ba9e6c..a52f37d13c 100644 --- a/src/common/k8s-api/json-api.ts +++ b/src/common/k8s-api/json-api.ts @@ -21,6 +21,7 @@ // Base http-service / json-api class +import { randomBytes } from "crypto"; import { merge } from "lodash"; import nodeFetch, { Response as NodeResponse, RequestInit as NodeRequestInit } from "node-fetch"; import { stringify } from "querystring"; @@ -83,8 +84,10 @@ export class JsonApi { protected getRequestUrl(path: string, useSubdomain = false) { if (window) { + const subdomain = useSubdomain ? `${randomBytes(2).toString("hex")}.` : ""; + const url = new URL(this.config.serverAddress); - return `${this.config.apiBase}${path}`; + return `${url.protocol}//${subdomain}${url.host}${this.config.apiBase}${path}`; } else { return `${this.config.serverAddress}${this.config.apiBase}${path}`; } diff --git a/src/main/lens-proxy.ts b/src/main/lens-proxy.ts index 3cd5182677..be42227271 100644 --- a/src/main/lens-proxy.ts +++ b/src/main/lens-proxy.ts @@ -185,15 +185,25 @@ export class LensProxy extends Singleton { } protected async handleRequest(req: http.IncomingMessage, res: http.ServerResponse) { + // allow to fetch apis in "clusterId.localhost:port" from "localhost:port" + // this should be safe because we have already validated cluster uuid + + res.setHeader("Access-Control-Allow-Origin", "*"); + res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS"); + res.setHeader("Access-Control-Allow-Headers", "Content-Type, X-Cluster-Id"); + + if (req.method === "OPTIONS") { + res.end(); + + return; + } + const cluster = this.getClusterForRequest(req); if (cluster) { const proxyTarget = await this.getProxyTarget(req, cluster.contextHandler); if (proxyTarget) { - // allow to fetch apis in "clusterId.localhost:port" from "localhost:port" - // this should be safe because we have already validated cluster uuid - res.setHeader("Access-Control-Allow-Origin", "*"); return this.proxy.web(req, res, proxyTarget); }