Database Access With No Typed Password
Updated
IntermediateWhat you'll learn
~30 min- Choose between a short-lived token (a credential that expires in minutes, so nothing needs rotating) and a rotated secret (a stored password that a named owner replaces on a schedule), and say which your platform can offer
- Read the connection provider that fetches the credential at runtime, retries a login failure once after a refresh, and then raises a named error
- Tell runtime delivery (the app can fetch a new copy) from startup delivery (the platform injects it once, so rotation needs a redeploy)
- Prove with tests that rotation reaches a running app, that the old password stops working, and that proxy.ts and client code never import the database module
No typed password, one pool, one door
You will write the database module for your app so that nobody types its credential into a setting, a pipeline variable or a file in the repository. The running app obtains the credential from the platform when it needs it. Either that credential is short-lived, or a named person owns replacing it on a schedule that a test checks. You also decide where in the codebase the module may be imported, and write a test that fails when someone breaks the decision.
The worked example runs on your laptop. A script starts SQL Server in a container, generates the app’s password, and keeps it in a file outside the repository. Lessons 34 to 37 land the same code on a real cloud by swapping one object, the platform seam (the Platform type in src/platform/types.ts, which every cloud lesson implements).
| Problem | The pattern | Where your platform lesson lands it | You decide |
|---|---|---|---|
| How the app proves itself to the database | The app fetches its credential from the platform at runtime; nothing typed. Short-lived token (DbAuth kind token) where the database accepts one, otherwise a rotated secret (kind secret) | 34: managed identity token · 35: Secrets Manager with RDS rotation · 36: Secret Manager | Whether your agency accepts a stored secret, and the name of the rotation owner |
| How a rotation reaches the running app | Runtime delivery: on a login failure, fetch the current secret once and retry once; startup delivery: a redeploy runbook | 34: token, nothing to rotate · 35: ECS injects at task start, so redeploy · 36: Cloud Run env var at start, or a mounted volume for the latest | Who runs the redeploy, and how fast after a rotation |
| Where database code may run | Route handlers and the server code behind them, through one door, withPool | Same on every platform | Which server entry points may call the database, in writing |
| How many connections | One pool per process, created lazily | Same on every platform | Pool size against your database tier’s connection limit |
| What local development uses | A generated password in a file outside the repository | Same on every platform | Which environments may ever hold a password |
The platform you inherit may have an older reason for the third row: the mssql driver could not be imported from edge middleware. That reason no longer applies. The proxy file in the pinned Next.js major (proxy.ts, the renamed middleware) runs on the Node runtime only, so the driver would load there. The advice survives for a better reason, covered below.
Two kinds of credential
The seam describes the database credential as one of two kinds. The type is the whole decision, so read it before any code.
REFERENCE CODE src/platform/types.ts (excerpt): database credential types (token vs. rotated secret) open reference hide reference Reference implementation from gov-dev-reference-app; open to inspect or compare with what your agent builds.
// src/platform/types.ts (excerpt)export interface SecretCredential { user: string; password: string; /** Written by the rotation job into the secret itself, so the app needs no extra permission to read it. */ rotatedAt: string;}
export type DbAuth = | { kind: 'token'; /** Passed to the driver; the driver asks the server which scope to use. No scope string in app code. */ credential: TokenCredentialLike; } | { kind: 'secret'; /** Fetches the current credential from the platform's secret store. */ get(): Promise<SecretCredential>; /** A named owner, e.g. a team mailbox, who answers for rotation. */ rotationOwner: string; maxAgeDays: number; /** * 'runtime': the app can fetch a fresh copy after a rotation. * 'startup': the platform injects it once when the container starts, so a * rotation reaches the app only through a redeploy (the runbook says who does it). */ delivery: 'runtime' | 'startup'; };Kind token is the passwordless case. The platform issues the app an identity, such as an Azure managed identity (an identity Azure issues to your app, so there is no password for anyone to hold). The driver asks it for a short-lived token, and the database checks the grant. There is no password, so there is nothing to rotate. Lesson 34 implements this on Azure Government.
Kind secret is the honest fallback, and on some managed SQL Server offerings it is the only choice. Per the cloud providers’ own documentation (sources and dates in the status box below), Amazon RDS for SQL Server and Google Cloud SQL for SQL Server do not offer a database login that the cloud’s identity system issues. A SQL login with a password is the route, and the pattern changes from “no secret” to three smaller promises: the secret lives in the platform’s secret store and never in an image or the repository, a named owner answers for rotating it, and a test checks that the rotation happened and that the app survives it.
Availability, authorization, agency approval, region support, and price are five separate facts. These are the availability facts this lesson leans on, each from the provider’s own documentation as fetched on the date above; none of them says anything about authorization or price.
- Amazon RDS for SQL Server: “IAM database authentication isn’t available with the following engines: RDS for Db2, RDS for Oracle, RDS for SQL Server” (AWS).
- Google Cloud SQL for SQL Server: “IAM authentication isn’t supported for database operations.” (Google). Microsoft Entra ID authentication exists on SQL Server 2022 or later only, with extra setup; whether it works with an Azure Government tenant was not verified.
- Azure SQL: managed-identity login works (Microsoft).
- Amazon ECS injects a Secrets Manager value only at container start: “Sensitive data is injected into your container when the container is initially started.” A rotation reaches a running task only by launching a new task or forcing a new deployment (AWS).
- Google Cloud Run resolves a secret exposed as an environment variable at instance start; a secret mounted as a volume is always the latest version (Google).
- AWS Secrets Manager lists built-in rotation for Amazon RDS and is listed for both GovCloud (US) regions (AWS).
Recheck the cited source and your agency’s authorization boundary before you rely on any of it.
Plan the change with your agent
Open your workspace agent at the project root with the project-memory file from Lesson 2 in place, switch to Plan mode (Shift+Tab, /plan, or the desktop app’s mode picker), and ask:
Read src/platform/types.ts and plan the database connection and pool module so it supports both token and rotated-secret credentials from getPlatform() and recovers from a runtime password rotation. Ask anything unclear.What to check in the plan before you approve
src/lib/db/connection.tsexportscreateConnectionProvider(target, auth, connect?), handlingDbAuthkind"token"(token-credentialwith no scope string in code) and kind"secret"(userandpasswordfromawait auth.get()).withPool(fn)creates one pool lazily per provider, never caches a failed connect, and handlesELOGINon a"secret"credential by throwingCredentialRefreshFailed("startup")for startup delivery or closing the pool, fetching once, and retrying once for runtime delivery.src/lib/db/pool.tscaches one provider onglobalThis, readstargetandauthfromgetPlatform(), and exportswithPool(fn)andclosePool()with no passwords or tokens in logs or error messages.
If the first plan retries login failures in a loop or refetches on startup delivery, nudge it before approving:
On an ELOGIN failure with runtime delivery, refresh the secret and retry at most once before throwing CredentialRefreshFailed.What you get
The agent plans the module, writes the files after approval, and runs the test. The failing turn below is the one to watch: it shows what the rotation test catches.
- Typed in the terminal:
claude - Mode:Plan mode
- You type in the session: Read src/platform/types.ts and plan the database connection and pool module so it supports both token and rotated-secret credentials from getPlatform() and recovers from a runtime password rotation. Ask anything unclear.
- The tool replies: Read src/platform/types.ts. DbAuth has kind 'token' and kind 'secret' with delivery 'runtime' or 'startup'. Proposed plan: 1. src/lib/db/connection.ts: createConnectionProvider(target, auth, connect?) with lazy pool creation and ELOGIN handling. 2. src/lib/db/pool.ts: one provider cached on globalThis, exporting withPool(fn) and closePool(). On ELOGIN with a secret credential, should runtime delivery retry once after a fresh auth.get() and startup delivery fail immediately?
- You type in the session: Yes. On an ELOGIN failure with runtime delivery, refresh the secret and retry at most once before throwing CredentialRefreshFailed.
- The tool replies: Created src/lib/db/connection.ts and src/lib/db/pool.ts. - kind token: authentication type token-credential, credential passed through, no scope string. - kind secret: the config is built from await auth.get(), so every new pool reads the current secret. - withPool: on ELOGIN with a secret credential, startup delivery throws CredentialRefreshFailed('startup'); runtime delivery closes the pool, fetches once and retries once. - pool.ts caches one provider on globalThis and exports withPool and closePool. One thing I could not confirm: whether @types/mssql lists token-credential. If the compiler rejects it I will stop and tell you rather than cast around it.
- You type in the session: Add a unit test that proves a rotation reaches the app, then run it.
- The tool replies: Created tests/unit/connection.test.ts with a fake server that accepts one password at a time. First run: FAIL a rotation reaches the app on the next login failure, with one fresh fetch AssertionError: expected get to have been called 2 times, but it was called 1 time The cause is in my code, not the test. I cached the credential object when the provider was created, so after the rotation the retry reused the old password and the second attempt failed with ELOGIN. A retry that sends the same password proves nothing.
- You type in the session: Fix it so the retry reads the secret again, and rerun.
- The tool replies: Changed configFor() to call auth.get() each time it builds a config, and made the retry path call open() after reset(), so the new pool gets a fresh fetch. I did not add a loop: one refresh, one retry, then CredentialRefreshFailed. npm test: Test Files 1 passed (1) Tests 12 passed (12) The 12 include the rotation-age cases for checkRotation: missing, unparseable, future-dated, too old, and in range.
- You type in the session: A teammate wants to read the vehicle count in src/proxy.ts to decide a redirect. What should I tell them?
- The tool replies: Tell them no, and the reason is not the runtime. proxy.ts runs a check on every matched path, so a pooled query there adds a database round trip to every page load. More importantly, proxy is not an authorization boundary: a matcher can exclude a path, and Server Functions are POSTs to the page route, so an exclusion skips them. Anything the proxy decides has to be decided again in the route handler or Server Function that does the work. If the redirect is a convenience, use a cookie check in proxy and keep the data check next to the data.
Illustrative session in Claude Code; the exact wording varies.
Now read what it wrote, then the part the AI cannot decide for you.
The connection provider
The first block holds the named error and the test for a login failure. A SQL Server “Login failed for user” error (number 18456) reaches Node as the driver code ELOGIN. The error carries which delivery the platform uses, so the message tells the on-call person what to do.
REFERENCE CODE src/lib/db/connection.ts (excerpt): login-failure predicate and CredentialRefreshFailed error open reference hide reference Reference implementation from gov-dev-reference-app; open to inspect or compare with what your agent builds.
// src/lib/db/connection.ts (excerpt)/** SQL Server "Login failed for user" (error 18456) surfaces as ELOGIN from the driver. */export const isLoginFailure = (err: unknown) => typeof err === 'object' && err !== null && (err as { code?: string }).code === 'ELOGIN';
export class CredentialRefreshFailed extends Error { constructor(readonly delivery: 'runtime' | 'startup') { super( delivery === 'startup' ? 'database login failed and this platform delivers the credential at startup: redeploy per the rotation runbook' : 'database login failed again after fetching the current credential from the secret store', ); this.name = 'CredentialRefreshFailed'; }}The config is built per connection attempt. A token credential goes to the driver untouched; the driver asks the server which resource the token is for, so no scope string appears in your code. A secret credential is fetched at that moment, which is what lets a rotation reach a new connection.
REFERENCE CODE src/lib/db/connection.ts (excerpt): per-connection config builder for token or secret credentials open reference hide reference Reference implementation from gov-dev-reference-app; open to inspect or compare with what your agent builds.
// src/lib/db/connection.ts (excerpt)async function configFor(target: DbTarget, auth: DbAuth): Promise<sql.config> { const base: sql.config = { server: target.server, database: target.database, port: target.port, options: { encrypt: true, trustServerCertificate: target.trustServerCertificate ?? false }, pool: { max: 10, min: 0, idleTimeoutMillis: 30_000 }, }; if (auth.kind === 'token') { return { ...base, authentication: { type: 'token-credential', options: { credential: auth.credential } } } as sql.config; } const c = await auth.get(); return { ...base, user: c.user, password: c.password };}The pool ceiling in the excerpt is an example. Your database tier has a connection limit, and every running instance of your app holds its own pool, so the ceiling multiplied by your instance count must stay under that limit. Read the limit for your tier from your database administrator and write the arithmetic next to the number.
The provider holds one pool. withPool is the only place a login failure is interpreted: one refresh, one retry, then a named error. A retry loop here would hammer the database with a dead password and lock the account. refresh is shared: when ten requests hit the rotated password at once, they wait on one new pool instead of each closing the others’ and opening their own (the unit test ten requests failing at once share one refresh proves it).
REFERENCE CODE src/lib/db/connection.ts (excerpt): lazy pool provider and single-retry rotation recovery open reference hide reference Reference implementation from gov-dev-reference-app; open to inspect or compare with what your agent builds.
// src/lib/db/connection.ts (excerpt)export function createConnectionProvider(target: DbTarget, auth: DbAuth, connect: PoolFactory = defaultFactory) { let pool: Promise<sql.ConnectionPool> | undefined;
const open = () => { const p = configFor(target, auth).then(connect); pool = p.catch((err: unknown) => { if (pool === guarded) pool = undefined; // a failed connect is never cached throw err; }); const guarded = pool; return pool; };
/** * Replace the pool a caller saw fail, once. Concurrent callers that saw the same * failed pool share one refresh; a caller that saw an older pool reuses the new one. */ async function refresh(failed: Promise<sql.ConnectionPool>) { if (pool !== failed) return pool ?? open(); pool = undefined; failed.then((p) => p.close(), () => undefined); // close in the background return open(); }
async function reset() { const old = pool; pool = undefined; if (old) await old.then((p) => p.close(), () => undefined); }
/** * Run a query function; on a login failure, refresh the credential once and retry. * ELOGIN also covers a locked account or a wrong user, so a second ELOGIN after the * refresh is not "rotation lag": it raises CredentialRefreshFailed for the owner. */ async function withPool<T>(fn: (pool: sql.ConnectionPool) => Promise<T>): Promise<T> { const seen = pool ?? open(); try { return await fn(await seen); } catch (err) { if (!isLoginFailure(err) || auth.kind !== 'secret') throw err; if (auth.delivery === 'startup') throw new CredentialRefreshFailed('startup'); try { return await fn(await refresh(seen)); } catch (again) { if (isLoginFailure(again)) throw new CredentialRefreshFailed('runtime'); throw again; } } }Caching the promise, not the pool, is the detail that matters: two requests that arrive before the first connect finishes both receive the same promise instead of each starting a connection. And a second ELOGIN right after a fresh fetch is not rotation lag: it also means a locked account or a wrong user, so CredentialRefreshFailed goes to the rotation owner rather than into another retry.
The one door
Every route handler calls withPool((pool) => ...) from src/lib/db/pool.ts and nothing else imports the driver’s pool. The provider is cached on globalThis because the dev server reloads modules, and a plain module-level variable would be recreated each time.
REFERENCE CODE src/lib/db/pool.ts: process-wide database pool door open reference hide reference Reference implementation from gov-dev-reference-app; open to inspect or compare with what your agent builds.
// The one door to the database (lesson 08). Route handlers and the server code they call// use withPool(); nothing else imports mssql's pool. One provider per process, cached on// globalThis because the dev server reloads modules.import type sql from 'mssql';import { getPlatform } from '../../platform/index.ts';import { createConnectionProvider } from './connection.ts';
type Provider = ReturnType<typeof createConnectionProvider>;const g = globalThis as unknown as { __db?: Promise<Provider> };
function provider(): Promise<Provider> { g.__db ??= getPlatform().then((p) => createConnectionProvider(p.db.target, p.db.auth)).catch((err: unknown) => { g.__db = undefined; // a failed start is not cached throw err; }); return g.__db;}
export async function withPool<T>(fn: (pool: sql.ConnectionPool) => Promise<T>): Promise<T> { return (await provider()).withPool(fn);}
export async function closePool(): Promise<void> { const p = g.__db; g.__db = undefined; if (p) await (await p).reset();}The pool stays inside the callback: a handler that keeps the pool in a variable would keep using a pool the provider has already replaced after a rotation.
Where database code may run
Here is the decision the old reason used to hide. The reference app allows database access only in route handlers and the server code they call. It does not allow it in proxy.ts, in client components, or directly in page components.
The runtime is not why. The reason is that the route handler is where your checks live: the session, the role from Lesson 5, input validation, and the error contract from Lesson 7. A query anywhere else runs without them. For proxy.ts this is stronger: it is not an authorization boundary at all. A matcher can leave a path out of its reach, and Server Functions are POST requests to a page route, so a matcher exclusion skips them too. Whatever the proxy decides, the code that does the work decides again.
Plenty of teams query from Server Components and Server Functions and keep the checks in a shared data-access layer that every caller must use. That works when each function calls the session and role checks itself, because the check travels with the data call instead of with the URL. If your agency chooses it, the contract test below changes shape (every exported data function must call the session check), but the test still exists. What you cannot do is allow database access from more places and keep the checks in one of them.
The worked example: generated secrets
The local platform in gov-dev-reference-app uses the secret kind with runtime delivery and a named owner (reference excerpt shown):
// src/platform/local/index.ts (excerpt) auth: { kind: 'secret', get: async () => JSON.parse(await readSecret('db-app')) as SecretCredential, // this secret's value is JSON rotationOwner: 'you (local development)', maxAgeDays: 30, delivery: 'runtime', },The script that starts the stack is where “nobody types it” becomes true. It generates both passwords, sets the app’s on the SQL login inside the container, and writes the secret to a directory outside the repository, with the owner-only permissions the umask line sets. Here is the reference excerpt from scripts/local-up.sh in gov-dev-reference-app:
# scripts/local-up.sh (excerpt)DIR="${M14_SECRET_DIR:-$HOME/.config/m14-reference}"PORT="${M14_SQL_PORT:-14330}"NAME=m14-sqlmkdir -p "$DIR" && chmod 700 "$DIR"gen() { printf '%sAa1!' "$(openssl rand -base64 33 | tr -d '/+=\n' | cut -c1-28)"; } # meets SQL Server complexity rulesSA="$(gen)"; APP="$(gen)"umask 077# ...sq "CREATE LOGIN app_user WITH PASSWORD = N'$APP', CHECK_POLICY = ON;"# ...printf '{"user":"app_user","password":"%s","rotatedAt":"%s"}' "$APP" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$DIR/db-app"Notice the last line: the rotation job writes rotatedAt into the secret itself, so the app and the test need no extra permission to learn when it was last rotated. On a cloud, that is the secret’s value written by the rotation function; on your laptop scripts/rotate-local.sh plays the rotation job, changing the password on the login first and then replacing the secret.
Prove it
Three checks. The first two prove the credential pattern, the third guards the boundary.
1. The provider’s contract, in a unit test. A fake server accepts exactly one password at a time, so a rotation is one assignment. Run it from gov-dev-reference-app to see this output:
$ npx vitest run tests/unit/connection.test.ts
RUN v5.1.0
Test Files 1 passed (1) Tests 12 passed (12)Verbose output names the cases: a rotation reaches the app on the next login failure with one fresh fetch; a refresh that still fails is a named error, not a retry loop; startup delivery never refetches and points at the redeploy runbook; other errors pass through untouched; a failed connect is not cached; token kind hands the credential to the driver and holds no scope string; five rotation-age cases for checkRotation; and ten requests failing at once share one refresh, one new pool, and all succeed.
The age check is a small pure function. It reads only the rotatedAt the rotation job wrote, and refuses a missing, unparseable, future-dated or too-old value:
REFERENCE CODE src/platform/rotation.ts: pure rotation-age check against maxAgeDays open reference hide reference Reference implementation from gov-dev-reference-app; open to inspect or compare with what your agent builds.
// The rotation-age check for secret-kind database credentials (lesson 08's Prove it).// It reads only the rotatedAt the rotation job wrote into the secret: metadata evidence// that rotation happened on schedule. That a rotation actually reaches the app is a// separate test (tests/env/rotation.env.test.ts).export type RotationVerdict = | { ok: true; ageDays: number } | { ok: false; reason: 'missing' | 'unparseable' | 'in-the-future' | 'too-old'; ageDays?: number };
export function checkRotation(rotatedAt: string | undefined, maxAgeDays: number, now = new Date()): RotationVerdict { if (!rotatedAt) return { ok: false, reason: 'missing' }; const t = Date.parse(rotatedAt); if (Number.isNaN(t)) return { ok: false, reason: 'unparseable' }; const ageDays = (now.getTime() - t) / 86_400_000; if (ageDays < -1 / 24) return { ok: false, reason: 'in-the-future', ageDays }; // more than an hour of clock skew if (ageDays > maxAgeDays) return { ok: false, reason: 'too-old', ageDays }; return { ok: true, ageDays };}2. Rotation against a real database. The unit test uses a fake server; this one uses the SQL Server container. It rotates the password with rotate-local.sh, kills the app’s open sessions as an idle timeout or failover would, then asserts the recovery, the exact number of secret fetches, and that the old password is dead. Here is the reference test excerpt from gov-dev-reference-app:
// tests/env/rotation.env.test.ts (excerpt) expect(await db.withPool(who)).toBe('app_user'); const before = secret();
execFileSync('bash', ['scripts/rotate-local.sh'], { stdio: 'pipe' }); // Force the pool to need a new connection, as an idle timeout or failover would.// ... expect(await db.withPool(who)).toBe('app_user'); // recovered without a restart expect(fetches).toBe(2); // by fetching the rotated secret once expect(checkRotation(secret().rotatedAt, auth.maxAgeDays).ok).toBe(true);// ... await expect(old.connect()).rejects.toMatchObject({ code: 'ELOGIN' }); // the old credential is deadWith the local stack up (npm run local:up), run it to see this output:
$ npm run test:env
Test Files 4 passed (4) Tests 6 passed (6)Six tests across four files: rotation recovers with exactly two secret fetches (the first at connect, one after the rotation) and the old password gets ELOGIN, and the rest cover sign-in, telemetry and platform selection. The fetch count is the point. One means the app never noticed the rotation; three means it retried in a loop.
The negative cases are already in the suite: the old password must be refused with ELOGIN, and in the unit test a secret that is still wrong after the refresh must end in CredentialRefreshFailed rather than a third attempt. Run each once and keep the output; a test you have never seen fail has not been shown to work.
3. The boundary test. Fails when proxy.ts or a client component imports the database module.
REFERENCE TEST src/lib/db/boundary.test.ts: static boundary check keeping database imports out of proxy.ts and client components open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
import { describe, it, expect } from "vitest";import { readdirSync, readFileSync, statSync } from "node:fs";import { join } from "node:path";
function walk(dir: string): string[] { return readdirSync(dir).flatMap((n) => { const p = join(dir, n); return statSync(p).isDirectory() ? walk(p) : [p]; });}
const files = walk("src").filter((f) => /\.(ts|tsx)$/.test(f) && !f.endsWith(".test.ts"));const importsDb = (f: string) => /from\s+["']@\/lib\/db(\/|["'])/.test(readFileSync(f, "utf8"));
describe("database boundary", () => { it("proxy.ts never imports the database module", () => { expect(files.filter((f) => f.endsWith("proxy.ts")).filter(importsDb)).toEqual([]); });
it("no client component imports the database module", () => { const offenders = files.filter( (f) => /^\s*["']use client["']/.test(readFileSync(f, "utf8")) && importsDb(f), ); expect(offenders).toEqual([]); });});Negative case: plant import { withPool } from "@/lib/db/pool" in src/proxy.ts, run the test, and read the failure.
What these tests cannot prove: that your platform’s rotation job actually runs, or that a login works in your cloud account. The first is why rotatedAt is checked against maxAgeDays; the second needs your subscription, and your platform lesson ends with its own check.
Delivery decides the runbook
The same code serves both deliveries. The only difference is what the platform can do after a rotation:
| Delivery | What the platform does | What the app does on a login failure | Who acts |
|---|---|---|---|
runtime | The app can read the secret store whenever it likes | Refreshes once, retries once | Nobody; the rotation reaches the app |
startup | Injects the secret into an environment variable once, when the container starts | Raises CredentialRefreshFailed('startup') with the runbook pointer | The named owner redeploys, or the pipeline does it after each rotation |
Environment-variable injection is the common cause of startup: it is cheap, and it hides the rotation problem until the old password dies. If your platform can only do startup, write the runbook before the first rotation: who is paged by the named error, who triggers the redeploy, and how long the app may be down.
A teammate argues: 'The proxy runs on the Node runtime now, so we can query the database there to block users who are suspended.' What is the strongest reply?
Your app runs on a container host that injects the database password as an environment variable when the container starts. The password is rotated on schedule. What do you expect, and what do you prepare?
The rotation test passes with the secret fetched exactly twice. A colleague changes the provider and the same test now reports three fetches. What does that most likely mean?
Key takeaway
Hold the database behind one door, withPool, that gets its credential from the platform at runtime. Prefer a short-lived token where the database accepts one. Where it does not, keep a rotated secret with a named owner, say whether delivery is runtime or startup, and let tests prove that rotation reaches the app, that the old password is refused, and that nothing outside route handlers can reach the module.
- LEADERSHIP DECISION
- Decide per platform whether the database credential is a token or a rotated secret, and name the rotation owner and the maximum age.
- PRACTITIONER ACTION
- Route every query through withPool, run the rotation env test, and keep the boundary test in the normal test command.
- SUCCESS MEASURE
- Audit finding avoided: no stored database password in settings, and a rotation-age check that fails before the credential goes stale.
Legend: LEADERSHIP DECISION = what a leader decides · PRACTITIONER ACTION = what the engineer does next · SUCCESS MEASURE = how you know, in calendar time, assessor-hours or cost, contract or revenue risk, or audit finding avoided
Next, Lesson 9 handles what the browser does with the data your routes return, and what it must show when a write fails.