Skip to content

fix(sandbox): deny reads of Zero credential stores - #681

Open
PierrunoYT wants to merge 23 commits into
Gitlawb:mainfrom
PierrunoYT:agent/deny-zero-credential-reads
Open

fix(sandbox): deny reads of Zero credential stores#681
PierrunoYT wants to merge 23 commits into
Gitlawb:mainfrom
PierrunoYT:agent/deny-zero-credential-reads

Conversation

@PierrunoYT

@PierrunoYT PierrunoYT commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

Summary

  • deny sandbox reads of Zero configuration, credential, encrypted-secret, and OAuth token stores
  • honor ZERO_OAUTH_TOKENS_PATH and ZERO_MCP_OAUTH_TOKENS_PATH overrides, including adjacent .secret files
  • preserve path normalization, existence filtering, deduplication, and explicit AllowRead opt-outs

Root cause

The sandbox scrubbed credential environment variables but its read-deny profile only covered cloud-provider paths. Under a read-all posture, an agent could still read Zero's own credential and OAuth stores from disk.

Windows read denial remains tracked separately in #662.

Fixes #675

Validation

  • go test ./internal/sandbox -count=1
  • go test ./... -count=1 with ANTHROPIC_API_KEY unset
  • go vet ./...
  • go run golang.org/x/vuln/cmd/govulncheck@v1.3.0 ./... (Go 1.26.5): no vulnerabilities found
  • go fmt ./...

Known repository/environment limitations

  • The pinned golangci-lint command ran with Go 1.26.5 and reported 35 pre-existing findings outside this patch; it reported none in the changed code.
  • make lint uses a Unix shell assignment that does not run under this Windows shell.
  • The race-enabled make test path cannot run because GCC is not installed; the complete non-race suite passed.

Summary by CodeRabbit

  • Security
    • Strengthened sandbox protections for credential-related reads (AWS, gcloud, Azure, Google application credentials, OAuth/MCP token stores, and Zero config).
    • Added separate “deny-if-exists” handling for credential-derived paths, using command-aware resolution (including override file paths) and improved deduping.
    • Landlock now rejects unsupported deny-read combinations.
  • Bug Fixes
    • Sandbox skips missing credential baselines safely while preserving correct enforcement when paths exist.
    • Improved isolation when credential data appears after launch.
    • More reliable token secret/store atomic write behavior to avoid stale temp artifacts.
  • Tests
    • Expanded coverage for new deny-if-exists and credential resolution semantics.

@coderabbitai

coderabbitai Bot commented Jul 14, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Credential deny-read computation now uses command-specific environment and directory context, covers Zero and token stores before creation, and resolves overrides literally. Linux bwrap conditionally denies existing credential targets, while OAuth writes use fixed protected temporary siblings.

Changes

Credential deny-read generation

Layer / File(s) Summary
Credential path resolution and profile wiring
internal/sandbox/profile.go, internal/sandbox/runner.go, internal/sandbox/export_test.go, internal/sandbox/landlock_linux.go
Permission profiles resolve credential paths from command context, store them in DenyReadIfExists, and include them in supported backend enforcement.
Credential denial and policy validation
internal/sandbox/manager_test.go, internal/sandbox/profile_test.go, internal/cli/sandbox_test.go, internal/sandbox/runner_test.go
Tests cover cloud, Google, Zero, OAuth, and MCP paths, absent stores, literal XDG handling, command-relative overrides, and serialized policy output.
Missing credential target handling
internal/sandbox/linux_helper.go, internal/sandbox/linux_helper_test.go, internal/sandbox/runner_linux_integration_test.go
Linux bwrap skips absent conditional targets and denies credential paths when they exist, with integration coverage for stores created after launch.

Atomic OAuth store writes

Layer / File(s) Summary
Fixed protected publication sibling
internal/oauth/encrypt.go, internal/oauth/store.go, internal/oauth/store_test.go
OAuth and encrypted secret writes use <path>.tmp with exclusive creation, cleanup, and stale-sibling tests.

Estimated code review effort: 4 (Complex) | ~75 minutes

Possibly related issues

  • Gitlawb/zero 675 — Directly addresses sandbox access to Zero OAuth and provider credential stores.
  • Gitlawb/zero 662 — Relates to the same credential deny-read generation and profile enforcement.
  • Gitlawb/zero 663 — Relates to credential deny-read handling across platform-specific enforcement.

Possibly related PRs

  • Gitlawb/zero#685 — Modifies the same credential deny-read profile construction.
  • Gitlawb/zero#658 — Interacts with profiles whose credential rules move into DenyReadIfExists.
  • Gitlawb/zero#79 — Touches the sandbox command planning and wrapper execution pipeline.

