Skip to content

audit: keep tracing spool, state and log private to the user (nightly security) - #499

Merged
haiyuan-eng-google merged 7 commits into
GoogleCloudPlatform:mainfrom
caohy1988:audit/security-smells-20260928
Sep 28, 2026
Merged

haiyuan-eng-google merged 7 commits into
GoogleCloudPlatform:mainfrom
caohy1988:audit/security-smells-20260928

Conversation

@caohy1988

@caohy1988 caohy1988 commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

Nightly security-smell audit (2026-09-28): insecure temp files and broad permissions in the Claude Code tracing producer.

Smell

bigquery_agent_analytics_tracing, the producer the Claude Code plugin vendors, defaults its spool, state and log to fixed names in the shared /tmp. It creates them with umask-default modes and reuses whatever already exists at those paths. The spool holds whole hook rows (prompts, responses, tool args and results). The drainer uploads every envelope it finds with the user's BigQuery credentials, to the project/dataset/table named inside the envelope.

Tainted input path (a51c39a)

Every hook runs with the defaults: plugins/claude_code/hooks/common.sh:38 execs python -m bigquery_agent_analytics_tracing.claude_code with no dir overrides, and .claude-plugin/marketplace.json serves the vendored copy, which is identical to producers/src.

  • producers/src/bigquery_agent_analytics_tracing/config.py:40-41,47: /tmp/bqaa-agent-tracing/spool, /tmp/bqaa-agent-tracing, /tmp/bqaa-agent-tracing.log, used by config.py:120-122 unless BQAA_* overrides are set.
  • Existing dirs reused with no owner/mode check: mkdir(parents=True, exist_ok=True) at claude_code.py:228, logger.py:107,391, drain.py:173,638.
  • Rows readable by any local user: logger.py:407-409 writes each envelope with write_text (0644 under umask 022) into 0755 dirs; _utils.py:165 appends the log at 0644, and dry-run mode logs whole rows.
  • Planted envelopes uploaded: drain.py:119 lists every event-*.json in the spool, drain.py:158-162 groups by the envelope's own project_id/dataset/table, and drain.py:583-584 writes them with the drainer's credentials.
  • Planted symlinks followed: drain.py:89 opens .drainer.pid with O_CREAT|O_RDWR, then drain.py:97-98 truncates it and writes the PID. claude_code.py:178,187-189 does the same for state_*.json, and logger.py:109 for the pidfile.

Fix

  • The default base is now per user: <tempfile.gettempdir()>/bqaa-agent-tracing-<uid>/, with spool/ and the log inside it.
  • New _utils.ensure_private_dir() creates missing dirs at 0700, parents included. It refuses a dir that is a symlink, owned by another user, world-writable, or under a parent owned by another user. It is used for the spool, state and dead-letter dirs, before the pidfile is opened, and on every drain pass, since the drainer outlives its startup check.
  • Spool envelopes are created 0600 with O_EXCL, and new log files 0600. The default log sits in the state dir and gets the same dir check, so a refused dir never receives the refusal message.
  • The drainer pidfile and state files are opened with O_NOFOLLOW.
  • A refused dir fails closed. Hooks already log and swallow errors (claude_code.main), and the drainer exits 1 without draining.

Compatibility:

  • Explicit BQAA_SPOOL_DIR / BQAA_STATE_DIR get the same checks, so a shared dir such as BQAA_STATE_DIR=/tmp is now refused.
  • An explicit BQAA_LOG_FILE outside the state dir only needs a parent chain owned by root or the user, so /dev/stderr and /var/log/... keep working (tightened in Round 2, below).
  • World-writable parents without the sticky bit stay allowed, because a Kubernetes emptyDir mounted at /tmp is 0777. The private dir inside is still checked on every use.
  • The old /tmp/bqaa-agent-tracing* paths are no longer used. Rows left in the old spool are not drained, and the old dir and log can be deleted.
  • plugins/claude_code_dist picks this up at the next tracing release sync, per its README; this PR does not edit it.

Proof

New producers/tests/test_private_dirs.py, 14 tests:

  • On a51c39a all 14 fail: 0755/0644 modes, DID NOT RAISE, the drainer returns 0 after uploading the planted envelope, and the victim file gets overwritten.
  • With this PR all 14 pass.
  • Mutation checks: dropping the per-pass drainer recheck fails only test_drainer_rechecks_spool_before_every_pass. Requiring sticky world-writable parents fails only test_world_writable_tmp_without_sticky_bit_still_works.

Probe on a51c39a vs this PR. It uses a sandboxed sticky "shared tmp", umask 022, and BigQuery stubbed at _write_batch_insert_rows_json:

a51c39a this PR
state/spool dirs, spooled envelope, dry-run log drwxr-xr-x dirs, -rw-r--r-- files; the prompt is readable by other users drwx------ dirs, -rw------- files
pre-created world-writable spool plus a planted envelope accepted; drain._drain_once writes to attacker-proj.planted.t with the victim's credentials refused (PermissionError); nothing uploaded
.drainer.pid symlink to ~/.bashrc planted in that spool file overwritten with the drainer PID refused; file unchanged. A symlink placed in a private spool (the O_NOFOLLOW layer alone) fails with ELOOP

End to end with the defaults (python -m bigquery_agent_analytics_tracing.claude_code, TMPDIR pointed at a sandbox, dry-run and spool mode): everything lands in $TMPDIR/bqaa-agent-tracing-<uid>/ as 0700 dirs and 0600 files, rc 0, no errors logged.

Checks (macOS, Python 3.13):

  • producers full suite: 558 passed, 4 skipped, 3 failed. The 3 failures fail identically on a51c39a (544 passed there): test_run_setup_check_wrapper_falls_back_when_bqaa_python_unrunnable and two test_token_fill_snippet_* tests. They pin PATH=/usr/bin:/bin:/usr/local/bin and hit the local macOS xcrun python3 shim.
  • In producers/, pyink --check src/ tests/ scripts/ is clean on 25.12.0 and on 26.5.1 (Producers CI does not pin pyink). isort --check-only is clean on 8.0.0 and 9.0.1.
  • The root format dirs are untouched and clean.

Round 2 (bb38ead)

Fixes from review:

  • Checks bound to the objects used. ensure_private_dir() now returns a PrivateDir: the dir opened with O_DIRECTORY|O_NOFOLLOW and checked with fstat (ours, not group- or world-writable). Its physical parents are checked by walking .. from that descriptor. Envelopes, state transactions, the pidfile, dead-letter moves, listing and removal all go through the descriptor (openat/mkdirat/renameat/unlinkat). A path swap after the check, which is possible in a non-sticky 0777 emptyDir /tmp, can no longer redirect them, and emptyDir still works. A StateStore keeps its checked dir for its lifetime, and the drainer re-checks on every pass.
  • Group-writable dirs refused. 0770/0775 spool, state, dead-letter and log dirs are refused like world-writable ones. The drainer uploads only regular envelope files we own; anything else is left in place and logged once.
  • POSIX-only APIs optional. getuid, geteuid, O_NOFOLLOW, the other new open flags and dir_fd support are looked up when used. Without getuid, the default dir uses the getpass login name, never a constant; without the others, the checks degrade to best effort.
  • Explicit log path. Opened with O_NOFOLLOW. It must be a character device or a regular file we own, and in a shared dir it must have no other hard link. An existing log that others can read is fchmoded to 0600, and a log dir of ours must be private. /dev/stdout and /dev/stderr are allowed explicitly.

Compatibility:

  • A group-writable explicit dir is now refused; fix it with chmod g-w.
  • A symlink at the explicit log path is no longer followed.
  • A symlinked ancestor is still followed, as before. The dir finally opened must be ours and private, and everything after goes through its descriptor.

Evidence:

  • 34 new cases in test_private_dirs.py.
    • On a git archive of 8914004 with only the new test file, 30 fail for the reported reasons. Examples: attacker-project uploaded after a post-check swap, the prompt written into the attacker's state file, the PID written into the attacker's pidfile, DID NOT RAISE for 0770/0775, symlinked/foreign/hard-linked/FIFO logs written to, and AttributeError without getuid/geteuid/O_NOFOLLOW.
    • The other 4 are compatibility guards: /dev/stderr, a terminal, no dir_fd support, and hard links in our own dir.
    • All 48 pass at bb38ead.
  • The reviewer's probe scripts at bb38ead:
    • The group-writable spool is refused.
    • The post-check swap drains nothing, and the attacker's state file stays {}.
    • The log symlink is not followed, and the existing log becomes 0600.
    • The missing-API probes import and write fine.
    • The compatibility probes are unchanged: hook rc 0 and drainer rc 1 on refusal, /dev/stderr works, and umask 000/022/077 all give 0700/0600.
  • 13 mutations each disable one protection, including fd binding, the .. walk, the owner/type checks, the device and stream allowances, and the POSIX guards. Each makes at least one test fail.
  • producers suite (macOS, Python 3.13): 592 passed, 4 skipped, and the same 3 xcrun-only failures as at 8914004 (558 passed there).
  • The affected modules also pass on Python 3.10, 3.11, 3.12 and 3.14.0a6. Those runs caught that some versions do not list os.lstat in os.supports_dir_fd, so the capability check no longer requires it.
  • pyink 25.12/26.5 and isort 8/9 are clean, and so is git diff --check.

Not verified:

  • Native Windows: the pre-existing fcntl import still blocks it.
  • A real second UID: other owners are simulated with stat fakes.
  • Live BigQuery.

Round 3 (5da9145)

Fix from review:

  • Explicit log opened relative to its checked dir. At bb38ead, a log dir that already existed was checked by path, and then the log was reopened by its full path. Another user who can rename that dir (for example in a non-sticky 0777 emptyDir parent) could swap in a symlink to their own dir right after the check. The append then went to a hard link to one of our files there, and the stale "not shared" verdict skipped the hard-link refusal.
  • The dir is now opened once, and every check runs on that descriptor: its owner (root or us), privacy if it is ours, and its physical parents (the .. walk). The log name is opened relative to it with O_NOFOLLOW, and the shared/private verdict behind the hard-link refusal comes from the same fstat.

Compatibility:

  • Symlinks leading to the log dir are still followed (/tmp is one on macOS). The dir actually opened is what gets checked.
  • Unchanged: /dev/stderr, /dev/null, terminals, 0600 tightening of an existing own log, the per-user default dir, and the path-based fallback without dir_fd support.
  • New narrowing: an explicit log dir we can write to but not list (e.g. mode 0300 or 1733) is now refused, because its descriptor is opened for reading.

Evidence:

  • test_explicit_log_stays_in_the_dir_checked_before_a_swap uses the reviewer's probe shape. On a git archive of bb38ead it fails, because our file behind the hard link gets the line. It passes here. The reviewer's probe flips the same way.
  • Three guard cases pass at both commits: a log dir owned by another user is refused, a log dir whose parent is owned by another user is refused, and a log dir reached through a symlink still works.
  • 7 mutations of the new code each make at least one test fail: open by path, no owner check, no .. walk, O_NOFOLLOW on the dir, no privacy check, always shared, never shared.
  • producers suite (macOS, Python 3.13): 596 passed, 4 skipped, and the same 3 xcrun-only failures (592 passed at bb38ead). The affected test files also pass on Python 3.10, 3.11, 3.12 and 3.14.0a6.
  • pyink 25.12/26.5 and isort 8/9 are clean, and so is git diff --check.

Not verified in Round 3: the same limits as above. The new code path on Linux is covered only by CI.

Round 4 (1914dc1)

