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-interceptionand never merged. Its findings and its recommended answers are carried here (§1). The number 0043 stays unused. - Amends:
- ADR 0036: §2 (the
proxypermission 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 dropsUpgrade" (§4); and the note of 2026-11-16 that "the CLI's WebSocket commands probably fail through the proxy". - ADR 0049 §1, narrowly (Q12 (a)): one vendor-specific transport (
northflank-addon) inklav-proxy. Policy stays generic. - ADR 0051 §3.3 (two new per-account quotas) and §1.2 (Q13 (a): port 5432 on the parent's egress list).
- ADR 0036: §2 (the
- 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:
- 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. GET /v1/port-forwarding/info/projects/{project}/addons/{addon}answers withtargetDomain, a separate host, plus the addon's instances and ports.- When a Postgres client connects to the forwarded address (
127.24.1.2:5432), the CLI opens one WebSocket per TCP connection towss://${targetDomain}/tunnel/projects/{project}/addons/{addon}/instance/{pod}/port/{port}withAuthorization: Bearer <the CLI's token>. That connection ignores--host. - 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 answers403 Forbidden (check the token's permissions). - 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, sonorthflank forwardand 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 withhyperand no upgrades (channel.rs:499-507). Itsforwardtakes the profile from the first path segment, requires a loopbackHost, refusesCONNECTandTRACE, and drops 32 request headers,upgradeandconnectionamong them (DROPPED_REQUEST_HEADERS,proxy.rs:92). - What a sandbox gets back. The proxy drops
set-cookie,set-cookie2andwww-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).ProxyProfileis{name, item_id, field?, header, prefix, upstream, rate_per_minute?, mcp?}(agent.rs:464).Scopehasdomains,items,methods,path_prefixesandmcp_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}withAuthorization: Bearer <token>.baseUrlis 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}, withhttps:replaced bywss:. Services and harnesses use the same shape, withservices/orharnesses/and sometimes?directConnect=true. - One WebSocket per accepted local TCP connection (class
Bd,handleConnection), opened with undici'sWebSocketand the sameAuthorizationheader.binaryTypeisarraybuffer. The duplex wrapperX()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
Hostheader rewritten. The client never speaks Postgres: whateverpsqlsends, including anSSLRequest, 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'sEnvHttpProxyAgentand uses it as the dispatcher for both the info call and the WebSocket. So the WebSocket honorsHTTPS_PROXYwithCONNECT targetDomain:443, and the info call to a127.0.0.1base URL skips the proxy throughNO_PROXY. - Local addresses. It binds
127.24.x.y(from127.24.1.1up). Without--skipHostnamesit edits the hosts file. - Not in the package: what
targetDomainlooks 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 needsHTTPS_PROXYandUpgrade: 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/andklav-forward run [--profile P] -- CMDsetHTTPS_PROXY,NO_PROXY=127.0.0.1,localhost,NODE_USE_ENV_PROXY=1and the trust variables.HTTP_PROXYis 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 byHostor the path.Hostmust equal the connection's host, or the answer is421. SNI must equal theCONNECThost. 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 aCONNECT host:portroute served withhyperupgrades. The forwarder never parses HTTP after TLS: the proxy'shyperis the only parser.
1.1 The mechanics, restated (so nothing here depends on the unmerged draft)
- The certificates, made by
klav-forward upafter the claim, throughklav-core(§11):- CA: a fresh Ed25519 key; basic constraints CA with path length 0; key usage
keyCertSign; a critical NameConstraints extension whose permitteddNSNamesubtrees are the sandbox's profile hosts and tunnel hosts, each wildcard written as its base. RFC 5280 makes adNSNameconstraintbasepermitbaseand 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, thenklav-corewipes it. - Leaf: a fresh Ed25519 key; SAN = exactly those hosts (a wildcard tunnel host as
*.base); extended key usageserverAuth; valid from 5 minutes before now until the sandbox'sexpires_at; a random serial and SHA-256 key identifiers. Its key signs only the server's TLS 1.3CertificateVerify. - Who enforces name constraints on a root the user added, per draft 0043's reading of default branches:
rustls-webpki0.103.16 does, and OpenSSL and Go atmasterdo. 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.
- CA: a fresh Ed25519 key; basic constraints CA with path length 0; key usage
- The files and variables, none of them secret, all under
~/.klav-forward/mode-b/:ca.pemgoes toNODE_EXTRA_CA_CERTS;bundle.pem(the system bundle followed byca.pem) goes toSSL_CERT_FILE,REQUESTS_CA_BUNDLEandCURL_CA_BUNDLE;- only the shims and
klav-forward runset them, andklav-forward downremoves the directory.
- At port 8791, for each connection, the forwarder:
- reads one
CONNECT host:porthead, at most 8 KiB within 20 s, and answers anything else405 klav_not_allowed; - looks the host up among the claim's
hosts:- not found: it answers
200and 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 gets503 klav_proxy_unreachable;
- not found: it answers
- on the proxy's
200, terminates the tool's TLS: TLS 1.3 only, ALPNhttp/1.1only, the leaf above, and SNI equal to theCONNECThost (otherwise anunrecognized_namealert); - relays the decrypted bytes without parsing them.
- reads one
- Clients that honor this, and the fallback:
reqwest(native roots),curland OpenSSL, NodefetchwithNODE_USE_ENV_PROXY=1(from Node 22.21 or 24.0), undici'sEnvHttpProxyAgent, Gonet/httpand Pythonrequests. 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 fromklav-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.
ProxyProfilegainstunnel(grantv: 5, §10):"tunnel": { "hosts": ["<exact host>"], "path_prefix": "/tunnel/", "idle_secs": 900, "max_secs": 28800 }hosts: 1–4 entries, each an exact host or*.base. A*.baseentry matches exactly one label (RFC 6125's wildcard, as a leaf SAN). It is a new grammar,TunnelHost, deliberately narrower thanDomainPattern, 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_secsandmax_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); wheretargetDomainlives isn't known yet (§15).- So the default is exact hosts. The
northflankpreset fills the exacttargetDomainthat the layer-8 hand test observes for each region the person uses.klav proxy grant --tunnel-host HOSTadds 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 answers403.klav-forward statusnames the host it saw, and the person adds it by re-signing.
- So the default is exact hosts. The
- 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:
- 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 (upstreamortunnel.hosts). - On
200, the forwarder terminates the tool's TLS with the leaf and relays the decrypted bytes, without parsing them. - 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 undertunnel.path_prefix, and the request carriesUpgrade: websocket,Connection: upgradeandSec-WebSocket-Version: 13. A plain request to a tunnel host is refused: a tunnel host isn't an API host; - there is no body.
- the method is
- The policy is ADR 0006's, with one new dimension.
Scopegainsupgrades: Vec<Upgrade>, whereUpgradeis a closed enum with one value,websocket.policy::Requestgainsupgrade: Option<Upgrade>. A request withupgradeis matched by a rule withoutupgradesonly if that rule denies, the same mechanism asmcp_tools(ADR 0049 §5.3, Q3) andunjudgeable. So:- today's
northflankgrants, whose rules allowGETonapi.northflank.com/, never allow a tunnel through a proxy update; - a tunnel needs a rule that names the tunnel host, the prefix,
GETandupgrades: [websocket], which the person signs.
- today's
- One access per tunnel. The proxy makes one signed
POST /v1/agent/accessper WebSocket handshake, never cached. ItsClaimscarriesdomain(the tunnel host),method: GET,path(without query), and a newupgrade: "websocket". Anaskholds the handshake up to 2 minutes, as ADR 0036 §9 does, and then answersklav_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_HEADERSlist and the profile's header, writes the real credential, writes a freshSec-WebSocket-Keyof its own, and forwardsSec-WebSocket-Protocolif present. - It never forwards
Sec-WebSocket-Extensions. Sopermessage-deflateis never negotiated, and frames stay uncompressed for the scan below.
- URL:
- The
101back to the tool carries onlyUpgrade,Connection,Sec-WebSocket-Accept(computed for the tool's own key) and the chosenSec-WebSocket-Protocol. Everything else is dropped:Set-Cookie,WWW-Authenticateand any vendor header. A non-101answer 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-tungsteniteover the upgradedhyperconnection 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
101the 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 oflen(value) − 1bytes 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 saysklav_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 − 1bytes 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.
- the proxy runs the whole-value matcher (the
- 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'sexpires_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
psqlisn't cut by a relay it can't see. Pongs don't count as activity foridle_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.
- idle:
- Teardown. Each tunnel registers in
cuts.rsbefore its access, as M3's calls do.- At once:
klav sandbox stop, the theft signal andreleased. - 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
1008and a reason (klav_sandbox_revoked,klav_agents_paused), then drops TCP.
- At once:
- 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,POSTandPATCHpass,DELETEasks,PUTis 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 addstunnelwith the hand-tested hosts, and one rule: allow, host = tunnel hosts,GET,/tunnel/,upgrades: [websocket](Q4).--tunnels-askmakes that ruleask. - The setup lines for a sandbox with this profile add the shim.
northflankin the shim'sPATHruns the real CLI with the mode (b) variables. The fourth line (northflank login … --host "$KLAV_FORWARD_NORTHFLANK_URL") stays. So REST calls go to127.0.0.1(mode (a), skipped byNO_PROXY), and the WebSocket goes throughHTTPS_PROXY(mode (b)). - What Part 1 doesn't solve: the database password. With Part 1 alone, the agent connects
psqlthrough 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://[email protected]:<port>/<db>?sslmode=disable, fromklav-forward env. There is no password in it.sslmode=disableis honest: the hop is loopback, and the channel to the proxy is pinned TLS 1.3. With libpq's defaultprefer, it also works, because the proxy answersSSLRequestwithN. - 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).
CancelRequestconnections 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 useklav runas 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.
"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. AStartupMessageasking 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) ornone. Onnorthflank_addon,verify-fullchecks the addon's certificate inside the tunnel for the chosen instance'sinternalHostnamefrom the info call (§8, step 5), and is the CLI's default there.noneis allowed only onnorthflank_addon, for an addon with TLS turned off, where the WebSocket's TLS already protects the hop. Fordirect, 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). Thepgitem then holds a read-only role.Rules.
Scopegainssql_classes: Vec<SqlClass>, whereSqlClassis a closed set:read,write,ddl,admin,unknown.policy::Requestgainssql_class. A request withsql_classis matched by a rule withoutsql_classesonly 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-onlyallow read; askwrite,ddl,admin,unknownallow read; denywrite,ddl,admin,unknownThis is Omar's stated default. "
DO,CALL, unrecognized and multi-statement batches ask" falls out of the classifier (§9.4), which puts them inadminorunknown.
8. Transports
direct. TCP tohost:portafter the proxy's own DNS check. ThenSSLRequest: anSanswer starts TLS 1.3 or 1.2 withrustlsand webpki roots, hostname-checked; anNanswer to averify-fullprofile closes. Direct TLS negotiation (sslnegotiation=direct, PostgreSQL 17 (from memory)) isn't used in v1.northflank_addon(Q12 (a)):- With the named Northflank profile's token, the proxy calls
GET /v1/port-forwarding/info/[teams/{team}/]projects/{p}/addons/{a}on that profile'supstream. This is a signed access like any call (GET, that path), so the person's rules on that profile apply. - It reads only
targetDomainand the instances'podName,internalHostnameandportsfrom the answer. - It checks
targetDomainagainst the Northflank profile'stunnel.hosts(§2). The same fail-closed rule holds: the API can't send the token to a host the person didn't sign. - It opens
wss://{targetDomain}/tunnel/…/instance/{pod}/port/{port}as in §4, with one access (upgrade: websocket), and speaks Postgres inside binary frames. - Inside, with
tls: verify-full, it sendsSSLRequestand runs TLS with webpki roots, checking the certificate for the chosen instance'sinternalHostname(a bare host name, or the session fails closed before any access; never plaintext). Withtls: none, it sends noSSLRequest. Layer 17 found that Northflank's Postgres addons require TLS (§15).
- This is the only vendor code in
klav-proxy, about 150 lines, behind aTransporttrait. ADR 0049 §1 ("no vendor logic") is amended for transports only; policy stays generic.
- With the named Northflank profile's token, the proxy calls
- Klav Cloud.
northflank_addonuses port 443 and works through the parent unchanged.directto 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)
SSLRequestgetsN, and the client continues in plaintext on the pinned channel.GSSENCRequestgetsN.CancelRequestis 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
NegotiateProtocolVersiondown to 3.0; user: ignored, because the role comes from the item;database: must be indatabases;- allowed parameters:
application_name(printable ASCII, at most 64 bytes),client_encoding(onlyUTF8),DateStyle,TimeZone,extra_float_digits; - refused:
replication,optionsand every other parameter, with08004.
- version: 3.0. A later minor version (3.2, PostgreSQL 18 (from memory)) gets
- Authentication toward the sandbox: the proxy sends
AuthenticationOkat once. The channel key already authenticated the sandbox (ADR 0036 §6). APasswordMessagefrom 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/accesswith permissionproxy,Claims {domain: host or tunnel host, pg_database}and the request'ssql_class: read. The server applies pause, revocation and the rules there. A refusal becomesErrorResponse 42501and 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, andoptions=-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/1relays, the forwarder's idle limit is 16 minutes. The proxy owns the session's timeout: it closes a session idle for 15 minutes with57P05("idle session closed by Klav"); - while the client is idle (
ReadyForQueryIwith no message in flight), the proxy sends the upstream an empty Simple Query every 60 s and swallows itsEmptyQueryResponse. That has no side effect, keeps the parent's relay alive ondirect, and never interleaves with the client's traffic. Onnorthflank_addon, §4's WebSocket pings do the same; statement_timeoutis 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.
- for
- 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-coregets the password as aSecretBox, 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
AuthenticationCleartextPasswordis refused unless the profile signsallow_cleartext_over_tls: trueand the hop is verified direct TLS (Q11); - an upstream that answers
AuthenticationOkwith no challenge is accepted and logged astrust.
- After authentication, the proxy reads
ParameterStatusand requires:standard_conforming_strings=onandclient_encoding=UTF8;- from PostgreSQL 14 on, where it is reported (from memory),
default_transaction_read_only=on. On older servers the proxy runsSHOW default_transaction_read_onlyitself before the first client message; - if
default_transaction_read_onlyis noton, the startupoptionsdid 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 opensBEGIN TRANSACTION READ ONLY; SET LOCAL statement_timeout = 240000; SET LOCAL search_path = "$user",public, requirescurrent_setting()to givetransaction_read_only = on,standard_conforming_strings = on,statement_timeout = 4minandsearch_path = "$user", public, runs thedblink/postgres_fdwcheck in that transaction, and requiresROLLBACKto leave the connection idle. Any error or any other value is55000, and the session is not opened. The approved-write role's own connection (read-onlyoff) has no such mode; - otherwise the session closes (
55000).
- Redaction. The proxy parses every upstream message, so it scans each
DataRow,NoticeResponse,ErrorResponseandParameterStatusfor the password and the Northflank token (whole value, theRedactor'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 withBEGIN READ WRITE; - a read-only transaction still allows some things: temporary-table writes, session settings, advisory locks,
pg_cancel_backendandpg_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:
- The proxy owns transaction mode. Statements that touch
transaction_read_only,default_transaction_read_only,transaction_isolationwithREAD WRITE,SET SESSION CHARACTERISTICS,session_authorization,role,search_path,client_encoding,standard_conforming_stringsorstatement_timeoutbeyond its cap, in any form (SET,RESET,set_config(), startup), are refused and never approvable. That coversBEGIN,START TRANSACTIONandSET TRANSACTIONwithREAD WRITEtoo. - It watches. On PostgreSQL 14 and later, a
ParameterStatusshowingdefault_transaction_read_only=offcloses the session at once. - The classifier's function allowlist (§9.4) stops
dblink_exec,pg_terminate_backend,set_configand their kind from running as a "read". - A read-only role is the strongest barrier, and the one the sheet recommends. With
write_item_idset, thepgitem's role has onlySELECTgrants, 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 (
ReadyForQuerystatusI). - The proxy sends its own
BEGIN READ WRITE, then the exact approved bytes, thenCOMMITon success orROLLBACKon error. It swallows its own messages' answers and reportsReadyForQueryI. - 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:
COMMITorROLLBACK, then send it alone". The block is already read-only, and PostgreSQL refuses a switch toREAD WRITEafter 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 SETs 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 itsSync), thenCOMMIT, orROLLBACKif the unit failed. The proxy swallows its own answers and reportsReadyForQuery I. TheSET LOCALvalues are the onesoptionspins.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
BEGINorSTART TRANSACTION(Simple Query) outside a block goes up with its own modes, which the classifier allows only withoutREAD WRITE. Before the sandbox's first statement runs in it, the proxy sendsSET TRANSACTION READ ONLYand the sameSET LOCALs, then answersBEGINandReadyForQuery T. Later units run in that block as they are, up to the sandbox's loneCOMMIT,ENDorROLLBACK.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 theSET LOCALs (checked on PostgreSQL 17:statement_timeoutback to0);- an extended-protocol
BEGIN, and aFlush-terminated group, outside a block (the wrapper is never held open across the sandbox's messages).
Two-phase commit and
ABORTstay refused as before. A loneCOMMIT,ROLLBACKor 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 (statusIbefore the proxy'sCOMMIT).- transaction control with any other statement in the same Simple Query (
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 = onandclient_encoding = UTF8, and ignoresdefault_transaction_read_only, which is the pooler's idleoff.Approved writes run in
BEGIN TRANSACTION READ WRITEwith the sameSET LOCALs. AfterCOMMIT, 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 nostatement_timeoutorsearch_pathpin, since itsoptionsare dropped too. Onlyread_only = offis 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
Bindto one is refused with26000before anything goes up or is asked. Inside the sandbox's own block, names work as usual. The proxy'sCOMMIT(a simple query) also ends the protocol's unnamed statement. Clients that sendParse,Bind,ExecuteandSynctogether (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''andstandard_conforming_strings=on(pinned),E'…'escapes,U&'…'andU&"…"withUESCAPE,B'…'andX'…'; - dollar quoting (
$tag$…$tag$), quoted identifiers; - positional parameters (
$1), and operators; - the input must be valid UTF-8 with no NUL (
client_encodingis pinned to UTF8). Anything it can't lex isunknown.
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:BEGINorSTART TRANSACTIONwith noREAD WRITE,COMMIT,END,ROLLBACK, andSAVEPOINT,RELEASEorROLLBACK TO; EXPLAINwithoutANALYZEin any form (ANALYZE,(ANALYZE),(ANALYZE true));EXPLAIN ANALYZEruns 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,MERGEandINTO, and the sequencesFOR UPDATE,FOR NO KEY UPDATE,FOR SHAREandFOR KEY SHARE;- this one rule closes writable CTEs (
WITH d AS (DELETE … RETURNING *) SELECT …),SELECT … INTOand row locks, with no grammar needed; INTOandFORare reserved words in PostgreSQL (from memory), so a bare column can't be called that.INSERT,UPDATE,DELETEandMERGEaren't, so an unquoted column calledupdatecosts an approval, never a leak. Quoted ("update"), it passes;
- this one rule closes writable CTEs (
- 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 areCOPY,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,CHECKPOINTandREASSIGN. SoSELECT comment, lock FROM postsstaysread; - 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 ofpg_catalogfunctions with no side effects: arithmetic, string, date and time, JSON, aggregate and window functions,current_*,pg_typeof,has_*_privilege,pg_get_*def,versionand the like. It is shipped as data and versioned with the vectors. Names are unqualified, or qualified aspg_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_xmlandts_stat, whose argument the classifier never sees as SQL. Each has a vector insql-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_pathis pinned (rule 1 of §9.3), so an unqualified name resolves topg_catalogfirst, as PostgreSQL does by default. A user who can create functions or operators in a schema still can't shadowpg_catalognames. Operators aren't checked, and stay in risk 117;
- Excluded:
- 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. SoSELECT 1; DROP TABLE users;isddl, and the card shows both statements. COPYis the one leading verb that can beread:COPY table TO STDOUTandCOPY (SELECT …) TO STDOUT, with the inner query meeting thereadrules, areread.COPY … FROM STDINiswrite, and a file orPROGRAMisadmin.
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; proptestthat wraps reads in random comments, whitespace and quoting, and checks the class never drops;- in the CI
test (postgres)task, every vector markedreadruns against a real PostgreSQL in a read-only transaction, which must not error with25006.
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
Bindup to 16 MiB. - Server→client notices and notifications are forwarded, redacted.
NotificationResponsecan't occur, becauseLISTENisn'tread.
9.6 Approvals and audit for a statement
One access per non-
readstatement or batch.Claimsgains:pg_class:write,ddl,adminorunknown;pg_verbs: the leading keywords per statement, up to 8, from a closed vocabulary such asDELETEorDROP TABLE, so they can't carry data;pg_sql: a digest, defined asSHA-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_keyappendspg_classandpg_sqlafter 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") matchespg_classand the first verb, on the same database and sandbox, neveradminorunknown, 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
ErrorResponsewith:S=ERROR,C=42501;M: "Klav: DELETE onis waiting for the person's approval (approval )"; 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
ReadyForQueryI, 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
0x29pg-statement: HPKE to the account's identity, withinfo = tuple("klav/v1/proxy/pg-statement-seal", account_id, agent_id, item_id, fingerprint_account)and plaintextlp(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_sqland shows asecuritycard on any mismatch; - the server deletes the blob when the approval is decided or expires.
- The server never sees the SQL.
- new kind
With
write_item_id, an approved write doesn't run on the session's connection. The proxy:- opens a second upstream connection (same transport, the write item's role, SCRAM as in §9.2) with
default_transaction_read_only=off; - sends exactly the approved bytes as one Simple Query, or as one
Parse/Bind/Execute/Syncwith the approved parameters; - 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
".
- opens a second upstream connection (same transport, the write item's role, SCRAM as in §9.2) with
Audit.
agent.accessentries 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.
- The server's log doesn't list each
10. Formats, versions, and older clients
Grant
v: 5, a superset ofv: 4, with:ProxyProfile.tunnel,ProxyProfile.pgand, insidepg,allow_cleartext_over_tls;Scope.upgradesandScope.sql_classes.
Older proxies and servers reject it (
deny_unknown_fields) and fail closed. A client signsv: 5only when a profile uses a new field, and the sheet asks for--every-device-is-updated, asv: 2–v: 4did.Claims gain
upgrade,pg_database,pg_class,pg_verbsandpg_sql. An older device's approvals list andklav log verifyfail 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_tunnelsforupgrade(Part 1);pg_guardfor thepg_*claims and the sealed route (Part 2).
While a switch is off, the server refuses those claims with
400 proxy_tunnels_offor400 pg_guard_off, and every existing answer stays byte-identical.GET /v1/agent/meadvertises a switch only while it is on. The proxy refuses tunnels or Postgres sessions with a clearKlav-Errorwhile it is off.Labels (spec §2.3):
klav/v1/proxy/pg-sql,klav/v1/proxy/pg-statement-seal. Blob0x29(spec §3;0x29is the next free kind, now that0x28is ADR 0051's). Vectors:docs/vectores/pg-proxy.json: SCRAM with RFC 7677's vector plus Klav's capped iterations, thepg_sqldigest, and0x29;docs/vectores/sql-guard.json: classification.
The channel API gains
hostsin the claim and status answers, and the routesCONNECT host:portandPOST /_klav/pg/<profile>(Upgrade: klav-pg/1). Version skew:- an older forwarder ignores
hostsand uses mode (a); - a newer forwarder with an older proxy finds no
hosts, turns mode (b) and Postgres off, andklav-forward statussays the proxy is too old.
- an older forwarder ignores
| 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,openssloropenssl-sys(all banned indeny.toml),libpg_queryunless Q7 (c), and nounsafein Klav's code. AGENTS.md's approved list gains, at the layer that adds each item: thex509-certbuilderline, thepbkdf2andstringprepline, thetokio-tungsteniteline, and the extendedrustlsapproval forklav-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):
- 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.
- Detect-and-cut in WebSocket tunnels can let up to
len − 1bytes of the token reach the tool before the cut, and only if the far end echoes it inside the tunnel (§4). - Layer A doesn't stop everything a read-only transaction allows. That includes temporary tables, advisory locks, and
pg_cancel_backendorpg_terminate_backendwhen privileged. Layer B's allowlist and a read-only role close most of it. A role withpg_signal_backendor superuser remains dangerous, and the sheet warns against granting one. - User code reached without call syntax isn't checked: operators, views, implicit casts, domain checks and column defaults. A view that calls
dblink_execruns it on a plainSELECT, outside Layer A. A role that can create functions or operators in a schema onsearch_pathcan makea + brun its own code. In-engine writes still fail under Layer A. The read-only role removesCREATE, and the sheet warns when the database hasdblinkorpostgres_fdw(the proxy readspg_extensionat session start and reports it inklav-forward status). - Mode (b) serves only tools that honor
HTTPS_PROXYand the trust variables (§1.1). Others fail closed with a placeholder: Node withoutNODE_USE_ENV_PROXY, tools that pin certificates or carry their own roots, and HTTP/2-only clients.klav-forward statussays so. - The server's audit log doesn't list individual reads, only the session and every non-read statement (§9.6; Q6).
- 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)
- Grant
v: 5as a superset ofv: 4, and two switches rather than one. TunnelHostwith a single-label wildcard, narrower thanDomainPattern.- Tunnels and Postgres sessions counted together, apart from call slots: 8 per sandbox, 32 per proxy, 16 per account in Klav Cloud.
- Pings every 60 s; idle 15 min and total 8 h by default.
- WebSocket extensions always stripped.
- Postgres profiles refused on the Mac proxy's loopback in v1.
- The startup parameter allowlist,
statement_timeoutpinned at 4 min, the 15-minute idle session and the empty-query keepalive, and protocol 3.0 only. - The SCRAM iteration cap of 4096–600 000.
- Approved writes only outside transaction blocks, autocommitted, with no transaction control inside.
- SQL-level
PREPAREandEXECUTEtreated asunknown. - A lease never covers
adminorunknown. - The 2-minute hold and
42501for pending, denied and expired. - Caps: 1 MiB per statement, 16 MiB per message, 64 KiB per sealed statement, 600 statements a minute.
- 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 SETs 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_PROXYshell-wide. The agent's own model calls and git would go through the forwarder and break when it stops.- Rewriting
targetDomainin 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.comfor 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-postgresorpostgres-protocol. Their SCRAM and MD5 would be cryptography outsideklav-core.- MD5 authentication. It would need
md-5inklav-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: featuressandbox-caandpg-scram,TunnelHost,Scope.upgradesandScope.sql_classes, andRequest.upgradeandRequest.sql_class; - in
klav-proto: grantv: 5,ProxyProfile.tunnelandProxyProfile.pg, the claims, and blob0x29; - in
klav-server: the two switches, the claims intarget_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-directand--pg-northflank-addon; - on Mac and iOS: the tunnel line and the SQL card.
- in
- 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 indocs/vectores/pg-proxy.jsonandsql-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):
- 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. klav-coresandbox-ca: CA signer (two signatures, then wiped), leafTlsSigner, layout withx509-certbuilder; spec §13.10 paragraph.klav-coreandklav-proto: grantv: 5(tunnel,TunnelHost,Scope.upgrades,Request.upgradewith the deny-only rule),Claims.upgrade, vectors.klav-server: theproxy_tunnelsswitch,upgradeintarget_key, andklav log verify. "Safe with older clients" review.klav-proxy: channel upgrades, mode (b)CONNECT,hostsin claim and status, the WebSocket relay with limits, pings, cuts and detect-and-cut. End-to-end tests against a fake WebSocket upstream, throughklav-nitro-parenttoo.klav-forward: port 8791, the certificates, shims,klav-forward run, and status lines. A CI client matrix:reqwest,curl, Nodefetchand undiciWebSocketwithEnvHttpProxyAgent, Go, and Python.klav-client,klav-cli, Mac and iOS:--tunnelsand--tunnel-host, the sheet, the card's tunnel line, and turning the switch on.- Hand test (Omar's go, a paid sandbox):
northflank forward addon … --skipHostnamesandpsqlwith its own password, from a Boat sandbox and through Klav Cloud. This recordstargetDomain(§15) and marks mode (b)'s box.
Part 2 (no Postgres password in the sandbox):
klav-corepg-scram:pbkdf2, SASLprep, proofs and the server-signature check; RFC 7677 vectors.klav-coreandklav-proto:pgprofile,Scope.sql_classesandRequest.sql_class(deny-only rule), thepg_*claims,pg_sql, blob0x29;pg-proxy.json.klav-proxyclassifier: lexer, classes, function allowlist;sql-guard.json,proptest, and the CI check against PostgreSQL.klav-proxyPostgres wire,direct: startup, SCRAM, Layer A, the query phase, holds, cancel, redaction. End-to-end in thetest (postgres)CI task.klav-proxynorthflank-addontransport (per Q12).klav-server: thepg_guardswitch, the generic sealed routePUT /v1/agent/approvals/{id}/sealed, hiding until the blob arrives, purge. "Safe with older clients" review.klav-forwardandklav-cli: the Postgres listener,--preset postgres, setup lines,klav approval showfor SQL.- Mac and iOS: the SQL card from the sealed blob, and Activity rows.
- Hand test (Omar's go):
horizon-stack's Postgres through the tunnel transport from a Boat sandbox: aSELECTpasses, aDELETEasks 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
targetDomainunder 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 (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(b) rcgen 0.14.10 with no features in klav-forward (+rcgen, yasna)(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 (b) A single-label wildcard from day one (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(b) Opt-in, handshakes ask with leases(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 (b) No inspection after the 101(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) (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(b) sqlparser 0.64.0 with an allowlist over its AST (+1 crate)(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)(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(b) Require two items (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(b) Verbs and digest only until ADR 0041's route exists (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(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(b) A generic signed "discovery recipe" (URL template and a JSON pointer) (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 (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 (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-cert0.3.1builderinklav-corebehindsandbox-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_catalogallowlist for function calls in reads; anything else isunknown(ask). - Q9 (a): one item works; setup recommends a read-only role plus optional
write_item_idfor 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;pbkdf20.13.0 andstringprep0.1.5 approved forklav-core(pg-scram). - Q12 (a):
northflank-addontransport inklav-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).