Suggested reviewers: anandh8x, vasanthdev2004

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.82% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and accurately describes the main change: denying reads of Zero credential stores.
Linked Issues check ✅ Passed The changes address #675 by denying reads for Zero credential/OAuth stores, overrides, and adjacent temp/lock/migration files.
Out of Scope Changes check ✅ Passed The added tests and helper changes stay focused on sandbox credential denial behavior and supporting write-path fixes.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/sandbox/profile.go`:
- Around line 206-214: The default Zero deny-read candidates in
internal/sandbox/profile.go:206-214 must include mcp-oauth-tokens.json.secret
alongside the other token files. Update the zeroFiles test slice in
internal/sandbox/manager_test.go:388-396 with the same path to enforce coverage;
both changes belong near the existing mcp-oauth-tokens.json entries.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 5c715035-5186-49df-889d-1fac687bba1c

📥 Commits

Reviewing files that changed from the base of the PR and between 6fc1220 and 51b2ea2.

📒 Files selected for processing (2)
  • internal/sandbox/manager_test.go
  • internal/sandbox/profile.go

Comment thread internal/sandbox/profile.go Outdated
@PierrunoYT
PierrunoYT marked this pull request as ready for review July 14, 2026 21:04
Copilot AI review requested due to automatic review settings July 14, 2026 21:04

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR hardens the sandbox’s default deny-read profile so sandboxed commands cannot read Zero’s own on-disk secrets (user config, cred stores, OAuth token stores), in addition to existing cloud-provider credential locations—closing a gap where environment scrubbing alone was insufficient.

Changes:

  • Expands credentialDenyReadPaths to include Zero’s config/credential/token files and to honor ZERO_OAUTH_TOKENS_PATH / ZERO_MCP_OAUTH_TOKENS_PATH (including adjacent .secret files).
  • Refactors credentialDenyReadPathsIn to take a structured options object, improving testability and supporting new inputs.
  • Adds/extends tests to validate the expanded deny list and AllowRead opt-outs.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
internal/sandbox/profile.go Extends default deny-read candidates to cover Zero credential/config/token files and env overrides; adds zeroUserConfigDir helper.
internal/sandbox/manager_test.go Updates deny-path unit tests for new candidates/options and adds a profile-level test for denying Zero token reads.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread internal/sandbox/profile.go Outdated
Comment thread internal/sandbox/profile.go Outdated
- Deny reads of mcp-oauth-tokens.json.secret in the default Zero
  config candidates: file-backed oauth stores keep their encryption
  secret in a sibling .secret file, so the default MCP token store
  needs the same protection as the override paths (CodeRabbit).
- Clarify that explicit credential-file overrides are still filtered
  by on-disk existence like every other candidate (Copilot).
- Align the zeroUserConfigDir doc comment with config.UserConfigDir:
  macOS honors XDG_CONFIG_HOME before falling back to ~/.config
  (Copilot).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
coderabbitai[bot]
coderabbitai Bot previously approved these changes Jul 14, 2026

@jatmn jatmn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I found issues that need to be addressed before this is ready.

Findings

  • [P1] Deny the migrated legacy MCP token backup
    internal/sandbox/profile.go:214
    NewTokenStore intentionally preserves the pre-unification mcp-oauth-tokens.json as mcp-oauth-tokens.json.migrated after importing it. That backup still contains the access and refresh tokens, but this list denies only the original filename; the override branch has the same omission. A sandboxed command can therefore read the persistent migrated backup under the read-all profile. Include the migrated filename for both default and override paths (and cover the migration path in the regression test) or remove/redact the backup before claiming the legacy store is protected.

  • [P1] Cover credential-store publication files, not just their final names
    internal/sandbox/profile.go:208
    The protected stores publish secret-bearing temporary siblings before their atomic rename: OAuth uses oauth-tokens.json.tmp-*, the credential store uses credentials.{enc,json}.*.tmp, encrypted stores create *.secret.*.tmp, and config writes .zero-config-*.tmp. Those files live in the same readable directory but do not match any added exact deny entry, so a sandboxed process can enumerate/poll the directory during a login or key/config update and read the token, API key, encryption key, or inline config secret. Deny the appropriate credential-file patterns or otherwise make the write paths unreadable for the lifetime of the sandbox, with a concurrent-publication regression test.

  • [P2] Do not drop default credential paths merely because they are absent when the sandbox starts
    internal/sandbox/profile.go:225
    The new rules are omitted whenever os.Stat initially returns an error. If a sandboxed command is already running while zero auth or a credential rotation creates one of these files, no later filesystem rule is installed and that command can read the newly created final store. The Linux helper already has a missing-path unreadable mount mode, and seatbelt can express a deny before a file exists, so retain the fixed default candidates (subject to the explicit AllowRead opt-out) and test creation after profile construction.

  • [P2] Resolve token overrides using the token stores' path semantics
    internal/sandbox/profile.go:218
    oauth.ResolveStorePath and mcp.ResolveTokenStorePath treat any non-absolute override as a literal path relative to the process working directory. normalizeProfilePath, however, expands a ~/... override before making it absolute. With ZERO_OAUTH_TOKENS_PATH=~/tokens.json, the real store is <cwd>/~/tokens.json while the deny entry targets $HOME/tokens.json; the actual token file remains readable. Normalize these overrides through the same resolver used by their stores (and add a relative-tilde case) before deriving DenyRead.

Address code review on PR Gitlawb#681:

- Deny credentialDenyReadPaths' Zero-config candidate as the containing
  directory instead of an itemized filename list. The token/credential/
  config stores each publish through a randomly-named .tmp-<pid>-<nanos>
  sibling before their atomic rename, and the legacy MCP token store
  leaves a mcp-oauth-tokens.json.migrated backup after importing it —
  none of those names were covered by the old itemized list, so a
  sandboxed command could read them under the read-all posture.

- Stop dropping default candidates that don't exist yet at profile-build
  time. A store created later in a long-lived sandboxed session (e.g. a
  concurrent ) previously got no deny rule at all; every
  backend already treats a deny rule over a not-yet-existing path as a
  harmless no-op that still takes effect once the path appears.

- Resolve ZERO_OAUTH_TOKENS_PATH / ZERO_MCP_OAUTH_TOKENS_PATH overrides
  the same way the token stores resolve them (relative-to-cwd, no ~
  expansion) instead of through normalizeProfilePath, which tilde-expands
  and so could derive a deny path different from where the store actually
  writes.

Adds regression coverage for the directory-wide deny (including the
migrated backup and synthetic temp-file siblings), for building the
profile before the store directory exists, and for the tilde-override
resolution mismatch.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
internal/sandbox/profile.go (1)

244-267: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Simplify path resolution by relying on filepath.Abs.

filepath.Abs inherently handles both relative and absolute paths, and automatically invokes filepath.Clean on its output. You can streamline this helper by removing the redundant filepath.IsAbs condition and the explicit filepath.Clean calls.

♻️ Proposed refactor
 func resolveCredentialOverridePath(override string) string {
 	override = strings.TrimSpace(override)
 	if override == "" {
 		return ""
 	}
-	if filepath.IsAbs(override) {
-		return filepath.Clean(override)
-	}
 	abs, err := filepath.Abs(override)
 	if err != nil {
 		return ""
 	}
-	return filepath.Clean(abs)
+	return abs
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/sandbox/profile.go` around lines 244 - 267, Update
resolveCredentialOverridePath to trim and reject empty overrides, then rely
solely on filepath.Abs for both absolute and relative paths. Remove the
filepath.IsAbs branch and explicit filepath.Clean calls, while preserving the
existing empty-string and Abs-error return behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@internal/sandbox/profile.go`:
- Around line 244-267: Update resolveCredentialOverridePath to trim and reject
empty overrides, then rely solely on filepath.Abs for both absolute and relative
paths. Remove the filepath.IsAbs branch and explicit filepath.Clean calls, while
preserving the existing empty-string and Abs-error return behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 20cdc36c-d46b-4198-9a7d-066526d292f3

📥 Commits

Reviewing files that changed from the base of the PR and between 0547046 and 43e81fd.

📒 Files selected for processing (2)
  • internal/sandbox/manager_test.go
  • internal/sandbox/profile.go

anandh8x
anandh8x previously approved these changes Jul 15, 2026

@anandh8x anandh8x left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Re-reviewing against commit 43e81fdd (head). The directory-wide deny on ~/.config/zero (patch 3/3) closes the atomic-rename temp-file and .migrated backup leak that the prior itemized list missed — the directory is the only stable primitive. The "emit whether or not it exists on disk" rule is correct (backends treat missing paths as no-ops, but the rule takes effect once the store appears mid-session, which the prior behavior would have missed). The resolveCredentialOverridePath fix aligns with the token stores' literal-CWD resolution instead of normalizeProfilePath's tilde expansion, closing the real mismatch the new test covers.

LGTM. The zeroUserConfigDir duplication is intentional (import cycle: config depends on sandbox); a follow-up to break the cycle is worth filing but not a blocker.

Cross-PR note: #681 / #682 / #685 are coordinated. Recommend rebasing #682 and #685 on top of #681 in that order to resolve the credentialDenyReadPaths signature and the scrubSensitiveEnv plumbing cleanly.

@gnanam1990 gnanam1990 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Local review: built and ran go test ./internal/sandbox on darwin/arm64 — one test fails (blocking). Plus one drift note.

Comment thread internal/sandbox/manager_test.go
Comment thread internal/sandbox/profile.go
Vasanthdev2004
Vasanthdev2004 previously approved these changes Jul 16, 2026

@Vasanthdev2004 Vasanthdev2004 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Approving. I checked the new helpers against the real store resolution: zeroUserConfigDir matches config.UserConfigDir exactly (including the macOS ~/.config/XDG behavior), and resolveCredentialOverridePath mirrors oauth.ResolveStorePath / mcp.ResolveTokenStorePath relative overrides resolve literally against cwd with no tilde expansion, so the deny rule lands on the path the store actually writes to. Denying the whole /zero directory is the right call given the random-named .tmp/.secret/.migrated siblings the stores publish, and emitting rules for not-yet-existing paths is safe (seatbelt treats them as no-ops, bwrap mounts a perms-000 tmpfs, Windows is skipped) so stores created mid-session stay covered. One minor residual worth a follow-up: for an explicit ZERO_OAUTH_TOKENS_PATH override, the atomic-write .tmp-- sibling isn't denied (only the file and .secret are), leaving a brief read window during a token write not a regression since overrides had no coverage before. Build, vet, gofmt, and the new tests pass here; the six sandbox-suite failures reproduce on clean main.

@Vasanthdev2004

Copy link
Copy Markdown
Collaborator

fix smoke tests and stuffs seems all good then

Recompute the expected Zero config deny path after MkdirAll and resolve
the temp base with EvalSymlinks so macOS /var -> /private/var does not
flake TestPermissionProfileDeniesZeroCredentialFiles. Add a parity test
that sandbox.zeroUserConfigDir stays aligned with config.UserConfigDir.

Co-authored-by: PierrunoYT <PierrunoYT@users.noreply.github.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/sandbox/zeroconfigdir_parity_test.go`:
- Line 1: Rename the test file from zeroconfigdir_parity_test.go to
profile_test.go so the tests for zeroUserConfigDir in profile.go reside
alongside the source file they cover.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 584d1c8c-ed4f-4446-88c8-e9f7a52829c6