Fix from review:

  • Explicit-log dir opened search-only. Round 3 opened it with O_RDONLY, which needs read permission on the dir, although looking the log up by name needs only search permission. A private log dir of ours that we can write and search but not list (0300, or 0100 with the log already there) therefore dropped every log line silently; bb38ead appended there. The handle is now O_SEARCH (macOS), else O_PATH (Linux), else O_RDONLY. Every Round 3 check still runs on it (fstat for owner and privacy, the .. walk, the relative O_NOFOLLOW open), so Round 3's "new narrowing" is lifted.
  • Symlinks leading to the dir are still followed, so the dir open has no O_NOFOLLOW. With it, an explicit /tmp/<name>.log on macOS (where /tmp is a symlink) is dropped and test_explicit_log_in_a_symlinked_dir_still_works fails.

Evidence:

  • test_explicit_log_in_a_dir_we_can_search_but_not_list_still_works (0300 and 0100; the reviewer's probe shape, real uid, no owner fakes): both cases fail on a git archive of 5da9145 and pass here and on bb38ead. test_explicit_log_without_search_only_open_flags_still_works covers platforms with neither flag. The Round 3 parent-swap test still passes.
  • Linux (Docker, kernel 6.8, uid 1000, Python 3.10 and 3.12, O_PATH): test_private_dirs.py and test_drain.py pass; on the 5da9145 tree only the two new cases fail. OS probes on macOS and Linux: O_RDONLY gets EACCES on a 0300 dir, and the search-only handle allows fstat, fstatat("..") and the relative append.
  • 4 mutations each fail the intended test: back to O_RDONLY, O_NOFOLLOW on the dir, no getattr guard, open by full path.
  • producers suite (macOS, Python 3.13): 599 passed, 4 skipped, and the same 3 xcrun-only failures (596 passed at 5da9145). The affected test files also pass on Python 3.10, 3.11, 3.12 and 3.14.0a6. pyink 25.12/26.5, isort 8/9 and git diff --check are clean.

Not verified in Round 4: a root-owned write-only dir such as 1733 (tests cannot chown), BSDs, and macOS releases older than this Mac's; plus the limits above.

… security)

The Claude Code tracing producer defaulted its spool, state and log to
fixed names in the shared /tmp (/tmp/bqaa-agent-tracing/{,spool/} and
/tmp/bqaa-agent-tracing.log), created them with umask-default modes and
reused whatever was already there. Any local user could therefore read
spooled prompts, responses and tool I/O (0644 files in 0755 dirs, plus
the dry-run log), pre-create the dir to plant envelopes that the
drainer uploads to a project of their choosing with the victim's
BigQuery credentials, or plant a .drainer.pid / state_*.json symlink
that the drainer and hooks follow, truncating and overwriting a file
such as ~/.bashrc.

- Default to a per-user dir, <tempdir>/bqaa-agent-tracing-<uid>/, with
  the spool and log inside it.
- ensure_private_dir(): create dirs 0700 (parents too), and refuse a
  dir that is a symlink, owned by another user or world-writable, or
  that sits under a parent owned by another user. Used for the spool,
  state and dead-letter dirs, before the drainer's pidfile, and on
  every drain pass since the drainer outlives its startup check.
- Spool envelopes are created 0600 with O_EXCL; new log files 0600.
  The default log (in the state dir) gets the same dir check, so a
  refused dir never receives the refusal message.
- Open the drainer pidfile and state files with O_NOFOLLOW.

World-writable parents without the sticky bit stay allowed, since
Kubernetes emptyDir /tmp is 0777; the private dir inside is still
verified on every use. plugins/claude_code_dist picks this up at the
next tracing release sync, per its README.

Tests: producers/tests/test_private_dirs.py (14 tests) fail on
a51c39a and pass with this change; full producers suite 558 passed,
4 skipped, and the same 3 macOS-only xcrun failures as on baseline.

@caohy1988 caohy1988 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.

Independent blind review on caohy1988's behalf, of head 8914004cf9dc6bbefae99b5810bde486d6dadec4 against a51c39a2dfaa6d863a0e16597f7b1b191b86effb. No peer reviews/comments, vault contents, or peer result artifacts were read. No branch modifications, pushes, or merges.

Rejection criteria, recorded before reading the diff:

  1. Any attacker-controlled path can still redirect or expose spool, state, logs, or pidfiles despite the promised protections.
  2. Legitimate overrides, upgrades, Kubernetes /tmp, hooks, draining, or non-POSIX use regress.
  3. The baseline proof, tests, format checks, or scope fail to support the claimed fix.

The baseline smell and the ordinary-path improvement are verified, but criteria 1 and 2 are met. The added checks do not establish a durable filesystem security boundary, and the newly unconditional POSIX API references violate the explicit portability contract.

What I tried and verified:

  • Read the PR description, sole commit message, complete base-to-head diff, changed modules and surrounding code, every shell wrapper under plugins/claude_code/hooks/, call sites found with rg, and plugin distribution/build behavior. Exactly the six specified producers/ files changed; #496/#497 files are untouched. git diff --check passes.
  • Python 3.13.5: python -m pytest tests/test_private_dirs.py --tb=short -q -p no:cacheprovider: 14 passed at head. Exported the baseline with git archive, copied in only the new test file: 14 failed. Failures include 0755/0644 modes, missing refusals, unsafe spool accepted by the drainer, and the symlink victim being modified. This independently confirms the tainted-input/before-and-after proof.
  • python -m pytest --tb=short -q -p no:cacheprovider: head 558 passed, 4 skipped, 3 failed. Baseline without the new tests: 544 passed, 4 skipped, the identical 3 failed. Failures are test_run_setup_check_wrapper_falls_back_when_bqaa_python_unrunnable and the two test_token_fill_snippet_* tests; these exercise the macOS system-Python/xcrun path (the latter emit the arm64/x86_64 libxcrun architecture error). They are not introduced here.
  • pyink --check src/ tests/ scripts/ (25.12.0, 66 files) and isort --check-only src/ tests/ scripts/ (8.0.0): pass.
  • Repeated the two claimed mutations in scratch copies: removing the per-pass drainer check gives 1 failed, 13 passed, solely test_drainer_rechecks_spool_before_every_pass; requiring sticky world-writable ancestors gives 1 failed, 13 passed, solely test_world_writable_tmp_without_sticky_bit_still_works.
  • Relative spool/state/log paths with umasks 000, 022, and 077 create 0700 directories and 0600 envelopes/state/log files. Benign explicit legacy-layout overrides work. With sandbox TMPDIR, defaults create a new per-user tree and leave pre-existing legacy-named spool/log files untouched; old rows are not migrated, as disclosed in the PR.
  • Foreground hook → spool → drainer probe: hook rc 0, envelope 0600, one row drained to the intended project. Spawn and BigQuery upload were stubbed. Unsafe-directory hook rc 0, drainer rc 1, a safe override log contains Refusing BQAA tracing dir, and the unsafe directory stays empty. /dev/stderr works. Preplanted envelope-temp and producer pidfile symlinks are refused with their targets unchanged.
  • Tried group-writable directories, swapping an ancestor after validation, writing state after a directory swap, symlinked log overrides, existing readable logs, and missing getuid, geteuid, and O_NOFOLLOW. Findings below. These are isolated local probes with synthetic content and stubbed uploads. Race scheduling and attacker placement were simulated under the reviewing UID; no cross-UID or native Windows runtime was used.

P0: none found.

P1 — Bind directory validation to the objects actually used; a per-pass path check is still racy.

Locations: _utils.py:149-155, _utils.py:178-188, drain.py:609-615, and claude_code.py:175-179.

The intentionally supported 0777 non-sticky parent lets another user rename the victim's entire 0700 base directory: rename permission is determined by the parent. After ensure_private_dir() returns a Path, all subsequent glob/read/open operations resolve that pathname again. An ancestor can be replaced with a symlink between check and use. O_NOFOLLOW on a state/pidfile protects only its final component, not these ancestors. StateStore additionally keeps using the pathname after constructor-time checks, making its exposure much longer than a single syscall window.

Deterministic probe: create emptydir mode 0777 with a genuine private private-user/spool; prepare a replacement tree containing event-planted.json addressed to attacker-project.planted.t; wrap drain.ensure_private_dir so it calls the real check, renames private-user aside, links that name to the replacement tree, and returns the already checked path. _drain_once(..., False) then reports:

swap_after_check {"drained": 1, "parent_mode": "0o777", "uploads": ["attacker-project"]}

A second probe constructs StateStore, swaps its base directory, and supplies a writable regular state_session.json in the replacement. store.set('current_prompt', 'synthetic-secret') writes into that replacement despite O_NOFOLLOW:

state_after_swap {"attacker_file": {"current_prompt": "synthetic-secret"}, "mode": "0o666"}

Suggested fix: retain a safely opened and fstat-validated directory descriptor, and perform creation, enumeration/reads, replacement, and removal relative to that trusted descriptor, including state transactions and pidfiles. Securely acquire/validate the directory chain. Keep the promised emptyDir support; simply banning all 0777 parents would fail another explicit requirement. Add a deterministic post-validation ancestor-swap regression, not only a symlink present before validation.

P1 — A group-writable spool passes the new “private” check and can still inject uploads.

Location: _utils.py:182-188, consumed at drain.py:609-615.

Only S_IWOTH is rejected. A directory owned by the victim with mode 0770 and a group containing other users is accepted unchanged. A group member can plant an envelope without any race; the drainer never checks the envelope's owner before trusting its destination. I chmod'ed the spool to 0770 and planted the same envelope used for the race probe:

group_writable_spool {"drained": 1, "mode": "0o770", "uploads": ["attacker-project"]}

This is the original credential-bearing planted-envelope path through a class of existing overrides that the new validator accepts. Suggested fix: reject group-writable spool/state/dead-letter directories (and account for group-writable ancestors in the secure traversal). Test 0770/0775 cases and enforce the intended owner-only invariant; checking directory ownership alone does not make its contents trustworthy.

P1 — Newly unconditional Unix APIs fail import or first write when the APIs are absent.

Locations: config.py:44-46, _utils.py:148, _utils.py:178, claude_code.py:179, logger.py:108, and drain.py:90.

Run from the repository root:

PYTHONPATH=producers/src python3 -c 'import os; del os.getuid; import bigquery_agent_analytics_tracing'

Head: AttributeError: module 'os' has no attribute 'getuid' at config.py:45, before environment overrides or hook error handling can help. The identical capability-removal probe imports successfully against baseline source. After normal import, deleting os.geteuid, or independently deleting os.O_NOFOLLOW, and invoking StateStore('s', root=<fresh temp dir>).set('x', 1) raises the respective AttributeError at head; both writes succeed against baseline.

These are capability simulations, not a claim that baseline fully supported Windows: its unconditional fcntl imports are pre-existing. Nevertheless this PR adds three unguarded dependencies and does not meet the requested no-import/first-write-crash contract. Suggested fix: use platform-aware per-user storage and permission/open/locking handling, with tests for absent APIs and a native Windows check. Preserve the POSIX security guarantees rather than substituting a shared constant user ID or silently discarding protection.

P2 — An explicit log override in a shared directory still follows a planted symlink and preserves readable existing modes.

Location: _utils.py:220-227.

The external-log branch checks ancestor owners, then opens the leaf without O_NOFOLLOW or an owner/mode check on the opened file. A root-owned sticky /tmp therefore passes. For a legitimate fixed-name override such as the old /tmp/bqaa-agent-tracing.log, another user can pre-create that name as a symlink to their writable file. My isolated sticky-directory probe logged the synthetic prompt into the symlink target:

