import type { Settings } from "@opengeni/config"; /** * File-mounted password for the runtime database login, so the password can be * rotated while pods keep running, without a restart. * * PostgreSQL keeps one password per role, and every pool opens new connections * all the time (idle timeout, maximum lifetime, growth under load). A password * fixed in the connection URL at process start therefore breaks every new * connection the moment the role's password changes. With these files the pool * reads the password on every connection attempt instead, and during a rotation * it holds two candidates: the previous password (still valid until the role * changes) and the current one (valid afterwards). * * Rotation contract for operators (in this order; docs/deployment.md): * 1. write previous = old password and current = new password, and confirm * kubelet refreshed the mounted Secret files on every pod (no restart); * 2. in one step, change the role's password and update the role * provisioning password and the URL password; each pool switches to the * current password on the first 28P01 of a login that used the previous * one, and logins that were already authenticating with it are refused * without moving the pool again; * 3. clear the previous file. */ export type DatabasePasswordFiles = { /** File holding the current password. Missing or empty: the URL password. */ currentPasswordFile?: string; /** File holding the previous password during a rotation. Missing or empty: none. */ previousPasswordFile?: string; }; /** * Content-free credential events. They carry candidate indexes and counts only, * never a password, a password length or a file's contents. */ export type DatabaseCredentialEvent = { /** The files changed, so the candidate order starts again at the first. */ type: "candidates_reloaded"; candidates: number; } | { /** * A login that used candidate `index` was refused with 28P01. `stale`: * the pool had already selected another password since that login read * its own, so the refusal neither moves the pool nor uses up an * operation's attempts. */ type: "candidate_refused"; index: number; candidates: number; stale: boolean; } | { /** A 28P01 of a login that used the selected candidate moved the pool to the next one. */ type: "candidate_switched"; fromIndex: number; toIndex: number; candidates: number; } | { /** * An operation gave up after a 28P01; its 28P01 surfaces. `reason`: * `every_candidate_refused` (each candidate refused this operation * while selected: the files hold no valid password) or `attempt_cap` * ({@link DATABASE_AUTHENTICATION_MAX_ATTEMPTS} attempts were made). */ type: "candidates_exhausted"; index: number; candidates: number; reason: DatabaseCredentialExhaustion; } | { /** A configured file exists but could not be read; it is treated as missing. */ type: "password_file_unreadable"; file: "current" | "previous"; code: string; }; /** Why an operation gave up after a 28P01 (see `candidates_exhausted`). */ export type DatabaseCredentialExhaustion = "every_candidate_refused" | "attempt_cap"; /** * Receives a pool's credential events. `createDb` also says which of its * connections the event is about: the query pool or its session-list LISTEN * connection (each keeps its own candidate index). */ export type DatabaseCredentialEventListener = (event: DatabaseCredentialEvent, connection?: "pool" | "notifications") => void; type PasswordFileSettings = Partial>; /** * The runtime login's password files from deployment settings * (`OPENGENI_DATABASE_PASSWORD_FILE`, `OPENGENI_DATABASE_PREVIOUS_PASSWORD_FILE`), * shaped as `createDb` options. Use only for pools that log in as the runtime * role (`OPENGENI_DATABASE_URL`): the files hold that login's password, never a * dedicated service role's. Neither setting → `{}` (the URL password, as before). */ export declare function databasePasswordFileOptions(settings: PasswordFileSettings): { passwordFiles?: DatabasePasswordFiles; }; /** Same as {@link databasePasswordFileOptions} for env-only entry points (CLIs). */ export declare function databasePasswordFileOptionsFromEnvironment(environment?: NodeJS.ProcessEnv): { passwordFiles?: DatabasePasswordFiles; }; /** A pool's file-backed password source, or undefined for today's URL password. */ export declare function rotatingDatabasePasswordFor(databaseUrl: string, passwordFiles: DatabasePasswordFiles | undefined, onEvent: DatabaseCredentialEventListener | undefined): RotatingDatabasePassword | undefined; /** PostgreSQL `invalid_password`. Raised only while authenticating a new connection. */ export declare const DATABASE_AUTHENTICATION_FAILURE_SQLSTATE = "28P01"; /** * The property under which an error raised while a connection was logging in * carries that login attempt's identity: the object the driver also passed to * the password function for that attempt. Our postgres.js patch sets it on * errors raised before any query ran; the managed-auth `pg` client sets it * with {@link tagDatabaseLoginAttempt}. */ export declare const DATABASE_LOGIN_ATTEMPT: unique symbol; /** Mark `error` as raised by the login attempt `login`; never throws. */ export declare function tagDatabaseLoginAttempt(error: unknown, login: object): void; /** The login attempt that raised `error` (or a nested cause), when the driver tagged it. */ export declare function databaseLoginAttemptOf(error: unknown): object | undefined; /** The event's one-line, content-free log message. */ export declare function databaseCredentialEventMessage(event: DatabaseCredentialEvent): string; /** * The log attributes of a credential event: the pool's name and the event's * index, count and stale facts, never a password. These names (and their * value grammars) are reviewed for the public telemetry boundary in * `@opengeni/observability`, which drops any other key from external logs. */ export declare function databaseCredentialEventAttributes(pool: string, event: DatabaseCredentialEvent, connection?: "pool" | "notifications"): Record; /** * One content-free log line per event: the message and * {@link databaseCredentialEventAttributes}. Refusals are logged too. * Defaults to `console.warn`, for processes without structured logging (CLIs, * scripts); {@link observeDatabaseCredentialEvents} also rate-limits. */ export declare function logDatabaseCredentialEvent(pool: string, log?: (message: string, attributes: Record) => void): DatabaseCredentialEventListener; /** * Prometheus counters of credential events, labelled by pool (`pool`, with a * `-notifications` suffix for a LISTEN connection) and candidate index, never * by a password. Indexes are positions in the candidate list * `[previous, current]`: with two candidates, 0 is the previous file's * password and 1 the current file's; with one, 0 is the only password (the * current file, or the URL password). */ export declare const DATABASE_CREDENTIAL_METRICS: { /** Labels: pool, index (the refused login's candidate), refusal ("stale" | "fresh"). */ readonly refusals: { readonly name: "opengeni_database_credential_refusals_total"; readonly help: "Database logins refused with 28P01, by pool, the login's candidate index and whether the pool had already moved past it (stale)."; }; /** Labels: pool, from_index, to_index. */ readonly switches: { readonly name: "opengeni_database_credential_switches_total"; readonly help: "Database pools that moved to the next password candidate after a fresh 28P01, by pool."; }; /** * Labels: pool, index (the selected candidate when the operation gave up), * reason ("every_candidate_refused" | "attempt_cap"). */ readonly exhaustions: { readonly name: "opengeni_database_credential_exhaustions_total"; readonly help: "Database operations that gave up after a 28P01 and surfaced it, by pool and reason."; }; /** Labels: pool, candidates (how many passwords the reloaded files offer). */ readonly reloads: { readonly name: "opengeni_database_credential_reloads_total"; readonly help: "Database password file changes a pool picked up, by pool and candidate count."; }; }; /** The part of an `Observability` that {@link observeDatabaseCredentialEvents} uses. */ export type DatabaseCredentialObserver = { warn(message: string, attributes: Record): void; incrementCounter(input: { name: string; help?: string; labels?: Record; }): void; }; /** * How often {@link observeDatabaseCredentialEvents} logs a repeated refusal, * switch or exhaustion of one pool (same kind and indexes). A rotation logs * each pool's first refusal and its switch; a wrong password that refuses * every login does not flood the logs. The counters stay exact. */ export declare const DATABASE_CREDENTIAL_LOG_INTERVAL_MS = 10000; /** * Logs credential events through `observability.warn` (see * {@link logDatabaseCredentialEvent}), repeated refusals, switches and * exhaustions at most once per {@link DATABASE_CREDENTIAL_LOG_INTERVAL_MS} * per pool and kind (the next logged line carries `suppressedCount`), and * counts every refusal, switch, exhaustion and reload * ({@link DATABASE_CREDENTIAL_METRICS}). An observer failure never reaches the * pool. */ export declare function observeDatabaseCredentialEvents(pool: string, observability: DatabaseCredentialObserver, options?: { logIntervalMs?: number; now?: () => number; }): DatabaseCredentialEventListener; /** * The password postgres.js would use for this URL when no `pass` option is * given: the URL's (percent-decoded) password, then `PGPASSWORD`, then empty. */ export declare function databaseUrlPassword(databaseUrl: string, environment?: NodeJS.ProcessEnv): string; /** The login name in a connection URL, percent-decoded; null when absent. */ export declare function databaseUrlUser(databaseUrl: string): string | null; /** True for a PostgreSQL authentication failure, including under nested causes. */ export declare function isDatabaseAuthenticationFailure(error: unknown): boolean; /** * Hard cap on the attempts of one operation. A refused operation is retried * whenever the pool selects another password than the refused login used, so * a rotation costs it one extra attempt, and a rollback that lands while it * retries one more; this bounds the rest, such as files with no valid * password. */ export declare const DATABASE_AUTHENTICATION_MAX_ATTEMPTS = 5; /** * @deprecated There is no time-based grace any more: a refusal is attributed * to the password its own login used, so stale refusals never move a pool. * Kept, at 0, for compatibility; nothing reads it. */ export declare const DATABASE_CREDENTIAL_STALE_FAILURE_GRACE_MS = 0; /** * Which candidate a login used. `generation` counts changes of the files' * contents (the candidate list); `selection` counts every change of the * selected candidate (a reload that changed the list, or a switch), so a * login refused after the pool moved on is recognized as stale even when the * pool has since come back to the same index. */ export type DatabaseCredentialPosition = { readonly generation: number; readonly selection: number; readonly index: number; }; /** * What a reported 28P01 did: `stale` (the login used a password the pool no * longer selects; nothing changed), `switched` (the pool moved to the next * candidate) or `unchanged` (the selected candidate was refused and no other * exists). */ export type DatabaseAuthenticationRefusal = "stale" | "switched" | "unchanged"; export type RotatingDatabasePasswordOptions = { files: DatabasePasswordFiles; /** Used when the current file is missing or empty (normally the URL password). */ fallbackPassword: string; onEvent?: DatabaseCredentialEventListener; /** Test seam; defaults to reading the file as UTF-8. */ readPasswordFile?: (path: string) => Promise; /** @deprecated Ignored: there is no time-based grace any more. */ staleFailureGraceMs?: number; /** @deprecated Ignored: there is no time-based grace any more. */ now?: () => number; }; /** * One pool's password source: candidates `[previous, current]` (previous only * when non-empty and different) with a sticky index. * * - Every connection attempt calls {@link password}, which re-reads both files, * so kubelet Secret updates apply without a restart. Only a change in the * files' contents resets the order to the first candidate (a new * "generation"); concurrent reads apply in the order they started. * - {@link password} records, per login attempt, the position it handed out. * A 28P01 is attributed to the refused login's own position * ({@link refusedPosition}), never to what the pool selects by the time the * refusal arrives. * - The index moves to the next candidate only after a 28P01 of a login that * used the currently selected candidate ({@link reportAuthenticationFailure}), * and then stays there. Logins that read an earlier selection are stale: * their refusals never move the pool, so concurrent refusals of one * candidate move it once, and a refusal of the newly selected candidate * moves it on at once, wrapping from the last to the first (for example * when a rollback reset the role to the old password). There is no * time-based grace. * * Passwords stay in memory only and never reach an event, an error or a log. */ export declare class RotatingDatabasePassword { #private; constructor(options: RotatingDatabasePasswordOptions); /** How many distinct passwords the last read produced (at least one). */ get candidateCount(): number; /** The selected candidate's position; for diagnostics and tests. */ get candidateIndex(): number; /** The selected candidate's position now. */ position(): DatabaseCredentialPosition; /** * The password for a connection attempt. Re-reads the files first. Pass the * driver's identity for this login attempt (`login`) so a 28P01 it raises * is attributed to exactly the password handed out here. */ password(login?: object): Promise; /** * The position the refused login used, from the login identity the driver * tagged `error` with; undefined when the error carries none (an untagged * driver) or the login was not handed a password by this source. */ refusedPosition(error: unknown): DatabaseCredentialPosition | undefined; /** Re-read the files; reset the order only when their contents changed. */ reload(): Promise; /** * Record a 28P01 of a login that used `refused` (see {@link refusedPosition}). * Moves to the next candidate only when that login used the current * selection and another distinct candidate exists. A stale refusal (the * selection changed since the login read its password) changes nothing. */ reportAuthenticationFailure(refused: DatabaseCredentialPosition): DatabaseAuthenticationRefusal; /** Record that an operation gave up after a 28P01 (see `candidates_exhausted`). */ reportExhausted(reason?: DatabaseCredentialExhaustion): void; } /** * Run `attempt` again after a 28P01, on the candidate the pool then selects. * The decision follows the refused login's own password, not the operation's: * - the pool now selects another password than the refused login used (a * stale refusal, or a fresh one that moved the pool on): retry; * - the refused login used the selected password and no other candidate * exists (a single password): fail fast, as before; * - and never more than {@link DATABASE_AUTHENTICATION_MAX_ATTEMPTS} attempts. * A password refused earlier in the operation is tried again when the pool * comes back to it: a rollback can make it valid again while the operation * retries. Without a credential (no password files) this is just `attempt()`. * * The refused login is identified by the driver's login tag * ({@link DATABASE_LOGIN_ATTEMPT}); an untagged 28P01 is attributed to the * candidate selected when the attempt started. * * Callers must only pass operations whose 28P01 proves that nothing ran: * PostgreSQL raises 28P01 only while authenticating a new connection, before * the server has accepted any statement on it, so running such an operation * again cannot apply anything twice. `canRetry` lets a caller veto a retry * when the operation got past that point (a transaction whose callback ran). * The last 28P01 surfaces unchanged. */ export declare function withDatabaseAuthenticationRetry(credential: RotatingDatabasePassword | undefined, attempt: () => Promise, canRetry?: () => boolean): Promise; export {};