diff --git a/src/lib/middleware/bearer-token-middleware.test.ts b/src/lib/middleware/bearer-token-middleware.test.ts index 65addd1048..83d7873962 100644 --- a/src/lib/middleware/bearer-token-middleware.test.ts +++ b/src/lib/middleware/bearer-token-middleware.test.ts @@ -63,4 +63,55 @@ describe('bearerTokenMiddleware', () => { expect(req.headers.authorization).toBe(exampleSignalToken); }); + + it('should always run for signal endpoint, regardless of the flag', () => { + const configWithBearerTokenMiddlewareFlagDisabled = createTestConfig({ + getLogger, + experimental: { + flags: { + bearerTokenMiddleware: false, + }, + }, + }); + + const middleware = bearerTokenMiddleware( + configWithBearerTokenMiddlewareFlagDisabled, + ); + + req.path = '/api/signal-endpoint/'; + + const bearerToken = `Bearer ${exampleSignalToken}`; + req.headers = { authorization: bearerToken }; + + middleware(req, res, next); + + expect(req.headers.authorization).toBe(exampleSignalToken); + }); + + it('should always run for signal endpoint, regardless of the flag, supporting instance path', () => { + const configWithBearerTokenMiddlewareFlagDisabled = createTestConfig({ + getLogger, + server: { + baseUriPath: '/some-test-instance', + }, + experimental: { + flags: { + bearerTokenMiddleware: false, + }, + }, + }); + + const middleware = bearerTokenMiddleware( + configWithBearerTokenMiddlewareFlagDisabled, + ); + + req.path = '/some-test-instance/api/signal-endpoint/'; + + const bearerToken = `Bearer ${exampleSignalToken}`; + req.headers = { authorization: bearerToken }; + + middleware(req, res, next); + + expect(req.headers.authorization).toBe(exampleSignalToken); + }); }); diff --git a/src/lib/middleware/bearer-token-middleware.ts b/src/lib/middleware/bearer-token-middleware.ts index 1d4b1baeb0..4b805d83a9 100644 --- a/src/lib/middleware/bearer-token-middleware.ts +++ b/src/lib/middleware/bearer-token-middleware.ts @@ -2,15 +2,17 @@ import type { Request, Response, NextFunction } from 'express'; import type { IUnleashConfig } from '../types'; export const bearerTokenMiddleware = ({ + server, getLogger, flagResolver, -}: Pick) => { +}: Pick) => { const logger = getLogger('/middleware/bearer-token-middleware.ts'); logger.debug('Enabling bearer token middleware'); + const baseUriPath = server.baseUriPath || ''; return (req: Request, _: Response, next: NextFunction) => { if ( - req.path.startsWith('/api/signal-endpoint/') || + req.path.startsWith(`${baseUriPath}/api/signal-endpoint/`) || flagResolver.isEnabled('bearerTokenMiddleware') ) { const authHeader = req.headers.authorization;