shared_log_symlink {"followed_symlink": true, "mode": "0o666"}
existing_log {"contains_prompt": true, "dir_mode": "0o755", "log_mode": "0o644"}

The second line is a separate legacy-layout override with an existing 0644 log: os.open(..., 0600) does not tighten an existing inode. This is a remaining vulnerability in explicitly overridden paths, not a claim that a fresh default log has mode 0644. Suggested fix: safely open and validate regular log files, reject foreign/symlink targets, and define handling of existing readable logs. Preserve intentional device sinks such as /dev/stderr through an explicit supported path, and test both cases.

The reproducible adversarial probes are saved locally in /tmp/bqaa-pr499-astra-review.gMVgSt/probes.py; command run from the head worktree:

PYTHONPATH=producers/src /usr/local/opt/python@3.13/bin/python3.13 /tmp/bqaa-pr499-astra-review.gMVgSt/probes.py

CI assessment:

gh pr checks 499 --repo GoogleCloudPlatform/BigQuery-Agent-Analytics-SDK reports all five Producers Python jobs, Producers format/build, and the other executed checks passing except Hash-lock drift check. I read that job's failed log. Regeneration changes dependency versions in all three locks, e.g. build 1.5.0 → 1.6.1, hatchling 1.31.0 → 1.32.4, google-cloud-bigquery 3.43.0 → 3.45.2, and command-header text. Base-to-head diff is empty for producers/pyproject.toml, producers/build-requirements.lock, deploy/otlp_receiver/, and .github/workflows/producers-ci.yml. These unchanged inputs feed regeneration (deploy/otlp_receiver/regen-locks.sh:60-63,93-99); this is external dependency/generator drift, not caused by the six source/test changes. I did not rerun the Docker lock generator locally, and this CI failure is not the basis for the verdict.

Not verified: native Windows execution, a real second local UID, or live BigQuery upload. No production services were called by the probes. The marketplace's existing vendored release remains unchanged until the separately documented release sync.

VERDICT: REQUEST_CHANGES @ 8914004

@caohy1988 caohy1988 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.

Blind review of PR #499 (head 8914004) on behalf of caohy1988. No changes made to the branch.

Rejection criteria (from the task contract, written before reading the diff)

  • RC1 — Tainted path real and closed: the default spool/state/log must no longer be fixed shared-/tmp names that another local user can pre-create, read, or plant envelopes/symlinks into; pidfile/state files must not be opened through symlinks.
  • RC2 — No legitimate-use break: explicit env/config overrides still work; upgrade from the old path is sane; K8s emptyDir 0777 /tmp works; no new import/first-write crash on non-POSIX; drainer and hooks keep working (hook rc 0, drainer rc 1 on refusal).
  • RC3 — Proof and scope: new tests fail on baseline a51c39a and pass on head; format checks pass; producers/ only; files of #496/#497 untouched.

What I tried (all in a worktree detached at the PR head; baseline via scratch copies)

  • Read the full diff plus callers: plugins/claude_code/hooks/common.sh:38 (no dir overrides, confirms tainted entry), claude_code.main (catches Exception, rc 0), drain.main (catches Exception, rc 1), _quarantine, _list_pending, _read_envelope, file_lock (no callers — dead code, untouched, fine).
  • producers: new tests 14/14 pass; full suite 556 passed, 4 skipped, 5 failed. All 5 failures reproduce identically on baseline (verified in a full git archive baseline tree): 2 test_build_claude_plugin + 2 test_token_fill_snippet hit the local macOS xcrun arch shim, 1 test_otlp_verify gets 502 via local proxy instead of 0. None are PR-caused. (PR body says 3 fail on the author's Mac; the extra 2 here are this machine's environment, failing on baseline too.)
  • New tests against baseline sources: 14/14 fail (mode assertions, DID NOT RAISE, drainer rc 0 + upload, victim overwrite) — the "fails before" claim holds.
  • Mutation check in a scratch copy: reverting the per-pass ensure_private_dir in _drain_once fails exactly test_drainer_rechecks_spool_before_every_pass — matches the PR's sensitivity claim.
  • isort --check-only and pyink --check on src/ tests/ scripts/: clean.
  • Breakage probes (throwaway script, all behaved): relative spool path works; BQAA_STATE_DIR=/tmp refused; old /tmp/bqaa-agent-tracing* unreferenced; umask 000 and 077 still yield 0700 dirs / 0600 files; BQAA_LOG_FILE=/dev/stderr works; corrupt envelope quarantined into 0700 dead-letter/; nested missing parents created 0700; hook e2e under sandboxed TMPDIR lands in per-uid base rc 0; refused hook rc 0 with zero writes; refused drainer rc 1 with zero uploads; concurrent ensure_private_dir from 2 procs, no crash; refusal IS logged when a separate valid log file is configured; BQAA_STATE_DIR="" behaves as before (no crash).
  • CI (gh pr checks 499): everything passes (Producers tests 3.10–3.14, both format checks, build, receiver self-test, root suite) except Hash-lock drift check, whose log shows only upstream PyPI version drift (build 1.5.0→1.6.1, hatchling, trove-classifiers, …). This PR touches no lock inputs, so that failure is not PR-caused.
  • Scope: diff touches only producers/src/bigquery_agent_analytics_tracing/{_utils,claude_code,config,drain,logger}.py + producers/tests/test_private_dirs.py. No system_evaluator.py, browser_smoke.sh, or test_looker_studio_dashboard.py. No stale /tmp/bqaa refs outside plugins/claude_code_dist (release-synced, disclosed in the PR).
  • Non-POSIX: baseline _utils.py already imports fcntl unconditionally and package __init__ imports logger, so the package never imported on Windows before or after — os.getuid() in config.py adds no new crash surface. CI is ubuntu-only.

Findings

P2 — Group-writable pre-existing dirs are accepted

producers/src/bigquery_agent_analytics_tracing/_utils.py:184 refuses only S_IWOTH. A pre-existing 0770 dir owned by the user is accepted (probe-confirmed), so group members could list spool names or plant envelopes that drain with the victim's credentials. The default path cannot be pre-created this way by an attacker (they cannot make victim-uid dirs), so this needs an explicit override or user action — hardening, not a hole in the claimed fix. Suggested fix: also refuse S_IWGRP, e.g. elif info.st_mode & (stat.S_IWOTH | stat.S_IWGRP):.

P2 — Explicit BQAA_LOG_FILE is opened through symlinks

producers/src/bigquery_agent_analytics_tracing/_utils.py:225 uses os.open without O_NOFOLLOW, so a pre-planted symlink at an explicitly configured log path is followed (probe-confirmed: victim file got the log line appended). The default log is unaffected (it sits in the private state dir). Note a blanket O_NOFOLLOW would break the supported /dev/stderr case (/dev/stderr is itself a symlink), so the fix needs a carve-out, e.g. lstat first and only refuse symlinks whose target is not a character device, or document that explicit log paths in shared dirs are the operator's responsibility.

P2 — Residual check-then-use window on non-sticky world-writable parents

ensure_private_dir (_utils.py:159-189) plus the per-pass recheck (drain.py:607-609) narrow but cannot close the rename-swap window when the parent is world-writable without the sticky bit (the deliberately allowed K8s emptyDir case): an attacker with write access to the parent can swap the verified dir between check and use, or mid-pass after the recheck. Closing it needs dirfd-relative opens (openat + O_DIRECTORY) instead of path checks. The PR documents the tradeoff; recording it as accepted residual risk.

P2 — Refusal is fully silent for default-log users

When the default state dir is refused, the hook returns rc 0 with no stderr and the refusal message is swallowed (claude_code.py:694-698, _utils.py:228) — by design, but it means an attacker pre-creating /tmp/bqaa-agent-tracing-<uid>, or a root-created base dir, disables victim tracing with zero signal. Fail-closed, so not a security hole; consider a last-resort stderr note on refusal (hooks already return 0, so a stderr line would not break the host agent).

P2 (cosmetic) — Refusal message is confusing when the path is a symlink

_utils.py:180-181 reports /tmp on macOS as "a symlink or not a directory" (lstat-based; on Linux the same case reads "writable by other users"). Accurate but likely to confuse. Optional: distinguish the symlink case in the message.

Against the rejection criteria

  • RC1: satisfied. Per-user 0700 base, refusal of symlinked/foreign-owned/world-writable dirs, 0600 envelopes with O_EXCL, 0600 logs, O_NOFOLLOW pidfile/state — all verified by the 14 fail-before/pass-after tests plus independent probes. The P2s above need an explicit override, group membership, or a race win; none reopen the claimed fixed-shared-/tmp path.
  • RC2: satisfied. Overrides (relative paths, separate log, /dev/stderr), old-path abandonment, emptyDir 0777, non-POSIX parity, and drainer/hook behavior all probed green.
  • RC3: satisfied. 14 fail on baseline / 14 pass on head, mutation-sensitive, format clean, producers-only scope, no #496/#497 files.

VERDICT: APPROVE @ 8914004

…iptors; reject group-writable; guard POSIX-only APIs

Round 2 of the PR GoogleCloudPlatform#499 review.

- ensure_private_dir() now returns a PrivateDir: the directory opened
  with O_DIRECTORY|O_NOFOLLOW and checked with fstat (a dir we own,
  neither group- nor world-writable), whose physical parents, walked
  via ".." from the descriptor, belong to root or us. Envelopes, state
  transactions, the pidfile, dead-letter moves, listing and removal all
  go through that descriptor (openat, mkdirat, renameat, unlinkat), so
  swapping a path component after the check, which another user can do
  in a non-sticky 0777 parent such as a Kubernetes emptyDir /tmp, no
  longer redirects anything. A StateStore keeps its checked dir for its
  lifetime; the drainer re-checks on every pass.
- Group-writable dirs are refused like world-writable ones. The drainer
  uploads only envelopes that are regular files we own; anything else
  is left in place and logged once.
- An explicit log path is opened with O_NOFOLLOW and must be a
  character device or a regular file we own (in a shared dir, with no
  other hard link); an existing one readable by others is fchmod'ed to
  0600, and a dir of ours holding it must be private. /dev/stdout and
  /dev/stderr stay supported explicitly.
- os.getuid, os.geteuid, O_NOFOLLOW and the other POSIX-only flags and
  dir_fd calls are looked up when used. Without getuid the default dir
  is named after the login name (getpass), never a constant; without
  geteuid or dir_fd support the checks degrade to best effort.

Tests: 34 new cases in producers/tests/test_private_dirs.py. 30 fail at
8914004 (git archive of 8914004 plus the new test file); the other 4
guard compatibility (/dev/stderr, a terminal, no dir_fd support, hard
links in a dir of ours). All 48 pass here. test_drain.py's helper tests
follow the new signatures. Full producers suite: 592 passed, 4 skipped,
and the same 3 macOS-only xcrun failures as at 8914004 (558 passed).

@caohy1988 caohy1988 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.

Blind Astra review of the full a51c39a2dfaa6d863a0e16597f7b1b191b86effb..bb38ead3ce5b6bc46224b8451ad768db53d3a31c diff, with the round-2 delta reviewed as 8914004..bb38ead (the supplied head-to-head diff is empty). No peer reviews/comments, prior-review files, or vault contents were read. The branch was not modified.

Rejection criteria, established before reading the diff

  1. A directory/file substitution redirects tracing reads or writes, or exposes spool, state, or log data to another user.
  2. Supported overrides, hooks, or platform fallbacks fail under the stated compatibility contract.
  3. Baseline proof, regression tests, or required checks fail to substantiate the claimed fix; distinguish pre-existing/environment failures from PR regressions.