📥 Commits

Reviewing files that changed from the base of the PR and between 43e81fd and 5b4f743.

📒 Files selected for processing (4)
  • internal/sandbox/export_test.go
  • internal/sandbox/manager_test.go
  • internal/sandbox/profile.go
  • internal/sandbox/zeroconfigdir_parity_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/sandbox/manager_test.go

Comment thread internal/sandbox/profile_test.go
@PierrunoYT
PierrunoYT requested review from gnanam1990 and jatmn July 17, 2026 13:14

@jatmn jatmn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I found issues that need to be addressed before this is ready.

Findings

  • [P1] Keep absent deny paths from aborting the Linux sandbox
    internal/sandbox/profile.go:228
    This now emits every missing default and override candidate (including ~/.azure and a fresh ~/.config/zero). The Linux backend translates a missing DenyRead target into --tmpfs <path> only after it has read-only-bound /; bubblewrap cannot create that target or its missing parents in the read-only tree, so startup fails before the requested command executes. For example, bwrap --ro-bind / / --tmpfs <existing-parent>/missing -- true exits with “Can't mkdir … Read-only file system.” Preserve backend-safe handling for nonexistent paths (or materialize them safely before the read-only bind) and add a real Linux launch regression test.

  • [P1] Cover all credential-bearing siblings of explicit token-store overrides
    internal/sandbox/profile.go:221
    An override outside the default config directory receives rules only for <path> and <path>.secret. OAuth publishes its token JSON through <path>.tmp-<pid>-<nanos>, encrypted storage creates <path>.secret.*.tmp, and MCP migration preserves the token-bearing legacy file at <ZERO_MCP_OAUTH_TOKENS_PATH>.migrated; none of those siblings is denied. A sandboxed command can poll the override directory during a save or read the durable migration backup and recover the token/key. Protect the required sibling set or use a safe directory-level containment approach for overrides, with publication and migration tests.

  • [P2] Resolve the config-root deny path with the store's literal XDG semantics
    internal/sandbox/profile.go:211
    zeroUserConfigDir returns a nonempty XDG_CONFIG_HOME verbatim, matching the config and token stores, but the later normalizeProfilePaths expands a leading ~. With XDG_CONFIG_HOME=~/zero-config, the stores use the literal cwd-relative ~/zero-config/zero/... path while this profile denies $HOME/zero-config/zero; the real config, provider credentials, and OAuth files remain readable in the sandbox. Resolve this candidate without tilde expansion (or through the same resolver used by the stores) and cover a literal-tilde XDG value.

Open inline review threads

The following inline threads remain open on GitHub:

  • Copilotinternal/sandbox/profile.go:170: the comment about existence filtering is stale; the filter was removed in the current head.
  • Copilotinternal/sandbox/profile.go:244: the macOS/XDG wording is now aligned in the current helper comment.
  • gnanam1990internal/sandbox/manager_test.go:511: the macOS path-normalization test issue is addressed by resolving the temp base and recomputing the expected path after creation.
  • gnanam1990internal/sandbox/profile.go:188: the resolver-drift concern is addressed by the new parity test against config.UserConfigDir.
  • CodeRabbitinternal/sandbox/zeroconfigdir_parity_test.go:1: the requested rename to profile_test.go has not been made; this is a non-blocking test-file organization nit.

