|
| 1 | +/* eslint-disable padded-blocks */ |
| 2 | +const Promise = require('bluebird') |
| 3 | + |
| 4 | +const { PrivateKeyNotFoundError, CertificateNotFoundError } = require('./errors') |
| 5 | + |
| 6 | +/** |
| 7 | + * Holds a cached private key and certificate data |
| 8 | + * @typedef KeyAndCert |
| 9 | + * @type {object} |
| 10 | + * @property {number} timestamp Timestamp of loading |
| 11 | + * @property {string} privKey Private key data in PEM format |
| 12 | + * @property {string} cert Certificate data in PEM format |
| 13 | + * @property {string} keyAlg JWT key algorithm (RS256, ES256, etc.) |
| 14 | + * @property {string} privKeyPassphrase Passphrase for the private key (if any) |
| 15 | + */ |
| 16 | + |
| 17 | + /** |
| 18 | + * Holds a private key and the corresponding passphrase |
| 19 | + * @typedef PrivateKeyAndPassphrase |
| 20 | + * @type {object} |
| 21 | + * @property {string} key Private key data in PEM format |
| 22 | + * @property {string} passphrase Passphrase for the private key (if any) |
| 23 | + */ |
| 24 | + |
| 25 | +/** |
| 26 | + * Synchronous or asnyhronous callback for loading private keys and certificates |
| 27 | + * @callback KeystoreService~keystoreReaderCallback |
| 28 | + * @return {Map.<KeyAndCert>} The loaded key and certificate data |
| 29 | + */ |
| 30 | + |
| 31 | +/** |
| 32 | + * Creates a new keystore service |
| 33 | + * @param {Object} signingKeyPassphrases Stores passphrases for each signing keys. Key: key id, value: passphrase |
| 34 | + * @param {KeystoreService~keystoreReaderCallback} keystoreReader Keystore reader callback (sync or async) |
| 35 | + * @param {integer} refreshInterval Interval of the keystore refresh [millisec] |
| 36 | + */ |
| 37 | +module.exports = (debugName, signingKeyPassphrases, keystoreReader, refreshInterval) => { |
| 38 | + |
| 39 | + const debug = require('debug')(debugName) |
| 40 | + |
| 41 | + /** The current signing key ID */ |
| 42 | + let currentSigningKeyId |
| 43 | + |
| 44 | + /** Cache for the private key and certificate data */ |
| 45 | + let keys = new Map() |
| 46 | + |
| 47 | + // Reading keystore asynchronously |
| 48 | + const keystoreReaderAsync = Promise.method(keystoreReader) |
| 49 | + const keystoreReaderTask = () => { |
| 50 | + keystoreReaderAsync(keys) |
| 51 | + .then(newKeys => { |
| 52 | + debug('Keystore reloaded, keys: ', newKeys.keys()) |
| 53 | + keys = newKeys |
| 54 | + currentSigningKeyId = selectCurrentSigningKeyId(keys) |
| 55 | + debug('Current signing key id: ' + currentSigningKeyId) |
| 56 | + }) |
| 57 | + .catch(err => { |
| 58 | + debug('Reading keystore failed', err) // FIXME: should signal this error somehow. an EventEmitter maybe? |
| 59 | + }) |
| 60 | + } |
| 61 | + keystoreReaderTask() // first call before starting timer |
| 62 | + setInterval(keystoreReaderTask, refreshInterval) |
| 63 | + |
| 64 | + /** |
| 65 | + * Selects the current signing key id |
| 66 | + * |
| 67 | + * @param {Array} currentKeys The current keys |
| 68 | + * @return {string} The selected key id |
| 69 | + */ |
| 70 | + function selectCurrentSigningKeyId (currentKeys) { |
| 71 | + /* eslint-disable no-useless-return */ |
| 72 | + if (currentKeys.size === 0) { |
| 73 | + return |
| 74 | + } else if (currentKeys.size === 1) { |
| 75 | + return currentKeys.keys().next().value |
| 76 | + } else { |
| 77 | + const now = Math.floor(Date.now() / 1000) |
| 78 | + const maxTimestamp = now - (20 * 60) // the youngest key to use |
| 79 | + const allKeys = Array.from(currentKeys) |
| 80 | + let allowedKeys = allKeys.filter(keyEntry => keyEntry[1].timestamp < maxTimestamp) |
| 81 | + debug('allowedKeys: ', allowedKeys) |
| 82 | + if (allowedKeys.length === 0) { |
| 83 | + allowedKeys = allKeys |
| 84 | + } |
| 85 | + allowedKeys = allowedKeys.sort((a, b) => a[0] > b[0] ? 1 : a[0] < b[0] ? -1 : 0) |
| 86 | + const entryToUse = allowedKeys[allowedKeys.length - 1] |
| 87 | + return entryToUse[0] |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + /** |
| 92 | + * Returns the ID of the signing key that has to be used for signing |
| 93 | + * @return {string} The ID of the key that has to be used for signing |
| 94 | + */ |
| 95 | + function getCurrentSigningKeyId () { |
| 96 | + return currentSigningKeyId |
| 97 | + } |
| 98 | + |
| 99 | + /** |
| 100 | + * PRIVATE function! Returns the passphrase for the given private key |
| 101 | + * @param {string} id The id of the private key |
| 102 | + * @return {string} The passphrase for the private key |
| 103 | + */ |
| 104 | + function getPrivateKeyPassphrase (id) { |
| 105 | + return signingKeyPassphrases[id] |
| 106 | + } |
| 107 | + |
| 108 | + /** |
| 109 | + * Returns the private key with the given id |
| 110 | + * Throws PrivateKeyNotFoundError if the certificate is not found in the store |
| 111 | + * |
| 112 | + * @param {string} id The private key id |
| 113 | + * @return {Promise.<PrivateKeyAndPassphrase, PrivateKeyNotFoundError>} Promise to the private key {key(PEM), passphrase} |
| 114 | + */ |
| 115 | + function getPrivateKey (id) { |
| 116 | + if (keys.has(id)) { |
| 117 | + const key = keys.get(id) |
| 118 | + return Promise.resolve({ |
| 119 | + alg: key.keyAlg, |
| 120 | + key: key.privKey, |
| 121 | + passphrase: getPrivateKeyPassphrase(id) |
| 122 | + }) |
| 123 | + } else { |
| 124 | + return Promise.reject(new PrivateKeyNotFoundError(`Loading private key ${id} failed`)) |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + /** |
| 129 | + * Returns the certificate with the given id |
| 130 | + * Throws CertificateNotFoundError if the certificate is not found in the store |
| 131 | + * |
| 132 | + * @param {string} id The certificate id |
| 133 | + * @return {Promise.<string, CertificateNotFoundError>} Promise to the certificate (PEM) |
| 134 | + */ |
| 135 | + function getCertificate (id) { |
| 136 | + if (keys.has(id)) { |
| 137 | + const key = keys.get(id) |
| 138 | + return Promise.resolve({ |
| 139 | + alg: key.keyAlg, |
| 140 | + cert: key.cert |
| 141 | + }) |
| 142 | + } else { |
| 143 | + return Promise.reject(new CertificateNotFoundError(`Loading certificate ${id} failed`)) |
| 144 | + } |
| 145 | + } |
| 146 | + |
| 147 | + /** |
| 148 | + * Represents a public key with a certificate chain attached |
| 149 | + * @typedef JWK |
| 150 | + * @type {object} |
| 151 | + * @property {string} kid Key id |
| 152 | + * @property {string} x5c X.509 certificate chain |
| 153 | + */ |
| 154 | + |
| 155 | + /** |
| 156 | + * Returns all certificates in JWKS format |
| 157 | + * |
| 158 | + * @return {Array.JWK} An array of JWK objects |
| 159 | + */ |
| 160 | + function getAllCertificatesAsJWKS () { |
| 161 | + const keySet = [] |
| 162 | + keys.forEach((key) => { |
| 163 | + keySet.push(key.pubkeyJwk) |
| 164 | + }) |
| 165 | + return keySet |
| 166 | + } |
| 167 | + |
| 168 | + return { |
| 169 | + getCurrentSigningKeyId, |
| 170 | + getPrivateKey, |
| 171 | + getCertificate, |
| 172 | + getAllCertificatesAsJWKS, |
| 173 | + getPrivateKeyPassphrase, |
| 174 | + selectCurrentSigningKeyId |
| 175 | + } |
| 176 | +} |
0 commit comments