a127c3978e8e8347c38e9e4d031ed9e9ed79199b
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 major
44 * @property {number} minor minor
45 * @property {number} patch 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>} schema version
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.
76 * @param {*} dbCtx db 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 object
105 * @param {string[]} properties properties
106 * @param {string[]} types 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 identifier
162 * @property {string=} credential credential
163 * @property {Date} created created
164 * @property {Date=} lastAuthentication last authentication
167 * @param {Authentication} 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 secret
183 * @property {string} description description
184 * @property {Date} created created at
187 * @param {Resource} 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 profile
202 * @property {Date} created created at
203 * @property {Date=} expires expires at
204 * @property {Date=} refreshExpires refresh expires at
205 * @property {Date=} refreshed refreshed at
206 * @property {*=} duration duration
207 * @property {*=} refreshDuration refresh duration
208 * @property {number | bigint=} refresh_count refresh count
209 * @property {boolean} is_revoked is revoked
210 * @property {boolean} is_token is token
211 * @property {string} client_id client id
212 * @property {string[]} scopes scopes
213 * @property {object=} profileData profile data
216 * @param {Token} 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 method
237 * @param {arguments} args 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.
247 * @param {*} dbCtx db context
249 async
almanacGetAll(dbCtx
) {
250 this._notImplemented('almanacGetAll', arguments
);
255 * Insert or update an almanac entry.
256 * @param {*} dbCtx db context
257 * @param {string} event event
258 * @param {Date=} date date
260 async
almanacUpsert(dbCtx
, event
, date
) {
261 this._notImplemented('almanacUpsert', arguments
);
266 * Fetch the authentication record for an identifier.
267 * @param {*} dbCtx db context
268 * @param {string} identifier identifier
269 * @returns {Promise<Authentication>} 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.
279 * @param {*} dbCtx db context
280 * @param {string} identifier identifier
281 * @returns {Promise<void>}
283 async
authenticationSuccess(dbCtx
, identifier
) {
284 this._notImplemented('authenticationSuccess', arguments
);
289 * Insert or update the credential for an identifier.
290 * @param {*} dbCtx db context
291 * @param {string} identifier identifier
292 * @param {string} credential credential
293 * @param {string=} otpKey otp key
294 * @returns {Promise<void>}
296 async
authenticationUpsert(dbCtx
, identifier
, credential
, otpKey
) {
297 this._notImplemented('authenticationUpsert', arguments
);
302 * Update the otpKey for an identifier.
303 * @param {*} dbCtx db context
304 * @param {string} identifier identifier
305 * @param {string=} otpKey otp key
306 * @returns {Promise<void>}
308 async
authenticationUpdateOTPKey(dbCtx
, identifier
, otpKey
) {
309 this._notImplemented('authenticationUpdateOTPKey', arguments
);
314 * Update the credential for an identifier.
315 * @param {*} dbCtx db context
316 * @param {string} identifier identifier
317 * @param {string} credential credential
318 * @returns {Promise<void>}
320 async
authenticationUpdateCredential(dbCtx
, identifier
, credential
) {
321 this._notImplemented('authenticationUpdateCredentials', arguments
);
326 * Determine if profile url is known to this service.
327 * @param {*} dbCtx db context
328 * @param {string} profile profile
329 * @returns {Promise<boolean>} is valid
331 async
profileIsValid(dbCtx
, profile
) {
332 this._notImplemented('profileGet', arguments
);
337 * Insert a new relationship between a profile endpoint and
338 * an authenticated identifier.
339 * @param {*} dbCtx db context
340 * @param {string} profile profile
341 * @param {string} identifier identifier
342 * @returns {Promise<void>}
344 async
profileIdentifierInsert(dbCtx
, profile
, identifier
) {
345 this._notImplemented('profileIdentifierInsert', arguments
);
350 * Adds a scope to be available for a profile to include on any authorization request.
351 * @param {*} dbCtx db context
352 * @param {string} profile profile
353 * @param {string} scope scope
354 * @returns {Promise<void>}
356 async
profileScopeInsert(dbCtx
, profile
, scope
) {
357 this._notImplemented('profileScopeInsert', arguments
);
362 * @typedef {object} ScopeDetails
363 * @property {string} description description
364 * @property {string[]=} profiles profiles
367 * @typedef {object} Profile
368 * @property {ScopeDetails} scope scope
371 * @typedef {{[profile: string]: Profile}} ProfileScopes
374 * @typedef {{[scope: string]: ScopeDetails}} ScopeIndex
375 * @property {ScopeDetails} scope scope details
378 * @typedef {object} ProfilesScopesReturn
379 * @property {ProfileScopes} profileScopes profile scopes
380 * @property {ScopeIndex} scopeIndex scope index
381 * @property {string[]} profiles profiles
384 * Returns an object containing:
385 * - an object with profiles as keys to objects with scopes as keys to scope objects,
386 * which each contain a description of the scope and a list of profiles offering it
387 * - an object with scopes as keys to the same scope objects
388 * - a list of profiles
389 * @param {*} dbCtx db context
390 * @param {string} identifier identifier
391 * @returns {Promise<ProfilesScopesReturn>} profiles scopes
393 async
profilesScopesByIdentifier(dbCtx
, identifier
) {
394 this._notImplemented('profilesScopesByIdentifier', arguments
);
399 * @typedef ProfileScopesRow
400 * @property {string} profile profile
401 * @property {string} scope scope
402 * @property {string} description description
403 * @property {string} application application
404 * @property {boolean} isPermanent avoid cleanup
405 * @property {boolean} isManuallyAdded avoid cleanup
408 * Convert db row data into associative structures.
409 * Same behavior is shared by multiple engines.
410 * @param {ProfileScopesRow[]} profileScopesRows profile scopes row
411 * @returns {ProfilesScopesReturn} profiles scopes
413 static _profilesScopesBuilder(profileScopesRows
) {
414 const scopeIndex
= {};
415 const profileScopes
= {};
416 const profileSet
= new Set();
418 (profileScopesRows
|| []).forEach(({ profile
, scope
, description
, application
, isPermanent
, isManuallyAdded
}) => {
419 if (scope
&& !(scope
in scopeIndex
)) {
420 scopeIndex
[scope
] = { // eslint-disable-line security/detect-object-injection
429 profileSet
.add(profile
);
430 if (!(profile
in profileScopes
)) {
431 profileScopes
[profile
] = {}; // eslint-disable-line security/detect-object-injection
434 if (profile
&& scope
) {
435 scopeIndex
[scope
].profiles
.push(profile
); // eslint-disable-line security/detect-object-injection
436 profileScopes
[profile
][scope
] = scopeIndex
[scope
]; // eslint-disable-line security/detect-object-injection
441 profiles: [...profileSet
],
449 * Sets list of additional scopes available to profile.
450 * @param {*} dbCtx db context
451 * @param {string} profile profile
452 * @param {string[]} scopes scopes
453 * @returns {Promise<void>}
455 async
profileScopesSetAll(dbCtx
, profile
, scopes
) {
456 this._notImplemented('profileScopesSetAll', arguments
);
461 * Create (or revoke a duplicate) code as a token entry.
462 * @param {*} dbCtx db context
463 * @param {object} data data
464 * @param {string} data.codeId code id
465 * @param {Date} data.created created at
466 * @param {boolean} data.isToken is token
467 * @param {string} data.clientId client id
468 * @param {string} data.profile profile uri
469 * @param {string} data.identifier identifier
470 * @param {string[]} data.scopes scopesx
471 * @param {number | null} data.lifespanSeconds null sets expiration to Infinity
472 * @param {number | null} data.refreshLifespanSeconds null sets refresh to none
473 * @param {object | null} data.profileData profile data from profile uri
474 * @returns {Promise<boolean>} whether redemption was successful
476 async
redeemCode(dbCtx
, { codeId
, created
, isToken
, clientId
, profile
, identifier
, scopes
, lifespanSeconds
, refreshLifespanSeconds
, profileData
} = {}) {
477 this._notImplemented('redeemCode', arguments
);
482 * @typedef {object} RefreshedToken
483 * @property {Date} expires expires at
484 * @property {Date} refreshExpires refresh expires at
485 * @property {string[]=} scopes if scopes were reduced
488 * Redeem a refresh token to renew token codeId.
489 * @param {*} dbCtx db context
490 * @param {string} codeId code id
491 * @param {Date} refreshed refreshed at
492 * @param {string[]} removeScopes remove scopes
493 * @returns {Promise<RefreshedToken>} refreshed token
495 async
refreshCode(dbCtx
, codeId
, refreshed
, removeScopes
) {
496 this._notImplemented('refreshCode', arguments
);
501 * Fetch a resource server record.
502 * @param {*} dbCtx db context
503 * @param {string} resourceId uuid
504 * @returns {Promise<Resource>} resource
506 async
resourceGet(dbCtx
, resourceId
) {
507 this._notImplemented('resourceGet', arguments
);
512 * Create, or update description of, a resourceId.
513 * @param {*} dbCtx db context
514 * @param {string=} resourceId uuid
515 * @param {string=} secret secret
516 * @param {string=} description description
517 * @returns {Promise<void>}
519 async
resourceUpsert(dbCtx
, resourceId
, secret
, description
) {
520 this._notImplemented('resourceUpsert', arguments
);
525 * Register a scope and its description.
526 * @param {*} dbCtx db context
527 * @param {string} scope scope
528 * @param {string} application application
529 * @param {string} description description
530 * @param {boolean} manuallyAdded is manually added
531 * @returns {Promise<void>}
533 async
scopeUpsert(dbCtx
, scope
, application
, description
, manuallyAdded
= false) {
534 this._notImplemented('scopeUpsert', arguments
);
539 * Remove a non-permanent scope if it is not currently in use.
540 * @param {*} dbCtx db context
541 * @param {string} scope scope
542 * @returns {Promise<boolean>} deleted
544 async
scopeDelete(dbCtx
, scope
) {
545 this._notImplemented('scopeDelete', arguments
);
550 * @typedef {number | bigint} CleanupResult
553 * @alias {object} CleanupResult
556 * Remove any non-permanent and non-manually-created scopes not currently in use.
557 * @param {*} dbCtx db context
558 * @param {number} atLeastMsSinceLast skip cleanup if already executed this recently
559 * @returns {Promise<CleanupResult>} cleanup result
561 async
scopeCleanup(dbCtx
, atLeastMsSinceLast
) {
562 this._notImplemented('scopeClean', arguments
);
567 * Forget tokens after they have expired, and redeemed codes after they have expired.
568 * @param {*} dbCtx db context
569 * @param {number} codeLifespanSeconds code lifespan seconds
570 * @param {number} atLeastMsSinceLast skip cleanup if already executed this recently
571 * @returns {Promise<CleanupResult>} cleanup result
573 async
tokenCleanup(dbCtx
, codeLifespanSeconds
, atLeastMsSinceLast
) {
574 this._notImplemented('tokenCleanup', arguments
);
579 * Look up a redeemed token by code_id.
580 * @param {*} dbCtx db context
581 * @param {string} codeId code id
582 * @returns {Promise<Token>} token
584 async
tokenGetByCodeId(dbCtx
, codeId
) {
585 this._notImplemented('tokenGetByCodeId', arguments
);
590 * Sets a redeemed token as revoked.
591 * @param {*} dbCtx db context
592 * @param {string} codeId - uuid
593 * @returns {Promise<void>}
595 async
tokenRevokeByCodeId(dbCtx
, codeId
) {
596 this._notImplemented('tokenRevokeByCodeId', arguments
);
601 * Revoke the refreshability of a codeId.
602 * @param {*} dbCtx db context
603 * @param {string} codeId - uuid
604 * @returns {Promise<void>}
606 async
tokenRefreshRevokeByCodeId(dbCtx
, codeId
) {
607 this._notImplemented('tokenRefreshRevokeByCodeId', arguments
);
612 * Get all tokens assigned to identifier.
613 * @param {*} dbCtx db context
614 * @param {string} identifier identifier
615 * @returns {Promise<Token[]>} token
617 async
tokensGetByIdentifier(dbCtx
, identifier
) {
618 this._notImplemented('tokensGetByIdentifier', arguments
);
623 * @typedef {object} RedeemedTicketData
624 * @property {string} subject subject
625 * @property {string} resource resource
626 * @property {string=} iss issuer
627 * @property {string} ticket ticket
628 * @property {string} token token
631 * Persist details of a redeemed ticket.
632 * @param {*} dbCtx db context
633 * @param {RedeemedTicketData} redeemedData redeemed data
634 * @returns {Promise<void>}
636 async
ticketRedeemed(dbCtx
, redeemedData
) {
637 this._notImplemented('ticketRedeemed', arguments
);
642 * Update details of a redeemed ticket that it has been published.
643 * @param {*} dbCtx db context
644 * @param {RedeemedTicketData} redeemedData redeemed data
645 * @returns {Promise<void>}
647 async
ticketTokenPublished(dbCtx
, redeemedData
) {
648 this._notImplemented('ticketTokenPublished', arguments
);
653 * Retrieve redeemed tokens which have not yet been published to queue.
654 * @param {*} dbCtx db context
655 * @param {number} limit limit
656 * @returns {Promise<RedeemedTicketData[]>} redeemed but not published
658 async
ticketTokenGetUnpublished(dbCtx
, limit
) {
659 this._notImplemented('ticketTokenGetUnpublished', arguments
);
664 module
.exports
= Database
;