Vasanthdev2004
Vasanthdev2004 previously approved these changes Jul 18, 2026

@Vasanthdev2004 Vasanthdev2004 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Re-approving. gnanam's blocker was the darwin/arm64 sandbox test failing, and the commit that addresses the macOS deny-path test plus config parity fixes it: the full smoke matrix is green now, macOS included. Denying the whole config dir rather than itemized filenames is the approach I already backed last round, since the stores publish random-named .tmp/.secret/.migrated siblings, so this is consistent with what I approved. gnanam will want to clear his own changes-requested once he re-runs, but from my side this is good.

@PierrunoYT
PierrunoYT requested review from anandh8x and jatmn July 25, 2026 15:36

@jatmn jatmn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I found issues that need to be addressed before this is ready.

Findings

  • [P1] Do not deny the whole user Zero config directory
    internal/sandbox/profile.go:254
    This makes the supported user-plugin root ($XDG_CONFIG_HOME/zero/plugins) unreadable. Plugin tools are executed through the sandbox and their commands/scripts live below that root, so an installed user plugin fails to start on both bwrap and Seatbelt. Narrow the deny to credential-bearing paths (while retaining coverage for publication artifacts), or explicitly preserve the supported non-secret subtrees.

  • [P1] Resolve relative token overrides from the same directory as the stores
    internal/sandbox/runner.go:181
    The profile now resolves ZERO_OAUTH_TOKENS_PATH, ZERO_MCP_OAUTH_TOKENS_PATH, and relative XDG paths from spec.Dir; the OAuth and MCP store resolvers use filepath.Abs, which resolves from the Zero process's current working directory. For example, when Zero starts in /repo with ZERO_OAUTH_TOKENS_PATH=tokens.json and runs a sandboxed command in /repo/subdir, the profile masks /repo/subdir/tokens.json while the real /repo/tokens.json remains readable through the read-all root. The new tests make both directories the same and therefore miss this bypass.

  • [P1] Do not leave newly created credential paths visible to an existing Linux sandbox
    internal/sandbox/linux_helper.go:282
    DenyReadIfExists entries that are absent while bwrap assembles the namespace are skipped. The root is then live-mounted read-only without a mask, so a durable sandboxed MCP server started before ~/.config/zero or a token file exists can read that credential as soon as another process creates it. The added smoke case only creates the store before constructing the later sandbox run; it does not cover the long-lived-session race this change claims to protect.

  • [P1] Keep publication files unguessable or protect their inode after creation
    internal/oauth/store.go:414
    Replacing randomized CreateTemp names with a predictable <token>.tmp makes the plaintext token (and, via the analogous secret path, the encryption key) observable to a sandboxed same-user process with write access to an override parent such as a workspace or /tmp. Such a process can wait for the known file, rename the opened inode into an allowed path, and read the data written through the still-open descriptor; the lock only coordinates cooperating Zero processes. On Linux, an absent sibling is also skipped by DenyReadIfExists at sandbox setup, which makes this practical for a long-lived sandbox. Use a private protected directory/randomized file strategy that cannot be moved into an allowed path, or enforce the required write and read protections for the entire publication lifecycle.

Four problems with the credential deny baseline, all in the same mechanism.

The whole-directory deny over $XDG_CONFIG_HOME/zero also hid the supported
user plugin, specialist, and command roots, whose commands and scripts are
executed through this sandbox, so an installed user plugin could no longer
start. Narrowing the deny to itemized files was not an option: the stores
publish through temporary names and a concurrent login can add a store that
did not exist when the profile was built, and only a directory rule covers
both. The directory deny therefore stays, and the non-secret subtrees are
carved back out through a new DenyReadCarveouts field: seatbelt re-allows
them after the deny (SBPL is last-match-wins) plus ancestor metadata so path
resolution can reach them, and bubblewrap masks the directory with --perms
111 instead of 000 -- unlistable but traversable -- and re-binds the carveout
read-only before the tmpfs is remounted read-only.

A relative ZERO_OAUTH_TOKENS_PATH, ZERO_MCP_OAUTH_TOKENS_PATH, or
XDG_CONFIG_HOME was resolved against the command directory only, while
oauth.ResolveStorePath and mcp.ResolveTokenStorePath call filepath.Abs, i.e.
resolve against the Zero process working directory. A command run from a
subdirectory therefore had the wrong path denied and the real store stayed
readable under the read-all posture. Relative candidates now resolve against
both directories, since the process that resolves the value is not
necessarily the one that writes the store. The regression test runs the
command from a different directory than the process, which the previous
tests did not.

bubblewrap cannot mount over a path that is absent when the namespace is
assembled, so a store created mid-session stayed readable through the live
read-only host-root bind for the rest of a long-lived sandbox session. The
directories Zero owns -- its config directory and the per-store publication
directories -- are now reported as EnsureDenyReadDirs and created (0700)
before the namespace is assembled, so their mask always exists. Third-party
stores such as ~/.aws are still skipped when absent: Zero must not create
them, and that limitation stays documented on the field.

The fixed <store>.tmp publication sibling made the plaintext token, and via
the same path its encryption key, observable to a same-user sandboxed process
with write access to an override parent: it could wait for the known name and
rename the opened inode into an allowed path. Both stores now publish through
a per-store <store>.publish directory with a randomly-named file inside. The
directory name is derived from the store path, so the profile can deny it up
front, while the random name inside is what cannot be waited for or renamed
away. A test keeps the duplicated suffix in step with oauth.PublicationDirSuffix.

Also adds the seatbelt render coverage that was missing: dropping
DenyReadIfExists from denyReadRules made every credential store readable
again on macOS without failing a single test.
@PierrunoYT

Copy link
Copy Markdown
Contributor Author

Pushed 0f6c87a for the review on 46d071d. All four P1s addressed; they turned out to be one mechanism pulling in four directions, so here is how the pieces fit together now.

[P1] Whole-directory deny made the user plugin root unreadable — real, and the fix could not be "itemize the credential files". The reason the deny was directory-level in the first place is the other two findings: the stores publish through temporary names, and a concurrent login can create a store that did not exist when the profile was built. Only a directory rule covers both. So the directory deny stays and the supported non-secret subtrees are carved back out through a new FileSystemPolicy.DenyReadCarveouts (plugins, specialists, commands — the roots that actually exist under <configDir>/zero; skills live under the data dir).

Both backends had to learn it:

  • seatbelt: the carveout allow is emitted after the deny rules, since SBPL is last-match-wins, plus (allow file-read-metadata file-test-existence (path-ancestors ...)) — the deny removes file-read-metadata on the directory too, so without the ancestor grant the carveout would be unreachable during path resolution. Metadata only, so the directory stays unreadable and unlistable.
  • bubblewrap: a --perms 000 tmpfs cannot be traversed, so a re-bound subpath below it would be useless. A directory with carveouts is masked --perms 111 (unlistable, traversable) and the carveouts are --ro-binded before --remount-ro freezes the tmpfs.

Carveouts are dropped when an AllowRead opt-out removed the deny, and any carveout falling inside a user-configured DenyRead root is dropped as well — the user's configuration outranks Zero's baseline.

[P1] Relative overrides resolved from the wrong directory — confirmed, and gnanam1990 flagged the same thing. oauth.ResolveStorePath / mcp.ResolveTokenStorePath call filepath.Abs, i.e. the Zero process cwd, while the profile resolved against spec.Dir. credentialOverrideBaseDirs now yields the process cwd and the command directory, and a relative override, or a relative XDG_CONFIG_HOME, produces one candidate per base — the process that resolves the value is not necessarily the one that writes the store, and two extra rules are cheap. TestBuildCommandPlanDeniesRelativeOverrideAtProcessAndCommandDir runs the command from <ws>/process/nested while the process sits in <ws>/process, and asserts both resolutions are denied and that neither parent directory is masked. TestCredentialDeniesMatchRelativeTokenOverridesFromStoreResolution no longer makes the two directories identical, which was the reason the old tests missed this.

[P1] Paths created mid-session stayed visible on Linux — bubblewrap genuinely cannot mount over an absent path, so the previous answer was to skip it; the fix is to make the path exist. EnsureDenyReadDirs carries the directories Zero owns — its config directory and the per-store publication directories — and the bwrap plan builder creates them 0700 before assembling the namespace, so the mask is always present and a store written afterwards lands inside an already-masked directory. Third-party stores (~/.aws, ~/.config/gcloud, ~/.azure, GOOGLE_APPLICATION_CREDENTIALS) are still skipped when absent — Zero should not be creating directories in someone's home on their behalf — and that remains documented on the field as the narrower claim. Creation only happens on the Linux bwrap path, so nothing changes for macOS or Windows plan construction. TestLinuxBwrapCreatesOwnedCredentialDirsBeforeMasking pins both halves; the Linux smoke test gains a genuine mid-session race case: the sandboxed command signals that it started, the test then creates the token, and the command's cat must still fail.

[P1] Predictable <store>.tmp publication — agreed, and reverting to a random name in a readable parent would not have helped either, since the parent can be listed. Both stores now publish through a per-store <store>.publish directory holding a randomly-named 0600 file: the directory name is derived from the store path so the profile can deny it up front, and the random name inside is what cannot be waited for, opened, or renamed away. Rename stays same-filesystem, so publication is still atomic. The suffix is duplicated into internal/sandbox (internal/mcp depends on it, so internal/oauth cannot be imported there) and TestCredentialPublicationDirSuffixMatchesStore fails if the two drift. The old .tmp / .secret.tmp names stay in the deny list to cover files an older Zero left behind.

gnanam1990 [Minor] no test asserted DenyReadIfExists reaches the rendered policy — correct, and the mutation check was right: TestSeatbeltProfileRendersCredentialBaselineAndCarveouts now asserts the deny rule is emitted for a DenyReadIfExists entry and that the carveout allow follows it, so dropping the field from denyReadRules fails.

Vasanthdev2004's residuals — (1) in-process read tools still resolve exclusions from Policy.DenyRead, unchanged here and worth its own issue; that boundary is being built in #685 for the daemon token and the same primitive is the natural home for these paths. (2) is fixed above. (3) is fixed for Zero's own stores and documented for third-party ones. (4) is fixed by the carveouts. Agreed on not closing #675 outright while the Windows half is still tracked by #662.

Validation: gofmt -l clean on every changed file, go vet ./..., full go test ./... -count=1 green, go run ./cmd/zero-release build, go run ./cmd/zero-release smoke, git diff HEAD --check, plus GOOS=linux and GOOS=darwin vet over internal/sandbox and internal/oauth (the Linux-only smoke additions compile under the Linux tag). -race cannot run here (no cgo/GCC on this machine); the affected concurrency is internal/oauth's lock-serialized publication, which passes the non-race suite. The pinned golangci-lint@v2.12.2 and govulncheck@v1.3.0 still build against Go 1.25.12 and cannot load this repository's Go 1.26.5 packages.

@jatmn jatmn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I found issues that need to be addressed before this is ready.

