diff --git a/.changeset/postgres-entra-auth.md b/.changeset/postgres-entra-auth.md new file mode 100644 index 0000000..fd53eca --- /dev/null +++ b/.changeset/postgres-entra-auth.md @@ -0,0 +1,7 @@ +--- +"@cosyte/pathways": patch +--- + +A `storage.postgres` block now takes `auth: entra`, which signs in to Azure Database for PostgreSQL with a Microsoft Entra ID access token from Azure's default chain (a managed identity, with `AZURE_CLIENT_ID` naming a user-assigned one) in place of a password, for both `pathways start` and `pathways migrate`. + +The connection URL names the database user and holds no password, such as `postgres://@:5432/pathways`. Each new connection signs in with a token for `https://ossrdbms-aad.database.windows.net/.default`, reused until 5 minutes before it expires and then asked for again. No token reaches a log or an error: when none can be had, the connection fails with the code `ERR_PATHWAYS_ENTRA_TOKEN`. It needs the optional peer dependency `@azure/identity`, which the Docker image carries. Without `auth`, or with `auth: password`, a block signs in with the login its URL holds, as before. diff --git a/README.md b/README.md index 813677a..e4df34d 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ version is 0.0.x, and a release may still change a key or an API, which its chan - [Why this exists](#why-this-exists) - [Status](#status) - [What the latest release ships](#what-the-latest-release-ships) +- [In the next release](#in-the-next-release) - [Install](#install) - [Usage](#usage) - [Documentation](#documentation) @@ -184,6 +185,19 @@ What follows is in the latest release, the one on npm: --- +## In the next release + +These are on `main` and land in the next release: + +- **PostgreSQL sign-in with Microsoft Entra ID.** `auth: entra` in a `storage.postgres` block signs + in to Azure Database for PostgreSQL with an access token for the managed identity Pathways runs + as, in place of a password, for `pathways start` and `pathways migrate`. The URL names the + database user and holds no password; a token is asked for again before it expires, and none + reaches a log or an error. + + +--- + ## Install Pathways needs Node.js 24 or later. Start a new project with the starter, which lists the package in diff --git a/docs-content/configuration-reference.md b/docs-content/configuration-reference.md index daaff74..15c6d1a 100644 --- a/docs-content/configuration-reference.md +++ b/docs-content/configuration-reference.md @@ -158,14 +158,18 @@ store without it, `pathways start` refuses that channel. #### Database server -| Key | Type | Default | -| ------------------ | ------------------ | -------------------------------- | -| `url` | secret reference | `{ env: PATHWAYS_DATABASE_URL }` | -| `tls` | [client TLS](#tls) | required unless `plaintext` | -| `plaintext` | boolean | `false` | -| `pool.max` | 1 to 1,000 | `10` | -| `pool.idleTimeout` | duration | `30s` | -| `connectTimeout` | duration | `10s` | +| Key | Type | Default | +| ------------------ | -------------------------------------- | -------------------------------- | +| `url` | secret reference | `{ env: PATHWAYS_DATABASE_URL }` | +| `tls` | [client TLS](#tls) | required unless `plaintext` | +| `plaintext` | boolean | `false` | +| `pool.max` | 1 to 1,000 | `10` | +| `pool.idleTimeout` | duration | `30s` | +| `connectTimeout` | duration | `10s` | +| `auth` | `password` or `entra`, PostgreSQL only | `password` | + +`auth: entra` signs in to PostgreSQL with a Microsoft Entra ID access token, for the user the URL +names, with no password in the URL. See [Store messages in a database server](./store-messages-in-a-database.md). diff --git a/docs-content/store-messages-in-a-database.md b/docs-content/store-messages-in-a-database.md index 0c52fad..81779de 100644 --- a/docs-content/store-messages-in-a-database.md +++ b/docs-content/store-messages-in-a-database.md @@ -57,14 +57,15 @@ npx pathways start The key is `postgres`, `mysql` (for MySQL and MariaDB) or `sqlserver`, and the settings are the same for each: -| Setting | Default | What it does | -| ------------------ | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | -| `url` | `{ env: PATHWAYS_DATABASE_URL }` | where the connection URL is read: an environment variable, a file, or a secret store | -| `tls` | required, unless `plaintext` | `{}` verifies the server against Node.js's built-in roots; `ca` trusts your own CA; `cert` and `key` present a client certificate | -| `plaintext` | `false` | `true` connects without TLS | -| `pool.max` | `10` | the most connections the pool opens | -| `pool.idleTimeout` | `30s` | how long an idle connection stays open | -| `connectTimeout` | `10s` | how long connecting may take | +| Setting | Default | What it does | +| ------------------ | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `url` | `{ env: PATHWAYS_DATABASE_URL }` | where the connection URL is read: an environment variable, a file, or a secret store | +| `tls` | required, unless `plaintext` | `{}` verifies the server against Node.js's built-in roots; `ca` trusts your own CA; `cert` and `key` present a client certificate | +| `plaintext` | `false` | `true` connects without TLS | +| `pool.max` | `10` | the most connections the pool opens | +| `pool.idleTimeout` | `30s` | how long an idle connection stays open | +| `connectTimeout` | `10s` | how long connecting may take | +| `auth` | `password` | PostgreSQL only: `entra` signs in with a Microsoft Entra ID access token; see [PostgreSQL with Microsoft Entra ID](#postgresql-with-microsoft-entra-id) | The URL holds the password, so it is read at start and never goes in the YAML: from an environment variable, or as `{ file: path }` or `{ secret: { provider, name } }` (see @@ -76,6 +77,47 @@ with `ssl` options is refused, and a MySQL or SQL Server URL with any options af Errors about the database name the setting at fault and the driver's error code, never the URL, the server or the login. +### PostgreSQL with Microsoft Entra ID + +Azure Database for PostgreSQL can take a Microsoft Entra ID access token in place of a password. With +`auth: entra`, Pathways asks for one as the managed identity it runs as and signs in with it, so no +database password exists: + +```yaml title="pathways.yaml" +storage: + postgres: + url: { env: PATHWAYS_DATABASE_URL } + tls: {} + auth: entra +``` + +- The URL names the database user and holds no password: + `postgres://@:5432/pathways`. The database user is the role the identity signs + in as, which for a managed identity made an Entra administrator is the identity's name. A URL with a + password is refused. +- The token comes from Azure's default chain in `@azure/identity` (`DefaultAzureCredential`): a + managed identity, a workload identity, or the environment. For a user-assigned managed identity, set + `AZURE_CLIENT_ID` to its client id. The Docker image carries `@azure/identity`; elsewhere, install it + in the project. +- Each new connection signs in with a token for the scope + `https://ossrdbms-aad.database.windows.net/.default`. A token is reused until 5 minutes before it + expires, then asked for again, so a pool that opens connections for days never sends an expired + one. A connection already open stays open when its token expires: the server checks the token at + sign-in only. +- `pathways migrate` signs in the same way as `pathways start`, from the same block. +- No token is written to a log, an error, or the output of a command. When none can be had, the + connection fails with the code `ERR_PATHWAYS_ENTRA_TOKEN`, and `pathways start` says + `the database could not be opened (ERR_PATHWAYS_ENTRA_TOKEN)`. + +`auth` may be [read from the environment](./configuration-reference.md#settings-from-the-environment), +such as `auth: { env: PATHWAYS_DATABASE_AUTH, default: password }`, so one file serves a deployment +that signs in with a password and one that does not. `auth: password`, the default, signs in with +the login the URL holds, as before. + +Our Terraform module for Azure, `cosyte/terraform-azurerm-pathways`, gives these names: its +`postgres.database_user` output is the database user, and its identity's `client_id` is the value +for `AZURE_CLIENT_ID`. + ### MySQL and MariaDB: prepared statements On MySQL and MariaDB, every statement that carries a value runs as a prepared statement: the diff --git a/src/config/load.ts b/src/config/load.ts index cfc2254..4247c54 100644 --- a/src/config/load.ts +++ b/src/config/load.ts @@ -609,6 +609,8 @@ function resolveStorage( idleTimeoutMs: server.pool?.idleTimeout ?? DEFAULT_POOL_IDLE_TIMEOUT_MS, }, connectTimeoutMs: server.connectTimeout ?? DEFAULT_DATABASE_CONNECT_TIMEOUT_MS, + // Only when set to entra, so a block without it reads as it did before. + ...(server.auth === "entra" ? { auth: server.auth } : {}), }; } diff --git a/src/config/schema.ts b/src/config/schema.ts index 3cdfc97..026b88a 100644 --- a/src/config/schema.ts +++ b/src/config/schema.ts @@ -1872,6 +1872,45 @@ const storagePool = z }) .meta({ description: "The connection pool." }); +/** + * How Pathways signs in to a PostgreSQL server: `password`, with the login the connection URL holds, + * or `entra`, with a Microsoft Entra ID access token as the password. + * + * @example + * ```ts + * POSTGRES_AUTH_KINDS.includes("entra"); // true + * ``` + */ +export const POSTGRES_AUTH_KINDS = ["password", "entra"] as const; + +/** `auth:` in a database server block, which only a `postgres` block may set. */ +const postgresAuth = envable( + // Stryker disable ObjectLiteral,StringLiteral: hover text, built once as the module loads + z.enum(POSTGRES_AUTH_KINDS).meta({ + description: + "PostgreSQL only. How the engine signs in: password, with the login the URL holds, or entra, with a Microsoft Entra ID access token from Azure's default chain (a managed identity, with AZURE_CLIENT_ID naming a user-assigned one) as the password, for the user the URL names and no password in it. Default password.", + }), +).optional(); +// Stryker restore ObjectLiteral,StringLiteral + +/** `auth:` belongs to a `postgres` block: the other servers sign in with the login the URL holds. */ +function authOnPostgresOnly( + value: { + readonly mysql?: { readonly auth?: unknown } | undefined; + readonly sqlserver?: { readonly auth?: unknown } | undefined; + }, + ctx: z.RefinementCtx, +): void { + for (const kind of ["mysql", "sqlserver"] as const) { + if (value[kind]?.auth === undefined) continue; + ctx.addIssue({ + code: "custom", + path: [kind, "auth"], + message: "is for PostgreSQL only; this server signs in with the login its URL holds", + }); + } +} + /** A database server: PostgreSQL, MySQL or MariaDB, or SQL Server. */ const serverStorage = restate( z @@ -1888,6 +1927,7 @@ const serverStorage = restate( connectTimeout: duration( "How long connecting may take: a duration such as 10s, or a number of milliseconds. Default 10s.", ).optional(), + auth: postgresAuth, }) .superRefine((value, ctx) => tlsOrPlaintext( @@ -2422,7 +2462,8 @@ const storage = restate( }); } }) - .superRefine(optionsWithModule), + .superRefine(optionsWithModule) + .superRefine(authOnPostgresOnly), (json) => { json["dependencies"] = { options: ["module"] }; json.if = { required: ["kind"] }; @@ -4796,8 +4837,23 @@ export interface ServerStorage { }; /** How long connecting may take, in milliseconds. */ readonly connectTimeoutMs: number; + /** + * PostgreSQL only: `entra` signs in with a Microsoft Entra ID access token as the password, for + * the user the URL names. Undefined, or `password`, signs in with the login the URL holds. + */ + readonly auth?: PostgresAuth | undefined; } +/** + * How Pathways signs in to a PostgreSQL server: one of {@link POSTGRES_AUTH_KINDS}. + * + * @example + * ```ts + * const auth: PostgresAuth = "entra"; + * ``` + */ +export type PostgresAuth = (typeof POSTGRES_AUTH_KINDS)[number]; + /** * A database the built-in store opens itself: SQLite, or a database server. * diff --git a/src/storage/dialects.ts b/src/storage/dialects.ts index 5552457..bc8af28 100644 --- a/src/storage/dialects.ts +++ b/src/storage/dialects.ts @@ -23,6 +23,7 @@ import { ConfigError } from "../config/load.js"; import type { DatabaseStorage, ServerStorage, StorageKind } from "../config/schema.js"; import { secretHolder, secretPlace, secretsOf, type SecretReader } from "../secrets/resolve.js"; import { clientTlsOptions, loadClientTls } from "../connectors/tls.js"; +import { defaultEntraCredential, entraPassword, type EntraCredential } from "./entra.js"; type Pg = typeof PgModule; type Mysql2 = typeof Mysql2Module; @@ -96,6 +97,31 @@ export interface DialectOptions { readonly env: SecretReader; /** Imports a driver package. Defaults to a plain `import()`. */ readonly importDriver?: DriverImport; + /** + * Makes the credential a PostgreSQL block with `auth: entra` asks for tokens with. Defaults to + * `DefaultAzureCredential` from `@azure/identity`; tests pass their own. + */ + readonly entraCredential?: () => Promise; +} + +/** The package `auth: entra` asks Microsoft Entra ID for tokens with, an optional peer dependency. */ +const IDENTITY_PACKAGE = "@azure/identity"; + +/** The credential for `auth: entra`, or a refusal naming the package when it is not installed. */ +async function entraCredentialFor( + options: DialectOptions, + where: string, +): Promise { + try { + return await (options.entraCredential ?? defaultEntraCredential)(); + } catch (error) { + // Object() makes a thrown non-object an empty one, with no code. + const { code } = Object(error) as { readonly code?: unknown }; + if (code !== "ERR_MODULE_NOT_FOUND" && code !== "MODULE_NOT_FOUND") throw error; + throw new ConfigError([ + `${where}.auth: entra needs the package ${IDENTITY_PACKAGE}, which is not installed; add it to the project with npm install ${IDENTITY_PACKAGE}`, + ]); + } } /** The URL schemes each database server's connection URL may use; the first is the one errors name. */ @@ -141,7 +167,10 @@ export async function dialectFor( switch (storage.kind) { case "postgres": { const [pg] = await loadDrivers(storage.kind, load, where); - return postgresDialect(pg as Pg, storage, url, tls); + if (storage.auth !== "entra") return postgresDialect(pg as Pg, storage, url, tls); + entraUrl(url, secretHolder(storage.url), `${where}.url`); + const credential = await entraCredentialFor(options, where); + return postgresDialect(pg as Pg, storage, url, tls, entraPassword(credential)); } case "mysql": { const [mysql2] = await loadDrivers(storage.kind, load, where); @@ -235,14 +264,63 @@ export function cachedStatements( /** TLS options as the drivers take them: verified always, with a CA and client pair when set. */ type TlsOptions = Readonly>; +/** + * Checks a URL for `auth: entra`: it names the user, the database user the identity signs in as, + * and holds no password, since the password is a token asked for per connection. + */ +function entraUrl(url: URL, name: string, where: string): void { + if (url.password !== "") { + throw new ConfigError([ + `${where}: the URL in ${name} holds a password; with auth: entra the password is an access token, so leave it out`, + ]); + } + if (url.username === "") { + throw new ConfigError([ + `${where}: the URL in ${name} names no user; with auth: entra it names the database user the identity signs in as`, + ]); + } + // A URL with a user and no host does not parse, so readUrl has refused it already. + try { + address(url, 0); + } catch { + throw new ConfigError([`${where}: the URL in ${name} is not percent-encoded correctly`]); + } +} + +/** The PostgreSQL default port. */ +const POSTGRES_PORT = 5_432; + +/** + * Where pg connects and as whom. With a password function (`auth: entra`), the URL taken apart, as + * pg would read it, with the function as the password: pg reads a URL's empty password over the + * one it is given. Without one, the URL as it is. + */ +function postgresTarget( + url: URL, + password: (() => Promise) | undefined, +): Readonly> { + if (password === undefined) return { connectionString: url.href }; + const { host, port, user, database } = address(url, POSTGRES_PORT); + return { + // pg reads the URL's other options (application_name, say) as settings of these names. + ...Object.fromEntries(url.searchParams), + host, + port, + user, + ...(database === "" ? {} : { database }), + password, + }; +} + function postgresDialect( pg: Pg, storage: ServerStorage, url: URL, tls: TlsOptions | undefined, + password?: () => Promise, ): Dialect { const pool = new pg.Pool({ - connectionString: url.href, + ...postgresTarget(url, password), // Always set, so neither the URL nor PGSSLMODE decides: readUrl refuses a URL with TLS options. ssl: tls ?? false, max: storage.pool.max, diff --git a/src/storage/entra.ts b/src/storage/entra.ts new file mode 100644 index 0000000..cae3571 --- /dev/null +++ b/src/storage/entra.ts @@ -0,0 +1,131 @@ +/** + * The scope of the access token Azure Database for PostgreSQL takes as a password from a Microsoft + * Entra ID login. + * + * @example + * ```ts + * await credential.getToken(POSTGRES_ENTRA_SCOPE); + * ``` + */ +export const POSTGRES_ENTRA_SCOPE = "https://ossrdbms-aad.database.windows.net/.default"; + +/** + * How long before its expiry a token is replaced, in milliseconds: a new connection never signs in + * with a token that has less left than this. + * + * @example + * ```ts + * const fresh = token.expiresOnTimestamp - ENTRA_TOKEN_MARGIN_MS > Date.now(); + * ``` + */ +export const ENTRA_TOKEN_MARGIN_MS = 300_000; + +/** + * The code of the error a new connection fails with when no token could be had. The key equals the + * value. + * + * @example + * ```ts + * if (error.code === ENTRA_CODES.ERR_PATHWAYS_ENTRA_TOKEN) console.error("no token"); + * ``` + */ +export const ENTRA_CODES = { + ERR_PATHWAYS_ENTRA_TOKEN: "ERR_PATHWAYS_ENTRA_TOKEN", +} as const; + +/** + * An access token, as `@azure/identity`'s credentials give it. + * + * @example + * ```ts + * const token: EntraAccessToken = { token: "synthetic", expiresOnTimestamp: Date.now() + 3_600_000 }; + * ``` + */ +export interface EntraAccessToken { + readonly token: string; + /** When the token expires, in milliseconds since the epoch. */ + readonly expiresOnTimestamp: number; +} + +/** + * A credential that gives access tokens: `DefaultAzureCredential` from `@azure/identity`, or a + * stand-in in a test. + * + * @example + * ```ts + * const credential: EntraCredential = new DefaultAzureCredential(); + * ``` + */ +export interface EntraCredential { + getToken(scopes: string): Promise; +} + +/** + * Azure's default chain, `DefaultAzureCredential` from `@azure/identity`: a managed identity (with + * `AZURE_CLIENT_ID` naming a user-assigned one), a workload identity, or the environment. Making it + * asks for no token. + * + * @throws when `@azure/identity` is not installed, with the code `ERR_MODULE_NOT_FOUND`. + * @example + * ```ts + * const password = entraPassword(await defaultEntraCredential()); + * ``` + */ +export async function defaultEntraCredential(): Promise { + const identity = (await import("@azure/identity")) as unknown as { + readonly DefaultAzureCredential: new () => EntraCredential; + }; + return new identity.DefaultAzureCredential(); +} + +/** The error a connection fails with when no token could be had: a fixed text and a code. */ +function tokenFailure(): Error { + return Object.assign( + new Error("no Microsoft Entra ID access token could be had for the database login"), + { code: ENTRA_CODES.ERR_PATHWAYS_ENTRA_TOKEN }, + ); +} + +/** + * The password function for a PostgreSQL pool that signs in with Microsoft Entra ID: each call, made + * for each new connection, returns an access token for {@link POSTGRES_ENTRA_SCOPE}. A token is + * reused until {@link ENTRA_TOKEN_MARGIN_MS} before it expires, then asked for again; calls made + * while one is asked for share it. When none can be had, the call rejects with a fixed text and the + * code `ERR_PATHWAYS_ENTRA_TOKEN`, never the credential's own error or a token, and the next call + * asks again. + * + * @example + * ```ts + * const pool = new pg.Pool({ host, user, database, password: entraPassword(credential) }); + * ``` + */ +export function entraPassword( + credential: EntraCredential, + now: () => number = Date.now, +): () => Promise { + let current: EntraAccessToken | undefined; + let asking: Promise | undefined; + const ask = async (): Promise => { + let token: EntraAccessToken | null; + try { + token = await credential.getToken(POSTGRES_ENTRA_SCOPE); + } catch { + // The credential's own text is left behind: it is Azure's, and can name the identity. + throw tokenFailure(); + } + if (token === null || typeof token.token !== "string" || token.token === "") { + throw tokenFailure(); + } + current = token; + return token.token; + }; + return () => { + if (current !== undefined && current.expiresOnTimestamp - ENTRA_TOKEN_MARGIN_MS > now()) { + return Promise.resolve(current.token); + } + asking ??= ask().finally(() => { + asking = undefined; + }); + return asking; + }; +} diff --git a/test/postgres-entra.test.ts b/test/postgres-entra.test.ts new file mode 100644 index 0000000..b24e654 --- /dev/null +++ b/test/postgres-entra.test.ts @@ -0,0 +1,518 @@ +import { createServer, type Server, type Socket } from "node:net"; +import { inspect } from "node:util"; + +import { DefaultAzureCredential } from "@azure/identity"; +import { Ajv } from "ajv"; +import { Kysely, sql } from "kysely"; +import pg from "pg"; +import { afterEach, describe, expect, it } from "vitest"; +import { parse as parseYaml } from "yaml"; + +import { ConfigError, loadProject } from "../src/config/load.js"; +import { configJsonSchemas, projectSchema, type ServerStorage } from "../src/config/schema.js"; +import { dialectFor, type DriverImport } from "../src/storage/dialects.js"; +import { + ENTRA_CODES, + ENTRA_TOKEN_MARGIN_MS, + POSTGRES_ENTRA_SCOPE, + defaultEntraCredential, + entraPassword, + type EntraAccessToken, + type EntraCredential, +} from "../src/storage/entra.js"; +import { StorageError } from "../src/storage/store.js"; +import { serverStorage, URL_ENV } from "./_helpers/databases.js"; +import { cleanUp, makeProject } from "./_helpers/helpers.js"; + +afterEach(cleanUp); + +/** Made-up tokens and a made-up password, so a test can check none reaches an error. */ +const TOKEN_ONE = "synthetic-entra-token-0001"; +const TOKEN_TWO = "synthetic-entra-token-0002"; +const PASSWORD = "synthetic-pw-0000"; + +const HOUR = 3_600_000; + +/** A stand-in credential that hands out `answers` in turn and records each scope it was asked for. */ +function fakeCredential(answers: (() => EntraAccessToken | null)[]) { + const scopes: string[] = []; + const credential: EntraCredential = { + getToken: (scope) => { + scopes.push(scope); + const answer = answers.shift(); + if (answer === undefined) return Promise.reject(new Error("no answer left")); + // A throw in the answer becomes the rejection. + return new Promise((resolve) => { + resolve(answer()); + }); + }, + }; + return { credential, scopes }; +} + +/** What a rejected promise rejected with. */ +async function failureOf(promise: Promise): Promise { + const error: unknown = await promise.then( + () => undefined, + (e: unknown) => e, + ); + expect(error).toBeInstanceOf(Error); + return error as Error & { code?: unknown }; +} + +/** Asserts that nothing an error shows, its text, its fields or its cause, holds `secrets`. */ +function expectNoSecret(error: unknown, ...secrets: string[]): void { + const shown = `${String(error)} ${inspect(error, { depth: 5, showHidden: true })} ${JSON.stringify(error)}`; + for (const secret of secrets) expect(shown).not.toContain(secret); +} + +describe("entraPassword", () => { + it("asks for a token for Azure Database for PostgreSQL's scope, and reuses it until near expiry", async () => { + let now = 1_000_000; + const { credential, scopes } = fakeCredential([ + () => ({ token: TOKEN_ONE, expiresOnTimestamp: now + HOUR }), + () => ({ token: TOKEN_TWO, expiresOnTimestamp: now + HOUR }), + ]); + const password = entraPassword(credential, () => now); + expect(await password()).toBe(TOKEN_ONE); + expect(scopes).toEqual(["https://ossrdbms-aad.database.windows.net/.default"]); + expect(POSTGRES_ENTRA_SCOPE).toBe("https://ossrdbms-aad.database.windows.net/.default"); + + // A connection opened later in the token's life reuses it. + now += HOUR - ENTRA_TOKEN_MARGIN_MS - 1; + expect(await password()).toBe(TOKEN_ONE); + expect(scopes).toHaveLength(1); + + // Within the margin of its expiry, the next connection gets a new token. + now += 1; + expect(await password()).toBe(TOKEN_TWO); + expect(scopes).toHaveLength(2); + }); + + it("replaces a token that has expired, and one handed out already near its expiry", async () => { + let now = 5_000_000; + const { credential, scopes } = fakeCredential([ + () => ({ token: TOKEN_ONE, expiresOnTimestamp: now + ENTRA_TOKEN_MARGIN_MS }), + () => ({ token: TOKEN_TWO, expiresOnTimestamp: now + HOUR }), + ]); + const password = entraPassword(credential, () => now); + expect(await password()).toBe(TOKEN_ONE); + // That token was within the margin from the start, so the next connection asks again. + expect(await password()).toBe(TOKEN_TWO); + now += 2 * HOUR; + await expect(password()).rejects.toMatchObject({ code: "ERR_PATHWAYS_ENTRA_TOKEN" }); + expect(scopes).toHaveLength(3); + }); + + it("asks once for connections opened together", async () => { + let release: (token: EntraAccessToken) => void = () => undefined; + let asked = 0; + const credential: EntraCredential = { + getToken: () => { + asked += 1; + return new Promise((resolve) => { + release = resolve; + }); + }, + }; + const password = entraPassword(credential, () => 0); + const waiting = [password(), password(), password()]; + release({ token: TOKEN_ONE, expiresOnTimestamp: HOUR }); + expect(await Promise.all(waiting)).toEqual([TOKEN_ONE, TOKEN_ONE, TOKEN_ONE]); + expect(asked).toBe(1); + }); + + it("fails with a fixed text and a code, never the credential's text or a token, and asks again next time", async () => { + let now = 0; + const { credential } = fakeCredential([ + () => ({ token: TOKEN_ONE, expiresOnTimestamp: now + HOUR }), + () => { + throw Object.assign(new Error(`refused for id-pw-example after ${TOKEN_ONE}`), { + name: "CredentialUnavailableError", + }); + }, + () => null, + () => ({ expiresOnTimestamp: now + HOUR }) as unknown as EntraAccessToken, + () => ({ token: "", expiresOnTimestamp: now + HOUR }), + () => ({ token: TOKEN_TWO, expiresOnTimestamp: now + HOUR }), + ]); + const password = entraPassword(credential, () => now); + expect(await password()).toBe(TOKEN_ONE); + now += HOUR; + + for (let failure = 0; failure < 4; failure += 1) { + const error = await failureOf(password()); + expect(error.message).toBe( + "no Microsoft Entra ID access token could be had for the database login", + ); + expect(error.code).toBe(ENTRA_CODES.ERR_PATHWAYS_ENTRA_TOKEN); + expect(error.cause).toBeUndefined(); + expectNoSecret(error, TOKEN_ONE, "id-pw-example"); + } + // The failures kept nothing: the next connection asks again, and gets a token. + expect(await password()).toBe(TOKEN_TWO); + }); +}); + +/** A stand-in pg whose Pool records what it was given. */ +function fakePg() { + const seen: { options?: Record } = {}; + const importDriver: DriverImport = () => + Promise.resolve({ + default: { + Pool: class { + constructor(options: Record) { + seen.options = options; + } + on(): void { + // The dialect listens for an idle connection's error; nothing is emitted here. + } + }, + }, + }); + return { seen, importDriver }; +} + +const entraStorage = (overrides: Partial = {}): ServerStorage => + serverStorage("postgres", { auth: "entra", ...overrides }); + +async function problemsOf(promise: Promise): Promise { + const error: unknown = await promise.catch((e: unknown) => e); + expect(error).toBeInstanceOf(ConfigError); + return (error as ConfigError).problems; +} + +describe("dialectFor: PostgreSQL with auth: entra", () => { + const credentialOf = (credential: EntraCredential) => () => Promise.resolve(credential); + + it("gives pg the URL taken apart, with a password function that hands out the token", async () => { + const { seen, importDriver } = fakePg(); + const { credential } = fakeCredential([ + () => ({ token: TOKEN_ONE, expiresOnTimestamp: Date.now() + HOUR }), + ]); + await dialectFor(entraStorage({ pool: { max: 3, idleTimeoutMs: 2_000 } }), { + env: { + [URL_ENV]: "postgres://id-pw%2Dexample@example.test/pathways?application_name=pathways", + }, + importDriver, + entraCredential: credentialOf(credential), + }); + const { password, ...rest } = seen.options ?? {}; + expect(rest).toEqual({ + application_name: "pathways", + host: "example.test", + port: 5_432, + user: "id-pw-example", + database: "pathways", + ssl: false, + max: 3, + idleTimeoutMillis: 2_000, + connectionTimeoutMillis: 15_000, + }); + expect(rest).not.toHaveProperty("connectionString"); + // A URL with no database leaves it to pg, which uses the user's name. + await dialectFor(entraStorage(), { + env: { [URL_ENV]: "postgres://id-pw-example@example.test:6432" }, + importDriver, + entraCredential: credentialOf(credential), + }); + expect(seen.options).toMatchObject({ host: "example.test", port: 6_432 }); + expect(seen.options).not.toHaveProperty("database"); + expect(typeof password).toBe("function"); + expect(await (password as () => Promise)()).toBe(TOKEN_ONE); + }); + + it("makes Azure's default chain from @azure/identity when no credential is given, asking for nothing yet", async () => { + const { seen, importDriver } = fakePg(); + await dialectFor(entraStorage(), { + env: { [URL_ENV]: "postgres://id-pw-example@example.test/pathways" }, + importDriver, + }); + expect(typeof seen.options?.["password"]).toBe("function"); + expect(await defaultEntraCredential()).toBeInstanceOf(DefaultAzureCredential); + }); + + it("leaves a block without auth on the URL as it is", async () => { + const { seen, importDriver } = fakePg(); + let made = 0; + const url = `postgres://u:${PASSWORD}@example.test:5433/pathways`; + for (const storage of [serverStorage("postgres"), entraStorage({ auth: "password" })]) { + await dialectFor(storage, { + env: { [URL_ENV]: url }, + importDriver, + entraCredential: () => { + made += 1; + return Promise.reject(new Error("not asked for")); + }, + }); + expect(seen.options).toMatchObject({ connectionString: url }); + expect(seen.options).not.toHaveProperty("password"); + } + expect(made).toBe(0); + }); + + it("hands pg a password it calls: the URL's empty password does not replace it", () => { + // pg reads a connection string's empty password over the one it is given, so the URL is taken + // apart for auth: entra. This holds pg to that. + const password = (): Promise => Promise.resolve(TOKEN_ONE); + const parsed = new pg.Client({ connectionString: "postgres://u@h/d", password }); + expect(typeof (parsed as unknown as { password: unknown }).password).not.toBe("function"); + const apart = new pg.Client({ host: "h", user: "u", database: "d", password }); + expect((apart as unknown as { password: unknown }).password).toBe(password); + }); + + it("refuses a URL with a password or no user, without repeating it", async () => { + const { importDriver } = fakePg(); + const cases = [ + [`postgres://id-pw-example:${PASSWORD}@example.test/pathways`, "holds a password"], + ["postgres://example.test/pathways", "names no user"], + ["postgres://id%zz@example.test/pathways", "is not percent-encoded correctly"], + ]; + for (const [url, what] of cases) { + const problems = await problemsOf( + dialectFor(entraStorage(), { + env: { [URL_ENV]: url ?? "" }, + importDriver, + entraCredential: () => Promise.reject(new Error("not asked for")), + }), + ); + expect(problems).toHaveLength(1); + expect(problems[0]).toContain(`pathways.yaml: storage.postgres.url: the URL in ${URL_ENV} `); + expect(problems[0]).toContain(what); + expect(problems[0]).not.toContain(PASSWORD); + } + }); + + it("names the package to install when @azure/identity is not there", async () => { + const { importDriver } = fakePg(); + expect( + await problemsOf( + dialectFor(entraStorage(), { + env: { [URL_ENV]: "postgres://id-pw-example@example.test/pathways" }, + importDriver, + entraCredential: () => + Promise.reject(Object.assign(new Error("synthetic"), { code: "ERR_MODULE_NOT_FOUND" })), + }), + ), + ).toEqual( + await problemsOf( + dialectFor(entraStorage(), { + env: { [URL_ENV]: "postgres://id-pw-example@example.test/pathways" }, + importDriver, + // A bundler's CommonJS build reports a missing package with the older code. + entraCredential: () => + Promise.reject(Object.assign(new Error("synthetic"), { code: "MODULE_NOT_FOUND" })), + }), + ), + ); + expect( + await problemsOf( + dialectFor(entraStorage(), { + env: { [URL_ENV]: "postgres://id-pw-example@example.test/pathways" }, + importDriver, + entraCredential: () => + Promise.reject(Object.assign(new Error("synthetic"), { code: "ERR_MODULE_NOT_FOUND" })), + }), + ), + ).toEqual([ + "pathways.yaml: storage.postgres.auth: entra needs the package @azure/identity, which is not installed; add it to the project with npm install @azure/identity", + ]); + // A package that is there and fails to load is not reported as missing. + const broken = new SyntaxError("synthetic"); + await expect( + dialectFor(entraStorage(), { + env: { [URL_ENV]: "postgres://id-pw-example@example.test/pathways" }, + importDriver, + entraCredential: () => Promise.reject(broken), + }), + ).rejects.toBe(broken); + }); +}); + +/** + * A stand-in PostgreSQL server that asks each connection for a cleartext password, records it, lets + * it in, and answers every query with an empty result. It speaks only as much of the protocol as pg + * needs for `select 1`. + */ +async function fakeServer(): Promise<{ server: Server; port: number; passwords: string[] }> { + const passwords: string[] = []; + const message = (type: string, body: Buffer): Buffer => { + const length = Buffer.alloc(4); + length.writeInt32BE(body.length + 4); + return Buffer.concat([Buffer.from(type), length, body]); + }; + const int32 = (value: number): Buffer => { + const buffer = Buffer.alloc(4); + buffer.writeInt32BE(value); + return buffer; + }; + const ready = message("Z", Buffer.from("I")); + const serve = (socket: Socket): void => { + let pending = Buffer.alloc(0); + let started = false; + socket.on("data", (data: Buffer) => { + pending = Buffer.concat([pending, data]); + for (;;) { + if (!started) { + if (pending.length < 4) return; + const length = pending.readInt32BE(0); + if (pending.length < length) return; + pending = pending.subarray(length); + started = true; + socket.write(message("R", int32(3))); + continue; + } + if (pending.length < 5) return; + const type = String.fromCharCode(pending[0] ?? 0); + const length = pending.readInt32BE(1); + if (pending.length < length + 1) return; + const body = pending.subarray(5, length + 1); + pending = pending.subarray(length + 1); + if (type === "p") { + passwords.push(body.subarray(0, body.length - 1).toString()); + socket.write(Buffer.concat([message("R", int32(0)), ready])); + } else if (type === "Q") { + socket.write(Buffer.concat([message("I", Buffer.alloc(0)), ready])); + } else if (type === "X") { + socket.end(); + } + } + }); + socket.on("error", () => undefined); + }; + const server = createServer(serve); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + const port = typeof address === "object" && address !== null ? address.port : 0; + return { server, port, passwords }; +} + +describe("pg with auth: entra, against a server that asks for a password", () => { + it("sends a token on each new connection, a new one once the last nears expiry", async () => { + const { server, port, passwords } = await fakeServer(); + let now = Date.now(); + const { credential } = fakeCredential([ + () => ({ token: TOKEN_ONE, expiresOnTimestamp: now + HOUR }), + () => ({ token: TOKEN_TWO, expiresOnTimestamp: now + 2 * HOUR }), + ]); + const realNow = Date.now; + Date.now = () => now; + try { + const dialect = await dialectFor( + entraStorage({ pool: { max: 3, idleTimeoutMs: 60_000 }, connectTimeoutMs: 5_000 }), + { + env: { [URL_ENV]: `postgres://id-pw-example@127.0.0.1:${String(port)}/pathways` }, + entraCredential: () => Promise.resolve(credential), + }, + ); + const db = new Kysely({ dialect }); + const together = (count: number) => + Promise.all(Array.from({ length: count }, () => sql`select 1`.execute(db))); + // Two queries at once: the pool opens two connections, and each sends the one token. + await together(2); + expect(passwords).toEqual([TOKEN_ONE, TOKEN_ONE]); + + // An hour on, the token is past the margin: the two open connections stay, and the third, + // opened now, signs in with a new token. + now += HOUR; + await together(3); + expect(passwords).toEqual([TOKEN_ONE, TOKEN_ONE, TOKEN_TWO]); + await db.destroy(); + } finally { + Date.now = realNow; + server.close(); + } + }); + + it("fails a connection with the code and a fixed text when no token can be had, and sends nothing", async () => { + const { server, port, passwords } = await fakeServer(); + const { credential } = fakeCredential([ + () => { + throw new Error(`synthetic failure holding ${TOKEN_ONE}`); + }, + ]); + try { + const db = new Kysely({ + dialect: await dialectFor(entraStorage({ connectTimeoutMs: 5_000 }), { + env: { [URL_ENV]: `postgres://id-pw-example@127.0.0.1:${String(port)}/pathways` }, + entraCredential: () => Promise.resolve(credential), + }), + }); + const error = await failureOf(sql`select 1`.execute(db)); + expect(error.code).toBe("ERR_PATHWAYS_ENTRA_TOKEN"); + expectNoSecret(error, TOKEN_ONE); + // As Store.open reports it: the code, and the fixed text. + const storage = new StorageError("open", error); + expect(storage).toMatchObject({ + reason: "open", + code: "ERR_PATHWAYS_ENTRA_TOKEN", + message: "the database could not be opened", + }); + expect(passwords).toEqual([]); + await db.destroy(); + } finally { + server.close(); + } + }); +}); + +describe("pathways.yaml: storage.postgres.auth", () => { + const MINIMAL = "source:\n file: { dir: ./inbox }\ndestinations:\n - file: { dir: ./outbox }\n"; + const project = (postgres: string, kind = "postgres") => ({ + "pathways.yaml": `storage:\n ${kind}: ${postgres}\n`, + "channels/a/channel.yaml": MINIMAL, + }); + + it("reads auth: entra, from the YAML or the environment, and leaves it out otherwise", async () => { + const entra = await loadProject(await makeProject(project("{ tls: {}, auth: entra }"))); + expect(entra.storage).toMatchObject({ kind: "postgres", auth: "entra" }); + + const fromEnv = project("{ tls: {}, auth: { env: DB_AUTH, default: password } }"); + const deployed = await loadProject(await makeProject(fromEnv), { env: { DB_AUTH: "entra" } }); + expect(deployed.storage).toMatchObject({ auth: "entra" }); + const local = await loadProject(await makeProject(fromEnv), { env: {} }); + expect(local.storage).not.toHaveProperty("auth"); + + const password = await loadProject(await makeProject(project("{ tls: {}, auth: password }"))); + expect(password.storage).not.toHaveProperty("auth"); + const none = await loadProject(await makeProject(project("{ tls: {} }"))); + expect(none.storage).not.toHaveProperty("auth"); + }); + + it("refuses another value, and auth on a server other than PostgreSQL", async () => { + const problems = async (files: Record): Promise => { + const error: unknown = await loadProject(await makeProject(files)).catch((e: unknown) => e); + expect(error).toBeInstanceOf(ConfigError); + return (error as ConfigError).problems.join("\n"); + }; + expect(await problems(project("{ tls: {}, auth: token }"))).toContain( + "pathways.yaml: storage.postgres.auth", + ); + for (const kind of ["mysql", "sqlserver"]) { + expect(await problems(project("{ tls: {}, auth: password }", kind))).toBe( + `pathways.yaml: storage.${kind}.auth: is for PostgreSQL only; this server signs in with the login its URL holds`, + ); + } + }); + + it("is in the JSON Schema an editor checks, as Zod reads it", () => { + const ajv = new Ajv({ strict: true, strictRequired: false, allErrors: true }); + const validate = ajv.compile(configJsonSchemas().project); + for (const [yaml, accepted] of [ + ["storage:\n postgres: { tls: {}, auth: entra }\n", true], + ["storage:\n postgres: { tls: {}, auth: { env: DB_AUTH, default: entra } }\n", true], + ["storage:\n postgres: { tls: {}, auth: token }\n", false], + ] as const) { + const value = parseYaml(yaml) as unknown; + expect(validate(value)).toBe(accepted); + expect(projectSchema.safeParse(value).success).toBe(accepted); + } + // The JSON Schema checks less than start does, never more: it lets auth on another server + // through, and start refuses it. + const mysql = parseYaml("storage:\n mysql: { tls: {}, auth: entra }\n") as unknown; + expect(validate(mysql)).toBe(true); + expect(projectSchema.safeParse(mysql).error?.issues).toEqual([ + expect.objectContaining({ code: "custom", path: ["storage", "mysql", "auth"] }), + ]); + }); +});