P1 — Existing explicit log parents are still checked by path, then reopened by path

At producers/src/bigquery_agent_analytics_tracing/_utils.py:437–442, the override branch checks the parent and calculates shared, but _open_nofollow(path, ...) subsequently resolves the entire path again. O_NOFOLLOW protects only the final component. The hard-link check at line 450 then uses the old parent's shared=False decision.

With BQAA_LOG_FILE=<non-sticky 0777 parent>/logs/bqaa.log outside the state directory, another local user able to rename logs can replace it with an ancestor symlink after validation. If the replacement tree contains a hard link to a victim-owned file, the file passes the ownership/type check and receives the append. This is relevant on systems permitting the attacker to create that hard link; a writable victim file also provides such a target on systems with protected-hardlink restrictions. My deterministic macOS probe appended SECRET_AFTER_SWAP to a separate victim.bashrc with two links. A reader opened while it was 0644 also received the secret despite the subsequent chmod. The probe schedules the rename in one process, as the PR's race tests do; it is not a real-second-UID run.

Command from the repository root:

PYTHONPATH=producers/src /tmp/astra499r2-evidence.49IbJ2/venv313/bin/python -m pytest /tmp/astra499r2-evidence.49IbJ2/test_independent.py -k explicit_log_parent_swap -q -s --tb=short

Observed output (timestamp omitted):

swapped= True victim= 'KEEP\n[...] SECRET_AFTER_SWAP\n' nlink= 2 prior_reader= 'KEEP\n[...] SECRET_AFTER_SWAP\n'
AssertionError: ... != 'KEEP\n'
1 failed, 5 deselected

Reproducer (save as a pytest file):

import asyncio
import json
import os
from pathlib import Path
import stat

import pytest
from bigquery_agent_analytics_tracing import _utils, claude_code, drain, logger
from bigquery_agent_analytics_tracing.config import BQAAConfig


def config(root):
    return BQAAConfig('p', 'd', state_dir=str(root / 'state'), spool_dir=str(root / 'spool'), log_file=str(root / 'state' / 'log'))


def test_explicit_log_parent_swap_cannot_append_to_hardlinked_victim(tmp_path, monkeypatch):
    shared = tmp_path / 'emptydir'
    shared.mkdir(mode=0o777)
    shared.chmod(0o777)
    logs = shared / 'logs'
    logs.mkdir(mode=0o700)
    attacker = tmp_path / 'attacker'
    attacker.mkdir()
    victim = tmp_path / 'victim.bashrc'
    victim.write_text('KEEP\n')
    victim.chmod(0o644)
    os.link(victim, attacker / 'bqaa.log')
    prior_reader = victim.open()  # A 0644 file can be opened before fchmod.
    cfg = config(tmp_path)
    cfg.log_file = str(logs / 'bqaa.log')
    real = _utils._check_dir
    swaps = []
    def check_then_swap(info, path):
        real(info, path)
        if path == logs and not swaps:
            logs.rename(shared / 'logs.saved')
            logs.symlink_to(attacker, target_is_directory=True)
            swaps.append(True)
    monkeypatch.setattr(_utils, '_check_dir', check_then_swap)
    _utils.log_to_file(cfg, 'SECRET_AFTER_SWAP')
    print('swapped=', bool(swaps), 'victim=', repr(victim.read_text()), 'nlink=', victim.stat().st_nlink, 'prior_reader=', repr(prior_reader.read()))
    prior_reader.close()
    assert victim.read_text() == 'KEEP\n'

Suggested fix: open and retain the existing explicit-log parent descriptor, validate that actual directory and its physical ancestry, derive the shared/private classification from its fstat, and open the basename relative to that descriptor. Preserve the explicit standard-stream/device allowances and legitimate hard links inside a checked private directory. Add the post-validation override-parent swap above to the regression tests. This meets rejection criterion 1; the spool/state descriptor work does not cover this branch.

Verification and attempted disproof

  • Read the PR description, full diff, round-2 source delta, hook wrappers, and surrounding callers found with repository-wide rg. Only the seven permitted producers/ files changed; none of the excluded PR #496/#497 files changed.
  • The baseline smell is substantiated: baseline config.py:40–47 uses fixed /tmp names, logger.py:407–409 writes envelopes with default permissions, and drain.py:119,158–162 reads and trusts their destinations. In archived baseline runs, the new tests expose 0755 directories, 0644 logs, accepted unsafe spools, symlink writes, and uploads to attacker-project.
  • At this head, cd producers && python -m pytest tests/test_private_dirs.py tests/test_drain.py --tb=short -q: 59 passed, including all 48 privacy cases. Those cover post-check spool/state/pidfile swaps, group/world-write refusal, foreign owners, symlinked envelopes, explicit-log symlinks/foreign files/hard links/FIFOs, /dev/stderr, a terminal, and individually missing POSIX APIs / dir_fd support.
  • The current privacy file copied into separate git archive trees: 45 failed / 3 passed on a51c39a; 30 failed / 18 passed on 8914004. Thus the claimed 30 round-2 failures reproduce. The terminal compatibility test initially caused SIGHUP in the old code; the completed comparison runs ignored SIGHUP in the pytest process. No source files in this worktree were swapped.
  • Independent probes: relative spool/state/log overrides under umask 000/022/077 produced 0700 directories and 0600 files and drained correctly; state tool transactions/removal stayed on the original directory after replacement; dead-letter rename stayed on its checked directory. Five cases passed; the explicit-log swap case above failed.
  • Actual shell hook wrappers with isolated TMPDIR: SessionStart/UserPromptSubmit returned 0 and used the per-user directory despite a pre-existing legacy-name tree and log symlink. Those old artifacts stayed unchanged. For both 0770 and 0777 refusal inputs, the hook returned 0, drainer 1, the safe diagnostic log contained Refusing BQAA tracing dir, and the unsafe directory stayed empty.
  • Full producer suite, Python 3.13.5: 592 passed, 4 skipped, 3 failed. An archived unmodified baseline suite reproduced the same three failures, with 544 passed, 4 skipped: test_run_setup_check_wrapper_falls_back_when_bqaa_python_unrunnable and both test_token_fill_snippet_* cases. These are the local x86_64/arm64 xcrun Python-shim problem, not a PR regression. Test environment installed [dev,receiver]; local wheel availability required cryptography<50 (resolved 48.0.1).
  • pyink --check src/ tests/ scripts/ (26.5.1), isort --check-only src/ tests/ scripts/ (9.0.1), and git diff --check a51c39a bb38ead passed. Final worktree status is clean at the requested SHA.

CI conclusion

gh pr checks 499 reports the producer Python 3.10–3.14 matrix, format, build, receiver self-test, and root tests passing. The only failure is Hash-lock drift check, job 108920332929. I read its failed log: regeneration updates, among others, build 1.5.0 → 1.6.1, hatchling 1.31.0 → 1.32.4, and pip-tools 7.6.0 → 7.6.1, then fails the checked-in-lock diff. git diff a51c39a bb38ead -- deploy/otlp_receiver producers/build-requirements.lock producers/pyproject.toml .github/workflows/producers-ci.yml is empty. This is dependency-resolution drift in unchanged inputs, not caused by this PR, and is not the basis for the verdict.

Limits

No live BigQuery, native Windows, or actual second UID was used. The missing-API tests pass, but they do not prove native Windows importability: unconditional fcntl imports already exist on baseline (_utils.py:25, logger.py:33, claude_code.py:50, drain.py:50 at this head). The PR acknowledges that pre-existing limitation; this review does not certify the broader native-Windows contract or independently verify all 13 claimed mutations. No P0 or additional P2 finding is raised.

VERDICT: REQUEST_CHANGES @ bb38ead

@caohy1988 caohy1988 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.

Blind review of PR #499 ROUND 2 (head bb38ead, base a51c39a) on behalf of caohy1988. No changes made to the branch. I also re-read only my own round-1 review (id 5337752547) to check closure of my round-1 findings; everything below was re-derived at the new head.

Rejection criteria (from the task contract, written before reading the diff)

  • RC1 — Tainted path real and closed: default spool/state/log are per-user 0700 (no fixed shared-/tmp names others can pre-create/read/plant into); symlinked, foreign-owned, and group- or world-writable dirs refused; envelopes 0600 O_EXCL; pidfile/state never opened through symlinks; round-2 extras hold — validation bound to an opened fd for create/enumerate/read/replace/remove, envelopes vetted for owner + regular-file type, explicit log refuses symlink/foreign/non-regular/hard-linked targets while /dev/stderr-style character devices work, POSIX-only APIs guarded with a per-user (never shared-constant) fallback.
  • RC2 — No legitimate-use break: explicit env/config overrides still work; upgrade from the old path is sane; K8s emptyDir 0777 /tmp works; no new import/first-write crash without POSIX APIs; drainer and hooks keep working (hook rc 0, drainer rc 1 on refusal).
  • RC3 — Proof and scope: new tests fail on baseline a51c39a (and the new round-2 tests fail on round-1 8914004) and pass on head; tests are sensitive to the protections (mutations break them); format checks pass; producers/ only; files of #496/#497 untouched.

What I tried (worktree detached at bb38ead; baselines via scratch git archive trees, never this worktree)

  • Full diff base..head plus round-2 diff 8914004..bb38ead; read _utils.py (PrivateDir/ensure_private_dir/_open_log), claude_code.py (StateStore/_LockedJSONStore/cleanup), drain.py (pidfile/list/read/quarantine/drain_once), config.py (_user_tag), logger.py (spool/ensure_drainer); enumerated callers repo-wide — changed helpers are used only inside the tracing producer + its tests; plugins/claude_code/hooks/common.sh:38 still execs hooks with no dir overrides (tainted entry as described); vendored plugins/claude_code_dist copy untouched as disclosed.
  • New tests at head: 47/48 pass; the single failure is test_log_to_a_terminal_device_still_works, which fails at os.openpty() in test setup with PermissionError because this sandbox denies pty allocation — before any PR code runs. CI Producers tests pass on 3.10–3.14, so this is environmental, not a code failure.
  • Full producers suite at head: 589 passed, 4 skipped, 6 failed. The 6 are: the sandbox pty test above plus 5 failures that reproduce identically on a pristine a51c39a tree (2 test_build_claude_plugin + 2 test_token_fill_snippet hit the local macOS xcrun arch shim; 1 test_otlp_verify gets a proxy response instead of status 0). None are PR-caused.
  • New tests against baseline a51c39a sources: 46 fail, 2 pass — the 2 passes are pure compatibility guards (test_hard_linked_log_in_a_dir_of_ours_still_works, test_log_to_dev_stderr_still_works). Every security assertion fails before the fix.
  • New (round-2) tests against round-1 8914004 sources: 31 fail, 17 pass. Minus the 1 sandbox-pty failure, that is exactly the PR's claimed 30 fail / 18 pass (14 round-1 tests + 4 compat guards: /dev/stderr, terminal, dir_fd param, own-dir hard link). The round-2 fail-before claim holds.
  • Mutation spot-checks (scratch copies): dropping _check_own_file from PrivateDir.open fails test_drainer_skips_envelope_owned_by_another_user; dropping _require_trusted_parents fails test_spool_refuses_dir_under_parent_owned_by_another_user; forcing path-based (fd-less) PrivateDir fails all 4 swap tests. The tests genuinely guard the new mechanisms.
  • isort --check-only, pyink --check on producers/src/ tests/ scripts/: clean. git diff --check base..head: clean.
  • Break probes (throwaway scripts under /tmp, all green unless noted): 0770 spool refused with clear message; symlinked ancestor followed and private real dir used; umask 000/077 still yield 0700/0600; relative spool works; pre-existing old /tmp/bqaa-agent-tracing ignored while new per-uid dir used; empty/missing-parent/directory BQAA_LOG_FILE never crashes or hangs; FIFO at default log: no hang, silent; dead-letter symlink aborts the drain pass fail-closed (PermissionError, envelope kept, nothing uploaded); ancestor rename after open does not redirect the handle (names()/open still hit the checked dir); pre-created 0666 log in own 0700 dir tightened to 0600 with content preserved; >256-deep path refused fail-closed; 50 StateStores leave fd delta 0; fork-based 2-proc x 30-iter ensure_private_dir creation race: rc 0/0, all 0700; refused hook rc 0 (silent with default log, logged with separate valid log); refused drainer rc 1 with zero uploads, planted envelope kept, refusal in log.
  • Verified by code reading that the _open_nofollow islink fallback can never see a dir_fd-relative target: fd-backed PrivateDir implies _dir_fd_supported(), which requires O_NOFOLLOW (_utils.py:161-172), and the only dir_fd-less _open_nofollow caller (_open_log else-branch) passes a full path.
  • Scope: diff touches only producers/src/bigquery_agent_analytics_tracing/{_utils,claude_code,config,drain,logger}.py, producers/tests/test_drain.py, producers/tests/test_private_dirs.py. No system_evaluator.py, browser_smoke.sh, or test_looker_studio_dashboard.py. No stale /tmp/bqaa-agent-tracing refs in producers/src or plugins/claude_code.
  • CI (gh pr checks 499): all pass (Producers tests 3.10–3.14, both format checks, build, receiver self-test, root suite) except Hash-lock drift check, whose log shows only upstream PyPI version drift (build, hatchling, trove-classifiers, …). This PR touches no lock inputs, so that failure is not PR-caused.
  • Non-POSIX: package still cannot import on native Windows due to the pre-existing unconditional import fcntl (unchanged, disclosed in the PR body) — no NEW crash surface; the POSIX guards plus the subprocess tests cover partial-POSIX degradation, and the no-getuid default stays per-user (getpass name, else per-pid, never a constant).