Findings

  • [P1] Fix the failing policy JSON golden test
    internal/cli/sandbox_test.go:567
    The test removes denyReadIfExists before comparing the golden output, but it leaves the newly added denyReadCarveouts and ensureDenyReadDirs fields intact. Both contain the test's temporary-home path, so TestRunSandboxPolicyJSONGoldenIncludesManagerBaselineFields now fails on every platform and all three required Smoke jobs are red. Assert and normalize/remove the new fields as part of the golden-test setup.

  • [P1] Normalize carveouts against the denied Zero config directory
    internal/sandbox/profile.go:435
    zeroDir is normalized as a candidate, while nonexistent plugins, specialists, and commands carveouts are normalized independently. On macOS, an existing /tmp/.../zero resolves to /private/tmp/.../zero, but its nonexistent children remain /tmp/...; pathWithinRoot then drops every carveout. The resulting profile denies the entire Zero config directory, preventing installed plugin/specialist/command content from being read. This is also the current macOS Smoke failure in TestCredentialDenyReadPathsIn.

  • [P1] Do not allow credential carveouts to resolve through symlinks
    internal/sandbox/profile.go:435
    normalizeProfilePaths resolves a plugins, specialists, or commands symlink before it is accepted as a carveout. If (for example) ~/.config/zero/plugins points at oauth-tokens.json, the resolved token path is re-allowed after the directory-level credential deny (and is re-bound by bwrap), so a sandboxed command can read the token. Only permit the intended real directory subtrees, without following a carveout symlink outside that subtree.

  • [P1] Preserve the parent process's credential roots when a child overrides its environment
    internal/sandbox/profile.go:249
    Supplying a non-nil CommandSpec.Env makes the deny baseline use only that environment. MCP stdio servers pass project-configured environment overrides through mergeProcessEnv, so a project can set HOME/XDG_CONFIG_HOME to an empty directory. The profile then omits the running Zero process's real config and token paths, while retaining the read-all root bind; the server can read the host OAuth store. Union the parent-process credential roots with child-environment roots rather than replacing the former.

  • [P1] Avoid mounting automatic credential masks beneath a user deny-read mask
    internal/sandbox/linux_helper.go:279
    A policy that denies $XDG_CONFIG_HOME (or $HOME) still retains the nested automatic $XDG_CONFIG_HOME/zero entry in DenyReadIfExists. Bubblewrap masks the parent first, then cannot create the nested mount destination in that read-only tmpfs, so every sandboxed command fails before execution. Drop automatic paths already covered by a user deny, or construct the mounts so nested targets remain valid.

  • [P1] Do not create command-controlled credential directories on the host before sandboxing
    internal/sandbox/linux_helper.go:287
    EnsureDenyReadDirs includes paths derived from XDG_CONFIG_HOME and both OAuth override variables, and ensureLinuxDenyReadDirs unconditionally calls os.MkdirAll before bwrap starts. A sandboxed MCP command can therefore cause host directories such as /home/user/outside/zero or /home/user/outside/tokens.publish to be created outside its workspace/write roots merely by setting its environment. Restrict any precreation to trusted, permitted roots or keep missing paths best-effort.

ampagent and others added 5 commits July 26, 2026 20:25
Preserve process credential roots alongside command overrides while limiting host precreation and read carveouts to trusted process-derived paths.

Canonicalize future credential roots through existing path aliases, reject symlink carveouts, and collapse automatic masks already covered by user or automatic directory denies. Normalize the policy golden and add regression coverage across profile, Seatbelt, and bubblewrap rendering.

Amp-Thread-ID: https://ampcode.com/threads/T-019fa019-2f41-7398-8692-75327064c6f0

Co-authored-by: Pierre Bruno <pierrebruno@hotmail.ch>
@PierrunoYT

Copy link
Copy Markdown
Contributor Author

Final security follow-up on current head 497aeb5:

  • normalized golden and macOS credential-mask paths consistently
  • made carveouts symlink-safe and trusted-process-derived only
  • retained both process and command credential roots conservatively
  • removed redundant nested automatic masks under user denies
  • prevented command-controlled environment paths from creating host directories
  • Oracle reviewed the security boundary
  • zero unresolved review threads remain; race tests, cross-platform checks, full validation, and all GitHub checks pass

The PR is mergeable. PierrunoYT requests a fresh human review to supersede the previous CHANGES_REQUESTED decision.

Preserve the expanded upstream credential baseline while retaining Zero store masking, trusted directory creation, and cross-platform carveout safety.

Amp-Thread-ID: https://ampcode.com/threads/T-019fa55a-85ad-76ef-ac88-f7b9c4d27cc0

Co-authored-by: Pierre Bruno <pierrebruno@hotmail.ch>
@PierrunoYT

Copy link
Copy Markdown
Contributor Author

PierrunoYT pushed bf75c60, a normal merge of current upstream/main (81a5e6c) into agent/deny-zero-credential-reads.

Conflict resolution and security follow-up

  • Preserved main's expanded credential baseline for npm, GitHub CLI, netrc, Docker, Kubernetes, Cloud SDK, cloud-provider, and Zero config paths.
  • Kept automatic credentials separate from user denyRead, with parent-process and command-environment roots unioned conservatively.
  • Restricted Linux precreation to Zero-owned directories derived from the parent process; command-controlled paths are deny-if-present only and cannot create host directories.
  • Removed automatic nested masks already covered by user or directory-level denies.
  • Kept the whole Zero config deny while making plugins, specialists, and commands carveouts canonical on macOS and rejecting symlink carveouts.
  • Updated the policy JSON normalization for every new manager-baseline field and the expanded credential set.
  • Added cross-platform regressions for relative/path-list tool overrides, uppercase/lowercase npm precedence, file-vs-directory masks, parent/child root union, and non-creation of command-controlled paths.

Validation

Local (Go 1.26.5):

  • make fmt-check
  • go vet ./...
  • go test ./... -count=1
  • go test -race ./internal/oauth ./internal/sandbox ./internal/cli -count=1
  • darwin/amd64 and windows/amd64 compile checks for internal/oauth, internal/sandbox, and internal/cli
  • go run ./cmd/zero-release build
  • go run ./cmd/zero-release smoke
  • make lint-static — 0 issues
  • make vulncheck — no vulnerabilities
  • git diff HEAD --check

GitHub checks on bf75c60 are all green: Ubuntu, macOS, and Windows Smoke; Performance Smoke; Security & code health; Zero Review; and CodeRabbit.

The PR is MERGEABLE with zero unresolved inline review threads. The remaining CHANGES_REQUESTED gate is the review on pre-fix commit 0f6c87a; @jatmn, a fresh review of the current head would be appreciated.

@PierrunoYT
PierrunoYT requested a review from jatmn July 27, 2026 23:42

@jatmn jatmn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I found issues that need to be addressed before this is ready.

Findings

  • [P1] Mask the committed OAuth/MCP store file for process-trusted overrides outside ~/.config/zero, not only the .publish directory
    internal/sandbox/linux_helper.go:285
    internal/sandbox/profile.go:446
    internal/oauth/store.go:412
    The default …/zero case is covered correctly: the whole directory is ensured and tmpfs-masked, so a rename into that tree stays hidden (including the mid-session integration case). A process-trusted ZERO_OAUTH_TOKENS_PATH / ZERO_MCP_OAUTH_TOKENS_PATH outside that directory is different. The profile ensures and masks <path>.publish, but only lists the final <path> in DenyReadIfExists. Bubblewrap skips absent file targets, so a sandbox launched before the first save has no mount on the store file itself. fileBlob.write publishes plaintext under the masked .publish tree and then Renames it into the unmasked parent; under the read-all --ro-bind / posture the committed token file becomes visible to the already-running sandbox as soon as the host save completes. TestPermissionProfileUnionsProcessAndCommandCredentialRootsWithoutCreatingCommandDirs encodes the .publish half of this contract for parentToken but never checks post-rename visibility. Please keep directory-level containment for default …/zero stores, but for out-of-tree process-trusted overrides also make the committed store path unreadable on Linux after first save (for example by masking a safe parent, pre-materializing a maskable placeholder, or another approach that does not reintroduce workspace-parent masking). Command-controlled overrides that deliberately omit EnsureDenyReadDirs are out of scope here.

