diff --git a/Framework/Backend/http/server.js b/Framework/Backend/http/server.js index 6b447b72c..f5a4a7ebc 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 859080466..295b758d9 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?token=${token}`) + .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 6084b1cdf..512b83123 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 6251fda07..f4b1fcfd3 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 7e1e1223d..b1b4797b4 100644 --- a/Framework/Frontend/test/mocha-index.js +++ b/Framework/Frontend/test/mocha-index.js @@ -372,6 +372,77 @@ 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 () => { + // 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'); + const service = new window.sessionService.constructor(); + const loaded = service.loadAndHideParameters({loginUrl: '/api/login'}); + 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); + + 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 59ee7613c..bb4541aa5 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 4c6f6a229..314421e4d 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