Skip to content

Commit

Permalink
Merge branch 'authn/bearer-tokens'
Browse files Browse the repository at this point in the history
  • Loading branch information
tsibley committed Apr 29, 2021
2 parents 1999d91 + 006a3dc commit e9239ab
Show file tree
Hide file tree
Showing 6 changed files with 458 additions and 186 deletions.
342 changes: 171 additions & 171 deletions static-site/LICENSE → LICENSE

Large diffs are not rendered by default.

27 changes: 27 additions & 0 deletions LICENSE.third-party
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
================================================================================
The following copyright and license applies to the original copy of
"lib/strategy.js" from the passport-http-bearer project into this project as
"src/authn/bearer.js". Subsequent modifications to this project's copy are
made under the same MIT license.

--------------------------------------------------------------------------------

Copyright (c) 2011-2013 Jared Hanson

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
================================================================================
101 changes: 88 additions & 13 deletions authn.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ const passport = require("passport");
const OAuth2Strategy = require("passport-oauth2").Strategy;
const {jwtVerify} = require('jose/jwt/verify'); // eslint-disable-line import/no-unresolved
const {createRemoteJWKSet} = require('jose/jwks/remote'); // eslint-disable-line import/no-unresolved
const {JWTClaimValidationFailed} = require('jose/util/errors'); // eslint-disable-line import/no-unresolved
const {JOSEError, JWTClaimValidationFailed} = require('jose/util/errors'); // eslint-disable-line import/no-unresolved
const BearerStrategy = require("./src/authn/bearer");
const sources = require("./src/sources");
const utils = require("./src/utils");

Expand Down Expand Up @@ -39,8 +40,27 @@ const COGNITO_CLIENT_ID = PRODUCTION
? "rki99ml8g2jb9sm1qcq9oi5n" // prod client limited to nextstrain.org
: "6q7cmj0ukti9d9kdkqi2dfvh7o"; // dev client limited to localhost and heroku dev instances

/* Registered clients to accept for Bearer tokens.
*
* In the future, we could opt to pull this list dynamically from Cognito at
* server start and might want to if we start having third-party clients, but
* avoid a start-time dep for now.
*/
const BEARER_COGNITO_CLIENT_IDS = [
"2vmc93kj4fiul8uv40uqge93m5", // Nextstrain CLI
];

/* Arbitrary ids for the various strategies for Passport. Makes explicit the
* implicit defaults; uses constants instead of string literals for better
* grepping, linting, and less magic; would be an enum if JS had them (or we
* had TypeScript).
*/
const STRATEGY_OAUTH2 = "oauth2";
const STRATEGY_BEARER = "bearer";

function setup(app) {
passport.use(
STRATEGY_OAUTH2,
new OAuth2Strategy(
{
authorizationURL: `${COGNITO_BASE_URL}/oauth2/authorize`,
Expand All @@ -53,16 +73,38 @@ function setup(app) {
async (accessToken, refreshToken, {id_token: idToken}, profile, done) => {
// Verify both tokens for good measure, but pull user information from
// the identity token (which is its intended purpose).
await verifyToken(accessToken, "access");
try {
await verifyToken(accessToken, "access");

const idClaims = await verifyToken(idToken, "id");
const user = {
username: idClaims["cognito:username"],
groups: idClaims["cognito:groups"],
};
const user = await userFromIdToken(idToken);

// All users are ok, as we control the entire user pool.
return done(null, user);
// All users are ok, as we control the entire user pool.
return done(null, user);
} catch (e) {
return e instanceof JOSEError
? done(null, false, "Error verifying token")
: done(e);
}
}
)
);

passport.use(
STRATEGY_BEARER,
new BearerStrategy(
{
realm: "nextstrain.org",
passIfMissing: true,
},
async (idToken, done) => {
try {
const user = await userFromIdToken(idToken, BEARER_COGNITO_CLIENT_IDS);
return done(null, user);
} catch (e) {
return e instanceof JOSEError
? done(null, false, "Error verifying token")
: done(e);
}
}
)
);
Expand Down Expand Up @@ -139,7 +181,19 @@ function setup(app) {
}
})
);

app.use(passport.initialize());

// If an Authorization header is present, then it must container a valid
// Bearer token. No session will be created for Bearer authn.
//
// If an Authorization header is not present, this authn strategy is
// configured (above) to pass to the next request handler (user restoration
// from session).
app.use(passport.authenticate(STRATEGY_BEARER, { session: false }));

// Restore user from the session, if any. If no session, then req.user will
// be null.
app.use(passport.session());

// Set the app's origin centrally so other handlers can use it
Expand Down Expand Up @@ -177,12 +231,12 @@ function setup(app) {
}
next();
},
passport.authenticate("oauth2")
passport.authenticate(STRATEGY_OAUTH2)
);

// Verify IdP response on /logged-in
app.route("/logged-in").get(
passport.authenticate("oauth2", { failureRedirect: "/login" }),
passport.authenticate(STRATEGY_OAUTH2, { failureRedirect: "/" }),
(req, res) => {
// We can trust this value from the session because we are the only ones
// in control of it.
Expand Down Expand Up @@ -257,6 +311,24 @@ function setup(app) {
});
}


/**
* Creates a user record from the given `idToken` after verifying it.
*
* @param {String} idToken
* @param {String|String[]} client. Optional. Passed to `verifyToken()`.
* @returns {Object} User record with e.g. `username` and `groups` keys.
*/
async function userFromIdToken(idToken, client = undefined) {
const idClaims = await verifyToken(idToken, "id", client);
const user = {
username: idClaims["cognito:username"],
groups: idClaims["cognito:groups"],
};
return user;
}


