Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions Framework/Backend/http/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
/**
* 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
*/
Expand All @@ -45,6 +46,7 @@
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();

Expand Down Expand Up @@ -201,6 +203,17 @@
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);
});
Comment on lines +211 to +214
}

// Router for static files (can grow with addStaticPath)

this.routerStatics = express.Router();
Expand Down
45 changes: 44 additions & 1 deletion Framework/Backend/test/mocha-http.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 }));
Expand Down Expand Up @@ -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')
Expand Down
16 changes: 13 additions & 3 deletions Framework/Frontend/js/src/sessionService.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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) {
Expand All @@ -60,6 +69,7 @@ export class SessionService {
}

history.replaceState({}, '', url);
return true;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion Framework/Frontend/test/index-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
71 changes: 71 additions & 0 deletions Framework/Frontend/test/mocha-index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
8 changes: 7 additions & 1 deletion Framework/docs/guide/http-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion Framework/docs/guide/openid.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading