Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Require auth for saving and loading projects #124

Merged
merged 6 commits into from
May 25, 2021
Merged
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
50 changes: 31 additions & 19 deletions src/api/routes/projects.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,37 @@
const ProjectsService = require('../route-services/projects');

const {
expressAuthorizationMiddleware,
expressAuthenticationOnlyMiddleware,
} = require('../../utils/authMiddlewares');

const projectsService = new ProjectsService();

module.exports = {
'projects#update': (req, res, next) => {
projectsService.updateProject(req.params.projectUuid, req.body)
.then((data) => res.json(data))
.catch(next);
},
'projects#delete': (req, res, next) => {
projectsService.deleteProject(req.params.projectUuid)
.then((data) => res.json(data))
.catch(next);
},

'projects#get': (req, res, next) => {
projectsService.getProjects().then((response) => res.json(response)).catch(next);
},
'projects#getExperiments': (req, res, next) => {
projectsService.getExperiments(req.params.projectUuid)
.then((response) => res.json(response)).catch(next);
},

'projects#update': [
expressAuthenticationOnlyMiddleware,
aerlaut marked this conversation as resolved.
Show resolved Hide resolved
aerlaut marked this conversation as resolved.
Show resolved Hide resolved
(req, res, next) => {
projectsService.updateProject(req.params.projectUuid, req.body)
.then((data) => res.json(data))
.catch(next);
}],
'projects#delete': [
expressAuthorizationMiddleware,
(req, res, next) => {
projectsService.deleteProject(req.params.projectUuid)
.then((data) => res.json(data))
.catch(next);
}],
'projects#get': [
expressAuthenticationOnlyMiddleware,
aerlaut marked this conversation as resolved.
Show resolved Hide resolved
(req, res, next) => {
projectsService.getProjects().then((response) => res.json(response)).catch(next);
},
],
'projects#getExperiments': [
expressAuthorizationMiddleware,
(req, res, next) => {
projectsService.getExperiments(req.params.projectUuid)
.then((response) => res.json(response)).catch(next);
}],
};
22 changes: 20 additions & 2 deletions src/specs/api.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -651,6 +651,18 @@ paths:
application/json:
schema:
$ref: ./models/HTTPError.v1.yaml
'401':
description: The request lacks authentication credentials.
content:
application/json:
schema:
$ref: ./models/HTTPError.v1.yaml
'403':
description: The request lacks authentication credentials.
aerlaut marked this conversation as resolved.
Show resolved Hide resolved
content:
application/json:
schema:
$ref: ./models/HTTPError.v1.yaml
'404':
description: Not Found
content:
Expand Down Expand Up @@ -815,10 +827,11 @@ paths:
$ref: ./models/api-body-schemas/Samples.v1.yaml
'/projects':
get:
summary: ''
summary: 'Get the list of projects'
operationId: getProjects
x-eov-operation-id: projects#get
x-eov-operation-handler: routes/projects
description: Get the projects
responses:
'200':
description: OK
Expand All @@ -828,4 +841,9 @@ paths:
type: array
items:
$ref: ./models/api-body-schemas/Project.v1.yaml
description: Get the projects
'401':
description: The request lacks authentication credentials.
content:
application/json:
schema:
$ref: ./models/HTTPError.v1.yaml
26 changes: 19 additions & 7 deletions src/utils/authMiddlewares.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@ const CacheSingleton = require('../cache');
const { CacheMissError } = require('../cache/cache-utils');
const { UnauthorizedError, UnauthenticatedError } = require('./responses');
const ExperimentService = require('../api/route-services/experiment');
const ProjectsService = require('../api/route-services/projects');

const experimentService = new ExperimentService();
const projectService = new ProjectsService();

/**
* Authentication middleware for Express. Returns a middleware that
Expand Down Expand Up @@ -134,23 +136,30 @@ const authenticationMiddlewareSocketIO = async (authHeader) => {
* @returns Promise that resolves or rejects based on authorization status.
* @throws {UnauthorizedError} Authorization failed.
*/
const authorize = async (experimentId, claim) => {
const authorize = async (authResource, claim, authByExperiment = true) => {
const { 'cognito:username': userName, email } = claim;

const {
rbac_can_write: canWrite,
} = await experimentService.getExperimentPermissions(experimentId);
let canWrite = null;

if (authByExperiment) {
const experiment = await experimentService.getExperimentPermissions(authResource);
if (experiment) canWrite = experiment.rbac_can_write;
} else {
const experiment = await projectService.getExperiments(authResource);
// experiment[0] because there is only 1 experiment per project
if (experiment) canWrite = experiment[0].rbac_can_write;
}

if (!canWrite) {
throw new UnauthorizedError(`Experiment ${experimentId} cannot be accesed (malformed).`);
throw new UnauthorizedError(`Experiment ${authResource} cannot be accesed (malformed).`);
}

// If the logged in user has the permissions, forward request.
if (canWrite.values.includes(userName)) {
return true;
}

throw new UnauthorizedError(`User ${userName} (${email}) does not have access to experiment ${experimentId}.`);
throw new UnauthorizedError(`User ${userName} (${email}) does not have access to ${authByExperiment ? 'experiment' : 'project'} ${authResource}.`);
};

/**
Expand All @@ -163,8 +172,11 @@ const expressAuthorizationMiddleware = async (req, res, next) => {
return;
}

const authByExperiment = !!req.params.experimentId;
const authResource = req.params.experimentId ? req.params.experimentId : req.params.projectUuid;

try {
await authorize(req.params.experimentId, req.user);
await authorize(authResource, req.user, authByExperiment);
aerlaut marked this conversation as resolved.
Show resolved Hide resolved
next();
return;
} catch (e) {
Expand Down
1 change: 1 addition & 0 deletions tests/api/routes/projects.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const request = require('supertest');
const expressLoader = require('../../../src/loaders/express');

jest.mock('../../../src/api/route-services/projects');
jest.mock('../../../src/utils/authMiddlewares');

describe('tests for projects route', () => {
let app = null;
Expand Down
34 changes: 34 additions & 0 deletions tests/utils/authMiddlewares.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const { UnauthorizedError, UnauthenticatedError } = require('../../src/utils/res

const {
mockDynamoGetItem,
mockDynamoBatchGetItem,
} = require('../test-utils/mockAWSServices');

const documentClient = new AWS.DynamoDB.DocumentClient();
Expand All @@ -16,6 +17,7 @@ describe('Tests for authorization/authentication middlewares', () => {
// Sample experiment permission data.
const data = {
experimentId: '12345',
projectId: '23456',
rbac_can_write: documentClient.createSet(['test-user']),
};

Expand Down Expand Up @@ -91,4 +93,36 @@ describe('Tests for authorization/authentication middlewares', () => {
await expressAuthorizationMiddleware(req, {}, next);
expect(next).toBeCalledWith(expect.any(UnauthenticatedError));
});

it('Express middleware can resolve using authorization using projectUuid', async () => {
mockDynamoBatchGetItem({
Responses: {
'experiments-test': [data],
},
});

const req = {
params: { projectUuid: '23456' },
};
const next = jest.fn();

await expressAuthorizationMiddleware(req, {}, next);
expect(next).toBeCalledWith(expect.any(UnauthenticatedError));
});

it('Express middleware with unknown projectUuid will throw unauth error', async () => {
mockDynamoBatchGetItem({
Responses: {
'experiments-test': [data],
},
});

const req = {
params: { projectUuid: '2345' },
};
const next = jest.fn();

await expressAuthorizationMiddleware(req, {}, next);
expect(next).toBeCalledWith(expect.any(UnauthenticatedError));
});
});