Repository navigation
feat(security): blob redaction, hop-by-hop filtering, query_raw lockdown (#3+4) - #135
Conversation
Bundles audit ship-order PRs #3 and #4 into a single PR. HIGH-01 + MEDIUM-06 + HIGH-06 (blob redaction): - New `crates/rewind-proxy/src/redact.rs` module with: - `redact_request_body()` — strips values of sensitive JSON keys (api_key, authorization, token, password, secret, credentials, etc.) from request bodies before blob store write - `redact_secrets()` — regex-based pattern matching on response blobs for OpenAI keys (sk-...), AWS access key IDs (AKIA...), Bearer tokens, and long hex tokens (40+ chars). Applied in both buffered and streaming response paths. - 8 unit tests for redaction logic MEDIUM-08 (hop-by-hop headers): - `redact::HOP_BY_HOP_HEADERS` denylist applied in the proxy header- forwarding loop. Strips transfer-encoding, te, trailer, upgrade, proxy-authorization, proxy-connection, keep-alive, expect per RFC 7230 §6.1. HIGH-02 (query_raw lockdown): - Removed PRAGMA and EXPLAIN from the query_raw allowlist — only SELECT and WITH are now permitted. Many PRAGMAs mutate state (journal_mode, foreign_keys, writable_schema). - New `Store::pragma_table_info()` validates the table name against sqlite_master before constructing the query, replacing the unsafe `format!("PRAGMA table_info({})", name)` pattern in the CLI. Audit doc updated: HIGH-01, HIGH-02, HIGH-06, MEDIUM-06, MEDIUM-08 all marked as fixed in PR #135. Ship order table updated. Tests: full workspace 370+/0, clippy clean on touched files. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
risjai
left a comment
There was a problem hiding this comment.
Security Review — PR #135 (blob redaction + hop-by-hop + query_raw lockdown)
Cross-verified against the source. The three fixes are the right moves, and the module layout (redact.rs) is clean. Found one concrete redaction bypass in the streaming path that should block, plus a SQLite CTE-based allowlist bypass in query_raw that isn't remotely exploitable today but is trivial to close.
🔴 Block
1. Streaming path stores raw upstream bytes unredacted
crates/rewind-proxy/src/lib.rs:618-622
// Also store raw SSE for forensics
{
let s = store.lock().unwrap();
let _ = s.blobs.put(&accumulated_raw); // available via hash if needed
}The synthetic response built from SSE deltas is redacted (L612-L616), but immediately after, accumulated_raw — the full raw SSE byte stream — is put into the blob store without going through redact_secrets. SSE frames legitimately carry tool-call argument JSON, upstream gateway error bodies, and sometimes x-request-id / auth-debug echoes from LLM providers' error paths. Anything the regex would have caught in the synthetic response also appears in the raw SSE, verbatim on disk. The PR body claims "both buffered AND streaming response paths" are redacted — that's only true for the synthetic blob; the raw SSE blob is a second copy that evades redaction.
Fix: run redact::redact_secrets(&accumulated_raw) before blobs.put, same as the synthetic blob above it. If you keep it unredacted for forensics, that decision needs to be an explicit opt-in flag, not a silent second write.
🟡 Should
2. WITH-prefixed DML bypasses the SELECT/WITH allowlist
crates/rewind-store/src/db.rs:1642-1653
SQLite accepts CTEs on INSERT/UPDATE/DELETE/MERGE statements (see sqlite.org/lang_with.html). The first-word check passes for:
WITH x AS (SELECT 1) DELETE FROM sessions;
WITH x AS (SELECT 1) UPDATE sessions SET name='owned' WHERE 1;
WITH x AS (SELECT 1) INSERT INTO timelines VALUES (...);All parse as valid SQLite and execute mutations. Grep confirms query_raw is CLI-only today (no HTTP/MCP exposure), so this is not a remote bypass — but (a) the audit explicitly contemplated MCP exposing it, (b) the whole point of this PR is defense-in-depth, and (c) the fix is one line.
Cleanest fix: after stmt.prepare(sql), check stmt.readonly() — rusqlite proxies SQLite's own read-only classifier, which correctly rejects WITH ... DELETE. Alternative: PRAGMA query_only = ON on the connection, or open a dedicated read-only connection with OpenFlags::SQLITE_OPEN_READ_ONLY.
3. redact_secrets silently passes through compressed/binary bodies
crates/rewind-proxy/src/redact.rs:170-176
let text = match std::str::from_utf8(data) {
Ok(s) => s,
Err(_) => return data.to_vec(), // binary blob, skip
};rewind-proxy uses reqwest with features ["stream", "json", "rustls-tls"] — no gzip/brotli, so upstream responses with Content-Encoding: gzip flow through the proxy compressed. The compressed bytes aren't valid UTF-8, the regex is skipped, and the gzipped body — which decompresses to the cleartext JSON including any secrets — lands on disk unredacted.
Two options: (a) enable reqwest's gzip/brotli features so response bodies are always decompressed before redaction, or (b) at minimum, log a warning when the binary fallback triggers so this doesn't fail silently. Option (a) is correct for recording fidelity anyway (replay of a compressed blob requires re-compression).
4. [0-9a-f]{40,} over-redacts legitimate content
crates/rewind-proxy/src/redact.rs:165
This catches SHA-1 (40), SHA-256 (64), and any long hex run. The blob store itself uses SHA-256 hex keys, so any response body that references a rewind blob hash, a git SHA, a request-id UUID concatenated with another, or a content-hash from the upstream provider gets redacted. Not a security bug — a debuggability hit. Consider scoping this to patterns that look like tokens (e.g., require a non-hex boundary + length≤128, or only match inside string-literal contexts in JSON). Or just drop it — the three named patterns (sk-, AKIA, Bearer) cover the actual threat.
5. Connection: <header-list> isn't parsed to extend hop-by-hop denylist
crates/rewind-proxy/src/redact.rs:131-140, crates/rewind-proxy/src/lib.rs:390-402
RFC 7230 §6.1 says the Connection header names additional hop-by-hop headers for that connection. The hardcoded list covers the canonical eight, but a client could send Connection: X-Internal-Auth + X-Internal-Auth: secret expecting the proxy to strip both. Today the code just skips Connection itself and forwards the named header. For an LLM proxy this is low-risk (clients don't typically use Connection extensions) but it's the kind of edge case audit findings tend to surface later.
🟢 Nit
- db.rs:1634-1641: two stacked doc comments on
query_raw— the old "Rejects any statement that is not a SELECT" line is stale and contradicts the new "SELECT and WITH" line directly below. - redact.rs:143:
is_hop_by_hoptakes&strassumed lowercase;is_sensitive_headerlowercases internally. The asymmetry is confusing — either both normalize, or the callsite comment should note "pass lowercase".axum'sHeaderName::as_str()is always lowercase so the callsite is correct, but a future caller passing"Transfer-Encoding"would silently fail. - redact.rs:115:
once_cell::sync::Lazycan bestd::sync::LazyLockon modern Rust, dropping theonce_celldep. - redact.rs:186-190: the JSON key regex only matches double-quoted string values. Numeric or boolean values (
"api_key": 12345) pass through. Rare but possible; serde reserializing would be safer if you ever need to cover them. - Test coverage misses: nested JSON keys (
{"config": {"api_key": "sk-..."}}— works by regex, but not asserted), streaming path redaction (no integration test exercises the streaming branch), andWITH ... DELETErejection once fixed.
Summary
Direction is right, especially the pragma_table_info() refactor — that's clean. Block on the streaming raw-SSE gap (real leak on disk), strongly recommend the WITH-DML fix via stmt.readonly(), and flag the gzip fallthrough for a follow-up. Rest is polish.
…uard, nits
Addresses blocking + should-fix items from the code review.
🔴 Blocker resolved:
- Raw SSE blob (accumulated_raw) now goes through redact_secrets() before
blobs.put. Previously the synthetic response was redacted but the raw
copy was written verbatim — a real secret leak on disk.
🟡 Should-fix resolved:
- query_raw now checks stmt.readonly() after prepare. Catches WITH-prefixed
DML (WITH x AS (...) DELETE/UPDATE/INSERT) that passed the first-word
allowlist. SQLite's own read-only classifier is authoritative.
- Dropped the over-aggressive [0-9a-f]{40,} regex pattern that was
redacting git SHAs, blob store hashes, and request IDs. The three
named patterns (sk-, AKIA, Bearer) cover the actual threat.
- Binary/compressed response bodies now log a tracing::debug warning
instead of silently skipping redaction. Full gzip decompression deferred
to a follow-up (requires enabling reqwest gzip feature).
🟢 Nits:
- Replaced once_cell::sync::Lazy with std::sync::LazyLock (stdlib);
dropped once_cell dep from rewind-proxy
- is_hop_by_hop now lowercases internally (matches is_sensitive_header
behavior; callers no longer need to pre-lowercase)
- Stale doc comment on query_raw cleaned up
Tests: 370+/0, clippy clean.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
Pushed 🔴 Blocker fixed: 🟡 Should-fix resolved:
🟢 Nits:
Follow-ups (not in this PR):
Tests: 370+/0, clippy clean. |
risjai
left a comment
There was a problem hiding this comment.
Re-review — PR #135 (post-fix commit 4936a89)
All blockers and most should-fixes addressed cleanly:
| Finding | Verdict |
|---|---|
| 🔴 Raw SSE stored unredacted | ✅ Fixed — redact_secrets(&accumulated_raw) before blobs.put |
🟡 WITH-DML bypass |
✅ Fixed — stmt.readonly() after prepare(). Correct defense-in-depth. |
| 🟡 Binary/compressed fallback | ✅ Mitigated — tracing::debug! log on non-UTF-8. Full fix (enable gzip feature) is a reasonable follow-up. |
🟡 [0-9a-f]{40,} over-redaction |
✅ Fixed — pattern dropped, comment explains why |
🟡 Connection extension headers |
Deferred — acceptable for LLM proxy threat model |
| 🟢 Stale doc comment | ✅ Fixed |
🟢 is_hop_by_hop case asymmetry |
✅ Fixed — both functions now normalize internally |
🟢 once_cell → LazyLock |
✅ Fixed — dep removed |
stmt.readonly() is the right call — it delegates to SQLite's own classifier, which handles CTEs, subqueries, and any future syntax additions correctly. Much better than trying to parse SQL yourself.
LGTM — ready to merge. 🚢
…136) Post-security-sprint version bump. PRs #133-#135 shipped changes to crates/ and web/src/ since the v0.12.9 GitHub release, and python/ changes since the 0.14.7 PyPI publish. Track 1 (Rust binary): Cargo.toml → Cargo.lock → python/rewind_cli.py → python-mcp/pyproject.toml → python-mcp/rewind_mcp_cli.py Track 2 (Python SDK): python/pyproject.toml → python/rewind_agent/__init__.py Post-merge checklist: 1. Create GitHub Release with tag v0.12.10 (triggers CI binary builds) 2. Run ./scripts/publish-pypi.sh from python/ directory 3. Run ./scripts/publish-mcp-pypi.sh from python-mcp/ directory Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Summary
Bundles audit ship-order PRs #3 and #4 into a single PR — closes 5 findings from the security audit.
query_rawallows state-mutating PRAGMAspragma_table_info()Implementation
New:
crates/rewind-proxy/src/redact.rsA standalone redaction module with:
redact_request_body()— strips values of sensitive JSON keys before blob store write. Keys matched (case-insensitive):api_key,api_secret,authorization,x-api-key,secret,password,token,access_token,refresh_token,private_key,client_secret,aws_secret_access_key,bearer,credentialsredact_secrets()— regex patterns on response blobs: OpenAI keys (sk-...), AWS access key IDs (AKIA...), Bearer tokens, long hex tokens (40+ chars)HOP_BY_HOP_HEADERS— denylist for RFC 7230 §6.1 hop-by-hop headersChanged:
crates/rewind-proxy/src/lib.rsredact::is_hop_by_hop()redact::redact_request_body(&body_bytes)beforeblobs.put()redact::redact_secrets(&resp_bytes)beforeblobs.put()Changed:
crates/rewind-store/src/db.rsquery_raw()now only allowsSELECTandWITH(removedPRAGMAandEXPLAIN)pragma_table_info(table_name)validates the name againstsqlite_masterbefore constructing the PRAGMA query — eliminates theformat!injection vectorChanged:
crates/rewind-cli/src/main.rscmd_query --tablesnow callsstore.pragma_table_info(name)instead ofstore.query_raw(&format!("PRAGMA table_info({})", name))Updated:
docs/security-audit.mdAll 5 findings marked as ✅ fixed in PR #135. Ship order table updated.
Test plan
cargo test --workspace— 370+ tests, 0 failurescargo clippyon touched crates — zero new errorsredact.rs: OpenAI key, AWS key, Bearer token, short string passthrough, request body key redaction, authorization in body, hop-by-hop detection, sensitive header detectionrewind query --tablesstill works viapragma_table_info()rewind query "SELECT * FROM sessions"still works (SELECT allowed)Ship order
No version bump — deferred until the security sprint is complete.
🤖 Generated with Claude Code