<!-- docs/decisiones/0052-websocket-tunnels-and-postgres-sql-guard.md at fe8e2a0c8c248c44514c31c7f73b89c3f9cafc92 · https://github.com/OmarAlex24/klav/blob/fe8e2a0c8c248c44514c31c7f73b89c3f9cafc92/docs/decisiones/0052-websocket-tunnels-and-postgres-sql-guard.md · status: stale -->

# 0052 · WebSocket tunnels through `HTTPS_PROXY` (sandbox mode (b)), and a Postgres credential proxy with a SQL guard

- Status: accepted (2026-11-28, Q1–Q14 all resolved as recommended (a) by Omar). Layer 1 (docs) done; implementation starts at Layer 2.
- Date: 2026-11-28
- Absorbs and replaces: the draft ADR 0043 ("Sandbox mode (b)"), proposed on 2026-11-17 on the branch `docs/adr-0043-sandbox-https-interception` and never merged. Its findings and its recommended answers are carried here (§1). The number 0043 stays unused.
- Amends:
  - [ADR 0036](0036-sandboxes-de-agentes.md): §2 (the `proxy` permission was HTTP only, and "one access per injected request" gains a session form for Postgres, §9.2); §5 step 5 and §7 mode (b) (rewritten by §1–§3 here); §7's limit "the proxy drops `Upgrade`" (§4); and the note of 2026-11-16 that "the CLI's WebSocket commands probably fail through the proxy".
  - [ADR 0049](0049-mcp-gateway.md) §1, narrowly (Q12 (a)): one vendor-specific *transport* (`northflank-addon`) in `klav-proxy`. Policy stays generic.
  - [ADR 0051](0051-hosted-nitro-enclave-proxy.md) §3.3 (two new per-account quotas) and §1.2 (Q13 (a): port 5432 on the parent's egress list).
- Builds on and doesn't replace: the pinned channel (ADR 0036 §6), the stream limits and the cuts registry of step M3 (ADR 0036 §7, note of 2026-11-25), the account-switch pattern of ADR 0041 §5.6 and ADR 0049 §9, and the sealed-blob route of ADR 0041 §5.3.

## Context

### What happened (2026-11-28)
Omar ran `northflank forward addon --project horizon-stack --addon postgres --skipHostnames` in a Boat sandbox that uses Klav:

1. The CLI's REST calls go through `--host "$KLAV_FORWARD_NORTHFLANK_URL"`, which is mode (a): `klav-forward` → `klav-proxy` → `https://api.northflank.com`. That works.
2. `GET /v1/port-forwarding/info/projects/{project}/addons/{addon}` answers with `targetDomain`, a separate host, plus the addon's instances and ports.
3. When a Postgres client connects to the forwarded address (`127.24.1.2:5432`), the CLI opens **one WebSocket per TCP connection** to `wss://${targetDomain}/tunnel/projects/{project}/addons/{addon}/instance/{pod}/port/{port}` with `Authorization: Bearer <the CLI's token>`. That connection ignores `--host`.
4. The CLI's token in a Klav sandbox is `klav-placeholder` (ADR 0036, decision of 2026-11-16). That connection never passes through the proxy, so Northflank answers `403 Forbidden (check the token's permissions)`.
5. Even with the tunnel working, the agent still needed the database password, fetched separately. That puts a second credential in the sandbox.

Omar approved designing both parts together:
- **Part 1:** `HTTPS_PROXY` (mode (b)) and WebSocket tunnels, so `northflank forward` and any similar tool works without the Northflank token entering the sandbox.
- **Part 2:** a Postgres credential proxy with a SQL guard, so the database password never enters the sandbox either.

**Omar's decision on the SQL policy, given with the request:** reads are allowed automatically. Writes and destructive statements ask Omar on the Mac, iPhone or CLI, showing the exact statement, and a profile can be set to strict read-only (`deny`).

### What I read, and when (all on 2026-11-28)
I ran nothing against Northflank, started no sandbox and called no provider.

| Source | What I took from it |
|---|---|
| `AGENTS.md`, `docs/diseno.md`, the ADR index, ADRs 0036, 0041 §5, 0042 §3 and §9, 0043 (draft branch), 0045 (decisions 6 and 8), 0049, 0051 §1–§3, §8–§10 and §19 | The accepted design and its numbering |
| `crates/klav-proxy/src/{proxy,channel,parent,net,cuts}.rs`, `crates/klav-forward/src/forward.rs`, `crates/klav-proto/src/agent.rs`, `crates/klav-core/src/policy.rs`, `crates/klav-core/Cargo.toml`, `crates/klav-daemon/src/prompt.rs`, at `main` `f8c51f9a` | What the code does today (below) |
| `@northflank/js-client` 0.13.0 and `@northflank/cli` 0.16.0, from npm (`dist/api-client.js`, `dist/port-forward/index.js`), read but not run | How forwarding works (below) |
| `Cargo.lock`, plus throwaway manifests resolved against the registry in a scratch directory on the external disk and compared with the workspace's lock by name and version | The dependency prices in §11 |
| The draft ADR 0043 at `40e03315` (branch `docs/adr-0043-sandbox-https-interception`) | Mode (b)'s design, restated in §1 so this ADR stands alone |
| **From memory, not read on 2026-11-28:** PostgreSQL's documentation on read-only transactions, `SET TRANSACTION`, `ParameterStatus` reporting, protocol 3.2 and `sslnegotiation=direct`; Northflank's customer domain `code.run` | Marked *(from memory)* where used, each checked at the layer §15 names |

### What the code at `main` does
- **Mode (a) only.** The forwarder relays each local connection to the proxy as bytes, over its own channel connection (`klav-forward/src/forward.rs:1-8`). The proxy serves HTTP/1.1 with `hyper` and no upgrades (`channel.rs:499-507`). Its `forward` takes the profile from the first path segment, requires a loopback `Host`, refuses `CONNECT` and `TRACE`, and drops 32 request headers, `upgrade` and `connection` among them (`DROPPED_REQUEST_HEADERS`, `proxy.rs:92`).
- **What a sandbox gets back.** The proxy drops `set-cookie`, `set-cookie2` and `www-authenticate` (`SANDBOX_DROPPED_RESPONSE_HEADERS`, `proxy.rs:145`), and redacts the whole injected value from headers and body.
- **Calls in flight are cut** when their sandbox ends or the person pauses (`cuts.rs`). Ends the proxy decides land at once; ends it learns of come within 30 s (ADR 0036 §7, note of 2026-11-25).
- **The grant.** It is `v: 1`–`v: 4` (`GRANT_PAYLOAD_VERSION_MCP` = 4, `agent.rs:197`). `ProxyProfile` is `{name, item_id, field?, header, prefix, upstream, rate_per_minute?, mcp?}` (`agent.rs:464`). `Scope` has `domains`, `items`, `methods`, `path_prefixes` and `mcp_tools` (`policy.rs:870`). Every one of these rejects unknown fields.
- **Klav Cloud's parent** gives the enclave egress with `CONNECT host:port`. It allows port 443 only unless the operator lists others, refuses non-public addresses (`parent.rs:1-27`), and cuts a relay after 300 s with no byte (`RELAY_IDLE`). The forwarder cuts a relay after 240 s with no byte (`forward.rs`, `RELAY_IDLE`).
- **`klav-proxy`'s own egress** refuses every non-public address (`net::is_public`), so it can't reach a database on a private network or a tailnet.

### How `@northflank/js-client` 0.13.0 forwards (read, not run)
- **The info call** goes to `${baseUrl}/v1/port-forwarding/info/[teams/{team}/]projects/{p}/addons/{a}` with `Authorization: Bearer <token>`. `baseUrl` is the context's `--host`, which is mode (a) and works today.
- **The tunnel URL** is `https://${targetDomain}/tunnel/[teams/{team}/]projects/{p}/addons/{a}/instance/{pod}/port/{internalPort}`, with `https:` replaced by `wss:`. Services and harnesses use the same shape, with `services/` or `harnesses/` and sometimes `?directConnect=true`.
- **One WebSocket per accepted local TCP connection** (class `Bd`, `handleConnection`), opened with undici's `WebSocket` and the same `Authorization` header. `binaryType` is `arraybuffer`. The duplex wrapper `X()` turns each message into stream bytes and writes each chunk as one binary message. No subprotocol is requested.
- **Bytes pass through untouched,** except that an HTTP port may get its `Host` header rewritten. **The client never speaks Postgres:** whatever `psql` sends, including an `SSLRequest`, goes into the tunnel as is, and the addon decides.
- **Proxy support.** If `HTTP_PROXY`, `HTTPS_PROXY` (or their lower-case forms) is set, the client builds undici's `EnvHttpProxyAgent` and uses it as the dispatcher for both the info call and the WebSocket. So the WebSocket honors `HTTPS_PROXY` with `CONNECT targetDomain:443`, and the info call to a `127.0.0.1` base URL skips the proxy through `NO_PROXY`.
- **Local addresses.** It binds `127.24.x.y` (from `127.24.1.1` up). Without `--skipHostnames` it edits the hosts file.
- **Not in the package:** what `targetDomain` looks like, whether it is shared with customer workloads, and whether Northflank's Postgres addons require TLS inside the tunnel. These are §15's first items.

### Goals
- An agent in a sandbox runs `northflank forward` (and any CLI or SDK that needs `HTTPS_PROXY` and `Upgrade: websocket`) with no Northflank token in the sandbox.
- An agent in a sandbox connects to Postgres with no database password in the sandbox, over direct TCP and TLS or through a Northflank tunnel.
- Reads pass; writes and destructive statements ask the person with the exact SQL; a profile can be strict read-only.
- The same binary and the same rules on a self-hosted proxy, on the Mac proxy, and in Klav Cloud's enclave.

### Non-goals
- Hiding data the database role can read: a sandbox with read access reads it (risk 114).
- Postgres for local agents on the Mac, private CAs, MySQL or Redis, and multi-statement write transactions (§14).
- A general interception box: the proxy only ever sees the sandbox's signed hosts.
- Replacing PostgreSQL's own roles, grants and row-level security.

## Decision

### Part 1 — mode (b) and WebSocket tunnels

### 1. What this ADR takes from the draft ADR 0043
Draft 0043 found that mode (b) can't work as ADR 0036 §5 and §7 sketched it. ADR 0036's sketch has a CA generated by the forwarder, signing on demand with `rcgen` and `aws-lc-rs`, and `HTTPS_PROXY` exported shell-wide. This ADR adopts 0043's design, with its recommended answers Q1 (a) through Q7 (a), unchanged except where §2 and §3 say otherwise:

- **Scoped `HTTPS_PROXY`.** Never shell-wide. Per-tool shims in `~/.klav-forward/bin/` and `klav-forward run [--profile P] -- CMD` set `HTTPS_PROXY`, `NO_PROXY=127.0.0.1,localhost`, `NODE_USE_ENV_PROXY=1` and the trust variables. `HTTP_PROXY` is never set. Mode (b) has its own port (`127.0.0.1:8791`), and mode (a)'s 8790 doesn't change.
- **The forwarder opens the tool's TLS, inside the sandbox.** It uses an ephemeral CA that signs its own certificate and one leaf for the sandbox's hosts, and is then wiped before any tool runs. The leaf key signs only the server's TLS 1.3 `CertificateVerify`. Trust lives only in the shims' environment, never in the system store.
- **Every key and signature stays in `klav-core`.** Where the certificate's bytes are laid out is Q2.
- **The profile is chosen by the channel's `CONNECT host:port`,** never by `Host` or the path. `Host` must equal the connection's host, or the answer is `421`. SNI must equal the `CONNECT` host. Two profiles of one sandbox on the same host are refused.
- **A non-profile host is passed through untouched,** never read.
- **The proxy always drops what the tool sends and writes the real header** (ADR 0036 §7 as written).
- **The wire.** The claim and status answers gain `hosts`. The channel gains a `CONNECT host:port` route served with `hyper` upgrades. **The forwarder never parses HTTP after TLS:** the proxy's `hyper` is the only parser.

#### 1.1 The mechanics, restated (so nothing here depends on the unmerged draft)
- **The certificates,** made by `klav-forward up` after the claim, through `klav-core` (§11):
  - **CA:** a fresh Ed25519 key; basic constraints CA with path length 0; key usage `keyCertSign`; a critical **NameConstraints** extension whose permitted `dNSName` subtrees are the sandbox's profile hosts and tunnel hosts, each wildcard written as its base. RFC 5280 makes a `dNSName` constraint `base` permit `base` and every name under it, so the constraint is wider than a single-label wildcard: it is defence in depth, and the leaf's SAN list is the binding limit. The CA key signs its own certificate and exactly one leaf, then `klav-core` wipes it.
  - **Leaf:** a fresh Ed25519 key; SAN = exactly those hosts (a wildcard tunnel host as `*.base`); extended key usage `serverAuth`; valid from 5 minutes before now until the sandbox's `expires_at`; a random serial and SHA-256 key identifiers. Its key signs only the server's TLS 1.3 `CertificateVerify`.
  - **Who enforces name constraints on a root the user added,** per draft 0043's reading of default branches: `rustls-webpki` 0.103.16 does, and OpenSSL and Go at `master` do. Checked for the exact client versions at layer 6. If a stack ignores them, nothing opens up, because no key remains to sign another leaf.
- **The files and variables,** none of them secret, all under `~/.klav-forward/mode-b/`:
  - `ca.pem` goes to `NODE_EXTRA_CA_CERTS`;
  - `bundle.pem` (the system bundle followed by `ca.pem`) goes to `SSL_CERT_FILE`, `REQUESTS_CA_BUNDLE` and `CURL_CA_BUNDLE`;
  - only the shims and `klav-forward run` set them, and `klav-forward down` removes the directory.
- **At port 8791,** for each connection, the forwarder:
  1. reads one `CONNECT host:port` head, at most 8 KiB within 20 s, and answers anything else `405 klav_not_allowed`;
  2. looks the host up among the claim's `hosts`:
     - **not found:** it answers `200` and relays bytes untouched over a direct TCP connection from the sandbox;
     - **found:** it opens a channel connection and sends the same `CONNECT`. A refusal is passed to the tool as is, and an unreachable proxy gets `503 klav_proxy_unreachable`;
  3. on the proxy's `200`, terminates the tool's TLS: TLS 1.3 only, ALPN `http/1.1` only, the leaf above, and SNI equal to the `CONNECT` host (otherwise an `unrecognized_name` alert);
  4. relays the decrypted bytes without parsing them.
- **Clients that honor this, and the fallback:** `reqwest` (native roots), `curl` and OpenSSL, Node `fetch` with `NODE_USE_ENV_PROXY=1` (from Node 22.21 or 24.0), undici's `EnvHttpProxyAgent`, Go `net/http` and Python `requests`. All of these come from draft 0043's reading and are unconfirmed per version until layer 6's matrix. A client that refuses an Ed25519 chain gets P-256 keys from `klav-core` (§11). A client that pins certificates, carries its own roots with no override, or needs HTTP/2 fails closed: it holds only a placeholder (risk 120).

**What 0043 left as a limit, and this ADR lifts:** "WebSockets don't pass: the proxy drops `Upgrade`" (0043 §7, risk 80).

### 2. Tunnel hosts: a dynamic `targetDomain`, fail-closed
`targetDomain` isn't the profile's `upstream`. It comes from an API answer at run time. Draft 0043 builds the leaf at the claim, from hosts known then. This section keeps that, and asks the person to sign the tunnel hosts.

- **`ProxyProfile` gains `tunnel`** (grant `v: 5`, §10):
  ```json
  "tunnel": { "hosts": ["<exact host>"], "path_prefix": "/tunnel/",
              "idle_secs": 900, "max_secs": 28800 }
  ```
  - **`hosts`:** 1–4 entries, each an exact host or `*.base`. A `*.base` entry matches **exactly one label** (RFC 6125's wildcard, as a leaf SAN). It is a new grammar, `TunnelHost`, deliberately narrower than `DomainPattern`, whose `*.` matches any depth (`policy.rs:200-211`).
  - **`path_prefix`:** canonical, at most 32 bytes (`MAX_GRANT_PATH_LEN`). `/tunnel/` fits. The full addon path (`/tunnel/projects/horizon-stack/addons/postgres`) doesn't, and needn't.
  - **`idle_secs` and `max_secs`:** see §4. Capped at 3600 and 86 400.
- **The leaf's SAN list** is the profile hosts plus the tunnel hosts, all known at the claim. The CA key is still wiped before any tool runs. So the "dynamic" host is dynamic only within what the person signed.
- **The discriminator: who else can serve under that name.** A wildcard tunnel host is safe only if every name it matches is Northflank's own infrastructure. If customer workloads can get a name there, a wildcard hands the real token to whoever runs that workload. Northflank's customer apps get names under `code.run` *(from memory)*; where `targetDomain` lives isn't known yet (§15).
  - **So the default is exact hosts.** The `northflank` preset fills the exact `targetDomain` that the layer-8 hand test observes for each region the person uses. `klav proxy grant --tunnel-host HOST` adds one, and the sheet shows each in full.
  - **A wildcard ships in the preset only if the hand test shows** that the parent domain serves Northflank infrastructure only. A wildcard the person types is shown in red.
  - **A changed `targetDomain`** (a new cluster) fails closed. The forwarder passes it through untouched (it's not a known host), the tool sends the placeholder, and Northflank answers `403`. `klav-forward status` names the host it saw, and the person adds it by re-signing.
- **Alternatives, for Q3:**
  - **A single-label wildcard from day one.** Fewer re-signs, but only safe under the discriminator above.
  - **Hosts vouched for by the upstream.** The proxy accepts a tunnel host only if it saw that host in a TLS-verified answer from the same profile's upstream to the same sandbox within the last 10 minutes. This is the most automatic. But the proxy would read a vendor's JSON (vendor logic, contra ADR 0049 §1), and the forwarder would need a CA alive to sign leaves on demand, which brings back the key 0043 wipes.

### 3. A tunnel is a mode (b) connection, judged as one call
Through the shim, the tool sends `CONNECT targetDomain:443` to the forwarder's port 8791. The forwarder sees a tunnel host, and from there it works as in §1.1:

1. The forwarder opens a channel connection, sends `CONNECT targetDomain:443`, and the proxy checks that the host is in one of the sandbox's profiles (`upstream` or `tunnel.hosts`).
2. On `200`, the forwarder terminates the tool's TLS with the leaf and relays the decrypted bytes, without parsing them.
3. **At the proxy,** a request on that connection whose host is a tunnel host is accepted only if all of the following hold, and otherwise gets `403 klav_not_allowed`:
   - the method is `GET`, the path is under `tunnel.path_prefix`, and the request carries `Upgrade: websocket`, `Connection: upgrade` and `Sec-WebSocket-Version: 13`. A plain request to a tunnel host is refused: a tunnel host isn't an API host;
   - there is no body.
4. **The policy** is ADR 0006's, with one new dimension. `Scope` gains `upgrades: Vec<Upgrade>`, where `Upgrade` is a closed enum with one value, `websocket`. `policy::Request` gains `upgrade: Option<Upgrade>`. **A request with `upgrade` is matched by a rule without `upgrades` only if that rule denies,** the same mechanism as `mcp_tools` (ADR 0049 §5.3, Q3) and `unjudgeable`. So:
   - today's `northflank` grants, whose rules allow `GET` on `api.northflank.com/`, **never allow a tunnel through a proxy update**;
   - a tunnel needs a rule that names the tunnel host, the prefix, `GET` and `upgrades: [websocket]`, which the person signs.
5. **One access per tunnel.** The proxy makes one signed `POST /v1/agent/access` per WebSocket handshake, never cached. Its `Claims` carries `domain` (the tunnel host), `method: GET`, `path` (without query), and a new `upgrade: "websocket"`. An `ask` holds the handshake up to 2 minutes, as ADR 0036 §9 does, and then answers `klav_approval_pending`. The JS client turns that into a refused connection, and the agent retries the TCP connection.

### 4. The WebSocket relay in `klav-proxy`
- **The upstream handshake is built by the proxy:**
  - URL: `wss://<tunnel host><path>[?query]`;
  - TLS: webpki roots, the proxy's DNS checks (`net::is_public`), no redirects;
  - headers: it drops every header on the `DROPPED_REQUEST_HEADERS` list and the profile's header, writes the real credential, writes a fresh `Sec-WebSocket-Key` of its own, and forwards `Sec-WebSocket-Protocol` if present.
  - **It never forwards `Sec-WebSocket-Extensions`.** So `permessage-deflate` is never negotiated, and frames stay uncompressed for the scan below.
- **The `101` back to the tool** carries only `Upgrade`, `Connection`, `Sec-WebSocket-Accept` (computed for the tool's own key) and the chosen `Sec-WebSocket-Protocol`. Everything else is dropped: `Set-Cookie`, `WWW-Authenticate` and any vendor header. A non-`101` answer is returned like any mode (a) answer, redacted, with the sandbox's dropped headers.
- **Frames are relayed, not bytes.** The proxy is a WebSocket endpoint on both sides, through `tokio-tungstenite` over the upgraded `hyper` connection and over its own upstream TLS stream (§11):
  - it enforces masking on each side (the tool's frames are masked, the proxy re-masks toward the upstream);
  - message size is capped at 16 MiB, fragments are reassembled up to that cap, and control frames are at most 125 bytes;
  - close codes pass through; a protocol error closes both sides with `1002`.
- **What redaction can and can't do here.** After the `101` the payload is a tunnelled byte stream, often binary, where replacing bytes would corrupt the inner protocol. So upstream→tool data is **detected and cut, never rewritten:**
  - the proxy runs the whole-value matcher (the `Redactor`'s encodings) over the concatenated payload, keeping a tail of `len(value) − 1` bytes of what it already forwarded;
  - when a match would complete inside a frame, that frame is **not** forwarded. Both sides are closed with `1008`, and the log line says `klav_redacted_cut`;
  - nothing is held back, so interactive protocols (Postgres's 6-byte `ReadyForQuery`) aren't delayed.
  - **The residue, written as risk 115:** up to `len − 1` bytes of the value can reach the tool before the cut, and only if the far end sends the token back inside the tunnel.
  - **Why the residue is small for tunnels.** The token is used only in the HTTP handshake. The far end is the tunnelled service (a database), which never received the token.
- **Limits:**
  - **idle:** `tunnel.idle_secs` (default 900) with no data frame either way;
  - **total:** `tunnel.max_secs` (default 8 h), and never past the sandbox's `expires_at`;
  - **keepalive:** the proxy sends a WebSocket ping both ways every 60 s, below the forwarder's 240 s and the Nitro parent's 300 s relay idle, so an idle `psql` isn't cut by a relay it can't see. Pongs don't count as activity for `idle_secs`;
  - **how many:** long-lived connections (tunnels and Postgres sessions together) are at most 8 per sandbox (`SANDBOX_LONG_LIVED`) and 32 per proxy, counted apart from the 4 call slots. Each one holds a channel connection, so 8 also leaves at least 4 of the forwarder's 12 relayed connections (`MAX_RELAYED`) and of the proxy's 16 per channel key (`max_per_key`) for calls and status.
- **Teardown.** Each tunnel registers in `cuts.rs` before its access, as M3's calls do.
  - **At once:** `klav sandbox stop`, the theft signal and `released`.
  - **Within 30 s:** TTL, inactivity, a removed issuer, the person's revocation, and a pause of all agents.
  - **At the next refused access** of any of that sandbox's calls: `sandbox_revoked`, or a pause of its issuer.
  - A cut closes both sides with `1008` and a reason (`klav_sandbox_revoked`, `klav_agents_paused`), then drops TCP.
- **Klav Cloud.** The enclave's upstream goes through the parent's `CONNECT targetDomain:443`, which the default port list already allows. Nothing changes in the parent. ADR 0051 §3.3's table gains **concurrent tunnels per account: 16**, and their bytes count against egress bytes per day.

### 5. The `northflank` preset
- **Unchanged:** `GET`, `POST` and `PATCH` pass, `DELETE` asks, `PUT` is refused, and role and token routes are not protected by path (decision of 2026-11-16).
- **Tunnels are opt-in:** `klav proxy grant ITEM --preset northflank --tunnels`. It adds `tunnel` with the hand-tested hosts, and one rule: allow, host = tunnel hosts, `GET`, `/tunnel/`, `upgrades: [websocket]` (Q4). `--tunnels-ask` makes that rule `ask`.
- **The setup lines** for a sandbox with this profile add the shim. `northflank` in the shim's `PATH` runs the real CLI with the mode (b) variables. The fourth line (`northflank login … --host "$KLAV_FORWARD_NORTHFLANK_URL"`) stays. So REST calls go to `127.0.0.1` (mode (a), skipped by `NO_PROXY`), and the WebSocket goes through `HTTPS_PROXY` (mode (b)).
- **What Part 1 doesn't solve:** the database password. With Part 1 alone, the agent connects `psql` through the tunnel with credentials it got some other way, as it did on 2026-11-28. That's Part 2.

### Part 2 — the Postgres credential proxy and SQL guard

### 6. Topology
```
sandbox                                     proxy host (self-hosted, Mac, or Klav Cloud enclave)
psql ──▶ klav-forward 127.0.0.1:15432 ══ pinned TLS 1.3 channel ══▶ klav-proxy (Postgres server side)
         (bytes only, after an HTTP          POST /_klav/pg/<profile>        │ classifier + Layer A
          upgrade on the channel)            Upgrade: klav-pg/1 → 101         │ SCRAM in klav-core
                                                                              ▼
                                       either  direct: TCP + TLS (verify-full) ──▶ db.example.com:5432
                                       or      northflank-addon: WSS ──▶ targetDomain/tunnel/…/port/5432
```
- **In the sandbox:** `KLAV_FORWARD_<PROFILE>_DATABASE_URL=postgresql://klav@127.0.0.1:<port>/<db>?sslmode=disable`, from `klav-forward env`. There is no password in it. `sslmode=disable` is honest: the hop is loopback, and the channel to the proxy is pinned TLS 1.3. With libpq's default `prefer`, it also works, because the proxy answers `SSLRequest` with `N`.
- **The forwarder** relays bytes after an upgrade request on the channel. It parses no Postgres, as it parses no HTTP (ADR 0036 §5, note of 2026-11-11). `CancelRequest` connections take the same route.
- **The proxy speaks Postgres to the sandbox as a server and to the database as a client.** Neither the Northflank token nor the database password ever goes to the sandbox:
  - **direct:** the password goes only to the database, inside TLS the proxy verifies;
  - **`northflank-addon`:** the token goes only to Northflank's tunnel host, and the password only into the tunnel, inside the database's own authentication. That is SCRAM, so the password itself never crosses the wire.
- **Sandbox only in v1.** The Mac proxy's loopback has no caller identity for Postgres (ADR 0042 §3; ADR 0049 §3.2's `klc1_` tokens are an HTTP header). So Postgres profiles are refused on loopback (`403 klav_not_allowed`), and local agents use `klav run` as today.

### 7. The Postgres profile
`ProxyProfile` gains `pg` (grant `v: 5`). A profile has either `pg` or `upstream` semantics, never both. `header` and `prefix` are empty for `pg` profiles.
```json
"pg": {
  "transport": { "direct": { "host": "db.example.com", "port": 5432 } },
  "databases": ["app"],
  "user_field": "username",
  "tls": "verify-full",
  "write_item_id": null
}
```
- **`transport`:** one of:
  - `direct {host, port}`: a public name only. A private address is refused at connect time, as every proxy call is (§6, Context);
  - `northflank_addon {profile, project, addon, team?, port}`, which names the Northflank profile whose token opens the tunnel (§8, Q12).
- **`databases`:** 1–4 names. A `StartupMessage` asking for another database is refused.
- **`user_field`:** the item field that holds the role name. The item's main secret is the password.
- **`tls`:** `verify-full` (webpki roots, hostname checked) or `none`. On `northflank_addon`, `verify-full` checks the addon's certificate inside the tunnel for the chosen instance's `internalHostname` from the info call (§8, step 5), and is the CLI's default there. `none` is allowed only on `northflank_addon`, for an addon with TLS turned off, where the WebSocket's TLS already protects the hop. For `direct`, a private CA isn't supported in v1 (RDS ships its own CA): Q11's notes.
- **`write_item_id` (optional):** a second item, a role allowed to write, used only for approved writes (§9.3). The `pg` item then holds a read-only role.
- **Rules.** `Scope` gains `sql_classes: Vec<SqlClass>`, where `SqlClass` is a closed set: `read`, `write`, `ddl`, `admin`, `unknown`. `policy::Request` gains `sql_class`. A request with `sql_class` is matched by a rule without `sql_classes` only if that rule denies, the same mechanism as §3. Both presets have one session rule (allow, `sql_classes: [read]`) plus:

  | Preset `postgres` (default) | Preset `postgres --read-only` |
  |---|---|
  | allow `read`; ask `write`, `ddl`, `admin`, `unknown` | allow `read`; deny `write`, `ddl`, `admin`, `unknown` |

  This is Omar's stated default. "`DO`, `CALL`, unrecognized and multi-statement batches ask" falls out of the classifier (§9.4), which puts them in `admin` or `unknown`.

### 8. Transports
- **`direct`.** TCP to `host:port` after the proxy's own DNS check. Then `SSLRequest`: an `S` answer starts TLS 1.3 or 1.2 with `rustls` and webpki roots, hostname-checked; an `N` answer to a `verify-full` profile closes. Direct TLS negotiation (`sslnegotiation=direct`, PostgreSQL 17 *(from memory)*) isn't used in v1.
- **`northflank_addon`** (Q12 (a)):
  1. With the named Northflank profile's token, the proxy calls `GET /v1/port-forwarding/info/[teams/{team}/]projects/{p}/addons/{a}` on that profile's `upstream`. This is a signed access like any call (`GET`, that path), so the person's rules on that profile apply.
  2. It reads only `targetDomain` and the instances' `podName`, `internalHostname` and `ports` from the answer.
  3. It checks `targetDomain` against the Northflank profile's `tunnel.hosts` (§2). The same fail-closed rule holds: the API can't send the token to a host the person didn't sign.
  4. It opens `wss://{targetDomain}/tunnel/…/instance/{pod}/port/{port}` as in §4, with one access (`upgrade: websocket`), and speaks Postgres inside binary frames.
  5. Inside, with `tls: verify-full`, it sends `SSLRequest` and runs TLS with webpki roots, checking the certificate for the chosen instance's `internalHostname` (a bare host name, or the session fails closed before any access; never plaintext). With `tls: none`, it sends no `SSLRequest`. Layer 17 found that Northflank's Postgres addons require TLS (§15).
  - **This is the only vendor code in `klav-proxy`,** about 150 lines, behind a `Transport` trait. ADR 0049 §1 ("no vendor logic") is amended for transports only; policy stays generic.
- **Klav Cloud.** `northflank_addon` uses port 443 and works through the parent unchanged. `direct` to 5432 needs the operator to list 5432 on the parent (Klav-wide, ADR 0051 §1.2), which is Q13.

### 9. The Postgres wire, in `klav-proxy`
The proxy implements protocol 3.0 by hand: framed messages, a type byte and a 32-bit length, with no crate. It is a strict state machine, and anything unexpected closes the session with an `ErrorResponse`.

#### 9.1 Startup (sandbox side)
- **`SSLRequest`** gets `N`, and the client continues in plaintext on the pinned channel. **`GSSENCRequest`** gets `N`.
- **`CancelRequest`** is mapped by the fake key below and forwarded on a fresh upstream connection, or a fresh tunnel. An unknown key is dropped silently, as Postgres does.
- **`StartupMessage`:**
  - **version:** 3.0. A later minor version (3.2, PostgreSQL 18 *(from memory)*) gets `NegotiateProtocolVersion` down to 3.0;
  - **`user`:** ignored, because the role comes from the item;
  - **`database`:** must be in `databases`;
  - **allowed parameters:** `application_name` (printable ASCII, at most 64 bytes), `client_encoding` (only `UTF8`), `DateStyle`, `TimeZone`, `extra_float_digits`;
  - **refused:** `replication`, `options` and every other parameter, with `08004`.
- **Authentication toward the sandbox:** the proxy sends `AuthenticationOk` at once. The channel key already authenticated the sandbox (ADR 0036 §6). A `PasswordMessage` from the client is a protocol violation.
- **`BackendKeyData`:** the proxy sends its own random process ID and key, and keeps the mapping to the upstream's.

#### 9.2 Upstream session and access
- **One access opens the session.** It is a signed `POST /v1/agent/access` with permission `proxy`, `Claims {domain: host or tunnel host, pg_database}` and the request's `sql_class: read`. The server applies pause, revocation and the rules there. A refusal becomes `ErrorResponse 42501` and the session closes.
- **Then a lease, not an access per `SELECT`.** Reads inside the session ride on that access, re-checked with a fresh access every 60 s while the session is open, as ADR 0038 §7 does for services. A refusal at a re-check closes the session.
  - Every non-read statement is its own access (§9.6).
  - This amends ADR 0036 §2's "one access per injected request, never cached" for Postgres sessions, and says so (Q6).
- **Upstream startup.** The proxy sends `user` = the item's role, `database` = the client's, `application_name` = `klav-proxy`, `client_encoding=UTF8`, and `options=-c default_transaction_read_only=on -c statement_timeout=240000`.
- **Idle sessions.** Postgres has no ping of its own, and the forwarder (240 s) and Klav Cloud's parent (300 s) cut relays that move no byte. So:
  - for `klav-pg/1` relays, the forwarder's idle limit is 16 minutes. The proxy owns the session's timeout: it closes a session idle for 15 minutes with `57P05` ("idle session closed by Klav");
  - while the client is idle (`ReadyForQuery` `I` with no message in flight), the proxy sends the upstream an empty Simple Query every 60 s and swallows its `EmptyQueryResponse`. That has no side effect, keeps the parent's relay alive on `direct`, and never interleaves with the client's traffic. On `northflank_addon`, §4's WebSocket pings do the same;
  - `statement_timeout` is pinned at 4 minutes, below the parent's 300 s, because a running query moves no byte and the empty query can't be sent then.
- **Authentication with the vault item's password, inside `klav-core`** (§11, Q11):
  - **`SASL SCRAM-SHA-256`** (RFC 5802/7677) is required. **`SCRAM-SHA-256-PLUS`** (`tls-server-end-point`) is used when the upstream offers it over direct TLS;
  - `klav-core` gets the password as a `SecretBox`, does SASLprep, `Hi()` (PBKDF2-HMAC-SHA-256, iterations capped at 4096–600 000 against a hostile server's CPU burn) and the proofs, and returns only the client-final message;
  - it verifies the server signature (`v=`), which proves the server knew the password's verifier;
  - **MD5 is refused** (`28000`, "the database asks for MD5; switch the role to SCRAM"), and Klav adds no MD5 dependency;
  - **cleartext `AuthenticationCleartextPassword` is refused** unless the profile signs `allow_cleartext_over_tls: true` and the hop is verified direct TLS (Q11);
  - an upstream that answers `AuthenticationOk` with no challenge is accepted and logged as `trust`.
- **After authentication,** the proxy reads `ParameterStatus` and requires:
  - `standard_conforming_strings=on` and `client_encoding=UTF8`;
  - from PostgreSQL 14 on, where it is reported *(from memory)*, `default_transaction_read_only=on`. On older servers the proxy runs `SHOW default_transaction_read_only` itself before the first client message;
  - if `default_transaction_read_only` is not `on`, the startup `options` did not take (a transaction-mode pooler drops them, §9.3 "Per transaction"). Then the proxy proves, fail-closed, that its own transaction holds Layer A instead. It opens `BEGIN TRANSACTION READ ONLY; SET LOCAL statement_timeout = 240000; SET LOCAL search_path = "$user",public`, requires `current_setting()` to give `transaction_read_only = on`, `standard_conforming_strings = on`, `statement_timeout = 4min` and `search_path = "$user", public`, runs the `dblink`/`postgres_fdw` check in that transaction, and requires `ROLLBACK` to leave the connection idle. Any error or any other value is `55000`, and the session is not opened. The approved-write role's own connection (read-only `off`) has no such mode;
  - otherwise the session closes (`55000`).
- **Redaction.** The proxy parses every upstream message, so it scans each `DataRow`, `NoticeResponse`, `ErrorResponse` and `ParameterStatus` for the password and the Northflank token (whole value, the `Redactor`'s encodings) and re-frames the message with the value replaced. This is full redaction, unlike §4's cut, because messages are framed. A message over 16 MiB closes the session.

#### 9.3 Layer A: the engine enforces read-only
**By default every transaction is `READ ONLY` at PostgreSQL itself.** So `SELECT delete_all_users()`, a writable CTE the classifier missed, or a parser edge case gets "cannot execute … in a read-only transaction" from the engine.

**Layer A alone is not a barrier,** and the ADR says why *(from memory of PostgreSQL's documentation; layer 12 checks each point against the CI's PostgreSQL)*:
- a session can change `default_transaction_read_only` (`SET`, `set_config()`), or start a transaction with `BEGIN READ WRITE`;
- a read-only transaction still allows some things: temporary-table writes, session settings, advisory locks, `pg_cancel_backend` and `pg_terminate_backend` (privilege permitting), and functions that open their own connections (`dblink_exec`, which writes outside this transaction);
- PostgreSQL's documentation describes read-only mode as a high-level notion that doesn't prevent every write to disk.

**What actually holds:**
1. **The proxy owns transaction mode.** Statements that touch `transaction_read_only`, `default_transaction_read_only`, `transaction_isolation` with `READ WRITE`, `SET SESSION CHARACTERISTICS`, `session_authorization`, `role`, `search_path`, `client_encoding`, `standard_conforming_strings` or `statement_timeout` beyond its cap, in any form (`SET`, `RESET`, `set_config()`, startup), are **refused and never approvable**. That covers `BEGIN`, `START TRANSACTION` and `SET TRANSACTION` with `READ WRITE` too.
2. **It watches.** On PostgreSQL 14 and later, a `ParameterStatus` showing `default_transaction_read_only=off` closes the session at once.
3. **The classifier's function allowlist** (§9.4) stops `dblink_exec`, `pg_terminate_backend`, `set_config` and their kind from running as a "read".
4. **A read-only role is the strongest barrier,** and the one the sheet recommends. With `write_item_id` set, the `pg` item's role has only `SELECT` grants, so PostgreSQL's privileges refuse any write, whatever the proxy parsed. Approved writes then run on a separate, short-lived upstream connection as the write role (§9.6).

**How an approved write runs** (without `write_item_id`):
- It runs only when the client is outside a transaction block (`ReadyForQuery` status `I`).
- The proxy sends its own `BEGIN READ WRITE`, then the exact approved bytes, then `COMMIT` on success or `ROLLBACK` on error. It swallows its own messages' answers and reports `ReadyForQuery` `I`.
- The session default never leaves `on`, so the next statement is read-only again.
- **Inside an open transaction block, a write is refused** with "Klav runs an approved write on its own: `COMMIT` or `ROLLBACK`, then send it alone". The block is already read-only, and PostgreSQL refuses a switch to `READ WRITE` after the block's first query *(from memory)*.
- **An approved write may not contain transaction control** (`BEGIN`, `COMMIT`, `ROLLBACK`, `SAVEPOINT`, `PREPARE TRANSACTION`).
- **v1 limit:** one approved write is one autocommitted unit. A multi-statement simple query counts as one unit, approved whole.

**Per transaction, behind a transaction-mode pooler** (added 2026-11-30 after layer 17's first run). On Northflank's Postgres 17 addon (`horizon-stack/postgres`, PostgreSQL 17.12), a transaction-mode pooler sits in front of the server. It drops `options` from the `StartupMessage`, so `ParameterStatus` reports `default_transaction_read_only = off`, and it resets session `SET`s between transactions: a `SET default_transaction_read_only = on` is `off` again at the next query. PgBouncer in transaction mode, Supabase's and Neon's poolers are expected to behave alike *(from memory, untested; PgBouncer may instead refuse the `options` parameter at startup, which fails the session closed)*. The session default can't carry Layer A there, but a transaction can: on that addon, `BEGIN TRANSACTION READ ONLY; SET LOCAL statement_timeout = 30000; SET LOCAL search_path = pg_catalog` gave `ReadyForQuery T`, `transaction_read_only = on` and the `SET LOCAL` values inside, `CREATE TABLE` failed with `25006`, and `COMMIT`/`ROLLBACK` came back `I`. When §9.2's probe finds the default `off` and the per-transaction check passes, the session runs in this mode:
- **Every read outside a transaction block runs in the proxy's own transaction:** `BEGIN TRANSACTION READ ONLY; SET LOCAL statement_timeout = 240000; SET LOCAL search_path = "$user",public`, the exact unit (a Simple Query, or one extended group up to its `Sync`), then `COMMIT`, or `ROLLBACK` if the unit failed. The proxy swallows its own answers and reports `ReadyForQuery I`. The `SET LOCAL` values are the ones `options` pins. `search_path = pg_catalog`, used in the hand test, would hide the user's unqualified tables (checked on PostgreSQL 17: `relation "t" does not exist`). The proxy drains before each unit, so this mode does not pipeline.
- **Every transaction on the connection is the proxy's.** A lone `BEGIN` or `START TRANSACTION` (Simple Query) outside a block goes up with its own modes, which the classifier allows only without `READ WRITE`. Before the sandbox's first statement runs in it, the proxy sends `SET TRANSACTION READ ONLY` and the same `SET LOCAL`s, then answers `BEGIN` and `ReadyForQuery T`. Later units run in that block as they are, up to the sandbox's lone `COMMIT`, `END` or `ROLLBACK`.
- **No transaction control may leave or replace the proxy's transaction** (T291's anti-escape rule). These are refused with `0A000`:
  - transaction control with any other statement in the same Simple Query (`COMMIT; SELECT …`, `BEGIN; …`) or in the same extended group;
  - `COMMIT`/`END`/`ROLLBACK AND CHAIN`, because the chained transaction stays read-only but drops the `SET LOCAL`s (checked on PostgreSQL 17: `statement_timeout` back to `0`);
  - an extended-protocol `BEGIN`, and a `Flush`-terminated group, outside a block (the wrapper is never held open across the sandbox's messages).

  Two-phase commit and `ABORT` stay refused as before. A lone `COMMIT`, `ROLLBACK` or savepoint statement with no block open goes up as is. Two backstops close the session (`55000`): the connection not idle after it, and a wrapped unit that leaves the proxy's transaction (status `I` before the proxy's `COMMIT`).
- **Layer A here depends on Layer B** seeing every transaction-control statement, because it is the proxy's own transaction and not the session default. The backstops only close the session after the fact.
- **The watch** still requires `standard_conforming_strings = on` and `client_encoding = UTF8`, and ignores `default_transaction_read_only`, which is the pooler's idle `off`.
- **Approved writes** run in `BEGIN TRANSACTION READ WRITE` with the same `SET LOCAL`s. After `COMMIT`, the proxy checks only that the connection is idle (`I`): the next read opens its own read-only transaction.
- **The write role's connection** (`write_item_id`) behind such a pooler gets no `statement_timeout` or `search_path` pin, since its `options` are dropped too. Only `read_only = off` is checked there, as before.
- **Prepared statements live only in their transaction.** On a pooler, the next transaction can land on another server connection, where the same name may be another statement the guard never classified. So outside a transaction block the guard forgets every statement name and portal, and a `Bind` to one is refused with `26000` before anything goes up or is asked. Inside the sandbox's own block, names work as usual. The proxy's `COMMIT` (a simple query) also ends the protocol's unnamed statement. Clients that send `Parse`, `Bind`, `Execute` and `Sync` together (psql, node-postgres, psycopg) work. A client that prepares in one group and binds in a later one, outside a block, does not, as behind any transaction-mode pooler.

#### 9.4 Layer B: the classifier, strict and fail-closed
**What it classifies:** every statement text the proxy forwards, meaning a Simple `Query`'s string and every `Parse`'s string. `Bind` values are data and are never classified as SQL, but they are bound into the approval digest (§9.6).

**The lexer is PostgreSQL's lexical grammar, done exactly** (Q7 (a)):
- comments: `--` and nested `/* */`;
- strings: `'…'` with `''` and `standard_conforming_strings=on` (pinned), `E'…'` escapes, `U&'…'` and `U&"…"` with `UESCAPE`, `B'…'` and `X'…'`;
- dollar quoting (`$tag$…$tag$`), quoted identifiers;
- positional parameters (`$1`), and operators;
- the input must be valid UTF-8 with no NUL (`client_encoding` is pinned to UTF8). Anything it can't lex is `unknown`.

**A statement is `read` only if every rule here holds** (anything else is `unknown`, unless it matches one of the class lists below):
- its first keyword is `SELECT`, `VALUES`, `TABLE`, `WITH`, `SHOW`, `EXPLAIN`, or transaction control on the read side: `BEGIN` or `START TRANSACTION` with no `READ WRITE`, `COMMIT`, `END`, `ROLLBACK`, and `SAVEPOINT`, `RELEASE` or `ROLLBACK TO`;
- `EXPLAIN` without `ANALYZE` in any form (`ANALYZE`, `(ANALYZE)`, `(ANALYZE true)`); `EXPLAIN ANALYZE` runs its statement and is classified as that statement;
- **no data-modifying token anywhere outside strings, comments and quoted identifiers:** the bare words `INSERT`, `UPDATE`, `DELETE`, `MERGE` and `INTO`, and the sequences `FOR UPDATE`, `FOR NO KEY UPDATE`, `FOR SHARE` and `FOR KEY SHARE`;
  - this one rule closes **writable CTEs** (`WITH d AS (DELETE … RETURNING *) SELECT …`), **`SELECT … INTO`** and **row locks**, with no grammar needed;
  - `INTO` and `FOR` are reserved words in PostgreSQL *(from memory)*, so a bare column can't be called that. `INSERT`, `UPDATE`, `DELETE` and `MERGE` aren't, so an unquoted column called `update` costs an approval, never a leak. Quoted (`"update"`), it passes;
- **utility verbs are judged only where a statement starts** (the start of the text or after a top-level `;`), because PostgreSQL's grammar allows them nowhere else. Those are `COPY`, `CREATE`, `ALTER`, `DROP`, `TRUNCATE`, `GRANT`, `REVOKE`, `LOCK`, `CALL`, `DO`, `EXECUTE`, `PREPARE`, `DEALLOCATE`, `LISTEN`, `NOTIFY`, `UNLISTEN`, `SET`, `RESET`, `DISCARD`, `VACUUM`, `ANALYZE`, `CLUSTER`, `REINDEX`, `REFRESH`, `COMMENT`, `SECURITY`, `IMPORT`, `LOAD`, `CHECKPOINT` and `REASSIGN`. So `SELECT comment, lock FROM posts` stays `read`;
- **every function call is on the allowlist.** A function call is an identifier, qualified or not, followed by `(`. The allowlist (Q8 (a)) is a curated list of `pg_catalog` functions with no side effects: arithmetic, string, date and time, JSON, aggregate and window functions, `current_*`, `pg_typeof`, `has_*_privilege`, `pg_get_*def`, `version` and the like. It is shipped as data and versioned with the vectors. Names are unqualified, or qualified as `pg_catalog`.
  - Excluded: `set_config`, `nextval`, `setval`, `pg_advisory*`, `pg_cancel_backend`, `pg_terminate_backend`, `pg_reload_conf`, `pg_read_*`, `lo_*`, `dblink*`, `txid_current`, `pg_notify`, `pg_sleep*` and every user function.
  - Also excluded: **functions that run SQL given to them as text,** such as `query_to_xml`, `query_to_xmlschema`, `query_to_xml_and_xmlschema`, `cursor_to_xml` and `ts_stat`, whose argument the classifier never sees as SQL. Each has a vector in `sql-guard.json`.
  - A call outside the list makes the statement `unknown` (ask by default). The person sees and approves it; it doesn't pass silently;
  - `search_path` is pinned (rule 1 of §9.3), so an unqualified name resolves to `pg_catalog` first, as PostgreSQL does by default. A user who can create functions or operators in a schema still can't shadow `pg_catalog` names. Operators aren't checked, and stay in risk 117;
- **one statement only per `Parse`** (PostgreSQL enforces this too).

**The other classes:**

| Class | Statements |
|---|---|
| `write` | `INSERT`, `UPDATE`, `DELETE`, `MERGE`, `COPY … FROM STDIN`, `SELECT … INTO`, row locks |
| `ddl` | `CREATE`, `ALTER`, `DROP`, `TRUNCATE`, `COMMENT`, `REINDEX`, `CLUSTER`, `VACUUM`, `ANALYZE`, `REFRESH` |
| `admin` | `GRANT`, `REVOKE`, `ALTER`, `CREATE` or `DROP` of a `ROLE` or `USER`, `ALTER SYSTEM`, `SECURITY LABEL`, `DO`, `CALL`, `LOCK`, `COPY` to or from a file or `PROGRAM`, `LOAD`, `CHECKPOINT`, `REASSIGN OWNED`, `IMPORT FOREIGN SCHEMA` |
| `unknown` | everything else: anything unlexable, functions off the list, SQL-level `PREPARE`, `EXECUTE` and `DEALLOCATE`, `LISTEN` and `NOTIFY`, `DISCARD`, and `SET` or `RESET` of anything not pinned |

- **A pinned setting is refused outright,** never asked (§9.3).
- **Multi-statement Simple Query.** The lexer splits it on top-level `;`. The batch takes the most restrictive class, and the approval covers the exact bytes of the whole batch. So `SELECT 1; DROP TABLE users;` is `ddl`, and the card shows both statements.
- **`COPY` is the one leading verb that can be `read`:** `COPY table TO STDOUT` and `COPY (SELECT …) TO STDOUT`, with the inner query meeting the `read` rules, are `read`. `COPY … FROM STDIN` is `write`, and a file or `PROGRAM` is `admin`.

**Why a lexer and not a parser crate.** `sqlparser` (0.64.0, Apache-2.0, no `unsafe`, one new crate; §11) has a PostgreSQL dialect, but it isn't PostgreSQL's grammar. A statement it parses differently from the server is a parser differential (T290). The allowlist above needs only tokens: a keyword set, a function-call shape and a statement split, the exact lexical rules of one engine. That is a much smaller surface to get exactly right. It is also how ADR 0049 kept its strict JSON parser in house. `libpg_query` would be PostgreSQL's own parser, but it is C built through `bindgen`, with `unsafe` FFI and a C toolchain in every build that has the feature. That includes the enclave image. Q7 offers both.

**Tests:**
- a corpus in `docs/vectores/sql-guard.json` (input → class), including every bypass in the request and the ones T289–T291 list;
- `proptest` that wraps reads in random comments, whitespace and quoting, and checks the class never drops;
- in the CI `test (postgres)` task, every vector marked `read` runs against a real PostgreSQL in a read-only transaction, which must not error with `25006`.

#### 9.5 Query phase: messages from the sandbox

| Message | v1 |
|---|---|
| `Q` Simple Query | Classified (§9.4), then forwarded, held for approval, or refused |
| `P` Parse | Classified. The class is stored by statement name; the unnamed statement is replaced on each `Parse` |
| `B` Bind, `D` Describe, `E` Execute, `C` Close, `H` Flush, `S` Sync | Forwarded. `E` runs the class of the portal's statement. A pipeline holding a non-`read` statement is held whole up to its `Sync` (§9.6) |
| `F` FunctionCall (fast path) | Refused (`42501`), never approvable in v1 |
| `d`, `c`, `f` copy data, done, fail | Only during a `COPY FROM STDIN` that ran approved; otherwise a protocol violation |
| `p` password or SASL | Protocol violation after startup |
| `X` Terminate | Forwarded, then the session ends |
| anything else | `08P01` and close |

- **Rate:** 600 statements a minute per sandbox and 60 sessions a minute. **Size:** a statement up to 1 MiB, and `Bind` up to 16 MiB.
- **Server→client notices and notifications** are forwarded, redacted. `NotificationResponse` can't occur, because `LISTEN` isn't `read`.

#### 9.6 Approvals and audit for a statement
- **One access per non-`read` statement or batch.** `Claims` gains:
  - `pg_class`: `write`, `ddl`, `admin` or `unknown`;
  - `pg_verbs`: the leading keywords per statement, up to 8, from a closed vocabulary such as `DELETE` or `DROP TABLE`, so they can't carry data;
  - `pg_sql`: a digest, defined as `SHA-256(tuple("klav/v1/proxy/pg-sql", agent_id(16), item_id(16), lp(database), raw_statement_bytes, lp(param_formats), u16_be(n) ‖ lp(param_1) ‖ … ‖ lp(param_n)))`, base64url without padding.
- **Keys.** `target_key` appends `pg_class` and `pg_sql` after method, path and sandbox. "Once" means the same bytes with the same parameters, so a retry spends it (ADR 0015 §2). A lease ("for a while") matches `pg_class` and the first verb, on the same database and sandbox, never `admin` or `unknown`, and the card says so.
- **While waiting,** the proxy holds the statement or pipeline for up to 2 minutes (ADR 0036 §9). Then it answers `ErrorResponse` with:
  - `S=ERROR`, `C=42501`;
  - `M`: "Klav: DELETE on <profile> is waiting for the person's approval (approval <id>)";
  - `H`: "Ask the person to approve it on their Mac or iPhone, wait for them to say it's done, then send exactly the same statement and parameters again".

  After that it sends `ReadyForQuery` `I`, and the session stays open. A denial says "was denied"; it has the same code. An expiry says "expired: ask again".
- **The card** (Mac, iPhone, `klav approval`) shows:
  - the caller (the sandbox label, "according to the proxy") and the profile;
  - the database and host, or "Northflank addon `horizon-stack/postgres`";
  - the class in color, the verbs, the statement count, the parameter count, and the length;
  - **the exact SQL and parameters,** from a sealed blob (below): escaped, monospaced, with control, *bidi* and zero-width characters made visible. Nothing is cut, and large statements scroll. Over the sealed blob's 64 KiB, the card says "too large to show" and offers only "Deny" (risk 119);
  - "according to the agent". The proxy only relays what the sandbox sent.
- **The Touch ID or Face ID prompt** shows fixed text, the profile and the first verb only (T140). Never the SQL.
- **The sealed blob** (Q10 (a)):
  - new kind **`0x29` `pg-statement`**: HPKE to the account's identity, with `info = tuple("klav/v1/proxy/pg-statement-seal", account_id, agent_id, item_id, fingerprint_account)` and plaintext `lp(database) ‖ raw_statement ‖ params`, at most 64 KiB;
  - uploaded with a signed `PUT /v1/agent/approvals/{id}/sealed`, the generic form of ADR 0041 §5.3's route, built in this stack (layer 14) and reused later by ADR 0041 (`0x24`) and ADR 0049 (`0x27`);
  - the approval stays hidden until the blob arrives;
  - the device recomputes `pg_sql` and shows a `security` card on any mismatch;
  - the server deletes the blob when the approval is decided or expires.
  - **The server never sees the SQL.**
- **With `write_item_id`,** an approved write doesn't run on the session's connection. The proxy:
  1. opens a second upstream connection (same transport, the write item's role, SCRAM as in §9.2) with `default_transaction_read_only=off`;
  2. sends exactly the approved bytes as one Simple Query, or as one `Parse`/`Bind`/`Execute`/`Sync` with the approved parameters;
  3. relays its results to the client and closes it.
  - Session state (temporary tables, prepared statements) isn't shared, so a write that depends on it fails with PostgreSQL's own error. The card says "runs as <write role>".
- **Audit.** `agent.access` entries carry the claims above, so the log shows "sandbox chat-123 → postgres:app DELETE (approved, digest …)". Reads are covered by the session access and its 60 s re-checks.
  - **The server's log doesn't list each `SELECT`** (Q6).
  - The proxy's local log line per session has counts by class, bytes and duration, never SQL.

### 10. Formats, versions, and older clients
- **Grant `v: 5`,** a superset of `v: 4`, with:
  - `ProxyProfile.tunnel`, `ProxyProfile.pg` and, inside `pg`, `allow_cleartext_over_tls`;
  - `Scope.upgrades` and `Scope.sql_classes`.

  Older proxies and servers reject it (`deny_unknown_fields`) and fail closed. A client signs `v: 5` only when a profile uses a new field, and the sheet asks for `--every-device-is-updated`, as `v: 2`–`v: 4` did.
- **Claims** gain `upgrade`, `pg_database`, `pg_class`, `pg_verbs` and `pg_sql`. An older device's approvals list and `klav log verify` fail on an unknown claim (ADR 0049 §9). So, following ADR 0041 §5.6, two account switches, each person-only and each after the "update every device first" sheet:
  - **`proxy_tunnels`** for `upgrade` (Part 1);
  - **`pg_guard`** for the `pg_*` claims and the sealed route (Part 2).

  While a switch is off, the server refuses those claims with `400 proxy_tunnels_off` or `400 pg_guard_off`, and every existing answer stays byte-identical. `GET /v1/agent/me` advertises a switch only while it is on. The proxy refuses tunnels or Postgres sessions with a clear `Klav-Error` while it is off.
- **Labels** (spec §2.3): `klav/v1/proxy/pg-sql`, `klav/v1/proxy/pg-statement-seal`. Blob `0x29` (spec §3; `0x29` is the next free kind, now that `0x28` is ADR 0051's). Vectors:
  - `docs/vectores/pg-proxy.json`: SCRAM with RFC 7677's vector plus Klav's capped iterations, the `pg_sql` digest, and `0x29`;
  - `docs/vectores/sql-guard.json`: classification.
- **The channel API** gains `hosts` in the claim and status answers, and the routes `CONNECT host:port` and `POST /_klav/pg/<profile>` (`Upgrade: klav-pg/1`). Version skew:
  - **an older forwarder** ignores `hosts` and uses mode (a);
  - **a newer forwarder with an older proxy** finds no `hosts`, turns mode (b) and Postgres off, and `klav-forward status` says the proxy is too old.

| Server | Proxy | Devices | What happens |
|---|---|---|---|
| older | new | any | No switch advertised: tunnels and Postgres refused with a clear error; mode (a) as today |
| new, switches off | new | any | As today |
| new, on | older | new | The older proxy can't read `v: 5` and fails closed; the person updates it |
| new, on | new | an older one left | That device fails its approvals list and reports tampering, as the sheet warned |
| new, on | new | new | This ADR |

Every layer that touches `klav-server` gets the "safe with older clients" review before merge (`main` deploys production).

### 11. Dependencies and the crypto rules
Measured by resolving each candidate in a throwaway manifest and comparing with the workspace's `Cargo.lock`. "No new crate" means every package it pulls is already locked at a compatible version.

| Need | Proposal | `Cargo.lock` delta | Rule |
|---|---|---|---|
| Laying out the CA and leaf certificates (Part 1) | **`x509-cert` 0.3.1 with its `builder` feature, in `klav-core`** behind a new non-default feature `sandbox-ca`, which only `klav-forward` turns on and `klav-wasm` never does. Ed25519 keys and signatures from `ed25519-dalek` (approved). | **No new crate** (`builder` pulls `sha1` and `signature`, already locked) | `x509-cert`, `der` and `spki` are approved today **for verification only** behind `nitro-attestation` (ADR 0051). Signing with them is a new use, so it needs approval (Q2). Everything stays in `klav-core`, so the "crypto only in `klav-core`" rule holds without an exception |
| (alternative) | `rcgen` 0.14.10, no features, in `klav-forward`, calling `klav-core` signers (draft 0043 P3 (a)) | +2 crates: `rcgen`, `yasna` | Layout outside `klav-core`; a new crate to approve |
| If a client refuses an Ed25519 chain | `p256` and `ecdsa`, already approved for passkeys and ADR 0045 signing, for these two keys too | none | Asked only if layer 6 finds such a client |
| The local TLS server in the forwarder | `rustls` and `tokio-rustls`, already in `klav-forward` for the channel only | none | Extends the "channel only" approval: TLS 1.3, `aws-lc-rs`, never `ring` |
| The channel's upgrades | `hyper` 1.12 `server` and `http1` (`serve_connection(…).with_upgrades()`) | none | Approved for `klav-proxy`; if upgrades need another feature, it is named in that PR |
| The WebSocket codec in the proxy | **`tokio-tungstenite` 0.30.0** with `default-features = false, features = ["handshake"]`, a direct dependency of `klav-proxy` | **No new crate** (locked today through `klav-sdk`'s CDP client) | Not cryptographic. Its SHA-1 for `Sec-WebSocket-Accept` is protocol framing, not a Klav primitive. TLS stays the proxy's own `rustls` |
| SCRAM-SHA-256 (Part 2) | **`pbkdf2` 0.13.0** (RustCrypto, MIT or Apache-2.0, no `unsafe`) with `hmac` 0.13 and `sha2` 0.11 (approved), in `klav-core` behind a new non-default feature `pg-scram` that only `klav-proxy` turns on | **+1 crate:** `pbkdf2` | **A new cryptographic dependency: this ADR is its request** (AGENTS.md). Implementing `Hi()` as a hand-written HMAC loop would be home-made crypto |
| SASLprep | `stringprep` 0.1.5, in `klav-core` under `pg-scram` | **No new crate** (locked through `sqlx-postgres`) | Not cryptographic, but a new direct dependency of `klav-core`, named here |
| SQL classification | **None:** a lexer in `klav-proxy` (Q7 (a)) | none | — |
| (alternative) | `sqlparser` 0.64.0, `default-features = false, features = ["std"]` | +1 crate: `sqlparser` (Apache-2.0, no `unsafe`, no other dependencies) | Not cryptographic; Q7 (b) |
| Postgres wire and MD5 | None: the wire is hand-written; MD5 is refused | none | `postgres-protocol` and `tokio-postgres` were looked at and rejected: they carry their own SCRAM and MD5, which would be cryptography outside `klav-core` |

- **Never:** `ring`, `openssl` or `openssl-sys` (all banned in `deny.toml`), `libpg_query` unless Q7 (c), and no `unsafe` in Klav's code.
- **`AGENTS.md`'s approved list gains,** at the layer that adds each item: the `x509-cert` `builder` line, the `pbkdf2` and `stringprep` line, the `tokio-tungstenite` line, and the extended `rustls` approval for `klav-forward`.

### 12. Threats
New rows for a §5.29 of the threat model, marked **proposed (ADR 0052)**. They take over draft 0043's T205–T209 and risks 79–80, which never merged; those IDs are taken now. So this ADR numbers from **T285** and **risk 114**.

| ID | Threat | Mitigation |
|---|---|---|
| T285 | The interception certificate is trusted beyond the tool or the sandbox (system store, shell-wide, saved in a template) | Shims only, never the system store (§1.1); the CA key is wiped before any tool runs; the leaf lives until `expires_at`; files sit under `~/.klav-forward`, which the template check refuses to save |
| T286 | Host confusion: the credential follows a `Host` header, an SNI, or an API answer to a host the person didn't sign | The profile is chosen by the channel's `CONNECT`; `Host` must equal it, or `421`; SNI must equal it; tunnel hosts are signed, exact by default (§2); the `northflank-addon` transport checks `targetDomain` against `tunnel.hosts` |
| T287 | A wildcard tunnel host matches a name a third party controls (a customer workload on a shared domain) | Exact hosts by default; a wildcard only after the hand test shows the domain serves infrastructure only, and shown in red on the sheet (§2) |
| T288 | WebSocket smuggling or desync: compression, fragmented control frames, unmasked client frames, an `Upgrade` on an API host | Frame-level relay on both sides; extensions stripped; masking enforced; caps; upgrades accepted only on tunnel hosts under the signed prefix, with `upgrades: [websocket]` in a rule (§3–§4) |
| T289 | SQL that looks like a read and writes: writable CTE, `SELECT … INTO`, row locks, a side-effecting function, `EXPLAIN ANALYZE`, `COPY`, multi-statement batches | Layer B (§9.4): keyword denylist outside strings, function allowlist, strictest class wins for a batch; Layer A (§9.3) refuses in-engine writes; a read-only role (`write_item_id`) refuses them by privilege |
| T290 | Classifier differential: comments, dollar quoting, `E''`, `U&` with `UESCAPE`, encodings, `standard_conforming_strings`, `search_path` shadowing | PostgreSQL's exact lexical rules; the encoding and `standard_conforming_strings` pinned and checked by `ParameterStatus`; `search_path` pinned; unlexable input is `unknown`; CI runs the read vectors against real PostgreSQL inside read-only transactions |
| T291 | The session escapes read-only: `SET`, `set_config`, `BEGIN READ WRITE`, `SET SESSION CHARACTERISTICS`, `SET ROLE`, startup `options` | Pinned settings refused in every form and never approvable; `options` refused at startup; `ParameterStatus` watched, closing on a flip; the proxy owns `BEGIN READ WRITE` (§9.3) |
| T292 | An approval spent on different SQL or parameters, or a write window that runs more than was approved | `pg_sql` binds the exact bytes and parameters; the device recomputes it from the sealed blob; the proxy's read-write transaction holds only the approved message group; no transaction control inside it (§9.3, §9.6) |
| T293 | A hostile or impersonated database: weak auth downgrade, a huge SCRAM iteration count, oversized messages | `verify-full` TLS; SCRAM with server-signature check, and `-PLUS` when offered; MD5 refused; cleartext only with signed opt-in over verified TLS; iterations capped; message caps |
| T294 | Untrusted SQL on the approval card: *bidi*, zero-width, look-alikes, a huge statement scrolling the real verb away | Verbs from a closed vocabulary; SQL only in the sealed card, escaped with control characters visible; the prompt shows fixed text, profile and verb only; over 64 KiB, deny only |
| T295 | Tunnels or sessions outlive a revocation | `cuts.rs` registration before access; immediate and 30 s paths (§4); a 60 s lease re-check for Postgres (§9.2) |
| T296 | `FunctionCall`, replication startup, `CancelRequest` abuse | `F` refused; `replication` refused; cancel keys are the proxy's own random ones, mapped, and unknown keys dropped |

**Residual risks (proposed 114–120):**

114. **A sandbox with read access reads every row the database role can read** (by design). Klav keeps the password and destructive writes out of the agent's hands. Table and column limits belong to PostgreSQL roles, row-level security or views, and the sheet says so. Exfiltration of what's readable is bounded only by rates.
115. **Detect-and-cut in WebSocket tunnels** can let up to `len − 1` bytes of the token reach the tool before the cut, and only if the far end echoes it inside the tunnel (§4).
116. **Layer A doesn't stop everything a read-only transaction allows.** That includes temporary tables, advisory locks, and `pg_cancel_backend` or `pg_terminate_backend` when privileged. Layer B's allowlist and a read-only role close most of it. A role with `pg_signal_backend` or superuser remains dangerous, and the sheet warns against granting one.
117. **User code reached without call syntax isn't checked:** operators, views, implicit casts, domain checks and column defaults. A view that calls `dblink_exec` runs it on a plain `SELECT`, outside Layer A. A role that can create functions or operators in a schema on `search_path` can make `a + b` run its own code. In-engine writes still fail under Layer A. The read-only role removes `CREATE`, and the sheet warns when the database has `dblink` or `postgres_fdw` (the proxy reads `pg_extension` at session start and reports it in `klav-forward status`).
120. **Mode (b) serves only tools that honor `HTTPS_PROXY` and the trust variables** (§1.1). Others fail closed with a placeholder: Node without `NODE_USE_ENV_PROXY`, tools that pin certificates or carry their own roots, and HTTP/2-only clients. `klav-forward status` says so.
118. **The server's audit log doesn't list individual reads,** only the session and every non-read statement (§9.6; Q6).
119. **A statement with its parameters over 64 KiB can't be approved,** only denied, because the card can't show it whole.

### 13. What this ADR chose on its own (Omar can overturn each)
1. Grant `v: 5` as a superset of `v: 4`, and two switches rather than one.
2. `TunnelHost` with a single-label wildcard, narrower than `DomainPattern`.
3. Tunnels and Postgres sessions counted together, apart from call slots: 8 per sandbox, 32 per proxy, 16 per account in Klav Cloud.
4. Pings every 60 s; idle 15 min and total 8 h by default.
5. WebSocket extensions always stripped.
6. Postgres profiles refused on the Mac proxy's loopback in v1.
7. The startup parameter allowlist, `statement_timeout` pinned at 4 min, the 15-minute idle session and the empty-query keepalive, and protocol 3.0 only.
8. The SCRAM iteration cap of 4096–600 000.
9. Approved writes only outside transaction blocks, autocommitted, with no transaction control inside.
10. SQL-level `PREPARE` and `EXECUTE` treated as `unknown`.
11. A lease never covers `admin` or `unknown`.
12. The 2-minute hold and `42501` for pending, denied and expired.
13. Caps: 1 MiB per statement, 16 MiB per message, 64 KiB per sealed statement, 600 statements a minute.
14. Approval digests bind parameters too.

### 14. Left for later, not designed here
- Postgres for local agents on the Mac (needs caller identity on loopback for non-HTTP).
- Private CAs for `direct` (RDS, Cloud SQL), and direct TLS negotiation.
- Multi-statement write transactions approved as one script.
- MySQL, Redis and other wire protocols through the same channel upgrade.
- Row and byte quotas per day for reads.
- A transparent redirect for tools that honor neither a base URL nor `HTTPS_PROXY` (needs root in the sandbox and both IP families).

### 15. Not verified (each checked at its layer, which stops if a claim is false)

| Claim | Checked at | If false |
|---|---|---|
| Name constraints enforced on an added root by the exact client versions | Layer 6 | Nothing opens up: the leaf's SAN list is the limit and no key remains (§1.1) |
| `targetDomain`'s shape, whether it's stable per region, and whether customers can get names under its parent | Layer 8 (hand test; one info call through the proxy's log). **Verified 2026-11-30** from a Boat sandbox through Klav Cloud (`proxy.klav.dev`, manifest 5 `f4b6e3c1`): `northflank forward addon --project horizon-stack --addon postgres --skipHostnames` opened tunnels via `~/.klav-forward/bin/northflank`, `NODE_EXTRA_CA_CERTS` and `HTTPS_PROXY=127.0.0.1:8791`; `targetDomain` was `proxy-forwarder--<id>.code.run`, under `.code.run`, Northflank's shared customer domain, so customers can get names under its parent | Exact hosts only; the wildcard never ships (§2). Confirmed: exact hosts only (T287) |
| Northflank's Postgres addons inside the tunnel: whether they require TLS (`SSLRequest`), with which certificate, and their auth method (SCRAM expected) | Layer 17. **Verified 2026-11-30 & 2026-12-01** on `horizon-stack/postgres`: a plain `StartupMessage` gets `FATAL 08P01: SSL required`; `SSLRequest` gets `S`, then TLS 1.3 (`TLS_AES_256_GCM_SHA384`) with a Let's Encrypt certificate for `*.postgres--<id>.addon.code.run`, which matches the instance's `internalHostname` (`primary.postgres--<id>.addon.code.run`, in the info answer) under system roots; then `AuthenticationSASL` with `SCRAM-SHA-256`. The proxy runs `verify-full` inside the tunnel against that name (PR #88), and the full Layer 17 end-to-end run passed on 2026-12-01 on `proxy.klav.dev` (`0.13.0`, commit `5b580dcd`, manifest 7) | `tls` per addon (`none` is allowed on the tunnel); if MD5, the addon's role must move to SCRAM, or the profile can't be used |
| undici's `EnvHttpProxyAgent` tunnels the WebSocket with `CONNECT` and accepts an Ed25519 chain from `NODE_EXTRA_CA_CERTS` on the Node in the template | Layer 6 (client matrix) and layer 8. **Verified 2026-11-30** in a Boat sandbox: `northflank forward addon … --skipHostnames` tunneled cleanly through `HTTPS_PROXY=127.0.0.1:8791` with the ephemeral Ed25519 CA | P-256 keys from `klav-core` (§11) |
| `hyper` 1.12 upgrades with the approved features | Layer 5 | One more feature of an approved crate, named in that PR |
| `x509-cert`'s builder signs with an `ed25519-dalek` key through the `signature` traits without extra features | Layer 2 | `rcgen` with no features (Q2 (b)) |
| `default_transaction_read_only` is reported in `ParameterStatus` from PostgreSQL 14 | Layer 12 (CI against PostgreSQL 13 and 16) | Below 14, the proxy re-checks with `SHOW` after every non-`read` statement |
| The startup `options` reach PostgreSQL on every host | Layer 17. **False on 2026-11-30** on Northflank's Postgres 17 addon (`horizon-stack/postgres`, 17.12), which runs a transaction-mode pooler: it drops `options` (`default_transaction_read_only = off` in `ParameterStatus`) and resets session `SET`s between transactions. **Verified end-to-end 2026-12-01** on `proxy.klav.dev` (`0.13.0`, commit `5b580dcd`, manifest 7, PRs #88, #90, #92) from a Boat sandbox with iPhone `0.13.0 (11)`: `SELECT` ran with `transaction_read_only = on`, `statement_timeout = 4min` and `search_path = "$user", public`; mixed `BEGIN; …; COMMIT;` batches were refused while separate queries passed; `DELETE … WHERE false` held for approval with exact HPKE-sealed (`0x29`) SQL on the iPhone and returned `DELETE 0` on approve-once; re-granting with `--read-only` refused `DELETE` immediately with `42501`; `klav log verify` passed (2054 events) | Layer A runs per transaction (§9.3 "Per transaction"), proved fail-closed at startup (§9.2). The CI covers it with a pooler shim in front of real PostgreSQL |
| Exactly which `pg_catalog` functions are side-effect free, against the PostgreSQL version in CI | Layer 11 | They leave the allowlist (fail-closed) |
| Whether `psql`, `node-postgres` and `psycopg` connect with `sslmode=disable` and an immediate `AuthenticationOk` | Layer 15 | That client's URL needs another parameter |

## Rejected alternatives
- **The CA on the proxy's host, opening every connection** (the prior art draft 0043 read). It would make the person's proxy see every intercepted byte of every sandbox, with a long-lived CA key shared by all of them.
- **`HTTPS_PROXY` shell-wide.** The agent's own model calls and git would go through the forwarder and break when it stops.
- **Rewriting `targetDomain` in the API answer** to a local name. That is vendor body rewriting in the proxy, and it still needs a certificate for the new name.
- **A suffix rule like `*.northflank.com` for tunnels** before the hand test shows who serves under it (T287).
- **Passing WebSocket frames as opaque bytes after the `101`.** No caps, no masking checks, no compression control, no cut.
- **SQL in clear in the signed claims.** The server would keep statements, often carrying data, in the audit log forever.
- **Trusting Layer A alone** (§9.3), or **the classifier alone** (T290).
- **`tokio-postgres` or `postgres-protocol`.** Their SCRAM and MD5 would be cryptography outside `klav-core`.
- **MD5 authentication.** It would need `md-5` in `klav-core`, and it is weak.
- **Letting the sandbox send its own password** to a proxy that checks it. The point is that the sandbox has none.

## Consequences
- **New:**
  - in `klav-core`: features `sandbox-ca` and `pg-scram`, `TunnelHost`, `Scope.upgrades` and `Scope.sql_classes`, and `Request.upgrade` and `Request.sql_class`;
  - in `klav-proto`: grant `v: 5`, `ProxyProfile.tunnel` and `ProxyProfile.pg`, the claims, and blob `0x29`;
  - in `klav-server`: the two switches, the claims in `target_key`, and the generic sealed route;
  - in `klav-proxy`: the channel upgrades, mode (b) `CONNECT`, the WebSocket relay, the Postgres wire, the classifier and the transports;
  - in `klav-forward`: mode (b), the shims, `klav-forward run`, and the Postgres listener;
  - in the CLI: `--tunnels`, `--tunnel-host`, `--preset postgres [--read-only]`, `--pg-direct` and `--pg-northflank-addon`;
  - on Mac and iOS: the tunnel line and the SQL card.
- **Spec:** §13.4 (grant `v: 5`), §13.10 (the two signers), §2.3 (labels), §3 (`0x29`), and a new §13.17 for the Postgres proxy. Vectors in `docs/vectores/pg-proxy.json` and `sql-guard.json`.
- **Glossary, at layer 1:** mode (b), tunnel host, WebSocket tunnel, Postgres profile, SQL class, SQL guard, read-only session, approved write, sealed statement.
- **Docs site:** "On the way" pages for both parts until each ships (ADR 0039 §3).
- **Roadmap:** the pointer "ADR 0043, PR #445" under "Después" is stale (that PR doesn't exist; the draft sits on a branch). Layer 1 replaces it with this ADR. Decision 6 of ADR 0045, "databases through the proxy afterwards", is what Part 2 designs.

## Plan in layers
Each layer is one PR of a stack (`gh stack`), with its tests, its roadmap box and, where it applies, the spec and vectors.

**Part 1 (Omar's `northflank forward`):**
1. **Docs:** this ADR accepted, threat model §5.29, glossary, a note in ADR 0036 §7 pointing here, the roadmap, and `AGENTS.md`'s approved list for what was approved.
2. **`klav-core` `sandbox-ca`:** CA signer (two signatures, then wiped), leaf `TlsSigner`, layout with `x509-cert` builder; spec §13.10 paragraph.
3. **`klav-core` and `klav-proto`:** grant `v: 5` (`tunnel`, `TunnelHost`, `Scope.upgrades`, `Request.upgrade` with the deny-only rule), `Claims.upgrade`, vectors.
4. **`klav-server`:** the `proxy_tunnels` switch, `upgrade` in `target_key`, and `klav log verify`. "Safe with older clients" review.
5. **`klav-proxy`:** channel upgrades, mode (b) `CONNECT`, `hosts` in claim and status, the WebSocket relay with limits, pings, cuts and detect-and-cut. End-to-end tests against a fake WebSocket upstream, through `klav-nitro-parent` too.
6. **`klav-forward`:** port 8791, the certificates, shims, `klav-forward run`, and status lines. A CI client matrix: `reqwest`, `curl`, Node `fetch` and undici `WebSocket` with `EnvHttpProxyAgent`, Go, and Python.
7. **`klav-client`, `klav-cli`, Mac and iOS:** `--tunnels` and `--tunnel-host`, the sheet, the card's tunnel line, and turning the switch on.
8. **Hand test (Omar's go, a paid sandbox):** `northflank forward addon … --skipHostnames` and `psql` with its own password, from a Boat sandbox and through Klav Cloud. This records `targetDomain` (§15) and marks mode (b)'s box.

**Part 2 (no Postgres password in the sandbox):**

9. **`klav-core` `pg-scram`:** `pbkdf2`, SASLprep, proofs and the server-signature check; RFC 7677 vectors.
10. **`klav-core` and `klav-proto`:** `pg` profile, `Scope.sql_classes` and `Request.sql_class` (deny-only rule), the `pg_*` claims, `pg_sql`, blob `0x29`; `pg-proxy.json`.
11. **`klav-proxy` classifier:** lexer, classes, function allowlist; `sql-guard.json`, `proptest`, and the CI check against PostgreSQL.
12. **`klav-proxy` Postgres wire, `direct`:** startup, SCRAM, Layer A, the query phase, holds, cancel, redaction. End-to-end in the `test (postgres)` CI task.
13. **`klav-proxy` `northflank-addon` transport** (per Q12).
14. **`klav-server`:** the `pg_guard` switch, the generic sealed route `PUT /v1/agent/approvals/{id}/sealed`, hiding until the blob arrives, purge. "Safe with older clients" review.
15. **`klav-forward` and `klav-cli`:** the Postgres listener, `--preset postgres`, setup lines, `klav approval show` for SQL.
16. **Mac and iOS:** the SQL card from the sealed blob, and Activity rows.
17. **Hand test (Omar's go):** `horizon-stack`'s Postgres through the tunnel transport from a Boat sandbox: a `SELECT` passes, a `DELETE` asks on the iPhone with the exact SQL, approve once, a read-only profile denies.

**Order:** within each part, layers 2 and 3 (and 9 and 10) can go together. Part 2 doesn't depend on Part 1's mode (b), only on its layers 3–5 (grant `v: 5`, upgrades and the WebSocket client). Q14 asks whether to put Part 2's tunnel transport first.

## Stop rules
- **Layer 8** finds `targetDomain` under a domain customers can use: no wildcard, ever. Exact hosts only, said in the preset.
- **Layer 11** finds a read vector that writes against real PostgreSQL: the layer stops until the rule that let it through is fixed and the vector stays in the corpus.
- **Layer 2** finds `x509-cert`'s builder needs more than the features named: stop and ask (Q2).
- **Any layer** that would add a crate not named in §11: stop and ask.

## Questions for Omar
| # | Question | Options | Recommendation |
|---|---|---|---|
| Q1 | Does ADR 0052 absorb draft 0043 (scoped shims, ephemeral CA wiped at start, keys in `klav-core`, profile chosen by `CONNECT`, pass-through for other hosts), with its Q1–Q7 recommended answers? (§1) | **(a) Yes; 0043 stays unmerged and its number unused**<br>(b) Merge 0043 first as its own ADR, then this one on top | **(a).** One decision, one review; nothing in 0043 changes except what §2–§3 add |
| Q2 | Which crate lays out the certificates? (§11) | **(a) `x509-cert` 0.3.1 `builder` in `klav-core` behind `sandbox-ca`: no new crate, a new use of an approved one**<br>(b) `rcgen` 0.14.10 with no features in `klav-forward` (+`rcgen`, `yasna`)<br>(c) `rcgen` with `aws_lc_rs` in `klav-forward` (crypto outside `klav-core`) | **(a).** Zero new crates, and keys, signatures and layout stay together in `klav-core` |
| Q3 | How are Northflank's tunnel hosts authorized? (§2) | **(a) Exact hosts signed in the profile, filled by the preset after the hand test; a single-label wildcard only if the test shows an infrastructure-only domain**<br>(b) A single-label wildcard from day one<br>(c) Hosts vouched for by a TLS-verified API answer to the same sandbox (needs the CA alive and vendor JSON reading) | **(a).** Fail-closed, and the CA key is still wiped |
| Q4 | What does `--tunnels` sign for the WebSocket handshake? (§5) | **(a) Opt-in `--tunnels`, handshakes `allow`; `--tunnels-ask` for `ask`**<br>(b) Opt-in, handshakes `ask` with leases<br>(c) On by default in the preset | **(a).** A tunnel isn't a write. In Part 1 the data plane still needs its own credentials, and Part 2's SQL guard governs Postgres |
| Q5 | What happens to the token inside a tunnel's data? (§4) | **(a) Frame relay with extensions stripped; detect-and-cut, no holdback; risk 115 written**<br>(b) No inspection after the `101`<br>(c) Replace bytes (corrupts binary protocols) | **(a)** |
| Q6 | What is one access, for a tunnel and for Postgres? (§3, §9.2) | **(a) One per WebSocket handshake. For Postgres: one per session, re-checked every 60 s, plus one per non-read statement (amends ADR 0036 §2, like ADR 0038)**<br>(b) One per statement, reads included | **(a).** (b) adds a server round trip to every `SELECT`; reads are allowed by policy anyway, and risk 118 says what the log loses |
| Q7 | How is SQL classified? (§9.4) | **(a) A strict PostgreSQL lexer with a keyword denylist and function allowlist in `klav-proxy`, no crate**<br>(b) `sqlparser` 0.64.0 with an allowlist over its AST (+1 crate)<br>(c) `libpg_query` (PostgreSQL's parser, C through FFI) | **(a).** The smallest surface that is exactly PostgreSQL's; fail-closed; no parser differential on grammar |
| Q8 | What about function calls inside reads? (§9.4) | **(a) A curated `pg_catalog` allowlist; anything else is `unknown` (ask)**<br>(b) Any function, trusting Layer A | **(a).** Layer A doesn't stop `dblink_exec` or `pg_terminate_backend` |
| Q9 | Which credential set-up do the presets recommend? (§9.3) | **(a) One item works (read-only session plus approved read-write transactions); the sheet recommends a read-only role with an optional `write_item_id` for approved writes**<br>(b) Require two items<br>(c) One item, with no role recommendation | **(a).** Easy to start; the strongest barrier one checkbox away |
| Q10 | How does the exact SQL reach the card? (§9.6) | **(a) Sealed blob `0x29`, with the generic sealed route built in this stack (layer 14), reused later by ADRs 0041 and 0049**<br>(b) Verbs and digest only until ADR 0041's route exists<br>(c) SQL in clear in the claims | **(a).** You asked to see the exact statement; (c) puts data in the server's log forever |
| Q11 | Which upstream authentication is accepted? (§9.2) | **(a) SCRAM-SHA-256 (and `-PLUS` when offered); cleartext only with a signed opt-in over verified TLS; MD5 never; `pbkdf2` approved for `klav-core`**<br>(b) SCRAM only | **(a)** |
| Q12 | How does Part 2 reach a Northflank addon? (§8) | **(a) A small `northflank-addon` transport in `klav-proxy`; ADR 0049 §1 amended for transports only**<br>(b) A generic signed "discovery recipe" (URL template and a JSON pointer)<br>(c) No tunnel transport: make the addon publicly reachable with TLS and use `direct` | **(a).** It is your case, and (b) is a mini-language for one vendor. (c) works from layer 12 either way |
| Q13 | `direct` Postgres on Klav Cloud (§8) | **(a) List 5432 on the parent's egress, Klav-wide**<br>(b) Klav Cloud supports only the tunnel transport for Postgres | **(a)**, at layer 12, with the same public-address refusal |
| Q14 | Which part first? (Plan) | **(a) Part 1, then Part 2, as planned**<br>(b) Part 2's tunnel transport first (layers 3–5, then 9–14): `psql` from the sandbox with no token or password sooner, mode (b) after | **(a)** if `northflank forward` for other addons matters as much as Postgres; **(b)** if your blocker is only Postgres |

## Omar's answers (2026-11-28)
Omar accepted the ADR with the recommended option **(a)** on every question **Q1–Q14**:
- **Q1 (a):** absorb draft 0043 into ADR 0052; number 0043 stays unused.
- **Q2 (a):** `x509-cert` 0.3.1 `builder` in `klav-core` behind `sandbox-ca` (no new crate).
- **Q3 (a):** exact signed tunnel hosts by default; single-label wildcard only if Layer 8 proves an infrastructure-only domain.
- **Q4 (a):** opt-in `--tunnels` (`allow`), `--tunnels-ask` (`ask`).
- **Q5 (a):** frame-level relay with extensions stripped; detect-and-cut (risk 115).
- **Q6 (a):** one access per WebSocket handshake; for Postgres, one per session (re-checked every 60 s) plus one per non-read statement.
- **Q7 (a):** strict PostgreSQL lexer with keyword denylist and function allowlist in `klav-proxy` (no new crate).
- **Q8 (a):** curated `pg_catalog` allowlist for function calls in reads; anything else is `unknown` (`ask`).
- **Q9 (a):** one item works; setup recommends a read-only role plus optional `write_item_id` for approved writes.
- **Q10 (a):** exact SQL sealed with HPKE (`0x29`) via the generic sealed-blob route (Layer 14).
- **Q11 (a):** SCRAM-SHA-256 (and `-PLUS`); cleartext only over verified TLS with signed opt-in; never MD5; `pbkdf2` 0.13.0 and `stringprep` 0.1.5 approved for `klav-core` (`pg-scram`).
- **Q12 (a):** `northflank-addon` transport in `klav-proxy` (narrow amendment to ADR 0049 §1).
- **Q13 (a):** list port 5432 on Klav Cloud parent egress at Layer 12 (public-address refusal unchanged).
- **Q14 (a):** Part 1 (`HTTPS_PROXY` + WebSocket tunnels) first, then Part 2 (Postgres credential proxy + SQL guard).