@PierrunoYT

Copy link
Copy Markdown
Contributor Author

PierrunoYT addressed the out-of-tree token-store masking finding in f25b3e7.

  • Process-trusted token and .secret final paths are tracked lexically and independently.
  • Linux Bubblewrap fails closed before runtime/helper launch when atomic replacement makes an exact-file deny unenforceable.
  • Durable directory masks, AllowRead, Seatbelt behavior, command-controlled environments, and terminal symlink semantics are preserved.
  • Added focused trust-boundary, selection, and early-failure regressions.

Validation: focused sandbox tests pass with -race; all fresh CI checks pass on Ubuntu, macOS, and Windows, including security, performance, CodeRabbit, and Zero Review. Ready for re-review.

@PierrunoYT
PierrunoYT requested a review from jatmn July 28, 2026 14:07

@jatmn jatmn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I found issues that need to be addressed before this is ready.

The first three items are rebase drift against current main, not defects in the new credential-deny logic itself. The remaining items are gaps in this PR's own design on head f25b3e7.

Findings

  • [P1] Rebase onto current main and resolve the sandbox conflicts before merge
    The live PR remains not mergeable (mergeable: false, head f25b3e7, base 81a5e6c, current main 8acd42a). git merge-tree shows conflicting edits in internal/sandbox/profile.go, internal/sandbox/profile_test.go, and internal/sandbox/runner_test.go. Please rebase, resolve those conflicts deliberately, and push so the resolved diff can be reviewed.

  • [P1] On rebase, restore git credential-store deny paths from #816
    internal/sandbox/profile.go:417
    main denies git's cleartext stores at ~/.git-credentials and ~/.config/git/credentials. This head's refactored credentialDenyReadPathsIn never had those paths — they are missing from the checkout, not removed by this patch. Port them into the new helper (deny the credentials file under ~/.config/git, not the whole git directory), bring over the #816 tests, and extend internal/cli/sandbox_test.go wantDenyRead so the policy JSON golden catches a regression.

  • [P1] On rebase, restore ZERO_DAEMON_REMOTE_TOKEN_FILE scrub from #677
    internal/sandbox/runner.go:1080
    main scrubs both ZERO_DAEMON_REMOTE_TOKEN and ZERO_DAEMON_REMOTE_TOKEN_FILE because TokenFromEnv accepts either form. This head only scrubs the inline variable. Restore the file-pointer scrub and TestScrubSensitiveEnv coverage from main when rebasing runner.go.

  • [P1] Give command-controlled token overrides durable Linux protection
    internal/sandbox/profile.go:254
    internal/sandbox/linux_helper.go:296
    f25b3e7 closes the process-trusted out-of-tree rename leak via fail-closed bwrap validation. Command-supplied overrides (CommandSpec.Env, including MCP-injected env) are still weaker by design: appendUntrusted copies only Paths and Dirs, never EnsureDirs, and tests require those paths to stay out of ProcessTrustedDenyReadFiles. On bubblewrap, absent token files or .publish directories are skipped, existing files get a /dev/null bind that store Rename can bypass, and plaintext in an unmasked .publish tree during the run stays readable. Please give command-env token paths the same durability as process-trusted stores without creating command-controlled host directories outside the token tree.

  • [P1] Pin relative process token denies to the store path, not rolling Getwd
    internal/sandbox/profile.go:288
    internal/oauth/store.go:138
    The stores resolve a relative ZERO_OAUTH_TOKENS_PATH with filepath.Abs once at open and write to that fixed path thereafter. credentialDenyReadPaths re-resolves the same override against current os.Getwd() on every BuildCommandPlan. After a cwd change, the profile can deny the wrong path while the real store stays readable. Derive process-trusted token denies from the same resolved location the writers use.

  • [P2] Make zero sandbox policy --json show command-scoped credential denies
    internal/cli/sandbox.go:71
    internal/sandbox/adapters.go:139
    Execution uses permissionProfileFromPolicy(..., spec.Dir, spec.Env); zero sandbox policy --json still uses PermissionProfileFromPolicy with no command context, so exported permissionProfile under-reports denyReadIfExists versus nested commands. Thread command context into introspection or document that the JSON view is process-env-only.

…fixes

Resolves the two sandbox conflicts deliberately rather than by side:

- internal/sandbox/profile.go keeps this branch's multi-home
  credentialDenyReadPathsIn and ports Gitlawb#816's git credential-store denies into
  it. ~/.git-credentials joins candidates only, not dirs, because it is a file
  and dirs drives directory-shaped handling; the XDG credentials file is added
  before the zero-directory handling so a normalization failure there cannot
  drop it. Gitlawb#816's tests come with it, rewritten against the new helper, and the
  policy JSON baseline in internal/cli/sandbox_test.go now lists both paths so
  the exported contract catches a regression.
- internal/sandbox/profile_test.go stays this branch's external-package file;
  the ported Gitlawb#816 tests need unexported symbols and live in their own internal
  test file.

runner.go's ZERO_DAEMON_REMOTE_TOKEN_FILE scrub from Gitlawb#677 merged cleanly and is
verified present. internal/config/command.go and the rest of main come through
untouched.

Also carries the review's two design fixes and the introspection note; see the
following commit message trailers in the PR discussion for what each one does.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@PierrunoYT

Copy link
Copy Markdown
Contributor Author

All six findings addressed in 64ca22e. GitHub now reports mergeable: MERGEABLE (was false).

One thing up front, since it affects how you read the diff: the merge commit carries both the conflict resolution and the two design fixes. I resolved and validated them together and did not want to push a merge whose tree I had not finished testing. If you would rather review them apart, say so and I will split it.

[P1] Merge with main. I merged upstream/main (8acd42a) rather than rebasing — the branch already carries an upstream merge commit and the PR is from a fork, so this keeps review anchors intact for the same resolved tree. Two conflicts, both resolved deliberately:

