Skip to content

feat(security): blob redaction, hop-by-hop filtering, query_raw lockdown (#3+4) - #135

Merged
risjai merged 2 commits into
masterfrom
feat/security-hardening-pr3-4
Apr 21, 2026
Merged

risjai merged 2 commits into
masterfrom
feat/security-hardening-pr3-4

Conversation

@risjai

@risjai risjai commented Apr 21, 2026

Copy link
Copy Markdown
Collaborator

Summary

Bundles audit ship-order PRs #3 and #4 into a single PR — closes 5 findings from the security audit.

Finding Title Fix
HIGH-01 Proxy forwards Authorization headers Hop-by-hop denylist + request blob redaction
HIGH-02 query_raw allows state-mutating PRAGMAs Locked to SELECT/WITH; new pragma_table_info()
HIGH-06 Proxy records response bodies verbatim Response blob regex redaction
MEDIUM-06 Recorded blobs contain API keys in plaintext Request + response redaction pipeline
MEDIUM-08 Proxy forwards hop-by-hop headers RFC 7230 §6.1 denylist

Implementation

New: crates/rewind-proxy/src/redact.rs

A 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, credentials
  • redact_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 headers
  • 8 unit tests covering all patterns + edge cases

Changed: crates/rewind-proxy/src/lib.rs

  • Header forwarding loop now skips hop-by-hop headers via redact::is_hop_by_hop()
  • Request blob written via redact::redact_request_body(&body_bytes) before blobs.put()
  • Response blob (both buffered and streaming paths) written via redact::redact_secrets(&resp_bytes) before blobs.put()

Changed: crates/rewind-store/src/db.rs

  • query_raw() now only allows SELECT and WITH (removed PRAGMA and EXPLAIN)
  • New pragma_table_info(table_name) validates the name against sqlite_master before constructing the PRAGMA query — eliminates the format! injection vector

Changed: crates/rewind-cli/src/main.rs

  • cmd_query --tables now calls store.pragma_table_info(name) instead of store.query_raw(&format!("PRAGMA table_info({})", name))

Updated: docs/security-audit.md

All 5 findings marked as ✅ fixed in PR #135. Ship order table updated.

Test plan

  • cargo test --workspace — 370+ tests, 0 failures
  • cargo clippy on touched crates — zero new errors
  • 8 unit tests in redact.rs: OpenAI key, AWS key, Bearer token, short string passthrough, request body key redaction, authorization in body, hop-by-hop detection, sensitive header detection
  • Existing proxy integration tests still pass (header forwarding behavior unchanged for non-hop-by-hop headers)
  • rewind query --tables still works via pragma_table_info()
  • rewind query "SELECT * FROM sessions" still works (SELECT allowed)

Ship order

# Fix Status
1 Fail-closed auth (CRITICAL-02) ✅ PR #133
2 SSRF guard (CRITICAL-01) ✅ PR #134
3+4 Blob redaction + hop-by-hop + query_raw lockdown ✅ This PR
5 Filesystem permissions (HIGH-03, LOW-07) ⏳ Follow-up

No version bump — deferred until the security sprint is complete.

🤖 Generated with Claude Code

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]>
@vercel

vercel Bot commented Apr 21, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
rewind Ready Ready Preview, Comment Apr 21, 2026 9:26am

@risjai risjai left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_hop takes &str assumed lowercase; is_sensitive_header lowercases internally. The asymmetry is confusing — either both normalize, or the callsite comment should note "pass lowercase". axum's HeaderName::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::Lazy can be std::sync::LazyLock on modern Rust, dropping the once_cell dep.
  • 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), and WITH ... DELETE rejection 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]>
@risjai

risjai commented Apr 21, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 4936a89 addressing all review items.

🔴 Blocker fixed:
Raw SSE blob (accumulated_raw) now goes through redact::redact_secrets() before blobs.put. The synthetic response was already redacted — this closes the second-copy leak.

🟡 Should-fix resolved:

# Issue Fix
2 WITH ... DELETE bypasses allowlist Added stmt.readonly() check after prepare() — SQLite's own read-only classifier catches CTE-wrapped DML
3 Compressed bodies skip redaction Added tracing::debug log when binary fallback triggers. Full gzip decompression (reqwest feature) deferred to follow-up
4 [0-9a-f]{40,} over-redacts Dropped the pattern. The three named patterns (sk-, AKIA, Bearer) cover the threat without hitting git SHAs and blob hashes
5 Connection: header extensions Low risk, noted for follow-up. Not in this commit

🟢 Nits:

  • once_cell::sync::Lazy → std::sync::LazyLock (stdlib), dropped once_cell dep
  • is_hop_by_hop now lowercases internally (matches is_sensitive_header pattern)
  • Stale doc comment on query_raw cleaned up

Follow-ups (not in this PR):

  • Enable reqwest gzip feature for proper decompression before redaction
  • Parse Connection: header value to extend hop-by-hop denylist dynamically

Tests: 370+/0, clippy clean.

@risjai risjai left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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. 🚢

@risjai
risjai merged commit 384992e into master Apr 21, 2026
6 checks passed
@risjai
risjai deleted the feat/security-hardening-pr3-4 branch April 21, 2026 10:38
risjai added a commit that referenced this pull request Apr 21, 2026
…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]>

This branch was successfully deployed

1 active deployment
Preview — 4936a891 Deployed Apr 21, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant