Scoped secret substitution, ai-jail 3.7.1 (from the fork's fix/secret-scope, on
branch zeo/ebuild-371; the 2026-11-27 security review of Zeo 0.31.0, J1-J5): the
placeholder becomes the real value only in Authorization (Basic decoded),
x-api-key and the query parameters a binding names (--secret KEY=host?param), and
a placeholder anywhere else refuses the request with 400 before any dial; the
response head is scrubbed of the real value; a decrypted request needs one Host
naming the CONNECT origin; a bare LF, lone CR or NUL in the head is refused; a
secret-bound host is intercepted on 443 only; plain-HTTP termination uses every
binding of the host. Must follow ai-jail-ssh-proxy.patch.

diff --git a/docs/SECURITY.md b/docs/SECURITY.md
index 5ba0ab3..1a180c6 100644
--- a/docs/SECURITY.md
+++ b/docs/SECURITY.md
@@ -324,16 +324,26 @@ kernel does (32-bit) so a high-bit variant cannot slip past the filter.
 On kernels ≥ 6.12 Landlock also scopes abstract Unix sockets and signals
 (best-effort) as a further backstop.
 
-Phantom credentials (`--secret KEY=host[,host...]`, filtered egress only)
-shift part of the trust boundary to the supervisor: the sandbox env holds an
-`AIJAIL-PHANTOM-…` placeholder, new for every launch, and the egress proxy
-substitutes the real value only in the request head — `Authorization: Basic`
-decoded and re-encoded — of requests to a bound host: plain-HTTP proxy
-requests, and on Linux HTTPS through CONNECT. Placeholders are not credentials
-— knowing one authorizes nothing — and real values live only in supervisor
-memory, never in any config file, the audit log, or the sandbox. Substitution
-is scoped per host: a placeholder sent to a host its key is not bound to goes
-out unchanged.
+Phantom credentials (`--secret KEY=host[,host...][?param,...]`, filtered
+egress only) shift part of the trust boundary to the supervisor: the sandbox
+env holds an `AIJAIL-PHANTOM-…` placeholder, new for every launch, and the
+egress proxy substitutes the real value in requests to a bound host —
+plain-HTTP proxy requests, and on Linux HTTPS through CONNECT on port 443 —
+and only where a credential belongs: the `Authorization` header
+(`Basic` decoded and re-encoded), the `x-api-key` header, and the values of the
+query parameters named after `?` (percent-encoded). A placeholder anywhere else
+in the request head — the path, an unnamed parameter, any other header —
+refuses the request with `400` before any dial, because a server that reflects
+that place (a redirect, an error page, `Access-Control-Allow-Origin`) would
+hand the real value back to the sandbox. So does a `Host` header that does not
+name the bound origin (domain fronting on a shared front end). The response
+head is scrubbed of the real value, raw and percent-encoded; the response body
+is not rewritten, so a host that echoes a credential in its body — and a named
+query parameter is the most echoed place — can still reveal it: bind a secret
+only to hosts that do not. Placeholders are not credentials — knowing one
+authorizes nothing — and real values live only in supervisor memory, never in
+any config file, the audit log, or the sandbox. Substitution is scoped per
+host: a placeholder sent to a host its key is not bound to goes out unchanged.
 
 HTTPS injection works by interception, and its trust anchor is narrow on
 purpose. The supervisor makes one CA per launch; its private key and every
diff --git a/src/cli.rs b/src/cli.rs
index 0dfea83..fbc7f5c 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -145,13 +145,18 @@ OPTIONS:
     --env-from-file <PATH>          Read KEY=VALUE lines from PATH (repeatable; file
                                     must be user-owned, mode 0600, outside the project;
                                     applies like --env, which wins on conflicts)
-    --secret <KEY=host[,host...]>   Keep KEY's real value out of the sandbox: the child
+    --secret <KEY=host[,host...][?param,...]>
+                                    Keep KEY's real value out of the sandbox: the child
                                     sees a per-launch placeholder; the egress proxy
                                     substitutes the real value only in requests to the
                                     named hosts, over HTTP or HTTPS (it trusts a CA made
-                                    for this launch and those hosts alone; Linux), Basic
-                                    auth included (repeatable; every host must be in
-                                    --allow-host, no port; requires filtered egress)
+                                    for this launch and those hosts alone; Linux, port
+                                    443), and only in the Authorization (Basic included)
+                                    and x-api-key headers and the query parameters named
+                                    after '?'; a placeholder anywhere else, or a Host
+                                    header naming another origin, refuses the request
+                                    (repeatable; every host must be in --allow-host, no
+                                    port; requires filtered egress)
     --inherit-env / --no-inherit-env
                                     Inherit the full host environment (default: off —
                                     only a safe allowlist is passed)
diff --git a/src/main.rs b/src/main.rs
index 40e362c..cd09bf0 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -206,12 +206,27 @@ fn prepare_secrets(
     let session = secret::session_nonce();
     let mut bindings = Vec::new();
     for (key, hosts_value) in bindings_spec {
-        let hosts = secret::split_hosts(&hosts_value);
+        let (hosts, query_params) = secret::split_spec(&hosts_value);
         if hosts.is_empty() {
             return Err(format!("--secret {key}: names no host"));
         }
+        if hosts_value.contains('?') && query_params.is_empty() {
+            return Err(format!(
+                "--secret {key}: names no query parameter after '?'"
+            ));
+        }
+        if let Some(bad) =
+            query_params.iter().find(|p| !secret::valid_query_param(p))
+        {
+            return Err(format!(
+                "--secret {key}: query parameter {bad:?} must be letters, digits, '_', '-' or '.'"
+            ));
+        }
         for host in &hosts {
-            if host.contains("://") || host.contains('/') || host.contains(':')
+            if host.contains("://")
+                || host.contains('/')
+                || host.contains(':')
+                || host.contains('?')
             {
                 return Err(format!(
                     "--secret {key}: host must be a bare hostname, not {host:?}"
@@ -258,6 +273,7 @@ fn prepare_secrets(
             .iter()
             .map(|host| {
                 secret::SecretBinding::with_session(&key, &real, host, &session)
+                    .with_query_params(query_params.clone())
             })
             .collect();
         // Remove EVERY entry for this key, then insert exactly one placeholder,
diff --git a/src/proxy.rs b/src/proxy.rs
index a8f7a44..198d9e5 100644
--- a/src/proxy.rs
+++ b/src/proxy.rs
@@ -951,9 +951,13 @@ fn handle_conn<S: ClientStream>(
     }
 
     // HTTPS injection: only an allowlisted (never a prompted) host that
-    // the launch's CA covers, which is to say a secret-bound one. Every
-    // other tunnel below stays opaque.
+    // the launch's CA covers, which is to say a secret-bound one, and only
+    // on the HTTPS port: the same host allowlisted on :22 carries SSH,
+    // which a TLS handshake would break. Every other tunnel below stays
+    // opaque. (The test hatch `danger_any_port` lets fixtures on
+    // ephemeral ports take this path.)
     if allowlisted
+        && (port == HTTPS_PORT || shared.config.danger_any_port)
         && let Some(ca) = shared.config.inject_ca.clone()
         && ca.covers(&host)
     {
@@ -1579,8 +1583,18 @@ fn body_framing(head: &[u8]) -> Result<BodyFraming, &'static str> {
         .windows(4)
         .position(|w| w == b"\r\n\r\n")
         .unwrap_or(head.len());
-    let text =
-        std::str::from_utf8(&head[..end]).map_err(|_| "malformed-request")?;
+    let raw = &head[..end];
+    // A bare LF, a lone CR or a NUL is a line end (or none) that another
+    // HTTP parser may read differently from the CRLF split below; a
+    // header hidden that way could carry a second framing.
+    for (at, byte) in raw.iter().enumerate() {
+        let bare_lf = *byte == b'\n' && (at == 0 || raw[at - 1] != b'\r');
+        let lone_cr = *byte == b'\r' && raw.get(at + 1) != Some(&b'\n');
+        if bare_lf || lone_cr || *byte == 0 {
+            return Err("ambiguous-framing");
+        }
+    }
+    let text = std::str::from_utf8(raw).map_err(|_| "malformed-request")?;
     let mut codings = Vec::new();
     let mut length: Option<u64> = None;
     for line in text.split("\r\n").skip(1) {
@@ -1778,21 +1792,20 @@ fn handle_http_termination<S: ClientStream>(
     // Secret-bound allowlisted hosts only: the allowlist check is the
     // same one CONNECT targets get, and the binding is what makes this
     // a termination request rather than a 405.
-    let binding = shared
+    let bound = shared
         .config
         .secrets
         .iter()
-        .find(|b| b.host.eq_ignore_ascii_case(&host));
+        .any(|b| b.host.eq_ignore_ascii_case(&host));
     let permitted = if shared.config.danger_any_port {
         allowlist_matches(&shared.config.allowlist, &host)
     } else {
         allowlist_permits(&shared.config.allowlist, &host, port)
     };
-    if !permitted || binding.is_none() {
+    if !permitted || !bound {
         reject(&mut client, &Reject::MethodNotAllowed);
         return;
     }
-    let binding = binding.expect("binding checked above");
 
     let framing = match body_framing(&request) {
         Ok(framing) => framing,
@@ -1813,25 +1826,37 @@ fn handle_http_termination<S: ClientStream>(
         .map(|p| p + 4)
         .unwrap_or(request.len());
     let (head, body_so_far) = request.split_at(head_end);
+    if !host_header_matches(head, &host, port, false) {
+        refuse_out_of_scope(
+            &mut client,
+            shared,
+            conn,
+            &host,
+            port,
+            "host-mismatch",
+        );
+        return;
+    }
 
-    // Only the binding for THIS host may substitute: the host check
+    // Only the bindings for THIS host may substitute: the host check
     // above decides whether this is a termination request; which
     // credentials may appear in it is scoped the same way, or a
     // sandboxed process could exfiltrate KEY_A's real value by sending
     // its placeholder to secret-bound host B.
-    let (rewritten, substitutions) =
-        crate::secret::rewrite_head(head, std::slice::from_ref(binding));
-    let rewritten = force_connection_close(&rewritten);
-    if let Some(log) = &shared.config.audit {
-        log.record(crate::audit::secret_inject_record(
+    let Ok(rewritten) = rewrite_for_host(head, &host, shared) else {
+        refuse_out_of_scope(
+            &mut client,
+            shared,
+            conn,
             &host,
-            &binding.key,
-            substitutions,
-        ));
-    }
+            port,
+            "secret-out-of-scope",
+        );
+        return;
+    };
 
-    conn.record.upstream(&binding.host, port);
-    let mut upstream = match tls_connect(&binding.host, port, &shared.config) {
+    conn.record.upstream(&host, port);
+    let mut upstream = match tls_connect(&host, port, &shared.config) {
         Ok(stream) => stream,
         Err(why) => {
             let (verdict, reason) = dial_failure_verdict(&why);
@@ -1861,18 +1886,143 @@ fn handle_http_termination<S: ClientStream>(
     // Upstream closes at the end of the response (Connection: close),
     // which ends this copy and the connection.
     let mut client_writer = client;
-    let _ = io::copy(
+    let _ = relay_scrubbed_response(
         &mut CountingReader::new(&mut upstream, down),
         &mut client_writer,
+        &bindings_for(&host, shared),
     );
     let _ = client_writer.shutdown_both();
 }
 
+/// The HTTPS port: the only one a secret-bound CONNECT is decrypted on.
+const HTTPS_PORT: u16 = 443;
+
+/// Longest response head scrubbed of real values; a longer one is
+/// relayed scrubbed up to here, the rest as it comes.
+const RESPONSE_HEAD_CAP: usize = 64 * 1024;
+
+/// The bindings whose host is `host`, the only ones a request to it may
+/// carry.
+fn bindings_for(
+    host: &str,
+    shared: &Shared,
+) -> Vec<crate::secret::SecretBinding> {
+    shared
+        .config
+        .secrets
+        .iter()
+        .filter(|b| b.host.eq_ignore_ascii_case(host))
+        .cloned()
+        .collect()
+}
+
+/// Whether the request head names the same origin the proxy will dial.
+/// A shared front end routes by `Host`, so a credential substituted for
+/// `host` must not travel under another one (domain fronting). Exactly
+/// one `Host` header, equal to `host` or `host:port` (case and a
+/// trailing dot ignored); `origin_form` also requires a target starting
+/// with `/`, the only form a decrypted CONNECT request may use. Plain
+/// HTTP carries an absolute-form target already checked by the caller,
+/// so there the header may be absent.
+fn host_header_matches(
+    head: &[u8],
+    host: &str,
+    port: u16,
+    origin_form: bool,
+) -> bool {
+    let Ok(text) = std::str::from_utf8(head) else {
+        return false;
+    };
+    let mut lines = text.split("\r\n");
+    let request_line = lines.next().unwrap_or_default();
+    if origin_form
+        && !request_line
+            .split(' ')
+            .nth(1)
+            .is_some_and(|t| t.starts_with('/'))
+    {
+        return false;
+    }
+    let normal = |h: &str| h.trim().trim_end_matches('.').to_ascii_lowercase();
+    let want = normal(host);
+    let with_port = format!("{want}:{port}");
+    let values: Vec<String> = lines
+        .filter_map(|line| line.split_once(':'))
+        .filter(|(name, _)| name.eq_ignore_ascii_case("host"))
+        .map(|(_, value)| {
+            let value = normal(value);
+            match value.rsplit_once(':') {
+                Some((name, p)) if p == port.to_string() => {
+                    format!("{}:{p}", name.trim_end_matches('.'))
+                }
+                _ => value,
+            }
+        })
+        .collect();
+    match values.as_slice() {
+        [] => !origin_form,
+        [one] => *one == want || *one == with_port,
+        _ => false,
+    }
+}
+
+/// Refuse a terminated request before any dial, with a 400 and an
+/// audit verdict naming why. Generic over the plain and decrypted sides.
+fn refuse_out_of_scope<S: Write>(
+    client: &mut S,
+    shared: &Shared,
+    conn: &mut Conn,
+    host: &str,
+    port: u16,
+    reason: &'static str,
+) {
+    audit_verdict(shared, host, port, "deny", reason);
+    conn.record.verdict(Verdict::Deny, reason);
+    let (code, text) = Reject::BadRequest.status();
+    let _ =
+        client.write_all(format!("HTTP/1.1 {code} {text}\r\n\r\n").as_bytes());
+    let _ = client.flush();
+}
+
+/// Copy a response from `upstream` to `client`, its head first scrubbed
+/// of every binding's real value ([`crate::secret::scrub_response_head`]).
+/// The body is copied as it comes: its length is the server's to state.
+fn relay_scrubbed_response<R: Read, W: Write>(
+    upstream: &mut R,
+    client: &mut W,
+    bindings: &[crate::secret::SecretBinding],
+) -> io::Result<u64> {
+    let mut buf = Vec::new();
+    let mut chunk = [0_u8; 4096];
+    let head_end = loop {
+        if let Some(at) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
+            break at + 4;
+        }
+        if buf.len() >= RESPONSE_HEAD_CAP {
+            break buf.len();
+        }
+        let n = upstream.read(&mut chunk)?;
+        if n == 0 {
+            break buf.len();
+        }
+        buf.extend_from_slice(&chunk[..n]);
+    };
+    let head = crate::secret::scrub_response_head(&buf[..head_end], bindings);
+    client.write_all(&head)?;
+    client.write_all(&buf[head_end..])?;
+    let rest = io::copy(upstream, client)?;
+    Ok(head.len() as u64 + (buf.len() - head_end) as u64 + rest)
+}
+
 /// Rewrite a request head for `host` with every binding of that host and
 /// nothing else, auditing each key's substitution count (never a value).
 /// Scoped like the plain-HTTP path: a placeholder of a key bound to
 /// another host passes through untouched.
-fn rewrite_for_host(head: &[u8], host: &str, shared: &Shared) -> Vec<u8> {
+fn rewrite_for_host(
+    head: &[u8],
+    host: &str,
+    shared: &Shared,
+) -> Result<Vec<u8>, crate::secret::OutOfScope> {
     let mut out = head.to_vec();
     for binding in shared
         .config
@@ -1881,7 +2031,7 @@ fn rewrite_for_host(head: &[u8], host: &str, shared: &Shared) -> Vec<u8> {
         .filter(|b| b.host.eq_ignore_ascii_case(host))
     {
         let (rewritten, substitutions) =
-            crate::secret::rewrite_head(&out, std::slice::from_ref(binding));
+            crate::secret::rewrite_head(&out, std::slice::from_ref(binding))?;
         out = rewritten;
         if let Some(log) = &shared.config.audit {
             log.record(crate::audit::secret_inject_record(
@@ -1891,7 +2041,7 @@ fn rewrite_for_host(head: &[u8], host: &str, shared: &Shared) -> Vec<u8> {
             ));
         }
     }
-    force_connection_close(&out)
+    Ok(force_connection_close(&out))
 }
 
 /// Answer a reply on the decrypted side of an intercepted tunnel and end
@@ -1975,7 +2125,30 @@ fn handle_tls_injection<S: ClientStream>(
         .map(|p| p + 4)
         .unwrap_or(request.len());
     let (head, body_so_far) = request.split_at(head_end);
-    let rewritten = rewrite_for_host(head, host, shared);
+    if !host_header_matches(head, host, port, true) {
+        refuse_out_of_scope(
+            &mut tls,
+            shared,
+            conn,
+            host,
+            port,
+            "host-mismatch",
+        );
+        finish_tls(&mut tls);
+        return;
+    }
+    let Ok(rewritten) = rewrite_for_host(head, host, shared) else {
+        refuse_out_of_scope(
+            &mut tls,
+            shared,
+            conn,
+            host,
+            port,
+            "secret-out-of-scope",
+        );
+        finish_tls(&mut tls);
+        return;
+    };
 
     conn.record.upstream(host, port);
     let mut upstream = match tls_connect(host, port, &shared.config) {
@@ -2004,7 +2177,18 @@ fn handle_tls_injection<S: ClientStream>(
     // Upstream closes at the end of the response (Connection: close). A
     // server that drops TCP without close_notify still delivered what it
     // sent, so the copy's error is not a failure of this exchange.
-    let _ = io::copy(&mut CountingReader::new(&mut upstream, down), &mut tls);
+    let _ = relay_scrubbed_response(
+        &mut CountingReader::new(&mut upstream, down),
+        &mut tls,
+        &bindings_for(host, shared),
+    );
+    finish_tls(&mut tls);
+}
+
+/// End the decrypted side of an intercepted tunnel.
+fn finish_tls<S: ClientStream>(
+    tls: &mut rustls::StreamOwned<rustls::ServerConnection, S>,
+) {
     tls.conn.send_close_notify();
     let _ = tls.flush();
     let _ = tls.sock.shutdown_both();
@@ -3838,6 +4022,75 @@ mod tests {
         );
     }
 
+    #[test]
+    fn body_framing_refuses_a_bare_lf_a_lone_cr_and_nul() {
+        for head in [
+            &b"POST / HTTP/1.1\r\nX-A: b\nTransfer-Encoding: chunked\r\nContent-Length: 3\r\n\r\n"[..],
+            b"POST / HTTP/1.1\r\nX-A: b\rTransfer-Encoding: chunked\r\n\r\n",
+            b"POST / HTTP/1.1\r\nX-A: b\0c\r\n\r\n",
+        ] {
+            assert_eq!(
+                body_framing(head),
+                Err("ambiguous-framing"),
+                "{}",
+                String::from_utf8_lossy(head)
+            );
+        }
+    }
+
+    #[test]
+    fn the_host_header_must_name_the_dialed_origin() {
+        let ok = |head: &str, origin_form| {
+            host_header_matches(
+                head.as_bytes(),
+                "api.example",
+                443,
+                origin_form,
+            )
+        };
+        assert!(ok("GET / HTTP/1.1\r\nHost: api.example\r\n\r\n", true));
+        assert!(ok(
+            "GET /v1 HTTP/1.1\r\nhost: API.Example.:443\r\n\r\n",
+            true
+        ));
+        // Domain fronting: another tenant behind the same front end.
+        assert!(!ok("GET / HTTP/1.1\r\nHost: other.example\r\n\r\n", true));
+        assert!(!ok(
+            "GET / HTTP/1.1\r\nHost: api.example:8443\r\n\r\n",
+            true
+        ));
+        // Two Host headers, none, or an absolute-form target inside TLS.
+        assert!(!ok(
+            "GET / HTTP/1.1\r\nHost: api.example\r\nHost: other.example\r\n\r\n",
+            true
+        ));
+        assert!(!ok("GET / HTTP/1.1\r\n\r\n", true));
+        assert!(!ok(
+            "GET https://other.example/ HTTP/1.1\r\nHost: api.example\r\n\r\n",
+            true
+        ));
+        // Plain HTTP: the absolute target was checked; Host may be absent.
+        assert!(ok("GET http://api.example/ HTTP/1.1\r\n\r\n", false));
+    }
+
+    #[test]
+    fn a_relayed_response_head_is_scrubbed_and_its_body_untouched() {
+        let b = crate::secret::SecretBinding::new("K", "real-v", "a.example");
+        let response = b"HTTP/1.1 200 OK\r\nx-echo: real-v\r\ncontent-length: 6\r\n\r\nreal-v";
+        let mut out = Vec::new();
+        let n = relay_scrubbed_response(
+            &mut &response[..],
+            &mut out,
+            std::slice::from_ref(&b),
+        )
+        .unwrap();
+        let out = String::from_utf8(out).unwrap();
+        assert_eq!(n as usize, out.len());
+        assert!(out.contains(&format!("x-echo: {}\r\n", b.placeholder)));
+        // The body keeps its stated length: it is not rewritten.
+        assert!(out.ends_with("\r\n\r\nreal-v"), "{out}");
+    }
+
     #[test]
     fn body_framing_refuses_every_smuggling_ambiguity() {
         for head in [
@@ -3952,8 +4205,9 @@ mod tests {
     }
 
     /// TLS fixture: the test-only self-signed cert from
-    /// tests/fixtures, serving the received x-test-key header back in
-    /// the response body.
+    /// tests/fixtures, serving the received x-api-key header back in
+    /// the response body -- a server that reflects a credential, which
+    /// is what lets these tests see the substituted value.
     fn tls_fixture() -> u16 {
         use rustls::pki_types::pem::PemObject;
         let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures");
@@ -4000,7 +4254,7 @@ mod tests {
                         .find_map(|line| {
                             line.split_once(':').and_then(|(name, v)| {
                                 name.trim()
-                                    .eq_ignore_ascii_case("x-test-key")
+                                    .eq_ignore_ascii_case("x-api-key")
                                     .then(|| v.trim().to_string())
                             })
                         })
@@ -4061,7 +4315,7 @@ mod tests {
         let request = format!(
             "GET http://127.0.0.1:{fixture}/v1/test HTTP/1.1\r\n\
              Host: 127.0.0.1:{fixture}\r\n\
-             x-test-key: {placeholder}\r\n\
+             x-api-key: {placeholder}\r\n\
              \r\n"
         );
         let stream = connect_and_send(proxy.port(), request.as_bytes());
@@ -4104,8 +4358,8 @@ mod tests {
         let request = format!(
             "GET http://127.0.0.1:{fixture}/ HTTP/1.1\r\n\
              Host: 127.0.0.1\r\n\
-             x-test-key: {placeholder_b}\r\n\
-             x-test-key-a: {placeholder_a}\r\n\
+             x-api-key: {placeholder_b}\r\n\
+             authorization: Bearer {placeholder_a}\r\n\
              \r\n"
         );
         let stream = connect_and_send(proxy.port(), request.as_bytes());
@@ -4123,7 +4377,7 @@ mod tests {
         drop(proxy);
 
         // The audit record shows exactly one substitution -- KEY_A's
-        // placeholder in x-test-key-a -- not two.
+        // placeholder in Authorization -- not two.
         let content = std::fs::read_to_string(
             home.join(".local/share/ai-jail/history.jsonl"),
         )
@@ -4153,7 +4407,7 @@ mod tests {
         let request = format!(
             "GET http://127.0.0.1:{fixture}/v1/test HTTP/1.1\r\n\
              Host: 127.0.0.1:{fixture}\r\n\
-             x-test-key: {placeholder}\r\n\
+             x-api-key: {placeholder}\r\n\
              \r\n"
         );
         let stream = connect_and_send(h.proxy.port(), request.as_bytes());
@@ -4307,7 +4561,7 @@ mod tests {
         let proxy = Proxy::start(config, None).unwrap();
         let request = format!(
             "POST http://127.0.0.1:{fixture}/ HTTP/1.1\r\n\
-             x-test-key: {placeholder}\r\n\
+             x-api-key: {placeholder}\r\n\
              Transfer-Encoding: chunked\r\n\r\n3\r\nabc\r\n0\r\n\r\n"
         );
         let stream = connect_and_send(proxy.port(), request.as_bytes());
@@ -4333,7 +4587,7 @@ mod tests {
         let proxy = Proxy::start(config, None).unwrap();
         let request = format!(
             "POST http://127.0.0.1:{fixture}/ HTTP/1.1\r\n\
-             x-test-key: {placeholder}\r\nContent-Length: 100\r\n\r\nabc"
+             x-api-key: {placeholder}\r\nContent-Length: 100\r\n\r\nabc"
         );
         let stream = connect_and_send(proxy.port(), request.as_bytes());
         stream.shutdown(Shutdown::Write).unwrap();
@@ -4428,7 +4682,7 @@ mod tests {
         // (the real host, behind real TLS) receives the real value.
         let request = format!(
             "POST /v1/test HTTP/1.1\r\nHost: 127.0.0.1\r\n\
-             x-test-key: {placeholder}\r\nConnection: keep-alive\r\n\
+             x-api-key: {placeholder}\r\nConnection: keep-alive\r\n\
              Transfer-Encoding: chunked\r\n\r\n2\r\nhi\r\n0\r\n\r\n"
         );
         let response = https_through_proxy(
@@ -4442,6 +4696,51 @@ mod tests {
         assert!(!response.contains(&placeholder), "{response}");
     }
 
+    #[test]
+    fn e2e_https_injection_refuses_a_placeholder_out_of_scope_or_fronted() {
+        // A path the server could reflect, a header it could echo, and a
+        // Host naming another tenant: each is refused before any dial, so
+        // the real value never leaves the proxy.
+        let fixture = tls_fixture();
+        let binding = crate::secret::SecretBinding::new(
+            "X_KEY",
+            "real-secret",
+            "127.0.0.1",
+        );
+        let p = binding.placeholder.clone();
+        let ca = Arc::new(
+            crate::tls_inject::InjectCa::generate(&["127.0.0.1".into()])
+                .unwrap(),
+        );
+        let root = inject_ca_pem_root(&ca);
+        let mut config = test_config(&["127.0.0.1"]);
+        config.secrets = vec![binding];
+        config.inject_ca = Some(ca);
+        config.danger_extra_roots = vec![fixture_root()];
+        let proxy = Proxy::start(config, None).unwrap();
+        for request in [
+            format!("GET /{p}/ HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n"),
+            format!(
+                "GET / HTTP/1.1\r\nHost: 127.0.0.1\r\nx-test-key: {p}\r\n\r\n"
+            ),
+            format!(
+                "GET / HTTP/1.1\r\nHost: other.example\r\nx-api-key: {p}\r\n\r\n"
+            ),
+        ] {
+            let response = https_through_proxy(
+                proxy.port(),
+                fixture,
+                root.clone(),
+                request.as_bytes(),
+            );
+            assert!(
+                response.starts_with("HTTP/1.1 400 Bad Request"),
+                "{request}\n{response}"
+            );
+            assert!(!response.contains("real-secret"), "{response}");
+        }
+    }
+
     #[test]
     fn e2e_https_injection_leaves_an_uncovered_tunnel_opaque() {
         // The CA covers another host, so the tunnel to the fixture is
@@ -4460,7 +4759,7 @@ mod tests {
         config.inject_ca = Some(ca);
         let proxy = Proxy::start(config, None).unwrap();
         let request = format!(
-            "GET / HTTP/1.1\r\nHost: 127.0.0.1\r\nx-test-key: {placeholder}\r\n\r\n"
+            "GET / HTTP/1.1\r\nHost: 127.0.0.1\r\nx-api-key: {placeholder}\r\n\r\n"
         );
         let response = https_through_proxy(
             proxy.port(),
@@ -4517,7 +4816,7 @@ mod tests {
         let request = format!(
             "POST http://127.0.0.1:{fixture}/upload HTTP/1.1\r\n\
              Host: 127.0.0.1:{fixture}\r\n\
-             x-test-key: {placeholder}\r\n\
+             x-api-key: {placeholder}\r\n\
              Content-Length: {}\r\n\r\n{body}",
             body.len()
         )
diff --git a/src/secret.rs b/src/secret.rs
index a6cd775..93cf8af 100644
--- a/src/secret.rs
+++ b/src/secret.rs
@@ -9,6 +9,15 @@
 //! proxy decrypts with a per-launch CA ([`crate::tls_inject`]). Every
 //! other CONNECT tunnel stays opaque and untouched.
 //!
+//! Inside that head the substitution is scoped to where a credential
+//! belongs: the `Authorization` and `x-api-key` header values, and the
+//! query parameters the binding names (`--secret KEY=host?param`). A
+//! placeholder anywhere else -- the path, another header -- refuses the
+//! request, because a server that reflects that place (a redirect, a 404
+//! page, CORS's `Access-Control-Allow-Origin`) would hand the real value
+//! back to the sandbox. The response head is scrubbed of the real value
+//! on its way back, as defence in depth.
+//!
 //! A placeholder is `AIJAIL-PHANTOM-<16 hex>`, derived from the key, the
 //! value and a per-launch session nonce: two launches never share one,
 //! so a placeholder seen in one session's logs says nothing about the
@@ -28,6 +37,10 @@ pub(crate) struct SecretBinding {
     pub placeholder: String,
     pub real: String,
     pub host: String,
+    /// Query parameters whose values may carry the placeholder, from the
+    /// `?param,param` suffix of the `--secret` value. Empty by default:
+    /// no query parameter is a credential unless the binding says so.
+    pub query_params: Vec<String>,
 }
 
 impl SecretBinding {
@@ -53,8 +66,15 @@ impl SecretBinding {
             placeholder: format!("AIJAIL-PHANTOM-{}", &digest[..16]),
             real: real.to_string(),
             host: host.to_string(),
+            query_params: Vec::new(),
         }
     }
+
+    /// The same binding, also allowed in the query parameters `params`.
+    pub(crate) fn with_query_params(mut self, params: Vec<String>) -> Self {
+        self.query_params = params;
+        self
+    }
 }
 
 // The real value never appears in debug output either.
@@ -65,6 +85,7 @@ impl std::fmt::Debug for SecretBinding {
             .field("placeholder", &self.placeholder)
             .field("real", &"[redacted]")
             .field("host", &self.host)
+            .field("query_params", &self.query_params)
             .finish()
     }
 }
@@ -97,56 +118,200 @@ pub(crate) fn split_hosts(value: &str) -> Vec<String> {
     hosts
 }
 
-/// Byte-replace every placeholder occurrence in `head` (the request
-/// line and headers only -- never the body) with the real value,
-/// returning the rewritten bytes and the substitution count for
-/// auditing. Multiple bindings stack; a placeholder that never appears
-/// costs nothing.
-pub(crate) fn rewrite_head(
-    head: &[u8],
-    bindings: &[SecretBinding],
-) -> (Vec<u8>, usize) {
-    let (mut out, mut substitutions) = rewrite_basic_auth(head, bindings);
-    for binding in bindings {
-        let (rewritten, count) = replace_all(
-            &out,
-            binding.placeholder.as_bytes(),
-            binding.real.as_bytes(),
-        );
-        out = rewritten;
-        substitutions += count;
+/// The hosts and the query parameters a `secret_hosts` value names:
+/// `host[,host...][?param[,param...]]`. The parameter list applies to
+/// every host of the value. A value without `?` names no parameter, which
+/// is every value written before parameters existed.
+pub(crate) fn split_spec(value: &str) -> (Vec<String>, Vec<String>) {
+    match value.split_once('?') {
+        Some((hosts, params)) => (split_hosts(hosts), split_hosts(params)),
+        None => (split_hosts(value), Vec::new()),
     }
-    (out, substitutions)
 }
 
-/// `Authorization: Basic` carries `base64(user:password)`, so a
-/// placeholder used as the password -- `git push` over HTTPS with a token
-/// does exactly that -- is invisible to a byte search. Decode each Basic
-/// credential in the head, substitute, and re-encode it. Any other
-/// header passes through unchanged; a credential that does not decode,
-/// or holds no placeholder, is left byte for byte.
-fn rewrite_basic_auth(
+/// Whether `name` can be a query parameter a binding names: a non-empty
+/// run of ASCII letters, digits, `_`, `-` and `.`, so it never needs
+/// percent-decoding to be compared.
+pub(crate) fn valid_query_param(name: &str) -> bool {
+    !name.is_empty()
+        && name
+            .bytes()
+            .all(|b| b.is_ascii_alphanumeric() || b"_-.".contains(&b))
+}
+
+/// The request was refused: a placeholder sat outside the places its
+/// binding allows, and substituting it there could reflect the real value.
+#[derive(Debug, PartialEq, Eq)]
+pub(crate) struct OutOfScope;
+
+/// Headers whose value is a credential, and the only ones substituted.
+const CREDENTIAL_HEADERS: [&[u8]; 2] = [b"authorization", b"x-api-key"];
+
+/// Substitute each binding's placeholder in `head` (the request line and
+/// headers only -- never the body) where a credential belongs: the
+/// [`CREDENTIAL_HEADERS`] values (Basic auth decoded and re-encoded) and
+/// the values of the query parameters the binding names (the real value
+/// percent-encoded). Returns the rewritten head and the substitution
+/// count for auditing, or [`OutOfScope`] when a placeholder remains
+/// anywhere else. A placeholder that never appears costs nothing.
+pub(crate) fn rewrite_head(
     head: &[u8],
     bindings: &[SecretBinding],
-) -> (Vec<u8>, usize) {
+) -> Result<(Vec<u8>, usize), OutOfScope> {
     let mut out = Vec::with_capacity(head.len());
     let mut substitutions = 0;
     let mut rest = head;
+    let mut first = true;
     loop {
         let line_end = find_subslice(rest, b"\r\n").unwrap_or(rest.len());
         let line = &rest[..line_end];
-        out.extend_from_slice(&rewrite_basic_line(
-            line,
-            bindings,
-            &mut substitutions,
-        ));
+        let rewritten = if first {
+            rewrite_request_line(line, bindings, &mut substitutions)
+        } else {
+            rewrite_header_line(line, bindings, &mut substitutions)
+        };
+        out.extend_from_slice(&rewritten);
+        first = false;
         if line_end == rest.len() {
             break;
         }
         out.extend_from_slice(b"\r\n");
         rest = &rest[line_end + 2..];
     }
-    (out, substitutions)
+    let leftover = bindings.iter().any(|binding| {
+        find_subslice(&out, binding.placeholder.as_bytes()).is_some()
+    });
+    if leftover {
+        return Err(OutOfScope);
+    }
+    Ok((out, substitutions))
+}
+
+/// Replace each binding's real value in a response head with its
+/// placeholder, raw and percent-encoded: a server that echoes the
+/// credential (a `Location` carrying the query, a debug header) must not
+/// hand it to the sandbox. Only the head is passed here; the body's
+/// length is the server's to state.
+pub(crate) fn scrub_response_head(
+    head: &[u8],
+    bindings: &[SecretBinding],
+) -> Vec<u8> {
+    let mut out = head.to_vec();
+    for binding in bindings {
+        if binding.real.is_empty() {
+            continue;
+        }
+        let encoded = percent_encode(binding.real.as_bytes());
+        for real in [binding.real.as_bytes(), encoded.as_slice()] {
+            out = replace_all(&out, real, binding.placeholder.as_bytes()).0;
+        }
+    }
+    out
+}
+
+/// The request line `METHOD SP target SP version`: only the values of
+/// the query parameters a binding names are substituted.
+fn rewrite_request_line(
+    line: &[u8],
+    bindings: &[SecretBinding],
+    substitutions: &mut usize,
+) -> Vec<u8> {
+    let mut parts = line.splitn(3, |b| *b == b' ');
+    let (Some(method), Some(target), Some(version)) =
+        (parts.next(), parts.next(), parts.next())
+    else {
+        return line.to_vec();
+    };
+    let Some(query_at) = target.iter().position(|b| *b == b'?') else {
+        return line.to_vec();
+    };
+    let (path, query) = (&target[..=query_at], &target[query_at + 1..]);
+    let mut rebuilt_query = Vec::with_capacity(query.len());
+    for (index, pair) in query.split(|b| *b == b'&').enumerate() {
+        if index > 0 {
+            rebuilt_query.push(b'&');
+        }
+        let Some(eq) = pair.iter().position(|b| *b == b'=') else {
+            rebuilt_query.extend_from_slice(pair);
+            continue;
+        };
+        let (name, value) = (&pair[..eq], &pair[eq + 1..]);
+        let mut value = value.to_vec();
+        for binding in bindings {
+            if binding.query_params.iter().any(|p| p.as_bytes() == name) {
+                let (rewritten, n) = replace_all(
+                    &value,
+                    binding.placeholder.as_bytes(),
+                    &percent_encode(binding.real.as_bytes()),
+                );
+                value = rewritten;
+                *substitutions += n;
+            }
+        }
+        rebuilt_query.extend_from_slice(name);
+        rebuilt_query.push(b'=');
+        rebuilt_query.extend_from_slice(&value);
+    }
+    let mut out = method.to_vec();
+    out.push(b' ');
+    out.extend_from_slice(path);
+    out.extend_from_slice(&rebuilt_query);
+    out.push(b' ');
+    out.extend_from_slice(version);
+    out
+}
+
+/// A header line: substituted only when its name is one of the
+/// [`CREDENTIAL_HEADERS`], and then only in its value.
+fn rewrite_header_line(
+    line: &[u8],
+    bindings: &[SecretBinding],
+    substitutions: &mut usize,
+) -> Vec<u8> {
+    let Some(colon) = line.iter().position(|b| *b == b':') else {
+        return line.to_vec();
+    };
+    let name = &line[..colon];
+    if !CREDENTIAL_HEADERS
+        .iter()
+        .any(|h| name.eq_ignore_ascii_case(h))
+    {
+        return line.to_vec();
+    }
+    let line = rewrite_basic_line(line, bindings, substitutions);
+    let colon = line.iter().position(|b| *b == b':').unwrap_or(line.len());
+    let mut value = line[colon..].to_vec();
+    for binding in bindings {
+        let (rewritten, n) = replace_all(
+            &value,
+            binding.placeholder.as_bytes(),
+            binding.real.as_bytes(),
+        );
+        value = rewritten;
+        *substitutions += n;
+    }
+    let mut out = line[..colon].to_vec();
+    out.extend_from_slice(&value);
+    out
+}
+
+/// RFC 3986 percent-encoding of everything outside the unreserved set,
+/// so a real value with `&`, `=`, `+` or `/` stays one query value.
+fn percent_encode(input: &[u8]) -> Vec<u8> {
+    const HEX: &[u8; 16] = b"0123456789ABCDEF";
+    let mut out = Vec::with_capacity(input.len());
+    for &b in input {
+        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
+            out.push(b);
+        } else {
+            out.extend_from_slice(&[
+                b'%',
+                HEX[usize::from(b >> 4)],
+                HEX[usize::from(b & 15)],
+            ]);
+        }
+    }
+    out
 }
 
 fn rewrite_basic_line(
@@ -158,8 +323,7 @@ fn rewrite_basic_line(
         return line.to_vec();
     };
     let (name, value) = (&line[..colon], &line[colon + 1..]);
-    let is_auth = name.eq_ignore_ascii_case(b"authorization")
-        || name.eq_ignore_ascii_case(b"proxy-authorization");
+    let is_auth = name.eq_ignore_ascii_case(b"authorization");
     let trimmed = value.trim_ascii_start();
     let scheme_len = b"basic ".len();
     if !is_auth
@@ -308,7 +472,7 @@ mod tests {
              \r\n",
             b.placeholder, b.placeholder
         );
-        let (out, count) = rewrite_head(head.as_bytes(), &[binding()]);
+        let (out, count) = rewrite_head(head.as_bytes(), &[binding()]).unwrap();
         let out = String::from_utf8(out).unwrap();
         assert_eq!(count, 2);
         assert!(!out.contains(&b.placeholder));
@@ -318,7 +482,7 @@ mod tests {
     #[test]
     fn rewrite_head_noop_without_placeholder() {
         let head = b"GET / HTTP/1.1\r\nhost: example.com\r\n\r\n";
-        let (out, count) = rewrite_head(head, &[binding()]);
+        let (out, count) = rewrite_head(head, &[binding()]).unwrap();
         assert_eq!(count, 0);
         assert_eq!(out, head);
     }
@@ -379,7 +543,7 @@ mod tests {
              Host: github.com\r\n\
              Authorization: Basic {credential}\r\n\r\n"
         );
-        let (out, count) = rewrite_head(head.as_bytes(), &[binding()]);
+        let (out, count) = rewrite_head(head.as_bytes(), &[binding()]).unwrap();
         let out = String::from_utf8(out).unwrap();
         assert_eq!(count, 1);
         let expected = base64_encode(b"x-access-token:sk-ant-real");
@@ -393,7 +557,7 @@ mod tests {
     #[test]
     fn basic_auth_without_a_placeholder_is_left_byte_for_byte() {
         let head = b"GET / HTTP/1.1\r\nAuthorization: Basic dXNlcjpwYXNz\r\nX-Other: Basic AIJAIL\r\n\r\n";
-        let (out, count) = rewrite_head(head, &[binding()]);
+        let (out, count) = rewrite_head(head, &[binding()]).unwrap();
         assert_eq!(count, 0);
         assert_eq!(out, head);
     }
@@ -403,13 +567,90 @@ mod tests {
         // A placeholder straddling a multibyte boundary still matches;
         // non-UTF-8 bytes elsewhere pass through untouched.
         let b = binding();
-        let mut head = b"GET / HTTP/1.1\r\nx-k: ".to_vec();
+        let mut head = b"GET / HTTP/1.1\r\nx-api-key: ".to_vec();
         head.extend_from_slice(&[0xff, 0xfe]);
         head.extend_from_slice(b.placeholder.as_bytes());
         head.extend_from_slice(b"\r\n\r\n");
-        let (out, count) = rewrite_head(&head, &[binding()]);
+        let (out, count) = rewrite_head(&head, &[binding()]).unwrap();
         assert_eq!(count, 1);
         assert!(out.windows(2).any(|w| w == [0xff, 0xfe]));
         assert!(String::from_utf8_lossy(&out).contains("sk-ant-real"));
     }
+
+    #[test]
+    fn a_placeholder_outside_a_credential_place_refuses_the_request() {
+        // Each of these places is one a server may reflect back.
+        let b = binding();
+        let p = &b.placeholder;
+        for head in [
+            format!("GET /{p}/ HTTP/1.1\r\nhost: a.example\r\n\r\n"),
+            format!("GET /?q={p} HTTP/1.1\r\nhost: a.example\r\n\r\n"),
+            format!("GET / HTTP/1.1\r\norigin: https://{p}.x\r\n\r\n"),
+            format!(
+                "GET / HTTP/1.1\r\nproxy-authorization: Bearer {p}\r\n\r\n"
+            ),
+            format!("GET / HTTP/1.1\r\nx-api-key: {p}\r\nx-echo: {p}\r\n\r\n"),
+        ] {
+            assert_eq!(
+                rewrite_head(head.as_bytes(), &[binding()]),
+                Err(OutOfScope),
+                "{head}"
+            );
+        }
+    }
+
+    #[test]
+    fn a_named_query_parameter_carries_the_value_percent_encoded() {
+        let b = SecretBinding::new("MAPS_KEY", "a&b=c/d+e", "maps.example")
+            .with_query_params(vec!["key".into()]);
+        let head = format!(
+            "GET /geo?x=1&key={}&y=2 HTTP/1.1\r\nhost: maps.example\r\n\r\n",
+            b.placeholder
+        );
+        let (out, count) =
+            rewrite_head(head.as_bytes(), std::slice::from_ref(&b)).unwrap();
+        assert_eq!(count, 1);
+        assert_eq!(
+            String::from_utf8(out).unwrap(),
+            "GET /geo?x=1&key=a%26b%3Dc%2Fd%2Be&y=2 HTTP/1.1\r\nhost: maps.example\r\n\r\n"
+        );
+        // Another parameter, even on the same binding, is not a credential.
+        let other = format!(
+            "GET /geo?q={} HTTP/1.1\r\nhost: maps.example\r\n\r\n",
+            b.placeholder
+        );
+        assert_eq!(
+            rewrite_head(other.as_bytes(), std::slice::from_ref(&b)),
+            Err(OutOfScope)
+        );
+    }
+
+    #[test]
+    fn the_response_head_loses_the_real_value() {
+        let b = SecretBinding::new("K", "s3cr&t", "a.example");
+        let head = b"HTTP/1.1 302 Found\r\nlocation: /x?key=s3cr%26t\r\nx-debug: s3cr&t\r\n\r\n";
+        let out = String::from_utf8(scrub_response_head(
+            head,
+            std::slice::from_ref(&b),
+        ))
+        .unwrap();
+        assert!(!out.contains("s3cr"), "{out}");
+        assert_eq!(out.matches(&b.placeholder).count(), 2);
+    }
+
+    #[test]
+    fn a_secret_value_names_hosts_then_query_parameters() {
+        assert_eq!(
+            split_spec("a.example,b.example?key,api_key"),
+            (
+                vec!["a.example".to_string(), "b.example".to_string()],
+                vec!["key".to_string(), "api_key".to_string()]
+            )
+        );
+        assert_eq!(split_spec("a.example"), (vec!["a.example".into()], vec![]));
+        assert!(valid_query_param("api_key.v-2"));
+        for bad in ["", "a b", "a=b", "a&b", "k%20"] {
+            assert!(!valid_query_param(bad), "{bad:?}");
+        }
+    }
 }
