feat: support k8s proxy working fine with cluster url has subpath

Signed-off-by: rui ma <ruima@alauda.io>
This commit is contained in:
rui ma
2023-07-05 21:52:05 +08:00
parent 6073ecc5f5
commit be6395601d
3 changed files with 56 additions and 1 deletions
@@ -638,4 +638,46 @@ describe('KubernetesProxy', () => {
expect(response.status).toEqual(500);
});
it('should get res through proxy with cluster url has sub path', async () => {
worker.use(
rest.get(
'http://localhost:9999/subpath/api/v1/namespaces',
(_req, res, ctx) => {
return res(
ctx.status(200),
ctx.json({
kind: 'NamespaceList',
apiVersion: 'v1',
items: [],
}),
);
},
),
);
permissionApi.authorize.mockResolvedValue([
{ result: AuthorizeResult.ALLOW },
]);
clusterSupplier.getClusters.mockResolvedValue([
{
name: 'cluster1',
url: 'http://localhost:9999/subpath',
authProvider: '',
},
]);
authTranslator.decorateClusterDetailsWithAuth.mockImplementation(
async x => x,
);
const app = express().use(
Router().use('/mountpath', proxy.createRequestHandler({ permissionApi })),
);
const requestPromise = request(app)
.get('/mountpath/api/v1/namespaces')
.set(HEADER_KUBERNETES_CLUSTER, 'cluster1');
worker.use(rest.all(requestPromise.url, (req: any) => req.passthrough()));
const response = await requestPromise;
expect(response.status).toEqual(200);
});
});
@@ -138,7 +138,15 @@ export class KubernetesProxy {
ws: true,
secure: !originalCluster.skipTLSVerify,
changeOrigin: true,
pathRewrite: { [`^${originalReq.baseUrl}`]: '' },
pathRewrite: async (path, req) => {
// Re-evaluate the cluster on each request, in case it has changed
const cluster = await this.getClusterForRequest(req);
const url = new URL(cluster.url);
return path.replace(
new RegExp(`^${originalReq.baseUrl}`),
url.pathname || '',
);
},
router: async req => {
// Re-evaluate the cluster on each request, in case it has changed
const cluster = await this.getClusterForRequest(req);