d5367df933c109f632140517b55790deb0251045
1 /* eslint-disable no-unused-vars */
4 const common
= require('../common');
5 const DatabaseErrors
= require('./errors');
6 const svh
= require('./schema-version-helper');
7 const uuid
= require('uuid');
9 const _fileScope
= common
.fileScope(__filename
);
12 constructor(logger
, options
) {
14 this.options
= options
;
19 * Perform tasks needed to prepare database for use. Ensure this is called
20 * after construction, and before any other database activity.
21 * At the minimum, this will validate a compatible schema is present and usable.
22 * Some engines will also perform other initializations or async actions which
23 * are easier handled outside the constructor.
26 const _scope
= _fileScope('initialize');
28 const currentSchema
= await
this._currentSchema();
29 const current
= svh
.schemaVersionObjectToNumber(currentSchema
);
30 const min
= svh
.schemaVersionObjectToNumber(this.schemaVersionsSupported
.min
);
31 const max
= svh
.schemaVersionObjectToNumber(this.schemaVersionsSupported
.max
);
32 if (current
>= min
&& current
<= max
) {
33 this.logger
.debug(_scope
, 'schema supported', { currentSchema
, schemaVersionsSupported: this.schemaVersionsSupported
});
35 this.logger
.error(_scope
, 'schema not supported', { currentSchema
, schemaVersionsSupported: this.schemaVersionsSupported
});
36 throw new DatabaseErrors
.MigrationNeeded();
42 * @typedef {Object} SchemaVersionObject
43 * @property {Number} major
44 * @property {Number} minor
45 * @property {Number} patch
48 * Query the current schema version.
49 * This is a standalone query function, as it is called before statements are loaded.
50 * @returns {Promise<SchemaVersionObject>}
52 async
_currentSchema() {
53 this._notImplemented('_currentSchema', arguments
);
58 * Perform db connection health-check, if applicable.
59 * Throw something if a database situation should pull us out of a load-balancer.
62 this._notImplemented('healthCheck', arguments
);
67 * Wrap a function call in a database context.
68 * @param {Function} fn fn(ctx)
71 this._notImplemented('context', arguments
);
75 * Wrap a function call in a transaction context.
77 * @param {Function} fn fn(txCtx)
79 async
transaction(dbCtx
, fn
) {
80 this._notImplemented('transaction', arguments
);
85 * Basic type checking of object properties.
87 * Types may be any of the built-in types:
89 * - bigint (also allowed with 'number')
91 * - number (this will also allow 'bigint')
97 * Types may also be any of the following:
104 * @param {Object} object
105 * @param {String[]} properties
106 * @param {String[]} types
108 _ensureTypes(object
, properties
, types
) {
109 const _scope
= _fileScope('_ensureTypes');
111 if (!(object
&& properties
&& types
)) {
112 this.logger
.error(_scope
, 'undefined argument', { object
, properties
, types
});
113 throw new DatabaseErrors
.DataValidation();
116 const supportedTypes
= [
132 types
.forEach((t
) => {
133 if (!supportedTypes
.includes(t
)) {
134 this.logger
.error(_scope
, 'unsupported type', { object
, properties
, types
, unsupportedType: t
});
135 throw new DatabaseErrors
.DataValidation();
139 properties
.forEach((p
) => {
140 // eslint-disable-next-line security/detect-object-injection
141 const pObj
= object
[p
];
142 const pType
= typeof pObj
;
143 if (!types
.includes(pType
)
144 && !(types
.includes('array') && Array
.isArray(pObj
))
145 && !(types
.includes('buffer') && pObj
instanceof Buffer
)
146 && !(types
.includes('date') && pObj
instanceof Date
)
147 && !(types
.includes('infinites') && Math
.abs(pObj
) === Infinity
)
148 && !(types
.includes('null') && pObj
=== null)
149 && !(types
.includes('number') && pType
=== 'bigint')
150 && !(types
.includes('uuid') && uuid
.validate(pObj
))) {
151 const reason
= `'${p}' is '${pType}', but must be ${types.length > 1 ? 'one of ' : ''}'${types}'`;
152 this.logger
.error(_scope
, reason
, {});
153 throw new DatabaseErrors
.DataValidation(reason
);
160 * @typedef {Object} Authentication
161 * @property {String} identifier
162 * @property {String=} credential
163 * @property {Date} created
164 * @property {Date=} lastAuthentication
167 * @param {Authentication} authentication
169 _validateAuthentication(authentication
) {
171 [['identifier'], ['string']],
172 [['credential'], ['string', 'null']],
173 [['created'], ['date']],
174 [['lastAuthentication'], ['date', 'infinites']],
175 ].forEach(([properties
, types
]) => this._ensureTypes(authentication
, properties
, types
));
180 * @typedef {Object} Resource
181 * @property {String} resourceId - uuid
182 * @property {String} secret
183 * @property {String} description
184 * @property {Date} created
187 * @param {Resource} resource
189 _validateResource(resource
) {
191 [['resourceId', 'secret', 'description'], ['string']],
192 [['resourceId'], ['uuid']],
193 [['created'], ['date']],
194 ].forEach(([properties
, types
]) => this._ensureTypes(resource
, properties
, types
));
199 * @typedef {Object} Token
200 * @property {String} codeId - uuid
201 * @property {String} profile
202 * @property {Date} created
203 * @property {Date=} expires
204 * @property {Date=} refreshExpires
205 * @property {Date=} refreshed
206 * @property {*=} duration
207 * @property {*=} refreshDuration
208 * @property {Number|BigInt=} refresh_count
209 * @property {Boolean} is_revoked
210 * @property {Boolean} is_token
211 * @property {String} client_id
212 * @property {String[]} scopes
213 * @property {Object=} profileData
216 * @param {Token} token
218 _validateToken(token
) {
220 [['codeId', 'profile', 'clientId'], ['string']],
221 [['codeId'], ['uuid']],
222 [['created'], ['date']],
223 [['expires', 'refreshExpires', 'refreshed'], ['date', 'null']],
224 [['isToken', 'isRevoked'], ['boolean']],
225 [['scopes'], ['array']],
226 [['profileData'], ['object', 'null']],
227 ].forEach(([properties
, types
]) => this._ensureTypes(token
, properties
, types
));
228 this._ensureTypes(token
.scopes
, Object
.keys(token
.scopes
), ['string']);
233 * Interface methods need implementations. Ensure the db-interaction
234 * methods on the base class call this, so they may be overridden by
235 * implementation classes.
236 * @param {String} method
237 * @param {arguments} args
239 _notImplemented(method
, args
) {
240 this.logger
.error(_fileScope(method
), 'abstract method called', Array
.from(args
));
241 throw new DatabaseErrors
.NotImplemented(method
);
246 * Get all the almanac entries.
249 async
almanacGetAll(dbCtx
) {
250 this._notImplemented('almanacGetAll', arguments
);
255 * Insert or update an almanac entry.
257 * @param {String} event
258 * @param {Date=} date
260 async
almanacUpsert(dbCtx
, event
, date
) {
261 this._notImplemented('almanacUpsert', arguments
);
266 * Fetch the authentication record for an identifier.
268 * @param {String} identifier
269 * @returns {Promise<Authentication>}
271 async
authenticationGet(dbCtx
, identifier
) {
272 this._notImplemented('authenticationGet', arguments
);
277 * Update the authentication record for the identifier that
278 * correct credentials have been supplied.
280 * @param {String} identifier
281 * @returns {Promise<void>}
283 async
authenticationSuccess(dbCtx
, identifier
) {
284 this._notImplemented('authenticationSuccess', arguments
);
289 * Insert or update the credential for an identifier.
291 * @param {String} identifier
292 * @param {String} credential
293 * @returns {Promise<void>}
295 async
authenticationUpsert(dbCtx
, identifier
, credential
) {
296 this._notImplemented('authenticationUpsert', arguments
);
301 * Determine if profile url is known to this service.
303 * @param {String} profile
304 * @returns {Promise<Boolean>}
306 async
profileIsValid(dbCtx
, profile
) {
307 this._notImplemented('profileGet', arguments
);
312 * Insert a new relationship between a profile endpoint and
313 * an authenticated identifier.
315 * @param {String} profile
316 * @param {String} identifier
317 * @returns {Promise<void>}
319 async
profileIdentifierInsert(dbCtx
, profile
, identifier
) {
320 this._notImplemented('profileIdentifierInsert', arguments
);
325 * Adds a scope to be available for a profile to include on any authorization request.
327 * @param {String} profile
328 * @param {String} scope
329 * @returns {Promise<void>}
331 async
profileScopeInsert(dbCtx
, profile
, scope
) {
332 this._notImplemented('profileScopeInsert', arguments
);
337 * @typedef {Object} ScopeDetails
338 * @property {String} description
339 * @property {String[]=} profiles
342 * @typedef {Object.<String, Object>} ProfileScopes
343 * @property {Object.<String, Object>} profile
344 * @property {Object.<String, ScopeDetails>} profile.scope
347 * @typedef {Object.<String, Object>} ScopeIndex
348 * @property {ScopeDetails} scope
351 * @typedef {Object} ProfilesScopesReturn
352 * @property {ProfileScopes} profileScopes
353 * @property {ScopeIndex} scopeIndex
354 * @property {String[]} profiles
357 * Returns an object containing:
358 * - an object with profiles as keys to objects with scopes as keys to scope objects,
359 * which each contain a description of the scope and a list of profiles offering it
360 * - an object with scopes as keys to the same scope objects
361 * - a list of profiles
363 * @param {String} identifier
364 * @returns {Promise<ProfileScopesReturn>}
366 async
profilesScopesByIdentifier(dbCtx
, identifier
) {
367 this._notImplemented('profilesScopesByIdentifier', arguments
);
372 * @typedef ProfileScopesRow
375 * @property description
376 * @property application
377 * @property isPermanent
378 * @property isManuallyAdded
381 * Convert db row data into associative structures.
382 * Same behavior is shared by multiple engines.
383 * @param {ProfileScopesRow[]} profileScopesRows
384 * @returns {ProfileScopesReturn}
386 static _profilesScopesBuilder(profileScopesRows
) {
387 const scopeIndex
= {};
388 const profileScopes
= {};
389 const profileSet
= new Set();
391 (profileScopesRows
|| []).forEach(({ profile
, scope
, description
, application
, isPermanent
, isManuallyAdded
}) => {
392 if (scope
&& !(scope
in scopeIndex
)) {
393 scopeIndex
[scope
] = { // eslint-disable-line security/detect-object-injection
402 profileSet
.add(profile
);
403 if (!(profile
in profileScopes
)) {
404 profileScopes
[profile
] = {}; // eslint-disable-line security/detect-object-injection
407 if (profile
&& scope
) {
408 scopeIndex
[scope
].profiles
.push(profile
); // eslint-disable-line security/detect-object-injection
409 profileScopes
[profile
][scope
] = scopeIndex
[scope
]; // eslint-disable-line security/detect-object-injection
414 profiles: [...profileSet
],
422 * Sets list of additional scopes available to profile.
424 * @param {String} profile
425 * @param {String[]} scopes
426 * @returns {Promise<void>}
428 async
profileScopesSetAll(dbCtx
, profile
, scopes
) {
429 this._notImplemented('profileScopesSetAll', arguments
);
434 * Create (or revoke a duplicate) code as a token entry.
436 * @param {Object} data
437 * @param {String} data.codeId
438 * @param {Date} data.created
439 * @param {Boolean} data.isToken
440 * @param {String} data.clientId
441 * @param {String} data.profile - profile uri
442 * @param {String} data.identifier
443 * @param {String[]} data.scopes
444 * @param {Number|Null} data.lifespanSeconds - null sets expiration to Infinity
445 * @param {Number|Null} data.refreshLifespanSeconds - null sets refresh to none
446 * @param {String|Null} data.resource
447 * @param {Object|Null} data.profileData - profile data from profile uri
448 * @returns {Promise<Boolean>} whether redemption was successful
450 async
redeemCode(dbCtx
, { codeId
, created
, isToken
, clientId
, profile
, identifier
, scopes
, lifespanSeconds
, refreshLifespanSeconds
, profileData
} = {}) {
451 this._notImplemented('redeemCode', arguments
);
456 * @typedef {Object} RefreshedToken
457 * @property {Date} expires
458 * @property {Date} refreshExpires
459 * @property {String[]=} scopes if scopes were reduced
462 * Redeem a refresh token to renew token codeId.
464 * @param {String} codeId
465 * @param {Date} refreshed
466 * @param {String[]} removeScopes
467 * @returns {Promise<RefreshedToken>}
469 async
refreshCode(dbCtx
, codeId
, refreshed
, removeScopes
) {
470 this._notImplemented('refreshCode', arguments
);
475 * Fetch a resource server record.
477 * @param {String} identifier uuid
478 * @returns {Promise<Resource>}
480 async
resourceGet(dbCtx
, resourceId
) {
481 this._notImplemented('resourceGet', arguments
);
486 * Create, or update description of, a resourceId.
488 * @param {String=} resourceId uuid
489 * @param {String=} secret
490 * @param {String=} description
491 * @returns {Promise<void>}
493 async
resourceUpsert(dbCtx
, resourceId
, secret
, description
) {
494 this._notImplemented('resourceUpsert', arguments
);
499 * Register a scope and its description.
501 * @param {String} scope
502 * @param {String} application
503 * @param {String} description
504 * @returns {Promise<void>}
506 async
scopeUpsert(dbCtx
, scope
, application
, description
, manuallyAdded
= false) {
507 this._notImplemented('scopeUpsert', arguments
);
512 * Remove a non-permanent scope if it is not currently in use.
514 * @param {String} scope
515 * @returns {Promise<Boolean>}
517 async
scopeDelete(dbCtx
, scope
) {
518 this._notImplemented('scopeDelete', arguments
);
523 * @typedef {Number|BigInt} CleanupResult
526 * @typedef {Object} CleanupResult
529 * Remove any non-permanent and non-manually-created scopes not currently in use.
531 * @param {Number} atLeastMsSinceLast skip cleanup if already executed this recently
532 * @returns {Promise<CleanupResult>}
534 async
scopeCleanup(dbCtx
, atLeastMsSinceLast
) {
535 this._notImplemented('scopeClean', arguments
);
540 * Forget tokens after they have expired, and redeemed codes after they have expired.
542 * @param {Number} codeLifespanSeconds
543 * @param {Number} atLeastMsSinceLast skip cleanup if already executed this recently
544 * @returns {Promise<CleanupResult>}
546 async
tokenCleanup(dbCtx
, codeLifespanSeconds
, atLeastMsSinceLast
) {
547 this._notImplemented('tokenCleanup', arguments
);
552 * Look up a redeemed token by code_id.
554 * @param {String} codeId
555 * @returns {Promise<Token>}
557 async
tokenGetByCodeId(dbCtx
, codeId
) {
558 this._notImplemented('tokenGetByCodeId', arguments
);
563 * Sets a redeemed token as revoked.
565 * @param {String} codeId - uuid
566 * @returns {Promise<void>}
568 async
tokenRevokeByCodeId(dbCtx
, codeId
) {
569 this._notImplemented('tokenRevokeByCodeId', arguments
);
574 * Revoke the refreshability of a codeId.
576 * @param {String} codeId - uuid
577 * @returns {Promise<void>}
579 async
tokenRefreshRevokeByCodeId(dbCtx
, codeId
) {
580 this._notImplemented('tokenRefreshRevokeByCodeId', arguments
);
585 * Get all tokens assigned to identifier.
587 * @param {String} identifier
588 * @returns {Promise<Tokens[]>}
590 async
tokensGetByIdentifier(dbCtx
, identifier
) {
591 this._notImplemented('tokensGetByIdentifier', arguments
);
595 /** @typedef {Object} RedeemedTicketData
596 * @property {String} subject
597 * @property {String} resource
598 * @property {String=} iss
599 * @property {String} ticket
600 * @property {String} token
603 * Persist details of a redeemed ticket.
605 * @param {RedeemedTicketData} redeemedData
606 * @returns {Promise<void>}
608 async
ticketRedeemed(dbCtx
, redeemedData
) {
609 this._notImplemented('ticketRedeemed', arguments
);
614 * Update details of a redeemed ticket that it has been published.
616 * @param {RedeemedTicketData} redeemedData
617 * @returns {Promise<void>}
619 async
ticketTokenPublished(dbCtx
, redeemedData
) {
620 this._notImplemented('ticketTokenPublished', arguments
);
624 * Retrieve redeemed tokens which have not yet been published to queue.
625 * @param {Number} limit
626 * @returns {Promise<RedeemedData[]>}
628 async
ticketTokenGetUnpublished(dbCtx
, limit
) {
629 this._notImplemented('ticketTokenGetUnpublished', arguments
);
634 module
.exports
= Database
;