Round-1 findings closure (my review 5337752547)

  • CLOSED: group-writable dirs refused (_utils.py:186, GROUP_WRITABLE tests, probe-confirmed).
  • CLOSED: explicit log no longer follows symlinks, with a /dev/stderr+/dev/stdout carve-out and char-device support (_utils.py:415-460, log tests, probe-confirmed).
  • CLOSED: check-then-use window closed via fd-bound PrivateDir for spool/state/dead-letter/pidfile/envelope paths (4 swap tests + M3 mutation + ancestor-rename probe).
  • CARRIED (still by design, P2 below): refusal is silent for default-log users; symlink refusal message is accurate but confusing.

Findings

P2 — Refusal is still fully silent for default-log users

When the default state dir is refused, the hook returns rc 0 with empty stderr (probe-confirmed at bb38ead): the refusal cannot be written into the refused dir, so an attacker pre-creating /tmp/bqaa-agent-tracing-<uid> disables victim tracing with zero signal. Fail-closed, so not a hole. Suggested fix: last-resort single stderr line on refusal (hooks already return 0, so it would not break the host agent).

P2 — StateStore pins its dir fd for life with no close()

claude_code.py:231 keeps self._dir open (the fd pinning is the point), but StateStore offers no close()/context-manager; cleanup relies on PrivateDir's weakref.finalize (_utils.py:275). One fd per hook call in a short-lived process is harmless (probe: 50 instances, fd delta 0 on CPython), but a long-lived non-refcounted host would hold fds until GC. Suggested fix: add StateStore.close() (+ __enter__/__exit__) delegating to self._dir.close().

P2 — Pre-existing own world-readable (0755) dirs are accepted

_check_dir (_utils.py:175-190) refuses only group/other writable, so a pre-existing own 0755 spool/state dir is accepted (probe-confirmed): file contents stay 0600, but envelope/state filenames (event-<time_ns>-<pid>-<rand>.json) are listable by local users, leaking activity timing. Suggested fix: also refuse (or chmod-to-0700, friendlier and safe since we own it) dirs readable by group/other.

P2 (observation) — Root-run with user-owned parents is refused

_require_trusted_parents/_require_trusted_chain require every ancestor to be root-or-euid, so running as root with a state dir under a user's home is now refused (fail-closed, safe direction; unusual for per-user tracing). No change suggested; recording the behavior.

P2 (cosmetic, carried) — Refusal message conflates symlink and non-directory

_utils.py:381-385 reports ELOOP/EMLINK/ENOTDIR uniformly as "a symlink or not a directory". Accurate but can confuse (e.g. macOS /tmp symlink case reads differently than the Linux writable-parent case). Optional: distinct messages per errno.

Against the rejection criteria

  • RC1: satisfied. All round-1 properties re-verified plus every round-2 claim probed or mutation-checked: fd-bound validation across drainer/StateStore/envelope-temp+rename/pidfile, group-writable refusal, envelope owner/type vetting with log-once skip, explicit-log symlink/foreign/FIFO/hard-link refusal with 0600 tightening and char-device allowance, POSIX guards with per-user fallback. The P2s need unusual setups and leak at most filenames/timing; none reopen the fixed-shared-/tmp path.
  • RC2: satisfied. Overrides (relative paths, separate log, missing log parents, /dev/stderr), old-path abandonment, emptyDir 0777 (test + non-sticky probes), POSIX-degradation (subprocess tests), hook rc 0 / drainer rc 1 refusal behavior — all green. One new tightening to be aware of: pre-existing group/other-readable logs are fchmoded to 0600 (disclosed, intended).
  • RC3: satisfied. 46/48 fail on a51c39a (2 compat guards pass), 30 fail on 8914004 modulo the 1 sandbox-pty environmental failure, all pass at head modulo the same environmental failure; 3/3 mutation spot-checks sensitive; isort/pyink/diff-check clean; producers-only scope; no #496/#497 files.

VERDICT: APPROVE @ bb38ead

…ated parent handle

Round 3 of the PR GoogleCloudPlatform#499 review.

An explicit log whose dir already existed was checked by path (owner
chain, private if ours, and whether others own it) and then reopened by
its full path. O_NOFOLLOW guards only the last component, so another
user able to rename that dir in a non-sticky shared parent could swap
it for a symlink to a dir of theirs right after the check. The append
then went to whatever sat there under the log's name, such as a hard
link to one of our files, and the stale "not shared" verdict skipped
the hard-link refusal.

The dir is now opened once (O_DIRECTORY; symlinks leading to it are
still followed, as before: /tmp is one on macOS) and every check is
made on that descriptor: fstat for its owner (root or us) and, if it is
ours, for being private; the ".." walk for its physical parents. The
log name is opened relative to it with O_NOFOLLOW, and the shared or
private verdict behind the hard-link refusal comes from the same fstat.
Without dir_fd support the path-based best effort is unchanged. A log
dir we can write to but not list (e.g. mode 0300 or 1733) is now
refused, since its descriptor is opened for reading.

Tests: test_explicit_log_stays_in_the_dir_checked_before_a_swap has the
reviewer's probe shape; it fails at bb38ead (our file behind the hard
link gets the line) and passes here. Three guard cases pass on both: a
log dir or its parent owned by another user is refused, and a log dir
reached through a symlink still works. Full producers suite: 596
passed, 4 skipped, and the same 3 macOS-only xcrun failures as at
bb38ead (592 passed there).

@caohy1988 caohy1988 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.

Blind Astra round-3 review of base a51c39a2dfaa6d863a0e16597f7b1b191b86effb through head 5da91451169a74a579dc4f16e7af8c23c39d035a, including the separate bb38ead..5da9145 diff. No prior reviews, comments, peer artifacts, or vault context were read.

Rejection criteria, established before reading the diff:

  1. Filesystem operations can still be redirected outside validated private directories, exposing tracing data or trusting attacker-controlled destinations.
  2. Legitimate overrides, hooks, or supported platform behavior regress.
  3. Security/compatibility claims lack reproducible evidence, tests introduce unexplained failures, or the change exceeds the producer-only scope.

P0: None found.
P1: None found.

P2 — Preserve safe write/search-only explicit log directories

At producers/src/bigquery_agent_analytics_tracing/_utils.py:441, the new parent handle uses O_RDONLY, requiring directory read permission even though appending a known filename needs only search permission. An owner-only 0300 directory containing our own 0600 log is safe and supports ordinary appends. Round 2 logs successfully there; this head raises EACCES opening the directory and log_to_file at lines 503–508 silently discards the log line. This loses diagnostics and, in dry-run mode, the tracing output.

The PR description accurately discloses this narrowing. It nevertheless meets rejection criterion 2 and conflicts with the supplied “No behavior break for legitimate users / explicit env/config overrides still work” contract. This is a P2 compatibility defect, not an unfixed directory-swap exploit. The requested fail-on-any-rejection-criterion rule is why the verdict below requests changes despite no P0/P1 finding.