/**
* Verifies all aspects of the given `token` (a signed JWT from our AWS Cognito
* user pool) which is expected to be used for the given `use`.
Expand All @@ -267,13 +339,16 @@ function setup(app) {
*
* @param {String} token
* @param {String} use
* @param {String} client. Optional `client_id` or list of `client_id`s
* expected for the token. Only relevant when `use` is not
* `access`. Defaults to this server's client id.
* @returns {Object} Verified claims from the token's payload
*/
async function verifyToken(token, use) {
async function verifyToken(token, use, client = COGNITO_CLIENT_ID) {
const {payload: claims} = await jwtVerify(token, COGNITO_JWKS, {
algorithms: ["RS256"],
issuer: COGNITO_USER_POOL_URL,
audience: use !== "access" ? COGNITO_CLIENT_ID : null,
audience: use !== "access" ? client : null,
});

const claimedUse = claims["token_use"];
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"p-limit": "^3.0.1",
"passport": "^0.4.0",
"passport-oauth2": "^1.5.0",
"passport-strategy": "^1.0.0",
"query-string": "^4.2.3",
"react-icons": "^3.11.0",
"request": "^2.88.0",
Expand Down
169 changes: 169 additions & 0 deletions src/authn/bearer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
/*
* Originally copied from "lib/strategy.js" in the passport-http-bearer project.
* The original copy is licensed under the MIT license. See the
* LICENSE.third-party file distributed alongside this project's own LICENSE file.
*
* Subsequent modifications have been made. These and any future modifications
* are licensed under the same MIT license.
*/

/* eslint-disable */

/**
* Module dependencies.
*/
var passport = require('passport-strategy')
, util = require('util');


/**
* Creates an instance of `Strategy`.
*
* The HTTP Bearer authentication strategy authenticates requests based on
* a bearer token contained in the `Authorization` header field.
*
* Applications must supply a `verify` callback, for which the function
* signature is:
*
* function(token, done) { ... }
*
* `token` is the bearer token provided as a credential. The verify callback
* is responsible for finding the user who posesses the token, and invoking
* `done` with the following arguments:
*
* done(err, user, info);
*
* If the token is not valid, `user` should be set to `false` to indicate an
* authentication failure. Additional token `info` can optionally be passed as
* a third argument, which will be set by Passport at `req.authInfo`, where it
* can be used by later middleware for access control. This is typically used
* to pass any scope associated with the token.
*
* Options:
*
* - `realm` authentication realm, defaults to "Users"
* - `scope` list of scope values indicating the required scope of the access
* token for accessing the requested resource
* - `passIfMissing` instead of failing, pass if no `Authorization` header was
* present in the request (defaults to false)
*
* Examples:
*
* passport.use(new BearerStrategy(
* function(token, done) {
* User.findByToken({ token: token }, function (err, user) {
* if (err) { return done(err); }
* if (!user) { return done(null, false); }
* return done(null, user, { scope: 'read' });
* });
* }
* ));
*
* For further details on HTTP Bearer authentication, refer to [The OAuth 2.0 Authorization Protocol: Bearer Tokens](http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer)
*
* @constructor
* @param {Object} [options]
* @param {Function} verify
* @api public
*/
function Strategy(options, verify) {
if (typeof options == 'function') {
verify = options;
options = {};
}
if (!verify) { throw new TypeError('HTTPBearerStrategy requires a verify callback'); }

passport.Strategy.call(this);
this.name = 'bearer';
this._verify = verify;
this._realm = options.realm || 'Users';
if (options.scope) {
this._scope = (Array.isArray(options.scope)) ? options.scope : [ options.scope ];
}
this._passReqToCallback = options.passReqToCallback;
this._passIfMissing = options.passIfMissing === undefined ? false : options.passIfMissing;
}

/**
* Inherit from `passport.Strategy`.
*/
util.inherits(Strategy, passport.Strategy);

/**
* Authenticate request based on the contents of a HTTP Bearer authorization
* header, body parameter, or query parameter.
*
* @param {Object} req
* @api protected
*/
Strategy.prototype.authenticate = function(req) {
var token;

if (req.headers && req.headers.authorization) {
var parts = req.headers.authorization.split(' ');
if (parts.length == 2) {
var scheme = parts[0]
, credentials = parts[1];

if (/^Bearer$/i.test(scheme)) {
token = credentials;
}
} else {
return this.fail(400);
}
}
else if (this._passIfMissing) {
return this.pass();
}

if (!token) { return this.fail(this._challenge()); }

var self = this;

function verified(err, user, info) {
if (err) { return self.error(err); }
if (!user) {
if (typeof info == 'string') {
info = { message: info }
}
info = info || {};
return self.fail(self._challenge('invalid_token', info.message));
}
self.success(user, info);
}

if (self._passReqToCallback) {
this._verify(req, token, verified);
} else {
this._verify(token, verified);
}
};

/**
* Build authentication challenge.
*
* @api private
*/
Strategy.prototype._challenge = function(code, desc, uri) {
var challenge = 'Bearer realm="' + this._realm + '"';
if (this._scope) {
challenge += ', scope="' + this._scope.join(' ') + '"';
}
if (code) {
challenge += ', error="' + code + '"';
}
if (desc && desc.length) {
challenge += ', error_description="' + desc + '"';
}
if (uri && uri.length) {
challenge += ', error_uri="' + uri + '"';
}

return challenge;
};


/**
* Expose `Strategy`.
*/
module.exports = Strategy;
4 changes: 2 additions & 2 deletions static-site/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,6 @@ The static documentation is automatically rebuilt every time the (parent) repo i

## License and copyright

Copyright 2014-2018 Trevor Bedford and Richard Neher.
Copyright 2014-2021 Trevor Bedford and Richard Neher.

Source code to Nextstrain is made available under the terms of the [GNU Affero General Public License](LICENSE.txt) (AGPL). Nextstrain is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
Source code to Nextstrain is made available under the terms of the [GNU Affero General Public License 3.0](../LICENSE) (AGPL-3.0). Nextstrain is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.

0 comments on commit e9239ab

Please sign in to comment.