From b7cb0e01e97d54be9183a1dae9d2c6e766089913 Mon Sep 17 00:00:00 2001 From: Isaac Hill <71404865+isaachilly@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:31:00 +0100 Subject: [PATCH 1/5] Add configurable API authentication routes Add optional api auth routes, plus a frontend session redirect to start login when no token is present. Add tests to cover the new auth flows. --- Framework/Backend/http/server.js | 13 +++++ Framework/Backend/test/mocha-http.js | 45 +++++++++++++++- Framework/Frontend/js/src/sessionService.js | 16 ++++-- Framework/Frontend/test/index-test.js | 2 +- Framework/Frontend/test/mocha-index.js | 59 +++++++++++++++++++++ Framework/docs/guide/http-server.md | 8 ++- Framework/docs/guide/openid.md | 2 +- 7 files changed, 138 insertions(+), 7 deletions(-) diff --git a/Framework/Backend/http/server.js b/Framework/Backend/http/server.js index 6b447b72c6..f5a4a7ebcf 100644 --- a/Framework/Backend/http/server.js +++ b/Framework/Backend/http/server.js @@ -34,6 +34,7 @@ class HttpServer { /** * Sets up the server, routes and binds HTTP and HTTPS sockets. * @param {object} httpConfig - configuration of HTTP server + * @param {boolean} [httpConfig.apiAuthRoutes] - registers "/api/login" and "/api/callback" when true * @param {object} [jwtConfig] - configuration of JWT * @param {object} [connectIdConfig] - configuration of OpenID Connect */ @@ -45,6 +46,7 @@ class HttpServer { httpConfig.tls = !httpConfig.tls ? false : httpConfig.tls; httpConfig.hostname = !httpConfig.hostname ? 'localhost' : httpConfig.hostname; this.limit = !httpConfig.limit ? '100kb' : httpConfig.limit; + this.apiAuthRoutes = Boolean(httpConfig.apiAuthRoutes); this.app = express(); @@ -201,6 +203,17 @@ class HttpServer { this.app.get('/', (req, res, next) => this.addDefaultUserData(req, res, next)); } + if (this.apiAuthRoutes) { + if (this.openid) { + this.app.get('/api/callback', (req, res) => this.identCallback(req, res)); + } + + this.app.get('/api/login', (req, res) => { + delete req.query.token; + return this.openid ? this.ident(req, res) : this.addDefaultUserData(req, res); + }); + } + // Router for static files (can grow with addStaticPath) this.routerStatics = express.Router(); diff --git a/Framework/Backend/test/mocha-http.js b/Framework/Backend/test/mocha-http.js index 8590804669..cfcac10221 100644 --- a/Framework/Backend/test/mocha-http.js +++ b/Framework/Backend/test/mocha-http.js @@ -39,7 +39,7 @@ const token = tokenService.generateToken(0, 'test', 'Test', 'admin'); describe('REST API', () => { before(() => { - httpServer = new HttpServer(config.http, config.jwt); + httpServer = new HttpServer({ ...config.http, apiAuthRoutes: true }, config.jwt); httpServer.get('/get-insecure', (req, res) => res.json({ ok: 1 }), { public: true }); httpServer.get('/get-authenticated-insecure', (req, res) => res.json({ session: req.session }), { public: true }); httpServer.get('/get-request', (req, res) => res.json({ ok: 1 })); @@ -87,6 +87,49 @@ describe('REST API', () => { }); }); + it('GET "/api/login" should redirect to "/" with the session and the given query', async () => { + const res = await request(httpServer) + .get('/api/login?q=HelloTest') + .expect(302); + + const parsedUrl = new url.URL(res.headers.location, 'http://localhost'); + assert.strictEqual(parsedUrl.pathname, '/'); + assert.strictEqual(parsedUrl.searchParams.get('q'), 'HelloTest'); + assert.strictEqual(parsedUrl.searchParams.get('personid'), '0'); + assert.ok(tokenService.verify(parsedUrl.searchParams.get('token'))); + }); + + it('GET "/api/login" with a valid token should ignore it and start a new session', async () => { + const res = await request(httpServer) + .get(`/api/login?token=${token}&personid=42&username=spoofed&q=HelloTest`) + .expect(302); + + const parsedUrl = new url.URL(res.headers.location, 'http://localhost'); + assert.strictEqual(parsedUrl.pathname, '/'); + assert.notStrictEqual(parsedUrl.searchParams.get('token'), token); + assert.strictEqual(tokenService.verify(parsedUrl.searchParams.get('token')).username, 'anonymous'); + assert.strictEqual(parsedUrl.searchParams.get('personid'), '0'); + assert.strictEqual(parsedUrl.searchParams.get('username'), 'anonymous'); + assert.strictEqual(parsedUrl.searchParams.get('q'), 'HelloTest'); + }); + + it('GET "/api/login" with an invalid token should ignore it and start a new session', async () => { + const res = await request(httpServer) + .get('/api/login?token=invalid') + .expect(302); + + const parsedUrl = new url.URL(res.headers.location, 'http://localhost'); + assert.strictEqual(parsedUrl.pathname, '/'); + assert.ok(tokenService.verify(parsedUrl.searchParams.get('token'))); + }); + + it('GET "/api/login" should respond 404 when "apiAuthRoutes" is not enabled', async () => { + const serverWithoutAuthRoutes = new HttpServer({ ...config.http, autoListen: false }, config.jwt); + await request(serverWithoutAuthRoutes.app) + .get('/api/login') + .expect(404); + }); + it('GET without token should respond 200/JSON', (done) => { request(httpServer) .get('/api/get-insecure') diff --git a/Framework/Frontend/js/src/sessionService.js b/Framework/Frontend/js/src/sessionService.js index 6084b1cdf5..512b831236 100644 --- a/Framework/Frontend/js/src/sessionService.js +++ b/Framework/Frontend/js/src/sessionService.js @@ -21,7 +21,7 @@ const { history } = window; * These are the parameters coming from the server only and represent * the current session */ -const authentificationParametersNames = ['personid', 'name', 'token', 'username', 'access']; +const authenticationParametersNames = ['personid', 'name', 'token', 'username', 'access']; /** * Class to store authenticated users's session and provide session-related services @@ -37,15 +37,24 @@ export class SessionService { /** * Load parameters from the query string inside sessionService * and remove them from the query string. + * @param {object} [options] - optional settings + * @param {string} [options.loginUrl] - where to send the browser if there is no token + * @return {boolean} true if loaded, false if redirecting */ - loadAndHideParameters() { + loadAndHideParameters({ loginUrl } = {}) { if (this.session) { throw new Error('the session is already loaded'); } const url = new URL(location); + + if (loginUrl && !url.searchParams.get('token')) { + location.assign(`${loginUrl}${url.search}`); + return false; + } + this.session = {}; - for (const authenticationParameterName of authentificationParametersNames) { + for (const authenticationParameterName of authenticationParametersNames) { const authenticationParameter = url.searchParams.get(authenticationParameterName); if (!authenticationParameter) { @@ -60,6 +69,7 @@ export class SessionService { } history.replaceState({}, '', url); + return true; } /** diff --git a/Framework/Frontend/test/index-test.js b/Framework/Frontend/test/index-test.js index 6251fda07d..f4b1fcfd38 100644 --- a/Framework/Frontend/test/index-test.js +++ b/Framework/Frontend/test/index-test.js @@ -19,7 +19,7 @@ const path = require('path'); * Reading config file * Start servers */ -const http = new HttpServer({ hostname: 'localhost', port: 8085 }, {}); +const http = new HttpServer({ hostname: 'localhost', port: 8085, apiAuthRoutes: true }, {}); http.addStaticPath(path.join(__dirname, 'public')); http.post('/ok.json', replyWithOk); diff --git a/Framework/Frontend/test/mocha-index.js b/Framework/Frontend/test/mocha-index.js index 7e1e1223d7..92b0886fa5 100644 --- a/Framework/Frontend/test/mocha-index.js +++ b/Framework/Frontend/test/mocha-index.js @@ -372,6 +372,65 @@ describe('Framework Frontend', function() { }); }); + describe('sessionService login api login redirect', function() { + let loginPage; // Separate page as the redirect reloads it, which would lose the state of the other tests + + beforeEach(async () => { + loginPage = await browser.newPage(); + await loginPage.goto(`http://localhost:${port}`, {waitUntil: 'networkidle0'}); + }); + + afterEach(async () => { + await loginPage.close(); + }); + + it('should redirect to the login without a token and come back with a new session', async () => { + const navigation = loginPage.waitForNavigation({waitUntil: 'networkidle0'}); + const {loaded, session} = await loginPage.evaluate(() => { + history.replaceState({}, '', '/?personid=9&q=HelloTest'); + const service = new window.sessionService.constructor(); + const loaded = service.loadAndHideParameters({loginUrl: '/api/login'}); + return {loaded, session: service.session}; + }); + await navigation; + + assert.strictEqual(loaded, false); + assert.strictEqual(session, null); + + const {search, personid} = await loginPage.evaluate(() => ({ + search: location.search, + personid: window.sessionService.get().personid, + })); + assert.strictEqual(search, '?q=HelloTest'); + assert.strictEqual(personid, '0'); + }); + + it('should load the session without redirecting when there is a token', async () => { + const {loaded, token} = await loginPage.evaluate(() => { + history.replaceState({}, '', '/?personid=1&name=Test&token=abc&username=test&access=admin'); + const service = new window.sessionService.constructor(); + const loaded = service.loadAndHideParameters({loginUrl: '/api/login'}); + return {loaded, token: service.get().token}; + }); + + assert.strictEqual(loaded, true); + assert.strictEqual(token, 'abc'); + }); + + it('should throw without a token when no login URL is given', async () => { + const message = await loginPage.evaluate(() => { + history.replaceState({}, '', '/'); + try { + new window.sessionService.constructor().loadAndHideParameters(); + } catch (error) { + return error.message; + } + }); + + assert.strictEqual(message, 'query string should contain the parameter personid'); + }); + }); + describe('BrowserStorage class', function() { it('should successfully set (key,value) in localStorage & sessionStorage', async () => { const storage = await page.evaluate(async () => { diff --git a/Framework/docs/guide/http-server.md b/Framework/docs/guide/http-server.md index 59ee7613ce..bb4541aa58 100644 --- a/Framework/docs/guide/http-server.md +++ b/Framework/docs/guide/http-server.md @@ -9,7 +9,7 @@ #### Instance ```js const {HttpServer} = require('@aliceo2/web-ui'); -HttpServer({port: PORT, hostname: HOSTNAME, tls: TLS_ENABLED, portSecure: HTTPS_PORT, key: TLS_KEY, cert: TLS_CERT, autoListen: AUTO_LISTEN}, JWT_CONF, OPENID_CONF); +HttpServer({port: PORT, hostname: HOSTNAME, tls: TLS_ENABLED, portSecure: HTTPS_PORT, key: TLS_KEY, cert: TLS_CERT, autoListen: AUTO_LISTEN, apiAuthRoutes: API_AUTH_ROUTES}, JWT_CONF, OPENID_CONF); ``` Where: * `HTTP_CONF` consists of following fields: @@ -26,9 +26,15 @@ Where: * [`allowBlobImages`] - adds `blob:` to `img-src` so blob-based images can be previewed/downloaded (default: `false`) * [`allowIframeCsp`] - **deprecated**, use `allowBlobImages`; * [`extraConnectSrc`] - sources appended to the default `connect-src` CSP directive (default: `[]`) + * [`API_AUTH_ROUTES`] - registers the authentication routes under `/api` (see below) (default: `false`) * [`JWT_CONF`] - JWT module config, see [JWT module](json-tokens.md) * [`OPENID_CONF`] - OpenID config, see [OpenID Connect module](openid.md) +#### Authentication routes +Registered only when `apiAuthRoutes` is `true`, so a reverse proxy can forward a single `/api` rule: + * `GET /api/login` - always starts a fresh login, ignoring any `token` in the query. With OpenID it redirects to the SSO, otherwise to `/` with a new anonymous session. The rest of the query is passed back to `/`. + * `GET /api/callback` - OpenID callback under `/api`, used when the SSO "Redirect URI" points to it (see [OpenID Connect module](openid.md)) + #### Public methods ```js diff --git a/Framework/docs/guide/openid.md b/Framework/docs/guide/openid.md index 4c6f6a2298..314421e4d6 100644 --- a/Framework/docs/guide/openid.md +++ b/Framework/docs/guide/openid.md @@ -31,7 +31,7 @@ openId: { 2. Register your application 3. Add "SSO Registration" 4. Select "OpenID Connect (OIDC)" -5. Set "Redirect URI": eg. `https://myapp.cern.ch/callback` +5. Set "Redirect URI": eg. `https://myapp.cern.ch/callback` or, with `apiAuthRoutes` enabled in the HTTP config, `https://myapp.cern.ch/api/callback` 6. Submit (do not check any boxes) ### Roles and e-group authorisation From 79ea54f4f3db46f455f278d2dea8ed9301b201cc Mon Sep 17 00:00:00 2001 From: Isaac Hill <71404865+isaachilly@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:45:24 +0100 Subject: [PATCH 2/5] Fix failing test, send valid token so passes api/ router middleware When the /api/login path is not registered the router falls back to /api, /api requires auth in its middleware and thus we get 403 not 404. --- Framework/Backend/test/mocha-http.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Framework/Backend/test/mocha-http.js b/Framework/Backend/test/mocha-http.js index cfcac10221..295b758d95 100644 --- a/Framework/Backend/test/mocha-http.js +++ b/Framework/Backend/test/mocha-http.js @@ -126,7 +126,7 @@ describe('REST API', () => { it('GET "/api/login" should respond 404 when "apiAuthRoutes" is not enabled', async () => { const serverWithoutAuthRoutes = new HttpServer({ ...config.http, autoListen: false }, config.jwt); await request(serverWithoutAuthRoutes.app) - .get('/api/login') + .get(`/api/login?token=${token}`) .expect(404); }); From 87f25a3349f60138868a801048bfb5617a5a87e2 Mon Sep 17 00:00:00 2001 From: Isaac Hill <71404865+isaachilly@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:16:53 +0100 Subject: [PATCH 3/5] Fix login redirect test racing the navigation Redirect read result from evaluate that triggers the navigation. Catch this error and also store the result in session storage. --- Framework/Frontend/test/mocha-index.js | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/Framework/Frontend/test/mocha-index.js b/Framework/Frontend/test/mocha-index.js index 92b0886fa5..08c6844eb2 100644 --- a/Framework/Frontend/test/mocha-index.js +++ b/Framework/Frontend/test/mocha-index.js @@ -386,14 +386,25 @@ describe('Framework Frontend', function() { it('should redirect to the login without a token and come back with a new session', async () => { const navigation = loginPage.waitForNavigation({waitUntil: 'networkidle0'}); - const {loaded, session} = await loginPage.evaluate(() => { + // The redirect destroys this page's context, so the result is kept in sessionStorage, which survives it + await loginPage.evaluate(() => { history.replaceState({}, '', '/?personid=9&q=HelloTest'); const service = new window.sessionService.constructor(); const loaded = service.loadAndHideParameters({loginUrl: '/api/login'}); - return {loaded, session: service.session}; + sessionStorage.setItem('redirectTestData', JSON.stringify({loaded, session: service.session})); + }).catch((error) => { + if (!error.message.includes('Execution context was destroyed')) { + throw error; + } }); await navigation; + const {loaded, session} = await loginPage.evaluate(() => { + const data = JSON.parse(sessionStorage.getItem('redirectTestData')); + sessionStorage.removeItem('redirectTestData'); + return data; + }); + assert.strictEqual(loaded, false); assert.strictEqual(session, null); From cc367058d10d3f36a1f2b16cc048349249a793ee Mon Sep 17 00:00:00 2001 From: Isaac Hill <71404865+isaachilly@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:38:02 +0100 Subject: [PATCH 4/5] Fix test as waitForNavigation also resolves on navigations such as replaceState --- Framework/Frontend/test/mocha-index.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Framework/Frontend/test/mocha-index.js b/Framework/Frontend/test/mocha-index.js index 08c6844eb2..05da27be44 100644 --- a/Framework/Frontend/test/mocha-index.js +++ b/Framework/Frontend/test/mocha-index.js @@ -385,7 +385,8 @@ describe('Framework Frontend', function() { }); it('should redirect to the login without a token and come back with a new session', async () => { - const navigation = loginPage.waitForNavigation({waitUntil: 'networkidle0'}); + // waitForNavigation also resolves on replaceState same-document calls + const navigation = loginPage.waitForNavigation({waitUntil: 'networkidle0', ignoreSameDocumentNavigation: true}); // The redirect destroys this page's context, so the result is kept in sessionStorage, which survives it await loginPage.evaluate(() => { history.replaceState({}, '', '/?personid=9&q=HelloTest'); From 1d758b35499152e5bb58db071110d1eadd91d60c Mon Sep 17 00:00:00 2001 From: Isaac Hill <71404865+isaachilly@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:38:27 +0100 Subject: [PATCH 5/5] Remove extra space --- Framework/Frontend/test/mocha-index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Framework/Frontend/test/mocha-index.js b/Framework/Frontend/test/mocha-index.js index 05da27be44..b1b4797b40 100644 --- a/Framework/Frontend/test/mocha-index.js +++ b/Framework/Frontend/test/mocha-index.js @@ -386,7 +386,7 @@ describe('Framework Frontend', function() { it('should redirect to the login without a token and come back with a new session', async () => { // waitForNavigation also resolves on replaceState same-document calls - const navigation = loginPage.waitForNavigation({waitUntil: 'networkidle0', ignoreSameDocumentNavigation: true}); + const navigation = loginPage.waitForNavigation({waitUntil: 'networkidle0', ignoreSameDocumentNavigation: true}); // The redirect destroys this page's context, so the result is kept in sessionStorage, which survives it await loginPage.evaluate(() => { history.replaceState({}, '', '/?personid=9&q=HelloTest');