Reproduction (macOS, actual UID 501, no ownership mocks; run with each checkout's producers/src on PYTHONPATH):

import tempfile
from pathlib import Path
from bigquery_agent_analytics_tracing._utils import log_to_file
from bigquery_agent_analytics_tracing.config import BQAAConfig

with tempfile.TemporaryDirectory() as tmp:
    root = Path(tmp)
    logs = root / "logs"
    logs.mkdir(mode=0o700)
    target = logs / "trace.log"
    target.write_text("existing\n")
    target.chmod(0o600)
    logs.chmod(0o300)
    try:
        with target.open("a") as handle:
            handle.write("ordinary append\n")
        log_to_file(
            BQAAConfig("p", "d", state_dir=str(root / "state"),
                       log_file=str(target)),
            "producer append",
        )
        assert "producer append" in target.read_text()
    finally:
        logs.chmod(0o700)

Command: PYTHONPATH=<checkout>/producers/src <venv>/bin/python -m pytest /tmp/astra499-r3-independent.SBJH9H/test_searchable_log_dir.py -q -s --tb=short.

  • Round 2: 1 passed; content contains both ordinary and producer appends.
  • Head: 1 failed; uid=501 dir_mode=0o300 log_mode=0o600 content='existing\\nordinary append\\n'.
  • Suggested fix: use a search/path-only parent descriptor where supported (O_SEARCH, or O_PATH on applicable platforms), retaining the descriptor-based owner/ancestor checks and the final relative O_NOFOLLOW open. A local OS probe verified O_SEARCH | O_DIRECTORY permits fstat and the relative append on this exact 0300 directory, while O_RDONLY | O_DIRECTORY fails with errno 13. Add this case to the regression tests; do not restore the vulnerable full-path reopen.

What I checked and tried:

  • Read the complete seven-file diff, surrounding source, hook wrappers, repository callers, plugin build/distribution contract, and producer CI configuration. The diff stays under producers/; none of the excluded #496/#497 files changed. The worktree remains clean at the requested head.
  • Verified the original smell from the baseline source and before/after tests: baseline config.py:40–47 uses fixed shared defaults; logger.py:407–409 creates envelopes with umask-derived permissions; drain.py:119,158–162 reads/group-selects destinations from that spool; claude_code.py:178,187–189 opens/truncates state by path. Baseline tests reproduce 0755 directories, 0644 logs, accepted unsafe directories, followed symlinks, and state written through a swapped directory.
  • Head command, from producers/: python -m pytest tests/test_private_dirs.py tests/test_drain.py --tb=short -q: 63 passed.
  • Copied the new security test file into independent git archive scratch trees. On the original base: 48 failed, 4 passed (some newer race tests fail because the new helper does not exist; the baseline permission/symlink/state failures above demonstrate actual unsafe behavior). On round 2: 1 failed, 51 passed; the sole failure is the explicit-log directory swap appending to the victim file. At head, all 52 security cases pass.
  • Nine independent adversarial/compatibility cases pass at head: swap a log ancestor at the final file-open call; substitute a hard link immediately before opening a log in root-owned /tmp; swap the spool before quarantine; swap state before stale cleanup; relative overrides with spaces under umasks 000/022/077; leave pre-existing old default names untouched while a default hook writes the per-user location; and refusal messages with hook rc 0 / drainer rc 1. The independent ancestor-swap case fails on round 2 by appending to the victim. The opened-inode hard-link refusal passes on both round 2 and head. Thus the principal round-3 security fix is supported by independent before/after evidence.
  • The checked-in cases also exercise symlink/foreign/FIFO envelopes or logs, group/world-writable directories, non-sticky 0777 emptyDir parents, retained state/spool/pidfile handles, 0600 log tightening, symlinked log ancestors, stderr/terminal devices, and absent POSIX APIs/dir_fd support.
  • Full head suite: python -m pytest --tb=short -q → 596 passed, 4 skipped, 3 failed. Baseline suite (excluding the copied new test file): 544 passed, 4 skipped, the same 3 failures. The failures are test_run_setup_check_wrapper_falls_back_when_bqaa_python_unrunnable and both test_token_fill_snippet_* cases. They pin PATH to /usr/bin:/bin:/usr/local/bin and hit the local xcrun architecture failure; baseline reproduces the same assertion/errors. They are not caused by this PR.
  • isort --check-only src/ tests/ scripts/, pyink --check src/ tests/ scripts/, and git diff --check base head pass. Local versions: Python 3.13.5, isort 9.0.1, pyink 26.5.1. Dependency installation required binary cryptography (48.0.1) because the latest source build hit a missing local Rust target.

CI: gh pr checks 499 shows producer tests on Python 3.10–3.14, producer format/build, root tests/format/build and receiver self-test passing. The only failure is Hash-lock drift check, for this exact head. I read its failed log: regeneration changes dependency versions (e.g. build 1.5.0→1.6.1, hatchling 1.31.0→1.32.4) and command headers in the three locks. git diff base head -- .github/workflows/producers-ci.yml deploy/otlp_receiver/ producers/build-requirements.lock producers/pyproject.toml is empty. Its workflow, generator, dependency inputs and lockfiles are unchanged, so this is unrelated regeneration drift, not a reason for this verdict.

Limits: no live BigQuery or actual second-UID execution; ownership tests simulate foreign owners. Missing-POSIX-API probes pass, but native Windows is not established: the pre-existing fcntl imports remain. The marketplace's released vendored artifact requires its normal later release sync; this source-only PR does not update it. No branch edits, push, merge, or approval-event review performed.

VERDICT: REQUEST_CHANGES @ 5da9145

@caohy1988 caohy1988 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.

Blind review of PR #499 ROUND 3 (head 5da9145, base a51c39a) on behalf of caohy1988. No changes made to the branch. I also re-read only my own round-1/round-2 reviews (ids 5337752547, 5338621884) to check closure of my earlier findings; everything below was re-derived at the new head.

Rejection criteria (from the task contract, written before reading the diff)

  • RC1 — Tainted path real and closed: default spool/state/log are per-user 0700 (no fixed shared-/tmp names others can pre-create/read/plant into); symlinked, foreign-owned, and group- or world-writable dirs refused; envelopes 0600 O_EXCL; pidfile/state never opened through symlinks; validation bound to an opened fd for create/enumerate/read/replace/remove; envelopes vetted for owner + regular-file type; explicit log refuses symlink/foreign/non-regular targets and hard links in shared dirs with the verdict from the opened file's fstat; round-3 claim holds — explicit log opened relative to a validated, retained parent handle.
  • RC2 — No legitimate-use break: explicit env/config overrides still work; upgrade from the old path is sane; K8s emptyDir 0777 /tmp works; no new import/first-write crash without POSIX APIs; drainer and hooks keep working (hook rc 0, drainer rc 1 on refusal).
  • RC3 — Proof and scope: new tests fail on baseline a51c39a (and the new round-3 test fails on round-2 bb38ead) and pass on head; tests are sensitive to the protections (mutations break them); format checks pass; producers/ only; files of #496/#497 untouched.

What I tried (worktree detached at 5da9145; baselines/mutations via scratch git archive trees, never this worktree)

  • Full diff base..head plus round-3 diff bb38ead..5da9145; read _utils.py (_check_log_dir, _open_in_log_dir, _open_log, PrivateDir), claude_code.py (_LockedJSONStore is fully fd-based: open/read/write/truncate/fsync on the fd, no path reopen), drain.py, config.py, logger.py; enumerated callers repo-wide — changed helpers are used only inside the tracing producer + its tests; plugins/claude_code/hooks/common.sh:38 still execs hooks with no dir overrides (tainted entry as described); plugins/ untouched including claude_code_dist, as disclosed.
  • New tests at head: 51/52 pass; the single failure is test_log_to_a_terminal_device_still_works, which fails at os.openpty() in test setup with PermissionError because this sandbox denies pty allocation — before any PR code runs. CI Producers tests pass on 3.10–3.14 (pty works on Linux), so this is environmental.
  • Full producers suite at head: 593 passed, 4 skipped, 6 failed. The 6 are: the sandbox pty test plus 5 that are environmental, each root-caused, none touching PR code paths — 2 test_token_fill_snippet + 1 test_run_setup_check_wrapper_falls_back hit the local macOS xcrun arch shim; 1 test_vendored_plugin_run_setup_check_succeeds_when_env_set fails because google.cloud.bigquery is not importable under the test's restricted PATH=/usr/bin:/bin (report shows required_deps_ok: false, verified by direct repro); 1 test_otlp_verify gets proxy 502 instead of status 0. The 3 file-based ones reproduce identically on a pristine a51c39a tree; the 2 plugin ones fail for the same environmental reasons (verified cause, not PR code).
  • New tests against baseline a51c39a sources: 49 fail, 3 pass — the 3 passes are pure compatibility guards (test_hard_linked_log_in_a_dir_of_ours_still_works, test_explicit_log_in_a_symlinked_dir_still_works, test_log_to_dev_stderr_still_works). Every security assertion fails before the fix.
  • Round-3 tests against round-2 bb38ead sources: test_explicit_log_stays_in_the_dir_checked_before_a_swap fails there (victim file gets the log line via the hard link after the swap) and passes at head; the 3 guard cases (foreign dir, foreign parent, symlinked dir) pass at both. The round-3 fail-before claim holds exactly.
  • Mutation spot-checks on head scratch copies: opening the log by path instead of dir_fd-relative fails exactly the new swap test; forcing shared=True fails 4 tests (2 group-writable-own-dir, own-dir hard-link guard, swap test). The shared verdict and the fd binding are genuinely guarded.
  • isort --check-only, pyink --check on producers/src/ tests/ scripts/: clean. git diff --check base..head: clean.
  • Break probes (throwaway scripts under /tmp, all green): swap hooked at _require_trusted_parents and at _open_nofollow (different interleavings than the test's _check_dir hook) — log still lands in the pinned dir, victim file untouched; log parent symlinked to a foreign-owned dir refused with zero writes; own 0300 (write-only) log dir refused without crash (the disclosed round-3 narrowing); .. as log name safe (EISDIR, silent); relative log path in private cwd works at 0600; fresh log in root-owned 1777 dir works while a hard link there is refused; simulated-root run refuses a root-owned 1777 log dir fail-closed; no-geteuid mode writes a fresh explicit log and still refuses a hard-linked one; no-dir_fd fallback writes a fresh explicit log and still refuses a symlink; umask 000/022/077 all yield 0700 dirs / 0600 envelopes and logs; 50 explicit-log opens leave fd delta 0 (dir handle closed); relative spool works; pre-existing old /tmp/bqaa-agent-tracing with planted envelope ignored while the new per-uid dir is used; BQAA_STATE_DIR="" no crash; directory-as-log and missing log parents never crash (parents created 0700); spool refusal message is clear (it is writable by its group or other users); refused hook rc 0 with zero writes; refused drainer rc 1 with zero uploads and envelope kept; dead-letter symlink aborts the drain pass fail-closed with the envelope kept; FIFO at default log does not hang; >256-deep path refused fail-closed; 2-proc x 30-iter ensure_private_dir creation race rc 0/0, all 0700.
  • CI (gh pr checks 499, run at head 5da9145): everything passes (Producers tests 3.10–3.14, both format checks, build, receiver self-test, root suite) except Hash-lock drift check, whose log shows only upstream PyPI version drift (trove-classifiers 2026.6.1.19→2026.9.21.13, pyproject-hooks, tomlkit, …). This PR touches no lock inputs, so that failure is not PR-caused.
  • Scope: diff touches only producers/src/bigquery_agent_analytics_tracing/{_utils,claude_code,config,drain,logger}.py, producers/tests/test_drain.py, producers/tests/test_private_dirs.py. No system_evaluator.py, browser_smoke.sh, or test_looker_studio_dashboard.py. No stale /tmp/bqaa-agent-tracing refs in producers/src or plugins/claude_code.
  • Non-POSIX: package still cannot import on native Windows due to the pre-existing unconditional import fcntl (unchanged, disclosed) — no new crash surface; POSIX guards plus the subprocess tests cover partial-POSIX degradation, and the no-getuid default stays per-user.

Round-1/round-2 findings closure (my reviews 5337752547, 5338621884)

  • CLOSED: group-writable dirs refused (_utils.py:186, probe P13a reconfirmed).
  • CLOSED: explicit log no longer follows symlinks, with /dev/stderr+/dev/stdout carve-out and char-device support (probes P9b, P2 reconfirmed).
  • CLOSED: check-then-use window closed via fd-bound opens for spool/state/dead-letter/pidfile — and now for the explicit log too (_utils.py:428-447, new swap test plus my P1a/P1b probes at different hook points).
  • CARRIED (still by design, P2s below): silent refusal for default-log users; StateStore has no close(); own 0755 dirs accepted; refusal message wording.

Findings

P2 — Refusal is still fully silent for default-log users

When the default state dir is refused, the hook returns rc 0 with zero writes and empty stderr (probe-confirmed at head): the refusal cannot be written into the refused dir, so an attacker pre-creating /tmp/bqaa-agent-tracing-<uid> disables victim tracing with zero signal. Fail-closed, so not a hole. Suggested fix: last-resort single stderr line on refusal (hooks already return 0, so it would not break the host agent).

P2 — StateStore pins its dir fd for life with no close()

producers/src/bigquery_agent_analytics_tracing/claude_code.py:231 keeps self._dir open (the fd pinning is the point), but StateStore offers no close()/context-manager; cleanup relies on PrivateDir's weakref.finalize (_utils.py:275). One fd per hook call in a short-lived process is harmless, but a long-lived non-refcounted host would hold fds until GC. Suggested fix: add StateStore.close() (+ __enter__/__exit__) delegating to self._dir.close().

P2 — Pre-existing own world-readable (0755) dirs are accepted

_check_dir (_utils.py:175-190) refuses only group/other writable, so a pre-existing own 0755 spool/state dir is accepted: file contents stay 0600, but envelope/state filenames (event-<time_ns>-<pid>-<rand>.json) are listable by local users, leaking activity timing. Suggested fix: also refuse (or chmod-to-0700, friendlier and safe since we own it) dirs readable by group/other.

P2 (new, coverage) — No test pins the _open_in_log_dir fallback or the no-euid log-dir verdict

_utils.py:437-440 (path-based fallback without dir_fd support) and the _euid() is None path through _check_log_dir (_utils.py:415-425, where shared is unconditionally true) are exercised by no test: the dir_fd/POSIX subprocess tests only use state-dir logs, which take the ensure_private_dir branch. My probes P8a/P8b/P9a/P9b show both behave correctly (fresh log written, symlink/hard-link still refused), so this is coverage debt, not a bug. Suggested fix: add a supports_dir_fd-emptied explicit-log test and a geteuid-removed explicit-log test mirroring test_without_dir_fd_support_unsafe_dirs_are_still_refused.

P2 (observation) — Root-run with a root-owned world-writable log dir is refused

_check_log_dir (_utils.py:422) computes shared = info.st_uid != euid, so a root-run process logging into a root-owned 1777 dir takes the private branch and _check_dir refuses it (probe P7-confirmed, fail-closed, silent). Same direction as the already-noted root-run-with-user-owned-parents refusal. Unusual for per-user tracing; no change suggested, recording the behavior.

P2 (cosmetic, carried) — Refusal message conflates symlink and non-directory

_utils.py:381-385 reports ELOOP/EMLINK/ENOTDIR uniformly as "a symlink or not a directory". Accurate but can confuse. Optional: distinct messages per errno.

Against the rejection criteria

  • RC1: satisfied. All round-1/round-2 properties re-verified at the new head plus the round-3 claim: explicit log opened relative to the checked parent descriptor with the hard-link verdict from the same fstat — proven by the fail-on-bb38ead/pass-on-head swap test, two independent swap probes at different hook points, the symlink-to-foreign-dir refusal probe, and two sensitive mutations. The P2s need unusual setups and leak at most filenames/timing; none reopen the fixed-shared-/tmp path.
  • RC2: satisfied. Overrides (relative spool/log, separate log, missing log parents, /dev/stderr, symlinked log dir), old-path abandonment, emptyDir 0777 (tests + non-sticky probes), POSIX degradation (subprocess tests + P8/P9 probes), umask invariance, hook rc 0 / drainer rc 1 refusal behavior — all green. Known narrowings, both disclosed and probe-confirmed: pre-existing readable logs are fchmoded to 0600, and write-only (0300/1733) log dirs are now refused.
  • RC3: satisfied. 49/52 fail on a51c39a (3 compat guards pass), the new swap test fails on bb38ead, all pass at head modulo the 1 sandbox-pty environmental failure; 2/2 mutation spot-checks sensitive; isort/pyink/diff-check clean; producers-only scope; no #496/#497 files.

VERDICT: APPROVE @ 5da9145

…h-only handle

Round 4 of the PR GoogleCloudPlatform#499 review.

Round 3 opened an explicit log's existing dir with O_RDONLY so it could
be checked on a descriptor. Opening a dir for reading needs read
permission, but looking a name up in it needs only search permission.
A private log dir of ours that we can write and search but not list
(mode 0300, or 0100 with the log already there) therefore made
log_to_file drop every line silently. bb38ead appended there, and so
does a plain append by path.

The dir is now opened search-only: O_SEARCH where the platform has it
(macOS), else O_PATH (Linux), else O_RDONLY as before. On macOS and
Linux such a handle supports every call made on it: fstat for the
owner and privacy checks, fstatat for the ".." walk, and openat for the
log name with O_NOFOLLOW. Nothing else changes. Symlinks leading to the
dir are still followed, so the dir open has no O_NOFOLLOW: that would
refuse /tmp on macOS (a symlink) and fail
test_explicit_log_in_a_symlinked_dir_still_works.

Tests: test_explicit_log_in_a_dir_we_can_search_but_not_list_still_works
(0300 and 0100; the reviewer's probe shape, real uid, no owner fakes)
fails at 5da9145 and passes here, on macOS and on Linux (Docker, uid
1000, O_PATH). test_explicit_log_without_search_only_open_flags_still_works
covers platforms with neither flag. The round-3 parent-swap test still
passes. Full producers suite: 599 passed, 4 skipped, and the same 3
macOS-only xcrun failures as at 5da9145 (596 passed there).

@caohy1988 caohy1988 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.

Blind Astra review of a51c39a2dfaa6d863a0e16597f7b1b191b86effb..1914dc1ba516db5b3b0135a72450288c9bfd9a04.

Rejection criteria, set before reading the diff:

  1. Path replacement or an unsafe pre-existing target can redirect tracing writes, state/PID updates, or authenticated envelope uploads after validation.
  2. A supported configuration regresses, including a searchable but unreadable explicit-log directory, overrides, shared 0777 temporary parents, or absence of the newly used POSIX APIs.
  3. The security smell lacks reproducible baseline evidence, the fix fails relevant checks, or the change exceeds the producers-only scope.

Findings: P0: none. P1: none. P2: none. No rejection criterion was demonstrated for this change.

What I checked:

  • Read the PR description, full base-to-head diff, surrounding implementation, all new tests, repository callers, Claude hook wrappers, plugin builder and distribution README. Only the seven declared producers files changed; the files reserved for #496/#497 are untouched. The supplied head-to-itself round-4 diff is empty, so I also reviewed git diff 1914dc1^ 1914dc1.
  • Round 4 selects O_SEARCH, then O_PATH, then O_RDONLY at _utils.py:444-445. It retains the same opened parent for fstat, the physical-parent walk and the relative no-follow open (:447-449); shared-directory hard-link refusal still uses the opened file's fstat (:479-488).
  • Exercised swaps after validation for the drainer, spool writer, StateStore, pidfile and explicit log; group/world-writable and foreign-owned directories; symlinked/foreign envelopes; symlinked, hard-linked and FIFO log targets; symlinked log ancestors; terminal/stderr output; and missing POSIX APIs. These are included in the passing targeted tests below.

Independent before/after evidence:

  • The baseline tainted path is concrete: fixed shared defaults in config.py:40-47, envelope creation with default permissions in logger.py:390-409, listing/reading attacker-controlled envelopes in drain.py:119-124, destination selection in drain.py:158-162, and pidfile symlink following/truncation in drain.py:89-98 (all line references in this bullet are at a51c39a).

  • Ran the same isolated probe with PYTHONPATH=<base-or-head>/producers/src python probe.py, with the BigQuery writer stubbed. Baseline drains a planted 0777 spool to ['attacker-project']; head raises PermissionError: ... writable by its group or other users and records []. Baseline overwrites a victim through .drainer.pid; head refuses the symlink and leaves unchanged intact. Under umask 022 baseline creates 0755 directories/0644 envelopes and logs; head creates 0700 directories/0600 files. Head also passes umasks 000 and 077.

  • Independent head probes pass fresh log creation in a 0300 directory (not just append to an existing log), relative spool/state/log overrides and a StateStore write after changing cwd, and an isolated legacy 0777 spool/log left untouched while new per-user defaults spool and drain successfully. Unsafe-directory entrypoints return hook=0 and drainer=1 and emit the refusal message to a safe explicit log.

  • Also ran an independent Python 3.12 Linux container probe with no network and real uid 1000: O_PATH successfully created/appended logs in 0300 and 0100 user directories and a root-owned 1733 directory. A real uid 1001 renamed uid 1000's validated log directory and substituted a symlink; the append remained in the retained original directory and the hard-linked victim stayed unchanged. A separate root-owned shared-directory hard link was refused. The initial bind-mount container stalled before execution; the successful run transferred only repository source and this probe over stdin.

Commands/results (macOS, non-root uid 501, Python 3.13):

  • cd producers && pytest --tb=short -q tests/test_private_dirs.py tests/test_drain.py: 66 passed.
  • Full pytest --tb=short -q: 599 passed, 4 skipped, 3 failed. An isolated git archive a51c39a baseline suite has 544 passed, 4 skipped, the same 3 failures: test_run_setup_check_wrapper_falls_back_when_bqaa_python_unrunnable and the two test_token_fill_snippet_* cases. Their subprocesses select this Mac's unusable xcrun Python shim (arm64 library versus x86_64 process); this is not introduced by the PR.
  • Copied only head test_private_dirs.py into isolated baseline and round-3 archives: baseline 48 failed, 7 passed (including substantive unsafe-write/permission failures and tests requiring new helpers); round 3 2 failed, 53 passed, precisely the 0300 and 0100 append cases. At head all 55 private-directory cases pass. This independently verifies the round-4 regression and closure without changing this worktree.
  • pyink --check src/ tests/ scripts/ (25.12.0), isort --check-only src/ tests/ scripts/ (8.0.0), and git diff --check a51c39a HEAD: pass.

CI: gh pr checks 499 shows producers tests passing on Python 3.10–3.14, both format checks and package builds passing. The sole failure is Hash-lock drift check. Its log shows regenerated dependency versions changing, e.g. build 1.5.0→1.6.1 and hatchling 1.31.0→1.32.4, and command-header drift. The lock inputs, generator, checked-in locks, pyproject and workflow are unchanged from a51c39a. This failure is unrelated to the tracing changes and does not warrant requesting changes here.

Limits: no live BigQuery writes; missing-API tests do not establish native Windows support (the pre-existing unconditional fcntl imports remain). The released marketplace distribution still needs the normal tracing release/vendor sync described in plugins/claude_code_dist/README.md; this producers-only PR correctly leaves that generated artifact alone. No peer review or comment was read, and no prior review verdict was reused. Worktree remains clean.

VERDICT: APPROVE @ 1914dc1

@caohy1988 caohy1988 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.

Blind review of PR #499 ROUND 4 (head 1914dc1, base a51c39a) on behalf of caohy1988. No changes made to the branch. I also re-read only my own round-1/round-2/round-3 reviews (ids 5337752547, 5338621884, 5339247220) to check closure of my earlier findings; everything below was re-derived at the new head.

Rejection criteria (from the task contract, written before reading the diff)

  • RC1 — Tainted path real and closed: default spool/state/log are per-user 0700 (no fixed shared-/tmp names others can pre-create/read/plant into); symlinked, foreign-owned, and group- or world-writable dirs refused; envelopes 0600 O_EXCL; pidfile/state never opened through symlinks; validation bound to an opened fd for create/enumerate/read/replace/remove; envelopes vetted for owner + regular-file type; explicit log opened relative to a validated, retained parent handle with the hard-link verdict from the same fstat; round-4 claim holds — the parent handle is search-only (O_SEARCH/O_PATH, O_RDONLY fallback) so an owner-only 0300 log dir keeps working while all round-3 protections are kept.
  • RC2 — No legitimate-use break: explicit env/config overrides still work; upgrade from the old path is sane; K8s emptyDir 0777 /tmp works; no new import/first-write crash without POSIX APIs; drainer and hooks keep working (hook rc 0, drainer rc 1 on refusal).
  • RC3 — Proof and scope: new tests fail on baseline a51c39a (and the new round-4 tests fail on round-3 5da9145) and pass on head; tests are sensitive to the protections (mutations break them); format checks pass; producers/ only; files of #496/#497 untouched.

What I tried (worktree detached at 1914dc1; baselines/mutations via scratch git archive trees, never this worktree)

  • Full diff base..head plus round-4 diff (git show 1914dc1: 4 lines in _utils.py, 2 tests). Re-read _utils.py (_open_in_log_dir 428-451, _check_log_dir 415-425, _open_log 454-495, PrivateDir/ensure_private_dir), claude_code.py (fd-based StateStore), drain.py, config.py, logger.py; enumerated callers repo-wide — changed helpers are used only inside the tracing producer + its tests; plugins/claude_code/hooks/common.sh still execs hooks with no dir overrides (tainted entry as described); plugins/ untouched including claude_code_dist, as disclosed.
  • New tests at head: 54/55 pass; the single failure is test_log_to_a_terminal_device_still_works, which fails at os.openpty() in test setup with PermissionError because this sandbox denies pty allocation — before any PR code runs. Linux CI passes it (below), so this is environmental.
  • Full producers suite at head: 596 passed, 4 skipped, 6 failed (second run; a first run also showed one transient ERROR in test_vendored_plugin_run_setup_check_resolves_versioned_package that passes in isolation and did not recur — flake, not PR code). The 6 are: the sandbox pty test plus 5 that reproduce identically on a pristine a51c39a tree (verified: 2 test_token_fill_snippet + 1 test_run_setup_check_wrapper_falls_back hit the local macOS xcrun shim; 1 test_vendored_plugin_run_setup_check_succeeds_when_env_set fails on restricted-PATH deps; 1 test_otlp_verify gets proxy 502 instead of status 0). None touch PR code paths; none are PR-caused.
  • New tests against baseline a51c39a sources: 49 fail, 6 pass — the 6 passes are pure compatibility guards (test_hard_linked_log_in_a_dir_of_ours_still_works, test_explicit_log_in_a_symlinked_dir_still_works, both search_but_not_list cases since baseline opens by path, without_search_only_open_flags, test_log_to_dev_stderr_still_works). Every security assertion fails before the fix.
  • Head tests against round-3 5da9145 sources: exactly the 2 new search_but_not_list cases fail (log line missing — the disclosed round-3 narrowing), plus the environmental pty one; the other 52 pass, including the round-3 swap test and the no-flags guard. The round-4 fail-before claim holds exactly.
  • Mutation spot-checks on head scratch copies, all specific: back to O_RDONLY fails exactly the 2 new search-only tests; adding O_NOFOLLOW to the dir open fails exactly test_explicit_log_in_a_symlinked_dir_still_works; opening the log by full path instead of dir_fd-relative fails exactly the round-3 swap test. The search-only handle, the no-O_NOFOLLOW choice, and the round-3 fd binding are each genuinely guarded.
  • Break probes (throwaway scripts under /tmp, all green): OS-level — O_RDONLY|O_DIRECTORY gets EACCES on a 0300 dir while the O_SEARCH handle supports fstat, fstatat(".."), and openat append; new-file creation in a 0300 dir works at 0600 (the test only covers pre-existing files); parent swap hooked at _require_trusted_parents (a different interleaving than the test's hook) still pins the write in the checked dir with the victim file untouched; own 0330 (group-wx) dir refused; 50 explicit-log opens in a 0300 dir leave fd delta 0 with all lines landed; no-flags fallback on 0300 drops silently without crashing (inherent — no search-only primitive); symlinked-to-foreign dir refused; .. as log name safe; umask 000 still yields 0700/0600; refused hook rc 0 silent, refused drainer rc 1 with the planted envelope kept and the refusal in a separate valid log (an initial rc-0 reading was my probe's bug: mkdir(0777) masked by umask — redone with explicit chmod 0777).
  • isort --check-only, pyink --check on producers/src/ tests/ scripts/: clean. git diff --check base..head: clean.
  • CI (gh pr checks 499, run at head 1914dc1): everything passes — Producers tests on 3.10–3.14 (Linux, so the O_PATH path and the pty test are covered), both format checks, build, receiver self-test, root suite — except Hash-lock drift check, whose log shows only upstream PyPI version drift (trove-classifiers 2026.6.1.19→2026.9.21.13, pyproject-hooks, tomlkit, …). This PR touches no lock inputs, so that failure is not PR-caused.
  • Scope: diff touches only producers/src/bigquery_agent_analytics_tracing/{_utils,claude_code,config,drain,logger}.py, producers/tests/test_drain.py, producers/tests/test_private_dirs.py. No system_evaluator.py, browser_smoke.sh, or test_looker_studio_dashboard.py. No stale shared-/tmp default refs in producers/src or plugins/claude_code.
  • Non-POSIX: package still cannot import on native Windows due to the pre-existing unconditional import fcntl (unchanged, disclosed) — no new crash surface. The round-4 line adds only _flag()-guarded lookups (O_SEARCH/O_PATH/O_CLOEXEC); the bare os.O_DIRECTORY is reached only behind _dir_fd_supported(), which requires it. No-getuid default stays per-user.

Round-1/round-2/round-3 findings closure (my reviews 5337752547, 5338621884, 5339247220)

  • CLOSED: group-writable dirs refused; explicit log no longer follows symlinks (with /dev/stderr+/dev/stdout carve-out and char-device support); check-then-use window closed via fd-bound opens for spool/state/dead-letter/pidfile and for the explicit log.
  • VERIFIED STILL CLOSED at this head: round-3 swap test passes; my independent swap probe at a different hook point pins the write; M3 mutation (open by path) fails exactly the swap test; every round-3 check (fstat owner/privacy, .. walk, relative O_NOFOLLOW open, shared verdict) still runs on the same retained handle, now search-only.
  • CLOSED by this round: the round-3 narrowing (write+search-but-not-list log dirs refused) is lifted — 0300 and 0100 dirs work with the line landed at 0600, proven fail-on-5da9145/pass-here.
  • CARRIED (still by design, P2s below): silent refusal for default-log users; StateStore has no close(); own 0755 dirs accepted; untested no-dir_fd/no-euid explicit-log paths; refusal message wording; root-run observations.

Findings

P2 (new, hardening) — No fallback if the kernel rejects the search-only dir open

_utils.py:444-445 picks O_SEARCH/O_PATH where defined and opens once. O_SEARCH has existed on macOS since 10.5 and O_PATH on Linux since 2.6.39, and CI-at-head plus my macOS probes cover both — so this is hypothetical on supported platforms. But if some kernel ever returned EINVAL/ENOSYS/EOPNOTSUPP for O_SEARCH|O_DIRECTORY, every explicit log in an existing dir would silently drop (the OSError is swallowed by log_to_file), where round 3's O_RDONLY worked. Suggested fix: on those errnos only, retry the dir open with O_RDONLY (still without O_NOFOLLOW, still running every check on the handle). Fail-closed either way; the retry just preserves logging on odd kernels.

P2 — Refusal is still fully silent for default-log users

When the default state dir is refused, the hook returns rc 0 with zero writes and empty stderr (probe-confirmed at head): the refusal cannot be written into the refused dir, so an attacker pre-creating /tmp/bqaa-agent-tracing-<uid> disables victim tracing with zero signal. Fail-closed, so not a hole. Suggested fix: last-resort single stderr line on refusal (hooks already return 0, so it would not break the host agent).

P2 — StateStore pins its dir fd for life with no close()

producers/src/bigquery_agent_analytics_tracing/claude_code.py:231 keeps self._dir open (the fd pinning is the point), but StateStore offers no close()/context-manager; cleanup relies on PrivateDir's weakref.finalize (_utils.py:275). One fd per hook call in a short-lived process is harmless, but a long-lived non-refcounted host would hold fds until GC. Suggested fix: add StateStore.close() (+ __enter__/__exit__) delegating to self._dir.close().

P2 — Pre-existing own world-readable (0755) dirs are accepted

_check_dir (_utils.py:175-190) refuses only group/other writable, so a pre-existing own 0755 spool/state dir is accepted: file contents stay 0600, but envelope/state filenames (event-<time_ns>-<pid>-<rand>.json) are listable by local users, leaking activity timing. Suggested fix: also refuse (or chmod-to-0700, friendlier and safe since we own it) dirs readable by group/other.

P2 (coverage, carried) — No test pins the _open_in_log_dir fallback or the no-euid log-dir verdict

_utils.py:437-440 (path-based fallback without dir_fd support) and the _euid() is None path through _check_log_dir (_utils.py:415-425, where shared is unconditionally true) are exercised by no test: the dir_fd/POSIX subprocess tests only use state-dir logs, which take the ensure_private_dir branch. My probes show both behave correctly (fresh log written, symlink/hard-link still refused), so this is coverage debt, not a bug. Suggested fix: add a supports_dir_fd-emptied explicit-log test and a geteuid-removed explicit-log test mirroring test_without_dir_fd_support_unsafe_dirs_are_still_refused; optionally also assert new-file creation in a 0300 dir (currently only my probe covers it — the new test pre-creates the file).

P2 (observation, carried) — Root-run with a root-owned world-writable log dir is refused

_check_log_dir (_utils.py:422) computes shared = info.st_uid != euid, so a root-run process logging into a root-owned 1777 dir takes the private branch and _check_dir refuses it (fail-closed, silent). Same direction as the already-noted root-run-with-user-owned-parents refusal. Unusual for per-user tracing; no change suggested, recording the behavior.

P2 (cosmetic, carried) — Refusal message conflates symlink and non-directory

_utils.py:381-385 reports ELOOP/EMLINK/ENOTDIR uniformly as "a symlink or not a directory". Accurate but can confuse. Optional: distinct messages per errno.

Against the rejection criteria

  • RC1: satisfied. All round-1/2/3 properties re-verified at the new head plus the round-4 claim: the explicit-log parent is opened search-only (O_SEARCH here, O_PATH on Linux CI, O_RDONLY fallback), 0300/0100 dirs work at 0600, and every round-3 protection still runs on the retained handle — proven by the fail-on-5da9145/pass-on-head pair, three specific mutations, an independent swap probe at a different hook point, and OS-level EACCES-vs-O_SEARCH verification. The P2s need unusual setups and leak at most filenames/timing; none reopen the fixed-shared-/tmp path.
  • RC2: satisfied. Overrides (relative spool/log, separate log, missing log parents, /dev/stderr, symlinked log dir, new-file-in-0300), old-path abandonment, emptyDir 0777 (tests + non-sticky probes), POSIX degradation (subprocess tests + probes), umask invariance, hook rc 0 / drainer rc 1 refusal behavior — all green. Known tightening, disclosed and intended: pre-existing readable logs are fchmoded to 0600.
  • RC3: satisfied. 49/55 fail on a51c39a (6 compat guards pass), exactly the 2 new tests fail on 5da9145, all pass at head modulo the 1 sandbox-pty environmental failure (green on Linux CI); 3/3 mutation spot-checks sensitive and specific; isort/pyink/diff-check clean; producers-only scope; no #496/#497 files.

VERDICT: APPROVE @ 1914dc1

@haiyuan-eng-google
haiyuan-eng-google merged commit 78a768b into GoogleCloudPlatform:main Sep 28, 2026
24 checks passed
haiyuan-eng-google pushed a commit that referenced this pull request Sep 29, 2026
…st (#501)

* chore(release): 0.5.4 — compaction_windows view, smoke-test unpickling allowlist

Bump the version to 0.5.4 and cut the CHANGELOG for the ten PRs merged
since v0.5.3 (#490–#497, #499, #500). [Unreleased] is left empty; the
#494 entry moves into [0.5.4].

* docs(changelog): tighten 0.5.4 compatibility notes

List every incidental name #490/#496 removed and where each lives
now, fix the permission repair to `chmod go-w`, scope the log-dir
symlink rule to logs outside the state directory, and qualify the
tracing checks' platform fallbacks.

* chore(release): date 0.5.4 for 2026-09-29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants