Skip to content

audit: full-codebase security + correctness review (Codex, multi-pass) #100

Closed

Description

@thehoff

Why

A recent merge (#99) shipped a CRITICAL security regression — the meta-flag passthrough path bypassed per-tool environment hardening (issues #36/#37/#38), silently re-exposing env-injection RCE vectors for 7 infrastructure binaries (docker, kubectl, aws, psql, gh, glab, gt). It was caught by Codex review before reaching production, but it shows the hardening surface is fragile and not comprehensively verified.

This issue tracks a full-codebase, line-by-line audit of contextcrawler via Codex peer review — every line checked against the application's security model, branding, and stated goals.

Audit criteria — every line is checked against

  1. Security model
  2. Correctness
  3. Branding & goals
    • contextcrawler not rtk in user-facing strings, help text, hook scripts (branding_lint covers some — verify coverage).
    • Behaviour matches the stated goal: a transparent, lossless-by-default token-optimisation proxy.
  4. Code quality
    • No unwrap()/panic! on the proxy hot path that could kill a user's command.
    • Exit-code propagation correct.
    • Test coverage on every security-relevant path.

Scope — ~78k LOC, 8 review groups

# Group Files ~LOC Priority
G1 Security core core/utils.rs, hooks/trust.rs, hooks/integrity.rs, hooks/permissions.rs, hooks/supply_chain_gate.rs, hooks/tirith_gate.rs ~8.3k CRITICAL
G2 Hook system + dispatch hooks/init.rs, hooks/hook_cmd.rs, hooks/hook_check.rs, hooks/rewrite_cmd.rs, hooks/hook_audit_cmd.rs, main.rs ~12.2k CRITICAL
G3 Filter engine + tracking core/toml_filter.rs, core/filter.rs, core/tracking.rs, core/config.rs, core/stream.rs, core/tee.rs, core/runner.rs, core/telemetry*.rs, core/display_helpers.rs ~8.7k HIGH
G4 Command filters: git + cloud cmds/git/, cmds/cloud/ ~12.5k CRITICAL (RCE-adjacent)
G5 Command filters: system + rust + js cmds/system/, cmds/rust/, cmds/js/ ~12.2k HIGH
G6 Command filters: python + ruby + go + jvm + dotnet cmds/python/, cmds/ruby/, cmds/go/, cmds/jvm/, cmds/dotnet/ ~11.7k HIGH
G7 Discover + analytics + learn + parser discover/, analytics/, learn/, parser/ ~13.2k MEDIUM
G8 TOML filter configs + test harness src/filters/*.toml (60), tests/*.rs — MEDIUM

Method

  • One Codex pass per group (large groups split into sub-passes for context budget).
  • Each pass is adversarial: assume the code is wrong, prove it right.
  • Findings triaged CRITICAL / IMPORTANT / NICE-TO-HAVE.
  • CRITICAL/IMPORTANT findings → fixed on dedicated branches, each Codex-re-reviewed before merge.
  • Progress tracked as a checklist on this issue; per-group finding summaries posted as comments.

Progress

  • G1 — Security core
  • G2 — Hook system + dispatch
  • G3 — Filter engine + tracking
  • G4 — Command filters: git + cloud
  • G5 — Command filters: system + rust + js
  • G6 — Command filters: python + ruby + go + jvm + dotnet
  • G7 — Discover + analytics + learn + parser
  • G8 — TOML filter configs + test harness

Activity

  1. thehoff commented on May 20, 2026

    @thehoff
    OwnerAuthor

    G1 — Security core — findings (3 Codex passes, all verified against source)

    CRITICAL

    1. hooks/integrity.rs:286,308 — runtime integrity check fails OPEN on NoBaseline.
      runtime_check() treats a missing .rtk-hook.sha256 baseline as "silent, continue". Deleting the baseline file makes a tampered hook execute undetected. Verified: the (true, false) arm → NoBaseline → runtime_check continues.
      Fix: fail closed on NoBaseline — block and require reinstall/re-baseline.

    2. Defence-in-depth gates bypassed on the live hook path. tirith_gate::check and supply_chain_gate::check are invoked only from rewrite_cmd.rs (the contextcrawler rewrite subcommand). The installed PreToolUse hook calls contextcrawler hook claude → hook_cmd.rs::process_claude_payload, which runs permissions + rewrite but never invokes either gate. Verified: zero tirith/supply_chain references in hook_cmd.rs.
      Fix / decision needed: wire both gates into process_claude_payload, or converge the two entrypoints. (Design call — see note below.)

    3. core/utils.rs:346-383 — PATH resolution trusts inherited PATH. resolve_binary has no trusted-path notion; an attacker-controlled earlier PATH entry wins, and the fallback is bare-name exec. This is already tracked as open issue harden(PATH): trusted-PATH resolution for wrapped binaries (defer trojan-on-PATH defense) #40 — the audit re-confirms it.

    IMPORTANT

    1. core/utils.rs:626-679 — secure_git_command misses --config-env (documented git env-injection RCE), and the forbidden config-key set omits alias.*, credential.helper, filter.* (all exec-capable).
    2. core/utils.rs:1088-1137 — secure_cargo_command strips RUSTFLAGS but not CARGO_ENCODED_RUSTFLAGS (higher precedence).
    3. core/utils.rs:2162-2209 — secure_node_command strips NODE_OPTIONS but not NODE_PATH (module-shadowing vector for npm/pnpm/vitest/eslint/prettier/prisma/next).
    4. hooks/integrity.rs:74-99 — the expected hash is a writable same-directory sidecar; an attacker who can write the hook dir replaces both hook and baseline and stays green.
    5. hooks/supply_chain_gate.rs — fails OPEN: any TOML-parse / registry-timeout / OSV-lookup error becomes Unavailable, and the caller only blocks on Block.
    6. hooks/supply_chain_gate.rs:229-262 — detection is raw-substring matching; /usr/bin/npm install, bash -lc 'npm install x', $(npm install x) all bypass it.

    NICE-TO-HAVE

    1. hooks/integrity.rs:258-327 — recovery text still emits rtk init / rtk verify / rtk-rewrite.sh.

    Confirmed airtight (positive results)

    • apply_universal_env_strip — covers LD_PRELOAD, DYLD_INSERT_LIBRARIES, LD_AUDIT, BASH_ENV, PROMPT_COMMAND, IFS, BASH_FUNC_* sweeps.
    • 14 of 17 secure_*_command builders airtight (rg, python, ruby, jvm, dotnet, go, kubectl, docker, aws, psql, curl, wget, gh, glab, gt, meta).
    • check_forbidden_rg_args — --pre/--pre-glob/-z/--search-zip blocked, no =value/bundling bypass.
    • scrub_secrets — Bearer / --password= / URL creds / API keys caught, no bypass shape found.
    • trust.rs — fail-CLOSED; corrupt/unreadable trust state → Untrusted.
    • permissions.rs — fail-CLOSED; parse error → Default → ask, not allow.
    • No reachable unwrap()/panic! on attacker input in utils.rs; no TOCTOU; no user-facing rtk strings in utils.rs.

    Note on finding 2: the docs describe Tirith as "opt-in", so partial intent is plausible — but a defence gate that only fires on a non-default subcommand is a real gap. Needs an explicit design decision, not a silent fix.

    • G1 — Security core
  2. thehoff commented on May 20, 2026

    @thehoff
    OwnerAuthor

    G2 — Hook system + dispatch — findings (4 Codex passes)

    CRITICAL

    1. hooks/hook_cmd.rs — hook payload parsing fails OPEN. Malformed JSON, missing/wrong-type fields, or oversized stdin never emit a blocking verdict — malformed JSON logs to stderr and returns Ok(()), shape errors become Ignore, oversize stdin returns Err with no JSON. Net: any of these → the agent's command runs unchecked. Lines 16-25, 43-55, 300-307, 365-385, 424-440.
      Fix: fail closed — emit a deny JSON on any payload error.

    2. main.rs:3483 — proxy mode argument injection via lossy OsString + auto-split. contextcrawler proxy lossily converts the first arg to UTF-8 then runs it through shell_split. A binary path containing whitespace (/Applications/My Tool/bin/x) is split into wrong tokens → wrong binary/args spawned silently.
      Fix: keep argv as OsString through to Command; make shell-splitting opt-in, not a heuristic.

    IMPORTANT

    1. hook_cmd.rs — deny output contract is inconsistent across runtimes; native-hook deny emits nothing (relies on the harness treating empty output as deny — undocumented/untested). Stale rtk in emitted strings (hook_cmd.rs:53,172).
    2. hook_cmd.rs — rewrite semantic safety: &&/heredoc/already-prefixed verified safe; ;, |, backtick/$(...) unverified — needs separator-specific tests.
    3. hook_cmd.rs:345, rewrite_cmd.rs:84 — non-test .unwrap() on as_object_mut() and an unreachable!() on the payload path.
    4. main.rs:2560 — absolute-path bin (/usr/bin/npm) doesn't match META_PASSTHROUGH_BINS → skips secure_meta_command env hardening, falls to run_fallback. Same vuln class as the fix: complete pre-clap intercepts — meta flags + grep flag fallbacks #99 CRITICAL. Fix: basename-normalise before the membership check.
    5. main.rs:1737 — grep -l short flag collides with internal --max-len; shadows standard grep -l <file>.
    6. init.rs:3744 — patch_gemini_settings() silently replaces a malformed settings.json with {} — destroys user config on parse failure.
    7. init.rs:2762,2779,2825 — RTK_CLAUDE_DIR/CODEX_HOME/HERMES_HOME env vars accepted verbatim as write/delete roots; a poisoned .env redirects writes outside ~/.claude.
    8. init.rs:549,1395,3298 — uninstall matches the hook entry by substring on the command string; an unrelated hook mentioning the filename gets deleted too.
    9. hook_check.rs:38-86 — status() reports healthy on a stale registration without verifying the target binary exists/is executable → silent-broken-hook false negative.
    10. hook_audit_cmd.rs:9-15,74-83 — log path resolved from RTK_AUDIT_DIR/HOME, read_to_string with no canonicalisation/symlink-check/size-cap → symlink-to-device or multi-GB log hangs/OOMs.

    NICE-TO-HAVE

    1. init.rs:3439 — install-detection greps CLAUDE.md for substring rtk; stale + false-positive-prone. Use the exact block marker.
    2. hook_check.rs:127,186,198 — on-disk marker still # rtk-hook-version:.

    Confirmed clean

    • main.rs: run_fallback integrity, exit-code propagation, check_forbidden ordering, integrity gate wiring — all clean.

    • init.rs: written hook-script content (no stale rtk, paths properly constructed), integrity-baseline write, panics, TOCTOU — clean.

    • hook_cmd.rs: && preservation, heredoc skip, no-double-wrap — verified safe.

    • G1 finding re-confirmed: zero tirith_gate/supply_chain_gate calls in hook_cmd.rs.

    • G2 — Hook system + dispatch

  3. thehoff commented on May 20, 2026

    @thehoff
    OwnerAuthor

    G3 — Filter engine + tracking — findings (3 Codex passes)

    IMPORTANT

    1. core/toml_filter.rs:492 — match_output short-circuit evaluates AFTER the replace stage. A replace rule that strips error markers (FAILED, error:) means the unless guard sees scrubbed text → a real build failure silently short-circuits to the filter's fixed "ok" message. Fix: snapshot raw output before replace; evaluate unless/match_output guards against the snapshot.
    2. core/filter.rs:327, core/toml_filter.rs:541 — unchecked arithmetic on config-reachable line caps: smart_truncate underflows on --max-lines 0; head_lines + tail_lines can overflow before the slice. Fix: saturating_*, reject max_lines = 0 at parse time.
    3. core/tracking.rs:1355 — RTK_DB_PATH / config.tracking.database_path opened verbatim — no canonicalisation (symlink/device redirect) and no 0600 on create, so the user's command-history DB is world-readable at default umask. Fix: canonicalise + $HOME-confine + 0600.
    4. core/stream.rs:342,391,493 — run_streaming uses an unbounded mpsc::channel() and grows raw/filtered buffers with no end-to-end cap → OOM on a huge-output command. (exec_capture_with_limits IS capped — only the streaming path is exposed.) Fix: bounded channel + output cap on the streaming path.
    5. core/stream.rs:345,422 — BufReader::lines().map_while(Result::ok) is strict UTF-8 — silently truncates child output at the first non-UTF-8 byte. Fix: byte-line read + lossy conversion.
    6. core/tee.rs:37,107 — RTK_TEE_DIR/config controls the tee path; raw child output written verbatim via fs::write — no 0600, no symlink-safe open, no size cap. Fix: confine dir, OpenOptions with restricted perms, size cap.
    7. core/display_helpers.rs:203 — week_start[5..] / week_end[5..] sliced without length check → panic on malformed date data. Fix: .get(5..) with fallback.

    TELEMETRY — flagged for a product decision (not a code bug)

    telemetry.rs / main.rs:2493 — maybe_ping() phones home. It IS gated (compile-time RTK_TELEMETRY_URL must be set, RTK_TELEMETRY_DISABLED=1 opts out, consent required) and the opt-out works. Payload: device_hash, version/OS/arch/install-method, first-word-only command aggregates (NOT full argv), savings stats, hook type, config counts. No raw argv, paths, or secrets transmitted. Two notes: (a) the endpoint URL is compile-time-injected, invisible in source; (b) payload/user-agent still RTK-branded. Given the local-first / cloud-independence posture — recommend an explicit decision: keep gated, default-off, or strip telemetry from the fork entirely. Your call.

    NICE-TO-HAVE

    1. core/tracking.rs:570 — row prune has no VACUUM; disk not reclaimed. Add VACUUM or PRAGMA auto_vacuum.
    2. core/tracking.rs:382 — WAL/busy-timeout PRAGMA errors silently ignored; no reopen path for a locked/corrupt DB.
    3. telemetry_cmd.rs:57 — user-facing copy still says RTK/rtk.

    Confirmed clean / SAFE

    • SQL injection — SAFE: all tracking.rs inserts/queries use bound ? params; no format!-built SQL.

    • Secret scrubbing — SAFE: original_cmd/rtk_cmd (and parse-failure rows) go through scrub_secrets before INSERT.

    • ReDoS — SAFE: filter engine uses Rust regex/RegexSet (linear-time, no backtracking).

    • Filter code-execution — SAFE: the TOML filter pipeline is pure data transformation; no Command/eval/shell-out.

    • Trust gating — SAFE: project/user filter files gated before load; can't shadow built-ins.

    • Subprocess deadlock — SAFE: stdout/stderr drained concurrently; no pipe-buffer deadlock.

    • Tracking panics — SAFE: tracking errors swallowed; track* never panics the parent.

    • RTK_DB_PATH / ~/.config/rtk/ / RTK_DATA_DIR paths — intentional legacy compat identifiers, not stale branding.

    • G3 — Filter engine + tracking

  4. thehoff commented on May 20, 2026

    @thehoff
    OwnerAuthor

    G4 — git + cloud command filters — findings (3 Codex passes)

    CRITICAL

    1. cmds/cloud/curl_cmd.rs:24-35 — curl -K/--config deny-list bypassed by attached-value form. The forbidden-arg check matches -K / --config as standalone tokens but NOT -K=file / --config=file, which curl accepts. curl -K=evil.curlrc → arbitrary curl-flag injection from a file, gate never fires. Fix: normalise each arg (strip leading -, split on =, take the key) before the deny check; regression-test -K=file.
    2. cmds/cloud/wget_cmd.rs:10-31,62-78 — wget gate misses dangerous flags entirely. --output-document/-O (arbitrary file overwrite), --input-file/-i (arbitrary file read as URL list), --load-cookies (cookie-theft pivot) are not in the deny-list, in any form. Fix: add all three (+ attached-value normalisation per finding 1); test each bypass shape.

    IMPORTANT

    1. cmds/cloud/psql_cmd.rs:39-40 — verbose mode logs the raw psql argv, which can hold a DSN with an inline password (postgres://user:pass@host). Fix: run the argv through scrub_secrets before logging.
    2. cmds/git/diff_cmd.rs normalize_diff_args — the -- re-insertion assumes the first -- is the path separator; an arg starting with -- or unexpected ordering can mis-place it, promoting a path to a revision. Fix: defensive ordering validation.
    3. cmds/git/git.rs — run_status (compact mode), run_stash (list/show), run_worktree (list) apply the output filter BEFORE checking git's exit code → a non-zero git exit is absorbed, caller sees apparent success with empty/truncated output. Fix: propagate the exit code on all three before/around filtering.
    4. cmds/git/gt_cmd.rs:139-141 — run_other does to_string_lossy() on OsString args before forwarding unknown gt subcommands to git; non-UTF-8 branch names/paths get silently mangled. Fix: keep OsString/OsStr through the dispatch.

    NICE-TO-HAVE

    1. cmds/git/git.rs:523 — stale rtk in a user-facing string.
    2. cmds/cloud/container.rs:204,374 — two rtk help/usage banner strings.

    Confirmed clean / PASS

    • git command construction — SECURE: every spawn in git.rs/diff_cmd.rs routes through the hardened git_cmd/secure_git_command builder; no bare Command::new("git"). Exec-capable -c config keys (core.sshCommand, core.fsmonitor, …) rejected upstream in main.rs.

    • gh/glab/gt — SECURE: all three use hardened builders; no bare spawns.

    • --json/--jq/--template passthrough — PASS: gh/glab treat them as value-flags, return raw stdout on parse failure — structured output not mangled.

    • cloud hardened builders — PASS: aws/docker/kubectl/curl/psql/wget all spawn via their secure_*_command builder; no bare Command::new.

    • curl JSON minifier (feat(curl): losslessly minify JSON response bodies #94) — intact: IgnoredAny validity gate + textual whitespace stripper both present.

    • container injection — PASS: docker/kubectl keep user args in argv slots; no shell-string concatenation.

    • panics — clean across all 8 files; from_utf8_lossy used for arbitrary command output.

    • git add no-bloat/synthetic-baseline (git add: tracking records -1300% savings (filter adds info to silent command) #89/filters: universal no-bloat guard — never emit output larger than raw #95) — confirmed not regressed.

    • G4 — git + cloud command filters

  5. thehoff commented on May 20, 2026

    @thehoff
    OwnerAuthor

    G5 — system + rust + js command filters — findings (3 Codex passes)

    No CRITICAL. 8 IMPORTANT, 2 NICE.

    IMPORTANT

    1. cmds/system/ls.rs:22 — user path args split on leading-dash and forwarded to ls unchanged; a path like -la or -R becomes an ls option. Fix: insert -- before path operands.
    2. cmds/system/tree.rs:27 — same path-as-flag injection, no -- boundary before user paths.
    3. cmds/system/env_cmd.rs:136 — env masking is real but incomplete: key-substring matching only. A secret under an innocuous key name (DATABASE_URL, connection strings) prints raw. Fix: value-aware redaction (scan values for token/password/URL-cred patterns).
    4. cmds/rust/cargo_cmd.rs (utils.rs:988, cargo_cmd.rs:93,168,1091) — strip_ansi() is NOT applied before failure-pattern matching, and secure_cargo_command() doesn't set CARGO_TERM_COLOR=never. If coloured cargo output is forced, ANSI wraps error:/FAILED → prefix match breaks → a real failure reads as success. Fix: set CARGO_TERM_COLOR=never in secure_cargo_command() (one-liner) or strip ANSI before matching.
    5. cmds/rust/cargo_cmd.rs:1148 — line[bracket_start+1..bracket_end] panics when [ sits after ] (possible in ANSI-tainted lines). Fix: guard bracket_start < bracket_end, fall through to raw line.
    6. cmds/js/prettier_cmd.rs:79-93 — filter_prettier_output() emits "Prettier: All files formatted correctly" for ANY output not matching its filename heuristics — including Prettier parse/config errors. Fix: gate the success string on exit code 0 AND a known marker.
    7. cmds/js/npm_cmd.rs:147, cmds/js/pnpm_cmd.rs:481 — install paths drop all npm WARN/notice/audit lines; a suspicious lifecycle/postinstall warning from a malicious package is silently swallowed. Fix: surface all WARN/notice/audit lines for install subcommands.
    8. cmds/js/prisma_cmd.rs:359-362 — unwrap_or(20) slice offset can exceed line length → char-boundary panic. Fix: bounded .get().

    NICE-TO-HAVE

    1. cmds/system/json_cmd.rs:25 — stale rtk read/rtk deps in error strings.
    2. cmds/rust/cargo_cmd.rs:1205 — filter_cargo_clippy caps error blocks at 10; findings beyond the cap silently dropped. Raise/remove the cap (correctness, given "failures never sacrificed").

    Confirmed clean / PASS

    • grep forbidden-args — COVERED: check_forbidden_rg_args applied at grep_cmd.rs:37 and the run_grep_format_passthrough site; no bypass.

    • find -exec — BLOCKED: -exec/-delete denylisted; -fprintf/-ok fall to the unknown-flag drop path. RCE surface closed.

    • cargo hardened builder — PASS: all production spawns via secure_cargo_command; no bare Command::new("cargo").

    • js hardened builder — PASS: every cmds/js/ spawn via secure_node_command/package_manager_exec; NODE_OPTIONS/NODE_PATH/NPM_CONFIG_* stripped.

    • js failure surfacing — PASS: vitest/jest/tsc/eslint propagate exit codes; no false-success on test/type/lint failures (prettier is the exception — finding 6).

    • pipe_cmd.rs — arg-list assembly, no shell string. local_llm.rs — parser-only, no subprocess/network. json_cmd.rs — propagates parse errors, no panic.

    • cargo exit codes flow run_streaming → run → main intact.

    • G5 — system + rust + js command filters

  6. thehoff commented on May 20, 2026

    @thehoff
    OwnerAuthor

    G6 — python/ruby/go/jvm/dotnet command filters — findings (3 Codex passes)

    Two inter-pass contradictions were resolved by reading source directly — noted inline.

    CRITICAL

    1. core/utils.rs:2619 — _JAVA_OPTIONS missing from JVM_DANGEROUS_ENVS. The list is JAVA_OPTS, JAVA_TOOL_OPTIONS, JDK_JAVA_OPTIONS, GRADLE_OPTS, GRADLE_USER_HOME. _JAVA_OPTIONS (leading underscore — a distinct, undocumented JVM var) injects JVM args = code-exec, and is not stripped by secure_jvm_command. The unit test at utils.rs:3104 also omits it. Verified against source — note: the G1 pass (G1a) wrongly reported secure_jvm_command as covering _JAVA_OPTIONS; it does not. Fix: add _JAVA_OPTIONS to the const AND the test.
    2. cmds/dotnet/binlog.rs:288, cmds/dotnet/dotnet_trx.rs:94 — binlog/trx files read wholesale with no size cap (fs::read + GzDecoder::read_to_end / read_to_string). A hostile/malformed .binlog or .trx → unbounded heap growth (OOM/DoS). Fix: size cap (e.g. 256 MB) before decompress/parse.
    3. cmds/dotnet/dotnet_cmd.rs:851,1028 — dotnet build success inferred from the English text marker Build succeeded / 0 Warning(s) 0 Error(s). A non-zero exit that still emits that text can render as ok. Fix: process exit code authoritative; text advisory only, discarded when it contradicts the exit code.

    IMPORTANT

    1. core/utils.rs:2662 — GOENV absent from GO_DANGEROUS_ENVS (go honours it as a config-file pointer that can set GOFLAGS etc.). Fix: add GOENV (verify dangerousness at fix time).
    2. core/stream.rs:307-391 — go/gradle filter predicates fed raw lines, no ANSI strip → coloured failure markers evade compaction (same class as the cargo finding G5). Fix: strip ANSI before feed_line()/filter_fn().
    3. cmds/python/pytest_cmd.rs:63, cmds/ruby/rspec_cmd.rs:165, cmds/ruby/rubocop_cmd.rs:109 — failure-pattern matching on un-stripped stdout; ANSI-wrapped FAILURES/Failures:/offense markers evade detection → a failing run misreported as passing. Fix: strip ANSI before parsing, or pass --no-color/-p no:terminal.
    4. cmds/go/golangci_cmd.rs:179-228 — find_subcommand_index() only skips values for a hard-coded global-flag subset; unknown separate-value flags misclassified, their values silently dropped. Fix: complete the value-flag table or use real CLI parsing.
    5. cmds/dotnet/dotnet_cmd.rs:261 — temp-file prefixes rtk_dotnet_* surface in verbose/cleanup output. Fix: rename to contextcrawler_*.

    Corrected — NOT a finding

    • G6a reported Ruby tools (rake/rubocop/rspec) bypassing secure_ruby_command. False positive — verified against source: ruby_exec (utils.rs:270) internally wraps secure_ruby_command, so RUBYOPT/RUBYLIB/GEM_HOME ARE stripped on those paths.

    Confirmed clean / PASS

    • Python hardened builders — PASS: all python-tool spawns via secure_python_command (PYTHONPATH/PYTHONSTARTUP/PYTHONHOME/PYTHONINSPECT stripped).

    • Ruby hardened builders — PASS (per the correction above).

    • DOTNET_STARTUP_HOOKS — PASS: stripped by secure_dotnet_command.

    • dotnet direct-indexing — all guarded by prior length checks; no reachable panic.

    • go/jvm — no reachable panics; no user-facing rtk branding (go/jvm).

    • G6 — python/ruby/go/jvm/dotnet command filters

  7. thehoff commented on May 20, 2026

    @thehoff
    OwnerAuthor

    G7 — discover / analytics / learn / parser — findings (3 Codex passes)

    CRITICAL

    1. discover/registry.rs:399-400,734-744 — RTK_DISABLED bypass via substring match. The "is RTK disabled" check substring-searches the whole env-prefix chunk of a command. A crafted prefix like FOO=RTK_DISABLED=1 git status disables rewriting — and therefore the permission/rewrite gates that ride on the hook — without genuinely setting RTK_DISABLED. A prompt-injected agent can prepend that to slip a command past the proxy. Fix: parse env assignments token-by-token; only honour a key named exactly RTK_DISABLED.

    IMPORTANT

    1. discover/registry.rs:378-397,269-274,817-819 — strip_absolute_path() strips ANY first token containing /, not just true absolute paths. ./git, repo/bin/git, any relative wrapper → normalised to git and rewritten as the real binary — a semantic substitution the command didn't ask for. Fix: only strip when the token starts with /.
    2. discover/provider.rs:88-124 — read_dir() entries trusted via path.is_dir(), which is true for symlinked dirs. A symlinked project dir under ~/.claude/projects/ redirects discover scanning outside that tree. Fix: symlink_metadata().is_symlink() reject, then canonicalise + prefix-check.
    3. discover/codex.rs:109-122 — reader.lines().map_while(|l| l.ok()) silently stops at the first I/O/UTF-8 error and drops the rest of the log → undercount from one bad byte. Fix: explicit per-line error handling, keep iterating.
    4. analytics/gain.rs:262,725,745 + analytics/session_cmd.rs:113 — byte-slice truncation (&s[..n]) on user-controlled command/history strings; a multibyte char split at a byte boundary panics and kills contextcrawler gain. Fix: char-safe truncation (chars().take(n)).

    NICE-TO-HAVE

    1. discover/report.rs:123-243 — user-facing headings + the issue URL github.com/rtk-ai/rtk/issues still RTK-branded.
    2. analytics/cc_economics.rs:436, analytics/session_cmd.rs:186 — rtk commands / rtk discover in user-facing copy.

    Confirmed clean / PASS

    • lexer.rs — PASS: shell tokeniser handles unbalanced quotes / nested $(...) / heredocs / huge input — no panic, no infinite loop, no ReDoS.

    • Rewrite classification — clean (apart from findings 1-2): no semantic-merge/split hazard found in rewrite_command.

    • reconcile.rs — clean: SQLite opened READ_ONLY; locked/corrupt DB → warning banner; UTC-consistent; tie-break panic-free.

    • SQL — PASS: all analytics/tracking queries via rusqlite::params!; no string-built SQL; corrupt/missing DB → graceful Err.

    • discover JSONL parse — clean: line-by-line, malformed lines skipped, no OOM.

    • learn/ + parser/ — clean: no persistence writes, no ReDoS, no panic on odd input.

    • No reachable non-test panics in discover/ (apart from the gain byte-slice in finding 5).

    • G7 — discover / analytics / learn / parser

  8. thehoff commented on May 20, 2026

    @thehoff
    OwnerAuthor

    G8 — TOML filter configs + test harness — findings (2 Codex passes)

    IMPORTANT

    1. 8 match_output filters lack an unless guard — brew-install, bundle-install, composer-install, dotnet-build, poetry-install, quarto-render, tofu-validate, uv-sync. A match_output rule rewrites the displayed output to a fixed success message; without an unless guard covering error|warning|failed|fatal, a partially-failed run whose output still contains the success pattern is shown to the agent as clean. (Graded IMPORTANT not CRITICAL: the exit code still propagates honestly — only the text an LLM agent reads is misleading. quarto-render's "Output created:" is the sharpest — it co-occurs with errors; dotnet-build's 0 Error(s) is the mildest — unlikely in a failed run.) Fix: add an unless guard to each.
    2. oxlint.toml:8, helm.toml:7 — strip_lines_matching regexes erase warning-summary lines (^Found \d+ warning, ^W\d{4}), so a warnings-only run collapses to empty/clean. Fix: keep warning summaries.
    3. tests/cloud_hardening.rs — shared cc-hardening-<pid>.sqlite DB across tests; order-dependence risk if a future assertion reads DB state. Fix: per-test temp RTK_DB_PATH.

    NICE-TO-HAVE

    1. gradle.toml, pio-run.toml, tofu-plan.toml, xcodebuild.toml — success-ish on_empty messages also fire when the tool crashes with no stdout. Consider gating on exit code.

    Test-harness verdicts (the meta-question: does the suite protect what it claims?)

    • Hardening tests are REAL spawn-checks, not list-checks — cargo_hardening, node_hardening, git_hardening, cloud_hardening, runtime_hardening, gh_glab_gt_hardening all spawn the actual binary and inspect the child env/output. The env-strip gaps this audit found (_JAVA_OPTIONS, NODE_PATH, CARGO_ENCODED_RUSTFLAGS) survived because the vars were never added to the strip list — the tests faithfully test an incomplete list. Adding the var to the list + the test's expected-set closes each.
    • branding_lint.rs gap = overbroad allowlist. File-scan scope is correct (walks all src/**/*.rs). But stale rtk strings in git.rs/container.rs/report.rs/hook_cmd.rs were explicitly exempted via KNOWN_UNBRANDED_TEXT_NEEDLES / HOOK_PROTOCOL_NEEDLES / permissive file-buckets — exemptions added to quiet rebrand-era false positives are now eating real violations. Fix: narrow exemptions to exact strings, not file-scope buckets. (Open issues harden(branding-lint): clap-aware sub-rule to catch /// doc-comment leaks before they reach --help #75/harden(branding-lint): shrink KNOWN_UNBRANDED_TEXT_NEEDLES debt list (70 → ≤20) #76 already track branding-lint hardening.)

    GAPs — bug classes the suite would NOT catch

    • harness_claude_code.rs — no test for a malformed/missing-field hook payload (the fail-open CRITICAL from G2 existed precisely because this wasn't tested).

    • harness_standalone.rs — exercises direct commands only, never the hook payload path.

    • proxy_nudge.rs — no OsString/shell-split edge cases (spaces, unicode, empty args) — the proxy CRITICAL from G2.

    • cloud_hardening.rs — shared-DB state leak (also finding 3).

    • G8 — TOML filter configs + test harness

  9. thehoff commented on May 20, 2026

    @thehoff
    OwnerAuthor

    AUDIT COMPLETE — consolidated summary (all 8 groups)

    Full-codebase Codex audit, ~78k LOC, 24 review passes. Tallies below count post-correction (two inter-pass contradictions were resolved against source — see G6).

    Findings by group

    Group CRITICAL IMPORTANT NICE Fix status
    G1 Security core 3 6 1 ✅ PR #101 merged
    G2 Hook + dispatch 2 10 2 ✅ PR #102 open (Codex-reviewed ×2)
    G3 Filter engine + tracking 0 7 3 ⬜ not fixed (+ telemetry product decision)
    G4 git + cloud 2 4 2 ⬜ not fixed
    G5 system + rust + js 0 8 2 ⬜ not fixed
    G6 python/ruby/go/jvm/dotnet 3 5 0 ⬜ not fixed
    G7 discover/analytics/learn/parser 1 4 2 ⬜ not fixed
    G8 TOML filters + tests 0 3 1 ⬜ not fixed

    CRITICALs still open (G3–G8 — need fix branches)

    • G4 — curl -K=file deny-list bypass (attached-value form); wget gate misses -O/-i/--load-cookies entirely.
    • G6 — _JAVA_OPTIONS missing from JVM env strip; dotnet binlog/trx parsed with no size cap (OOM); dotnet build success inferred from English text marker (non-zero exit can render ok).
    • G7 — RTK_DISABLED detected by substring over the env-prefix chunk → FOO=RTK_DISABLED=1 git status bypasses the rewriter + gates.

    Two items needing a product/design decision (not auto-fixable)

    1. Defence-in-depth gates not on the live hook path (G1) — tirith_gate/supply_chain_gate fire only on contextcrawler rewrite, not hook claude. Wire them in, or formally document them as opt-in-only.
    2. Telemetry (G3) — maybe_ping() phones home (gated, opt-out works, first-word-only command aggregates, no secrets/argv). Given the local-first posture: keep gated, default-off, or strip from the fork.

    Cross-cutting themes the audit surfaced

    • Env-strip lists are incomplete, not absent — the hardening tests are real spawn-checks; the gaps (_JAVA_OPTIONS, NODE_PATH, CARGO_ENCODED_RUSTFLAGS, GOENV) are simply missing list entries. A single "known dangerous env" registry with a completeness test would prevent recurrence.
    • ANSI-before-matching — multiple filters (cargo, pytest, rspec, rubocop, go/gradle) match failure patterns on un-stripped output; forced colour can hide a failure. Systemic — fix once in the shared filter path.
    • match_output without unless — 8 TOML filters can show a misleading success message (exit code stays honest).
    • branding-lint allowlist is overbroad — real stale rtk strings exempted alongside false positives.

    What's confirmed SOLID

    SQL injection (bound params), secret scrubbing before persist, ReDoS (linear-time regex), filter pipeline has no code-execution, trust gate + permissions fail-closed, 14/17 secure_* env builders airtight, lexer robust, git/gh/glab/cloud command construction uses hardened builders, no reachable panics on most hot paths.

    All 8 groups checked above. G3–G8 fix branches to follow.

  10. added 6 commits that reference this issue on May 20, 2026
  11. 4 remaining items

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions