diff --git a/Framework/Backend/http/server.js b/Framework/Backend/http/server.js index 54cbd06d4..f0d596f83 100644 --- a/Framework/Backend/http/server.js +++ b/Framework/Backend/http/server.js @@ -25,6 +25,11 @@ const url = require('url'); const { LogManager } = require('../log/LogManager'); const { buildUrl } = require('./buildUrl.js'); +/** + * Query parameters set only by the server + */ +const AUTH_QUERY_PARAMS = ['personid', 'name', 'username', 'access', 'token']; + /** * HTTPS server verifies identity using OpenID Connect and provides REST API. * Each request is authenticated with JWT token. @@ -193,6 +198,14 @@ class HttpServer { this.app.get('/', (req, res, next) => this.addDefaultUserData(req, res, next)); } + // Mounted before the API routers so these routes skip JWT verification + this.routerAuth = express.Router(); + this.routerAuth.get('/login', (req, res) => this.startLogin(req, res)); + if (this.openid) { + this.routerAuth.get('/callback', (req, res) => this.identCallback(req, res)); + } + this.app.use('/api/auth', this.routerAuth); + // Router for static files (can grow with addStaticPath) this.routerStatics = express.Router(); @@ -281,6 +294,24 @@ class HttpServer { return this.ident(req, res, next); } + /** + * Starts a fresh login (/api/auth/login), ignoring any session parameters in the query. + * The rest of the query is passed back to "/" once logged in. + * @param {Request} req - Express Request object + * @param {Response} res - Express Response object + * @return {object} redirection + */ + startLogin(req, res) { + const query = Object.fromEntries(Object.entries(req.query) + .filter(([key]) => !AUTH_QUERY_PARAMS.includes(key))); + + if (this.openid) { + const state = Buffer.from(JSON.stringify(query)).toString('base64'); + return res.redirect(this.openid.getAuthUrl(state)); + } + return this.addDefaultUserData({ query }, res); + } + /** * Serves local static file or directory under defined URI * @param {string} localPath - local directory to be served @@ -488,10 +519,8 @@ class HttpServer { // Read back user params from state const userQuery = JSON.parse(Buffer.from(req.query.state, 'base64').toString('ascii')); - // Concatenates with user query - Object.assign(query, userQuery); - - res.redirect(buildUrl('/', query)); + // Session parameters set by the server take precedence over the user's + res.redirect(buildUrl('/', { ...userQuery, ...query })); }).catch((reason) => { this.logger.errorMessage(`OpenId failed: ${reason}`); res.status(401).send('OpenId failed'); diff --git a/Framework/Backend/test/mocha-http.js b/Framework/Backend/test/mocha-http.js index 859080466..633749ca1 100644 --- a/Framework/Backend/test/mocha-http.js +++ b/Framework/Backend/test/mocha-http.js @@ -87,6 +87,76 @@ describe('REST API', () => { }); }); + it('GET "/api/auth/login" should redirect to "/" with the session and the given query', async () => { + const res = await request(httpServer) + .get('/api/auth/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/auth/login" with a valid token should ignore it and start a new session', async () => { + const res = await request(httpServer) + .get(`/api/auth/login?token=${token}&personid=42&username=spoofed&access=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('access'), 'admin'); + assert.strictEqual(parsedUrl.searchParams.get('q'), 'HelloTest'); + }); + + it('GET "/api/auth/login" with an invalid token should ignore it and start a new session', async () => { + const res = await request(httpServer) + .get('/api/auth/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/auth/login" with OpenID should keep only the user query in the state', async () => { + const server = new HttpServer({ ...config.http, autoListen: false }, config.jwt); + server.openid = { getAuthUrl: (state) => `https://sso.example/auth?state=${state}` }; + + const res = await request(server.app) + .get(`/api/auth/login?token=${token}&personid=42&name=Spoofed&username=spoofed&access=admin&q=HelloTest`) + .expect(302); + + const state = new url.URL(res.headers.location).searchParams.get('state'); + assert.deepStrictEqual(JSON.parse(Buffer.from(state, 'base64').toString()), { q: 'HelloTest' }); + }); + + it('OpenID callback should not let the state override the session set by the server', async () => { + const server = new HttpServer({ ...config.http, autoListen: false }, config.jwt); + server.openid = { + callback: async () => ({ + claims: () => ({ cern_person_id: 7, cern_upn: 'real', name: 'Real', cern_roles: ['guest'] }), + }), + }; + const state = Buffer.from(JSON.stringify({ personid: '42', access: 'admin', q: 'HelloTest' })).toString('base64'); + + const location = await new Promise((resolve, reject) => server.identCallback( + { query: { state }, headers: {} }, + { redirect: resolve, status: () => ({ send: reject }) }, + )); + + const parsedUrl = new url.URL(location, 'http://localhost'); + assert.strictEqual(parsedUrl.searchParams.get('personid'), '7'); + assert.strictEqual(parsedUrl.searchParams.get('username'), 'real'); + assert.strictEqual(parsedUrl.searchParams.get('access'), 'guest'); + assert.strictEqual(parsedUrl.searchParams.get('q'), 'HelloTest'); + }); + 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..cdba7f429 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,27 @@ export class SessionService { /** * Load parameters from the query string inside sessionService * and remove them from the query string. + * Without a token, redirects to the login and throws to stop the caller while the page unloads. + * @return {void} + * @throws {Error} when there is no token (redirecting) or a session parameter is missing */ loadAndHideParameters() { if (this.session) { throw new Error('the session is already loaded'); } const url = new URL(location); + + if (!url.searchParams.has('token')) { + const loginUrl = new URL('/api/auth/login', location.origin); + loginUrl.search = url.search; // The server drops any stale session parameters + // Replace so the page without a token is not left in the history, where "back" would redirect again + location.replace(loginUrl); + throw new Error('No session token, redirecting to login'); + } + this.session = {}; - for (const authenticationParameterName of authentificationParametersNames) { + for (const authenticationParameterName of authenticationParametersNames) { const authenticationParameter = url.searchParams.get(authenticationParameterName); if (!authenticationParameter) { diff --git a/Framework/Frontend/test/mocha-index.js b/Framework/Frontend/test/mocha-index.js index 7e1e1223d..91d4b8b9b 100644 --- a/Framework/Frontend/test/mocha-index.js +++ b/Framework/Frontend/test/mocha-index.js @@ -372,6 +372,70 @@ describe('Framework Frontend', function() { }); }); + describe('sessionService 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(); + }); + + afterEach(async () => { + await loginPage.close(); + }); + + it('should redirect to the login without a token and come back with a new session', async () => { + // "/index.html" is served statically, so the page loads without a token and sessionService redirects + await loginPage.goto(`http://localhost:${port}/index.html?personid=9&q=HelloTest`, {waitUntil: 'networkidle0'}); + + const {pathname, search, personid} = await loginPage.evaluate(() => ({ + pathname: location.pathname, + search: location.search, + personid: window.sessionService.get().personid, + })); + assert.strictEqual(pathname, '/'); + assert.strictEqual(search, '?q=HelloTest'); + assert.strictEqual(personid, '0'); + }); + + it('should not keep the page without a token in the history', async () => { + await loginPage.goto(`http://localhost:${port}`, {waitUntil: 'networkidle0'}); + const initialLength = await loginPage.evaluate(() => history.length); + await loginPage.goto(`http://localhost:${port}/index.html`, {waitUntil: 'networkidle0'}); + + // One entry for the logged in page; the page without a token was replaced + const historyLength = await loginPage.evaluate(() => history.length); + assert.strictEqual(historyLength, initialLength + 1); + }); + + it('should load the session without redirecting when there is a token', async () => { + await loginPage.goto(`http://localhost:${port}`, {waitUntil: 'networkidle0'}); + + const token = await loginPage.evaluate(() => { + history.replaceState({}, '', '/?personid=1&name=Test&token=abc&username=test&access=admin'); + const service = new window.sessionService.constructor(); + service.loadAndHideParameters(); + return service.get().token; + }); + + assert.strictEqual(token, 'abc'); + }); + + it('should throw when a session parameter is missing', async () => { + await loginPage.goto(`http://localhost:${port}`, {waitUntil: 'networkidle0'}); + + const message = await loginPage.evaluate(() => { + history.replaceState({}, '', '/?token=abc'); + 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 ea5abfd7e..cb3af16cc 100644 --- a/Framework/docs/guide/http-server.md +++ b/Framework/docs/guide/http-server.md @@ -28,6 +28,12 @@ Where: * [`JWT_CONF`] - JWT module config, see [JWT module](json-tokens.md) * [`OPENID_CONF`] - OpenID config, see [OpenID Connect module](openid.md) +#### Authentication routes +Registered under `/api/auth` so a reverse proxy serving the frontend only needs to forward `/api`, and skip JWT verification: + * `GET /api/auth/login` - always starts a fresh login, ignoring any session parameters (`token`, `personid`, `name`, `username`, `access`) 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/auth/callback` - OpenID callback, used when the SSO "Redirect URI" points to it (see [OpenID Connect module](openid.md)). `/callback` is still available. + +The frontend `sessionService.loadAndHideParameters()` redirects to `/api/auth/login` when the page has no token, so a frontend served without going through `/` logs in by itself. #### Public methods ```js diff --git a/Framework/docs/guide/openid.md b/Framework/docs/guide/openid.md index 4c6f6a229..efc12f5e6 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`. If a reverse proxy (eg. nginx) serves the frontend and only forwards `/api` to the Node server, use `https://myapp.cern.ch/api/auth/callback` instead. Must match `redirect_uri` in the config 6. Submit (do not check any boxes) ### Roles and e-group authorisation