'use strict'; var PromiseA = require('bluebird'); var crypto = require('crypto'); module.exports.create = function (bigconf, deps, app) { var Jwks = { restful: {} }; var Grants = { restful: {} }; // This tablename is based on the tablename found in the objects in model.js. // Instead of the snake_case the name with be UpperCammelCase, converted by masterquest-sqlite3. function attachSiteStore(tablename, req, res, next) { return req.getSiteStore().then(function (store) { req.Store = store[tablename]; next(); }); } function detachSiteStore(req, res, next) { delete req.Store; next(); } Jwks.thumbprint = function (jwk) { // To produce a thumbprint we need to create a JSON string with only the required keys for // the key type, with the keys sorted lexicographically and no white space. We then need // run it through a SHA-256 and encode the result in url safe base64. // https://stackoverflow.com/questions/42588786/how-to-fingerprint-a-jwk var keys; if (jwk.kty === 'EC') { keys = ['crv', 'x', 'y']; } else if (jwk.kty === 'RSA') { keys = ['e', 'n']; } else { return PromiseA.reject(new Error('invalid JWK key type ' + jwk.kty)); } keys.push('kty'); keys.sort(); var missing = keys.filter(function (name) { return !jwk.hasOwnProperty(name); }); if (missing.length > 0) { return PromiseA.reject(new Error('JWK of type '+jwk.kty+' missing fields ' + missing)); } // I'm not 100% sure this behavior is guaranteed by a real standard, but when we use an array // as the replacer argument the keys are always in the order they appeared in the array. var jwkStr = JSON.stringify(jwk, keys); var hash = crypto.createHash('sha256').update(jwkStr).digest('base64'); return PromiseA.resolve(hash.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+/g, '')); }; Jwks.restful.get = function (req, res) { var promise = req.Store.find({ kid: req.params.kid }, { limit: 1 }).then(function (results) { if (!results.length) { throw new Error('no keys stored with kid "'+req.params.kid+'"'); } var jwk = results[0]; // We need to sanitize the key to make sure we don't deliver any private keys fields if // we were given a key we could use to sign tokens on behalf of the user. We also don't // want to deliver the sub or any other PPIDs. var whitelist = [ 'kty', 'alg', 'kid', 'use' ]; if (jwk.kty === 'EC') { whitelist = whitelist.concat([ 'crv', 'x', 'y' ]); } else if (jwk.kty === 'RSA') { whitelist = whitelist.concat([ 'e', 'n' ]); } var result = {}; whitelist.forEach(function (key) { result[key] = jwk[key]; }); return result; }); app.handlePromise(req, res, promise, "[issuer@oauth3.org] retrieve JWK"); }; Jwks.restful.saveNew = function (req, res) { var jwk = req.body; var promise = Jwks.thumbprint(jwk).then(function (kid) { if (jwk.kid && jwk.kid !== kid) { throw new Error('provided kid "'+jwk.kid+'" does not match calculated "'+kid+'"'); } jwk.kid = kid; jwk.sub = req.params.sub; return req.Store.upsert(jwk.sub+'/'+jwk.kid, jwk); }).then(function () { return { success: true }; }); app.handlePromise(req, res, promise, "[issuer@oauth3.org] create JWK"); }; Grants.authorizeReq = function (req) { return PromiseA.resolve().then(function () { // It might seem unnecessary to wrap a promise in another promise, but this way it will // catch the error thrown when a token isn't found and verifyAsync isn't a function. return req.oauth3.verifyAsync(); }).then(function (token) { // Just because the token is valid doesn't mean the token is authorized to get or save grants. // The only place that should be allowed to access grants on behalf of the user is the issuer. if (token.iss !== token.azp) { throw new Error("token does not allow access to grants"); } var sub = token.sub || token.ppid || (token.acx && (token.acx.id || token.acx.appScopedId)); if (!sub) { if (!Array.isArray(token.axs) || !token.axs.length) { throw new Error("no account pairwise identifier"); } var allowed = token.axs.some(function (acc) { return (req.params.sub || req.query.sub) === (acc.id || acc.ppid || acc.appScopedId); }); if (!allowed) { throw new Error("no account pairwise identifier matching '" + req.params.sub + "'"); } sub = req.params.sub || req.query.sub; } return sub; }); }; Grants.restful.get = function (req, res) { var promise = Grants.authorizeReq(req).then(function (sub) { return req.Store.get(sub+'/'+(req.params.azp || req.query.azp)); }).then(function (result) { if (!result) { throw new Error('no grants found'); } return { sub: result.sub, azp: result.azp, scope: result.scope, }; }); app.handlePromise(req, res, promise, "[issuer@oauth3.org] retrieve grants"); }; Grants.restful.saveNew = function (req, res) { var promise = Grants.authorizeReq(req).then(function (sub) { if (typeof req.body.scope !== 'string') { throw new Error("malformed request: 'scope' should be a string"); } var scope = req.body.scope.split(/[+ ,]+/g).join(','); var grant = { sub: sub, azp: req.params.azp, scope: scope, }; return req.Store.upsert(grant.sub+'/'+grant.azp, grant); }).then(function () { return {success: true}; }); app.handlePromise(req, res, promise, '[issuer@oauth3.org] save grants'); }; app.use( '/jwks', attachSiteStore.bind(null, 'IssuerOauth3OrgJwks')); app.get( '/jwks/:kid.json', Jwks.restful.get); app.post( '/jwks/:sub', Jwks.restful.saveNew); app.use( '/grants', attachSiteStore.bind(null, 'IssuerOauth3OrgGrants')); app.get( '/grants', Grants.restful.get); app.get( '/grants/:sub/:azp', Grants.restful.get); app.post( '/grants/:sub/:azp', Grants.restful.saveNew); app.use(detachSiteStore); };