[P1] #816 git credential denies. Ported, with two placement decisions worth flagging: ~/.git-credentials joins candidates only and not dirs, because it is a file and dirs drives directory-shaped handling (bwrap binds, carveouts); and the XDG git/credentials entry is added before the zero-directory block so a normalizeProfilePath failure there cannot silently drop it. Both #816 tests came across, rewritten against the new helper, and internal/cli/sandbox_test.go's wantDenyRead now lists both paths — so the exported policy JSON is what catches a regression, as you asked.

[P1] #677 token-file scrub. Merged cleanly from main; verified present with its TestScrubSensitiveEnv coverage. internal/config/command.go comes through untouched.

[P1] Command-supplied token overrides. New CommandDenyReadFinalFiles on the profile, populated from the untrusted resolutions. It deliberately earns none of the process-trusted privileges — no carveouts, no EnsureDenyReadDir, no host mutation, so a command still cannot steer Zero into creating directories — but it now carries the same durability: validateLinuxBwrapPermissionProfile fails closed on it exactly as it already did for process-trusted stores. That is the only honest answer bubblewrap can give when a /dev/null bind is detachable by the store's next rename and an absent path is skipped outright. Seatbelt enforces these as ordinary pathname rules, present or not, so it has no reason to refuse.

Two things keep this from firing on every command: entries already covered by a user deny or by a directory Zero actually masks are filtered out (so the default store inside <config>/zero is not a fail-closed reason), and a path that lands in both lists is reported once, as the process-trusted store it is.

[P1] Relative token denies. The process base directory is now captured once during package initialization instead of re-read per BuildCommandPlan. That is what makes it equal the directory the stores resolved against — nothing in Zero calls os.Chdir today, so pinning keeps the two equal if one is ever added, instead of letting them drift per call.

This changed the contract two existing tests relied on, so they get a seam rather than a rewrite: PinProcessCredentialBaseDir (test-only, in export_test.go) moves the pin with a test that chdirs to simulate a process running elsewhere. TestCredentialDeniesMatchRelativeTokenOverridesFromStoreResolution is now the strongest form of your requirement — it pins the base dir to the same directory oauth.ResolveStorePath resolved in, and asserts the profile names exactly that file.

[P2] zero sandbox policy --json. Documented rather than threaded, because there is no command to thread: the command has not been chosen when this runs. The payload now carries a permissionProfileNote saying the profile is derived from this process's environment and working directory and that an executed command can add further credential deny-read entries, and Backend.BuildPlan says the same in godoc. A consumer diffing this against a nested command's profile now knows why they differ.

Tests. Two new regressions beyond the ported #816 pair, both verified on Linux:

  • TestCommandSuppliedTokenOverrideFailsClosedOnBubblewrap — asserts the baseline (no override) still plans successfully, then that a command-supplied override lands in CommandDenyReadFinalFiles, stays out of ProcessTrustedDenyReadFiles and EnsureDenyReadDirs, fails bwrap planning closed, and creates nothing on the host.
  • TestProcessCredentialBaseDirDoesNotFollowWorkingDirectoryChangest.Chdir between two profile builds must not move the deny.

Validation

  • go build ./... plus GOOS=linux / GOOS=darwin cross-builds; go vet ./...
  • go test ./... on Windows
  • go test ./internal/sandbox ./internal/cli ./internal/tools under WSL/Linux, where the credential deny-read paths actually execute (they skip on Windows)
  • git diff --check clean; gofmt -l clean for every touched file

One pre-existing Linux failure I did not introduce and left alone: TestSelectBackendChoosesPlatformAdapterWithFallback/linux_helper_missing_falls_back_explicitly fails under WSL2 because backend selection reports wsl. I confirmed it fails identically on f25b3e7 in a clean worktree.

@PierrunoYT
PierrunoYT requested a review from jatmn July 29, 2026 12:18

@jatmn jatmn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the contribution. I do not see any actionable merge-blocking issues from my review of the #675 credential-deny surface at head 64ca22e5.

The default-path fix is implemented and tested: ~/.config/zero is denied whole with plugin/specialist/command carveouts, EnsureDenyReadDirs plus bubblewrap masking covers the mid-session race for Zero-owned stores, OAuth/MCP publication writes pair with .publish denies, and parent/command credential roots are unioned without command-controlled host directory creation. Required CI is green. Windows read denial remains correctly deferred to #662.

Rechecking the prior draft against current code: out-of-tree process-trusted overrides do not leave a live bubblewrap bypass at head — validateLinuxBwrapPermissionProfile refuses launch when ProcessTrustedDenyReadFiles is populated (TestEngineBuildCommandPlanValidatesBwrapBeforeCreatingRuntime). Git credential paths and absent third-party stores follow the same documented best-effort model as ~/.aws. AWS/Azure env override gaps predate this PR.

Follow-up (not blocking merge) @Vasanthdev2004

  • [Needs maintainer decision] Linux policy for out-of-tree ZERO_OAUTH_TOKENS_PATH / ZERO_MCP_OAUTH_TOKENS_PATH
    internal/sandbox/linux_helper.go:223
    internal/sandbox/profile.go:250
    Bubblewrap cannot durably deny a replaceable file pathname; the current answer is fail-closed (sandboxed commands refuse to start when an out-of-tree process-trusted override is set). That is secure at head but breaks users who rely on a custom absolute token path outside ~/.config/zero. The alternative is committed-path masking after first save without masking workspace parents. Pick the product tradeoff explicitly rather than treating fail-closed as a temporary gap.

  • [P2] Deny the filesystem path behind ZERO_DAEMON_REMOTE_TOKEN_FILE (#677 follow-up)
    internal/sandbox/runner.go:1084
    internal/sandbox/profile.go:356
    Scrubbing the variable in this PR closes half of the #677 leak class. The on-disk bearer token at a known path (for example under ~/.zero, which is outside the ~/.config/zero deny tree) remains readable under the read-all posture. That gap largely predates this PR; extend the credential baseline the same way GOOGLE_APPLICATION_CREDENTIALS is handled.

  • [P3] Include permissionProfileNote on zero sandbox policy --effective --json
    internal/cli/sandbox.go:250
    internal/cli/sandbox.go:112
    Plain --json documents that the embedded profile is process-only and that command context can add denies or trigger bubblewrap fail-closed rejection. --effective --json serializes the same process-derived profile without that note, even though doctor/TUI steer operators to --effective for inspection.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Sandbox can read Zero's own OAuth and provider credential stores

8 participants