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
37 changes: 33 additions & 4 deletions Framework/Backend/http/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@
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.
Expand Down Expand Up @@ -193,6 +198,14 @@
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));
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
if (this.openid) {
this.routerAuth.get('/callback', (req, res) => this.identCallback(req, res));
}
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
this.app.use('/api/auth', this.routerAuth);

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

this.routerStatics = express.Router();
Expand Down Expand Up @@ -281,6 +294,24 @@
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
Expand Down Expand Up @@ -488,10 +519,8 @@
// 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');
Expand Down
70 changes: 70 additions & 0 deletions Framework/Backend/test/mocha-http.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
16 changes: 14 additions & 2 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,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) {
Expand Down
64 changes: 64 additions & 0 deletions Framework/Frontend/test/mocha-index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
6 changes: 6 additions & 0 deletions Framework/docs/guide/http-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
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`. 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
Expand Down
Loading