Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/postgres-entra-auth.md
Original file line number Diff line number Diff line change
@@ -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://<database_user>@<host>: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.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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.
<!-- changesets: postgres-entra-auth -->

---

## Install

Pathways needs Node.js 24 or later. Start a new project with the starter, which lists the package in
Expand Down
20 changes: 12 additions & 8 deletions docs-content/configuration-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

Expand Down
58 changes: 50 additions & 8 deletions docs-content/store-messages-in-a-database.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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://<database_user>@<host>: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
Expand Down
2 changes: 2 additions & 0 deletions src/config/load.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 } : {}),
};
}

Expand Down
58 changes: 57 additions & 1 deletion src/config/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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(
Expand Down Expand Up @@ -2422,7 +2462,8 @@ const storage = restate(
});
}
})
.superRefine(optionsWithModule),
.superRefine(optionsWithModule)
.superRefine(authOnPostgresOnly),
(json) => {
json["dependencies"] = { options: ["module"] };
json.if = { required: ["kind"] };
Expand Down Expand Up @@ -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.
*
Expand Down
82 changes: 80 additions & 2 deletions src/storage/dialects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<EntraCredential>;
}

/** 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<EntraCredential> {
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. */
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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<Record<string, unknown>>;

/**
* 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<string>) | undefined,
): Readonly<Record<string, unknown>> {
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<string>,
): 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,
Expand Down
Loading
Loading