diff --git a/plugins/gateway-backend/.eslintrc.js b/plugins/gateway-backend/.eslintrc.js new file mode 100644 index 0000000000..e2a53a6ad2 --- /dev/null +++ b/plugins/gateway-backend/.eslintrc.js @@ -0,0 +1 @@ +module.exports = require('@backstage/cli/config/eslint-factory')(__dirname); diff --git a/plugins/gateway-backend/catalog-info.yaml b/plugins/gateway-backend/catalog-info.yaml new file mode 100644 index 0000000000..880b0d4a25 --- /dev/null +++ b/plugins/gateway-backend/catalog-info.yaml @@ -0,0 +1,9 @@ +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: backstage-plugin-gateway-backend + title: '@backstage/plugin-gateway-backend' +spec: + lifecycle: experimental + type: backstage-backend-plugin + owner: maintainers diff --git a/plugins/gateway-backend/package.json b/plugins/gateway-backend/package.json new file mode 100644 index 0000000000..c4549cc482 --- /dev/null +++ b/plugins/gateway-backend/package.json @@ -0,0 +1,49 @@ +{ + "name": "@backstage/plugin-gateway-backend", + "version": "1.0.0", + "backstage": { + "role": "backend-plugin" + }, + "publishConfig": { + "access": "public", + "main": "dist/index.cjs.js", + "types": "dist/index.d.ts" + }, + "private": true, + "license": "Apache-2.0", + "main": "src/index.ts", + "types": "src/index.ts", + "files": [ + "dist" + ], + "scripts": { + "build": "backstage-cli package build", + "clean": "backstage-cli package clean", + "lint": "backstage-cli package lint", + "prepack": "backstage-cli package prepack", + "postpack": "backstage-cli package postpack", + "start": "backstage-cli package start", + "test": "backstage-cli package test" + }, + "dependencies": { + "@backstage/backend-defaults": "workspace:^", + "@backstage/backend-plugin-api": "workspace:^", + "@backstage/catalog-client": "workspace:^", + "@backstage/errors": "workspace:^", + "@backstage/plugin-catalog-node": "workspace:^", + "@opentelemetry/api": "^1.9.0", + "@opentelemetry/core": "^2.0.0", + "express": "^4.17.1", + "express-promise-router": "^4.1.0", + "http-proxy-middleware": "^3.0.3", + "zod": "^3.22.4" + }, + "devDependencies": { + "@backstage/backend-app-api": "workspace:^", + "@backstage/backend-test-utils": "workspace:^", + "@backstage/cli": "workspace:^", + "@types/express": "^4.17.6", + "@types/supertest": "^2.0.8", + "supertest": "^6.2.4" + } +} diff --git a/plugins/gateway-backend/src/index.ts b/plugins/gateway-backend/src/index.ts new file mode 100644 index 0000000000..10d01d5f19 --- /dev/null +++ b/plugins/gateway-backend/src/index.ts @@ -0,0 +1,16 @@ +/* + * Copyright 2025 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { gatewayPlugin as default } from './plugin'; diff --git a/plugins/gateway-backend/src/plugin.test.ts b/plugins/gateway-backend/src/plugin.test.ts new file mode 100644 index 0000000000..65cfdc6ad5 --- /dev/null +++ b/plugins/gateway-backend/src/plugin.test.ts @@ -0,0 +1,137 @@ +/* + * Copyright 2025 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { createBackend } from '@backstage/backend-defaults'; +import { Backend } from '@backstage/backend-app-api'; +import { mockServices } from '@backstage/backend-test-utils'; +import { + coreServices, + createBackendPlugin, + createServiceFactory, +} from '@backstage/backend-plugin-api'; +import { Router } from 'express'; + +describe('gateway', () => { + let backend: Backend; + let anotherBackend: Backend; + + const dummyPlugin = createBackendPlugin({ + pluginId: 'dummy', + register(env) { + env.registerInit({ + deps: { + httpRouter: coreServices.httpRouter, + }, + async init({ httpRouter }) { + const router = Router(); + router.get('/foo', (_req, res) => { + res.json({ foo: true }); + }); + + httpRouter.use(router); + }, + }); + }, + }); + + const discovery = mockServices.discovery.mock(); + + beforeAll(async () => { + backend = createBackend(); + backend.add(mockServices.rootHttpRouter.factory()); + backend.add( + mockServices.rootConfig.factory({ + data: { + backend: { baseUrl: 'http://localhost:7777', listen: { port: 7777 } }, + }, + }), + ); + backend.add(mockServices.auth.factory()); + backend.add(mockServices.httpAuth.factory()); + backend.add( + createServiceFactory({ + service: coreServices.discovery, + deps: {}, + factory: () => discovery, + }), + ); + backend.add(dummyPlugin); + backend.add(import('./')); + + anotherBackend = createBackend(); + anotherBackend.add(mockServices.rootHttpRouter.factory()); + anotherBackend.add( + mockServices.rootConfig.factory({ + data: { + backend: { baseUrl: 'http://localhost:7778', listen: { port: 7778 } }, + }, + }), + ); + anotherBackend.add(mockServices.auth.factory()); + anotherBackend.add(mockServices.httpAuth.factory()); + anotherBackend.add(mockServices.discovery.factory()); + anotherBackend.add( + createBackendPlugin({ + pluginId: 'external-plugin', + register(env) { + env.registerInit({ + deps: { + rootHttpRouter: coreServices.rootHttpRouter, + httpRouter: coreServices.httpRouter, + }, + async init({ httpRouter }) { + const router = Router(); + router.get('/foo', (_req, res) => { + res.json({ bar: true }); + }); + + httpRouter.use(router); + }, + }); + }, + }), + ); + await Promise.all([backend.start(), anotherBackend.start()]); + }, 15_000); + + afterAll(async () => { + await backend.stop(); + await anotherBackend.stop(); + }); + + it('should invoke the endpoint of an installed plugin', async () => { + const response = await fetch('http://localhost:7777/api/dummy/foo'); + expect(response.status).toBe(200); + + const data = await response.json(); + expect(data).toEqual({ foo: true }); + }); + + it('should proxy requests for unknown plugins', async () => { + discovery.getBaseUrl.mockImplementation(async (pluginId: string) => { + if (pluginId === 'external-plugin') { + return 'http://localhost:7778/api/external-plugin'; + } + return `http://localhost:7777/api/${pluginId}`; + }); + const response = await fetch( + 'http://localhost:7777/api/external-plugin/foo', + ); + expect(response.status).toBe(200); + + const data = await response.json(); + expect(data).toEqual({ bar: true }); + }); +}); diff --git a/plugins/gateway-backend/src/plugin.ts b/plugins/gateway-backend/src/plugin.ts new file mode 100644 index 0000000000..94b979d1bc --- /dev/null +++ b/plugins/gateway-backend/src/plugin.ts @@ -0,0 +1,51 @@ +/* + * Copyright 2025 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { + coreServices, + createBackendPlugin, +} from '@backstage/backend-plugin-api'; +import { createRouter } from './router'; +import { instanceMetadataServiceRef } from '@backstage/backend-plugin-api/alpha'; +import { Handler } from 'express'; + +/** + * gateway backend plugin + * + * @public + */ +export const gatewayPlugin = createBackendPlugin({ + pluginId: 'gateway', + register(env) { + env.registerInit({ + deps: { + logger: coreServices.logger, + rootHttpRouter: coreServices.rootHttpRouter, + instanceMeta: instanceMetadataServiceRef, + discovery: coreServices.discovery, + }, + async init({ logger, discovery, instanceMeta, rootHttpRouter }) { + rootHttpRouter.use( + '/api/:pluginId', + createRouter({ + discovery, + instanceMeta, + logger, + }) as Handler, + ); + }, + }); + }, +}); diff --git a/plugins/gateway-backend/src/router.ts b/plugins/gateway-backend/src/router.ts new file mode 100644 index 0000000000..14a4ec0b7d --- /dev/null +++ b/plugins/gateway-backend/src/router.ts @@ -0,0 +1,63 @@ +/* + * Copyright 2025 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DiscoveryService, LoggerService } from '@backstage/backend-plugin-api'; +import { InstanceMetadataService } from '@backstage/backend-plugin-api/alpha'; +import { Request, Response, NextFunction } from 'express'; +import { createProxyMiddleware } from 'http-proxy-middleware'; +import { context } from '@opentelemetry/api'; +import { getRPCMetadata } from '@opentelemetry/core'; + +export function createRouter({ + discovery, + instanceMeta, +}: { + discovery: DiscoveryService; + instanceMeta: InstanceMetadataService; + logger: LoggerService; +}) { + const localPluginIds = new Set( + instanceMeta + .getInstalledFeatures() + .filter(f => f.type === 'plugin') + .map(f => f.pluginId), + ); + + const proxy = createProxyMiddleware({ + changeOrigin: true, + router: async (req: Request<{ pluginId: string }>) => { + const pluginId = req.params.pluginId; + return discovery.getBaseUrl(pluginId); + }, + }); + + return function proxyMiddleware( + req: Request<{ pluginId: string }>, + res: Response, + next: NextFunction, + ) { + if (localPluginIds.has(req.params.pluginId)) { + next(); + return; + } + + const rpcMetadata = getRPCMetadata(context.active()); + if (rpcMetadata) { + rpcMetadata.route = req.baseUrl; + } + + proxy(req, res, next); + }; +} diff --git a/plugins/gateway-backend/src/setupTests.ts b/plugins/gateway-backend/src/setupTests.ts new file mode 100644 index 0000000000..f3a222d4e1 --- /dev/null +++ b/plugins/gateway-backend/src/setupTests.ts @@ -0,0 +1,16 @@ +/* + * Copyright 2025 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {};