Merge pull request #16514 from overleaf/jpa-enforce-oauth-scope

[web] restrict access to oauth endpoints to their respective clients

GitOrigin-RevId: 6ffa6008130588e44d336e2af32584ee20ad3ffc
This commit is contained in:
Jakob Ackermann 2024-01-17 09:29:21 +00:00 committed by Copybot
parent e01af0e9c6
commit 797f2c518d
2 changed files with 20 additions and 12 deletions

View file

@ -306,19 +306,26 @@ const AuthenticationController = {
return doRequest return doRequest
}, },
requireOauth() { /**
* @param {string} scope
* @return {import('express').Handler}
*/
requireOauth(scope) {
if (typeof scope !== 'string' || !scope) {
throw new Error(
"requireOauth() expects a non-empty string as 'scope' parameter"
)
}
// require this here because module may not be included in some versions // require this here because module may not be included in some versions
const Oauth2Server = require('../../../../modules/oauth2-server/app/src/Oauth2Server') const Oauth2Server = require('../../../../modules/oauth2-server/app/src/Oauth2Server')
return function (req, res, next) { return function (req, res, next) {
if (next == null) {
next = function () {}
}
const request = new Oauth2Server.Request(req) const request = new Oauth2Server.Request(req)
const response = new Oauth2Server.Response(res) const response = new Oauth2Server.Response(res)
return Oauth2Server.server.authenticate( Oauth2Server.server.authenticate(
request, request,
response, response,
{}, { scope },
function (err, token) { function (err, token) {
if (err) { if (err) {
// use a 401 status code for malformed header for git-bridge // use a 401 status code for malformed header for git-bridge
@ -329,14 +336,15 @@ const AuthenticationController = {
err.code = 401 err.code = 401
} }
// send all other errors // send all other errors
return res res
.status(err.code) .status(err.code)
.json({ error: err.name, error_description: err.message }) .json({ error: err.name, error_description: err.message })
} } else {
req.oauth = { access_token: token.accessToken } req.oauth = { access_token: token.accessToken }
req.oauth_token = token req.oauth_token = token
req.oauth_user = token.user req.oauth_user = token.user
return next() next()
}
} }
) )
} }

View file

@ -574,7 +574,7 @@ describe('AuthenticationController', function () {
this.res.json = sinon.stub() this.res.json = sinon.stub()
this.res.status = sinon.stub().returns(this.res) this.res.status = sinon.stub().returns(this.res)
this.res.sendStatus = sinon.stub() this.res.sendStatus = sinon.stub()
this.middleware = this.AuthenticationController.requireOauth() this.middleware = this.AuthenticationController.requireOauth('scope')
}) })
describe('when Oauth2Server authenticates', function () { describe('when Oauth2Server authenticates', function () {