Skip to content

fix(secrets): secrets configure deletes the credential backing the SecretRef it just wrote - #117795

Closed
yetval wants to merge 1 commit into
openclaw:mainfrom
yetval:fix/secrets-apply-env-scrub-self-delete
Closed

yetval wants to merge 1 commit into
openclaw:mainfrom
yetval:fix/secrets-apply-env-scrub-self-delete

Conversation

@yetval

@yetval yetval commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

openclaw secrets configure --apply (and secrets apply --from <plan>) rewrites models.providers.*.apiKey to an env SecretRef such as env:default:OPENAI_API_KEY, and in the same operation deletes the OPENAI_API_KEY= assignment that the new ref resolves from. On the next start the ref the migration had just written is unresolvable: openclaw secrets audit reports unresolved=1 and the provider has no credential at all. The defect is still on main at 9386ac096632: scrubEnvFiles builds its key set from listKnownSecretEnvVarNames() with no awareness of the refs the same plan is writing, and scrubEnvRaw deletes any line whose key is in that set and whose value is one of the plaintext values the plan migrated out of config. For a plaintext-to-env migration both conditions hold by construction.

Non-goal, stated up front: this does not touch the cross-provider same-value over-scrub in #97660. Retention here is scoped to the ids the current plan's own targets read.

Why This Change Was Made

Three narrower repairs were tried and were all wrong.

Exempting the planned variable name retained a same-named value even when apply had validated a different one, so a restarted process could silently authenticate as a stale credential. Binding retention to the state-directory file fixed that but assumed the state .env is the only dotenv source a fresh process reads, which is false: when OPENCLAW_CONFIG_PATH points outside the state directory, gateway startup also loads the config directory's .env.

The third, at the previously reviewed head c6d1f394bbcc, walked the files in load order but retained the first raw line whose value matched. ClawSweeper's P1 and the medium security finding were right: readDotEnvFile reduces a file through dotenv.parse before any cross-file precedence is applied, and within one file the last assignment of a name wins. A retained first line followed by a stale duplicate under the same name left the stale value effective, so a fresh gateway authenticated with a credential apply never validated. Scenario C in the proof below shows that happening on c6d1f394bbcc with the real runtime.

Retention is now derived from each file's runtime-effective assignment instead of its first matching line:

const durableLineByKey = new Map<string, number>();
assignments.forEach((match, index) => {
  const envKey = match?.[1] ?? "";
  if (
    allowedEnvKeys.has(envKey) &&
    retainableEnvValues.get(envKey) === parseEnvAssignmentValue(match?.[2] ?? "")
  ) {
    durableLineByKey.set(envKey, index);
  }
});

durableLineByKey keeps the last index whose parsed value equals the value apply validated the ref against, which is the assignment dotenv.parse would surface for that file. Every other assignment of a retained name in that file is removed, so the durable source is also the effective one and no shadowed or shadowing duplicate can become the active credential. Names with no matching assignment fall through to the unchanged scrub.

Across files, envRefValuesAwaitingSource starts as the plan's own source: "env" targets mapped to env[ref.id], which is exactly the value validateProjectedSecretsState resolves for that ref (resolveEnvRefs in src/secrets/resolve.ts returns params.env[ref.id] unchanged). A name is dropped from that map once a file has supplied it, so the first file that can back a ref is the only one that retains it and every lower-precedence copy is still scrubbed.

The ordering is not a coincidence maintained by hand. listSecretsDotEnvPaths returns [stateDir/.env, dirname(configPath)/.env], and resolveGatewayRunDotEnvPaths in src/cli/gateway-cli/pre-bootstrap.ts hands loadGlobalRuntimeDotEnvFiles exactly [resolveStateDir/.env, resolveConfigDir/.env]. loadParsedDotEnvFiles in src/infra/dotenv-global.ts is first-wins across that list and never overrides a value already in process.env. The scrubber and the loader consume the same sequence.

scrubEnvFiles is the only place that decides which dotenv assignments a plan removes, so the self-delete, the stale-retention hazard, the same-file precedence hazard, and the external-config case are all decided in one function. Nothing downstream compensates.

Sibling surfaces: scrubAuthProfilesForProviderTargets and scrubLegacyAuthJson clear stores that env SecretRefs never read from, so neither can delete a ref's source; they are unchanged. file and exec refs never read a dotenv assignment, so they are skipped and their scrub behavior is unchanged. ~/.config/openclaw/gateway.env is loaded by the runtime but is not in listSecretsDotEnvPaths, so secrets apply never scrubbed it and still does not. Working-directory .env files are likewise outside listSecretsDotEnvPaths.

User Impact

An operator who migrates a provider credential to an env SecretRef keeps a working provider after restart instead of an unresolvable ref, and the credential a restarted gateway resolves is the one apply validated rather than a stale duplicate that happened to sit later in the same file. With options.scrubEnv off nothing changes, and every dotenv value not backing one of this plan's own env refs is scrubbed exactly as before; the pre-existing scrub assertions pass unmodified.

Production delta is +48/-10 in one file, net +38, unchanged from the previously reviewed head even though the retention predicate is now precedence-correct. Docs +20/-1, tests +182/-2.

Evidence

  • node scripts/run-vitest.mjs src/secrets/apply.test.ts - 43 passed.
  • New table-driven case removes a same-file duplicate declared before/after the retained env SecretRef source fails on the rebased previous head with expected [ Array(1) ] to include <stateEnvPath> (the .env was never rewritten, so the shadowing duplicate survived) and passes here. That is the P1 regression ClawSweeper asked for.
  • node scripts/run-oxlint.mjs src/secrets/apply.ts src/secrets/apply.test.ts - clean. oxfmt - clean.
  • tsgo -p tsconfig.core.json - no diagnostic in src/secrets; the only output is pre-existing TS4058/TS2883 declaration-naming noise in src/auto-reply/**, src/infra/embedded-state-lock.ts, and src/media-understanding/** caused by this worktree resolving @types/node through a linked node_modules.
  • node scripts/check-docs-mdx.mjs - passed, 772 files. node scripts/docs-link-audit.mjs - 6495 internal links, 0 broken.
  • git diff --check - clean.

Rebased onto main 9386ac096632 with no conflicts.

Real behavior proof

Behavior addressed: openclaw secrets configure --apply deleted the .env assignment that the env SecretRef it had just written resolves from, leaving the provider with no credential in every fresh gateway process; with OPENCLAW_CONFIG_PATH outside the state directory the deleted file was the config-adjacent .env. At the previously reviewed head the retained line was the first raw match rather than the file's effective assignment, so a later duplicate under the same name stayed effective and a fresh gateway resolved a credential apply never validated.
Real environment tested: real buildConfigureCandidatesForScope plus buildSecretsConfigurePlan plus runSecretsApply in one process, then real loadGlobalRuntimeDotEnvFiles and real resolveSecretRefValue in a second process started after the operator shell export is gone, both against one temporary state directory, on pristine main 9386ac096632, on the previously reviewed head c6d1f394bbcc rebased onto that same main, and on this branch head 2bd3590467904b89e4f8ce79873402257dd4c395. Nothing is stubbed: real dotenv startup hydration using the same path selection resolveGatewayRunDotEnvPaths makes, real plan builder, real apply writer, real dotenv scrubber, real resolver, real files on disk.
Exact steps or command run after this patch: node --import tsx apply-run.mts <root> <scenario> to seed the config and .env files for the scenario and run the apply, then env -u OPENAI_API_KEY node --import tsx fresh-gateway-run.mts <root> <scenario> to hydrate a second process from the gateway dotenv set and resolve the provider ref.
Evidence after fix:

# SCENARIO A: config directory outside the state directory holds the only credential line
#   seeded: etc-openclaw/.env -> "OPENAI_API_KEY=sk-openai-live-9c2f\nUNRELATED=value"
#           state/.env        -> "UNRELATED=value"

# BEFORE (pristine main 9386ac096632)
apply changed        true
openclaw.json apiKey {"source":"env","provider":"default","id":"OPENAI_API_KEY"}
state/.env           "UNRELATED=value\n"
etc-openclaw/.env    "UNRELATED=value\n"
fresh process env OPENAI_API_KEY  null
openai provider auth              provider credential unresolved  Environment variable "OPENAI_API_KEY" is missing or empty.

# AFTER (this patch 2bd3590467904b89e4f8ce79873402257dd4c395), identical inputs
apply changed        true
openclaw.json apiKey {"source":"env","provider":"default","id":"OPENAI_API_KEY"}
state/.env           "UNRELATED=value\n"
etc-openclaw/.env    "OPENAI_API_KEY=sk-openai-live-9c2f\nUNRELATED=value\n"
fresh process env OPENAI_API_KEY  "sk-openai-live-9c2f"
openai provider auth              resolved provider credential  "sk-openai-live-9c2f"

# SCENARIO B: both files carry the same credential line, higher-precedence source must win alone
#   seeded: state/.env        -> "OPENAI_API_KEY=sk-openai-live-9c2f\nUNRELATED=value"
#           etc-openclaw/.env -> "OPENAI_API_KEY=sk-openai-live-9c2f\nUNRELATED=value"

# BEFORE (pristine main 9386ac096632)
state/.env           "UNRELATED=value\n"
etc-openclaw/.env    "UNRELATED=value\n"
fresh process env OPENAI_API_KEY  null
openai provider auth              provider credential unresolved  Environment variable "OPENAI_API_KEY" is missing or empty.

# AFTER (this patch 2bd3590467904b89e4f8ce79873402257dd4c395), identical inputs
state/.env           "OPENAI_API_KEY=sk-openai-live-9c2f\nUNRELATED=value\n"
etc-openclaw/.env    "UNRELATED=value\n"
fresh process env OPENAI_API_KEY  "sk-openai-live-9c2f"
openai provider auth              resolved provider credential  "sk-openai-live-9c2f"

# SCENARIO C: the state .env declares the name twice, validated value first, rotated-out value second
#   seeded: state/.env -> "OPENAI_API_KEY=sk-openai-live-9c2f\nOPENAI_API_KEY=sk-openai-rotated-out-4a11\nUNRELATED=value"
#   apply validates the ref against sk-openai-live-9c2f, inherited from the operator shell

# BEFORE (pristine main 9386ac096632)
state/.env           "OPENAI_API_KEY=sk-openai-rotated-out-4a11\nUNRELATED=value\n"
fresh process env OPENAI_API_KEY  "sk-openai-rotated-out-4a11"
openai provider auth              resolved provider credential  "sk-openai-rotated-out-4a11"

# PREVIOUSLY REVIEWED HEAD (c6d1f394bbcc, first-raw-line retention), identical inputs
state/.env           "OPENAI_API_KEY=sk-openai-live-9c2f\nOPENAI_API_KEY=sk-openai-rotated-out-4a11\nUNRELATED=value\n"
fresh process env OPENAI_API_KEY  "sk-openai-rotated-out-4a11"
openai provider auth              resolved provider credential  "sk-openai-rotated-out-4a11"

# AFTER (this patch 2bd3590467904b89e4f8ce79873402257dd4c395), identical inputs
state/.env           "OPENAI_API_KEY=sk-openai-live-9c2f\nUNRELATED=value\n"
fresh process env OPENAI_API_KEY  "sk-openai-live-9c2f"
openai provider auth              resolved provider credential  "sk-openai-live-9c2f"

Observed result after fix: in scenario A the provider moves from having no credential after restart to resolving sk-openai-live-9c2f from the config-adjacent file a fresh gateway actually loads. In scenario B only the higher-precedence assignment survives and the redundant lower-precedence copy is removed, so one readable source per ref is kept rather than every matching one. In scenario C both pristine main and the previously reviewed head hand the restarted process sk-openai-rotated-out-4a11, a credential apply never validated; this patch removes the shadowing duplicate and the restarted process resolves sk-openai-live-9c2f.
What was not tested: no live provider request is made, only the credential a restarted process resolves; no managed gateway service restart was driven, the second process stands in for it using the same dotenv path selection gateway startup makes; the full build was not run; ~/.config/openclaw/gateway.env and working-directory .env files are loaded by the runtime but are not in listSecretsDotEnvPaths, so they are neither scrubbed nor retained here.

Documentation

docs/gateway/secrets.md gains a Retained dotenv sources section. It names the two files secrets apply scrubs in the order the gateway loads them, states that only openclaw gateway run loads the active config directory's .env while normal CLI commands load the working-directory and state-directory files instead, and therefore that a ref whose only retained source is the config-directory file resolves in the gateway but not in a fresh CLI such as the post-apply openclaw secrets audit. It states the two precedence rules that make retention correct: first file wins across files, last assignment wins within a file, which is why the other assignments of a retained name in that file are removed. The agent-access boundary section still says plainly that an env SecretRef does not satisfy that boundary: the retained line stays agent-readable, the re-audit keeps reporting PLAINTEXT_FOUND, and completing the boundary requires file or exec refs. docs/gateway/secrets-plan-contract.md records the scrubEnv retention rule in the same terms.

Open maintainer decisions

  1. scrubEnv default-behavior change on an auth path. After this lands, an upgrade that migrates a dotenv value to an env ref keeps that one line instead of deleting it, and removes the other assignments of that name in the same file. That is the intended repair and it is recorded in the plan contract doc, but it changes a default-on scrub on a credential path and is worth an explicit accept. ClawSweeper also flags a Stored data model change on src/secrets/apply.test.ts; that file is fixture JSON inside a suite, and no on-disk format, schema version, or persisted shape changes in this PR.

  2. P3 asked for the invariant as a comment at the call site; it is carried by naming and docs instead. The map is now named envRefValuesAwaitingSource, so envRefValuesAwaitingSource.delete(retainedKey) reads as consuming a pending ref rather than as ordinary map cleanup, and the lifecycle invariant itself is written down in docs/gateway/secrets-plan-contract.md and the new Retained dotenv sources section. Root AGENTS.md does ask for an inline comment on cross-path lifecycle ordering, so if a maintainer wants it at the code site rather than in the name, say so and it goes in.

  3. Production delta is +38, not net-neutral. The growth is the retention predicate, its inputs, and the first-wins bookkeeping. Absorbing it into an existing owner would mean giving scrubEnvRaw knowledge of the file list, which merges two responsibilities rather than removing one, so the delta is proposed as justified rather than avoidable.

@yetval
yetval marked this pull request as ready for review August 2, 2026 04:14
@yetval
yetval requested a review from a team as a code owner August 2, 2026 04:14
@yetval
yetval force-pushed the fix/secrets-apply-env-scrub-self-delete branch from 9ae5669 to 201c887 Compare August 2, 2026 04:33
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. P1 High-priority user-facing bug, regression, or broken workflow. labels Aug 2, 2026
@clawsweeper

clawsweeper Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed August 14, 2026, 12:41 PM ET / 16:41 UTC.

ClawSweeper review

What this changes

The PR retains the runtime-effective dotenv assignment needed by each newly written environment SecretRef, removes same-file shadowing duplicates, and documents dotenv precedence.

Regression provenance

Possible regression — probable (reproduction; reviewed change). No predecessor PR is attributed.

Merge readiness

⚠️ Needs maintainer review before merge - 8 items remain

The core repair is still necessary and the refreshed branch fixes the current-main self-delete path, but it needs two documentation/context corrections and an explicit maintainer security-boundary decision before merge.

Priority: P1
Reviewed head: 2bd3590467904b89e4f8ce79873402257dd4c395
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The real behavior proof and owner-layer repair are strong, while two review findings and a security-boundary decision remain.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The PR body provides a redacted two-process after-fix trace through real planning, apply, gateway dotenv hydration, and SecretRef resolution.
Patch quality 🦐 gold shrimp (3/6) Security review found an item that needs attention.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body provides a redacted two-process after-fix trace through real planning, apply, gateway dotenv hydration, and SecretRef resolution.
Evidence reviewed 6 items Current-main defect: Current main removes any known secret dotenv assignment whose parsed value was migrated, without exempting a newly written env SecretRef source.
PR owner-boundary repair: The branch selects the last matching assignment in a file and consumes a retained key after the first precedence-valid dotenv source.
Runtime precedence contract: Gateway startup reads state dotenv first, optionally config-adjacent dotenv second, and preserves pre-existing process values; dotenv parsing produces one effective entry per key before cross-file precedence.
Findings 2 actionable findings [P2] Narrow the cleanup promise to values this scrubber removes
[P3] Explain cross-file retention consumption at the delete site
Security Needs attention Default retention leaves a credential source on disk: The new retention map intentionally preserves one dotenv credential assignment; this is necessary for restart-time resolution but leaves agent-readable plaintext and must be explicitly accepted.

How this fits together

Secrets apply converts configured credentials to SecretRefs and scrubs plaintext storage. Gateway startup then loads dotenv files and resolves environment-backed references for provider authentication.

flowchart LR
A[Secrets plan] --> B[Secrets apply]
B --> C[Dotenv scrub]
C --> D[Gateway startup]
D --> E[Dotenv loading]
E --> F[SecretRef resolution]
F --> G[Provider authentication]
Loading

Decision needed

Question Recommendation
Should default-on secrets apply retain one validated plaintext dotenv assignment when converting a credential to an env SecretRef? Accept durable env sources: Accept the documented tradeoff after the documentation and lifecycle-context findings are fixed.

Why: This is the necessary behavior for a restarted gateway to resolve an env SecretRef, but it intentionally preserves agent-readable credential material and changes the security meaning of the default scrub.

Before merge

  • Narrow the cleanup promise to values this scrubber removes (P2) - This says every stale or lower-precedence copy is removed, but scrubEnvRaw only removes a lower-precedence assignment when its parsed value is in migratedValues; a different stale value remains. Document the actual boundary so operators do not infer a clean audit from this migration.
  • Explain cross-file retention consumption at the delete site (P3) - Add a short invariant comment here: deleting this key prevents a lower-precedence dotenv file from becoming a second retained source. This is cross-file lifecycle ordering, and the repository policy requires that context at the code site.
  • Resolve security concern: Default retention leaves a credential source on disk - The new retention map intentionally preserves one dotenv credential assignment; this is necessary for restart-time resolution but leaves agent-readable plaintext and must be explicitly accepted.
  • Resolve merge risk (P1) - The documentation says all stale or lower-precedence copies are scrubbed, but a lower-precedence value that differs from the migrated plaintext is retained.
  • Resolve merge risk (P1) - The default-on repair deliberately leaves one plaintext credential on disk for environment SecretRefs; maintainers must accept that security tradeoff.
  • Resolve merge risk (P1) - Production code grows by 38 net lines for a bug fix; the added precedence selection is owner-local, but deserves review.
  • Complete next step (P2) - A maintainer must decide the default plaintext-retention boundary after the contributor resolves the two concrete review findings.

Findings

  • [P2] Narrow the cleanup promise to values this scrubber removes — docs/gateway/secrets.md:829
  • [P3] Explain cross-file retention consumption at the delete site — src/secrets/apply.ts:755-756
  • [low] Default retention leaves a credential source on disk — src/secrets/apply.ts:735
Agent review details

Security

Needs attention: The branch correctly surfaces that env SecretRefs retain plaintext, but accepting that default security boundary remains a maintainer decision.

PR surface

Source +38, Tests +180, Docs +19. Total +237 across 4 files.

View PR surface stats
Area Files Added Removed Net
Source 1 48 10 +38
Tests 1 182 2 +180
Docs 2 20 1 +19
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 250 13 +237

Review metrics

Metric Value Why it matters
Production versus test LOC production +48/-10 (net +38); tests +182/-2; docs +20/-1 The added production logic implements dotenv precedence and duplicate removal; the regression coverage is substantially larger and behavior-focused.
Default cleanup behavior 1 changed default path: scrubEnv Default-on secrets apply now retains one validated dotenv assignment instead of deleting every migrated matching assignment.

Stored data model

Persistent data-model change detected: serialized state: src/secrets/apply.test.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: canonical
Canonical: #117795
Summary: This PR is the canonical candidate for the newly-written env SecretRef self-delete; the shared-value and systemd restart work are adjacent but distinct.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Correct the retention contract before merge (recommended)
    Narrow the docs to values actually removed and add the required lifecycle comment at the cross-file key-consumption point.
  2. Accept the plaintext-source tradeoff
    A maintainer may accept retaining one validated dotenv source as the required compatibility behavior for env SecretRefs.

Technical review

Best possible solution:

Keep the precedence-aware repair in secrets apply, correct the cleanup promise, add the lifecycle invariant at the consuming delete, and merge only if the maintainer accepts one durable plaintext source for env SecretRefs.

Do we have a high-confidence way to reproduce the issue?

Yes: current main's value-based scrub and the branch's focused parsed-dotenv regression cases establish the failure and the repaired precedence path, although this review did not execute untrusted branch code.

Is this the best way to solve the issue?

Mostly yes: retention belongs in the sole dotenv scrub owner and matches gateway loading precedence, but the cleanup documentation and lifecycle explanation must match the narrower implementation.

Full review comments:

  • [P2] Narrow the cleanup promise to values this scrubber removes — docs/gateway/secrets.md:829
    This says every stale or lower-precedence copy is removed, but scrubEnvRaw only removes a lower-precedence assignment when its parsed value is in migratedValues; a different stale value remains. Document the actual boundary so operators do not infer a clean audit from this migration.
    Confidence: 0.97
  • [P3] Explain cross-file retention consumption at the delete site — src/secrets/apply.ts:755-756
    Add a short invariant comment here: deleting this key prevents a lower-precedence dotenv file from becoming a second retained source. This is cross-file lifecycle ordering, and the repository policy requires that context at the code site.
    Confidence: 0.94

Overall correctness: patch is incorrect
Overall confidence: 0.94

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against ffd42dd8a390.

Labels

Label justifications:

  • P1: A default secrets migration can otherwise leave a provider without a credential after restart.
  • merge-risk: 🚨 compatibility: The default cleanup behavior now preserves a credential source that existing users may expect to be scrubbed.
  • merge-risk: 🚨 auth-provider: The retained assignment determines whether a provider env SecretRef resolves at gateway startup.
  • merge-risk: 🚨 security-boundary: The branch intentionally keeps one plaintext credential assignment on disk.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (live_output): The PR body provides a redacted two-process after-fix trace through real planning, apply, gateway dotenv hydration, and SecretRef resolution.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides a redacted two-process after-fix trace through real planning, apply, gateway dotenv hydration, and SecretRef resolution.

Evidence

Security concerns:

  • [low] Default retention leaves a credential source on disk — src/secrets/apply.ts:735
    The new retention map intentionally preserves one dotenv credential assignment; this is necessary for restart-time resolution but leaves agent-readable plaintext and must be explicitly accepted.
    Confidence: 0.98

What I checked:

  • Current-main defect: Current main removes any known secret dotenv assignment whose parsed value was migrated, without exempting a newly written env SecretRef source. (src/secrets/apply.ts:152, ffd42dd8a390)
  • PR owner-boundary repair: The branch selects the last matching assignment in a file and consumes a retained key after the first precedence-valid dotenv source. (src/secrets/apply.ts:169, 2bd359046790)
  • Runtime precedence contract: Gateway startup reads state dotenv first, optionally config-adjacent dotenv second, and preserves pre-existing process values; dotenv parsing produces one effective entry per key before cross-file precedence. (src/infra/dotenv-global.ts:71, 2bd359046790)
  • Regression coverage: Added cases cover state and config-adjacent sources plus both same-file duplicate orderings, resolving the ref from parsed post-apply dotenv state. (src/secrets/apply.test.ts:376, 2bd359046790)
  • Documentation mismatch: The docs promise removal of every stale or lower-precedence copy, but the implementation only removes a lower-precedence assignment when its value is in migratedValues; a different stale value remains. Public docs: docs/gateway/secrets.md. (docs/gateway/secrets.md:829, 2bd359046790)
  • History provenance: The inspected current-main blame boundary carries the original scrubber through commit 5c3fd2f; older history could not be hydrated because the partial clone's remote DNS lookup failed. (src/secrets/apply.ts:152, 5c3fd2fbe97b)

Likely related people:

  • Peter Steinberger: The available blame boundary carries the existing scrubber through a current-main commit by Peter; deeper provenance was unavailable in the partial clone. (role: recent current-main contributor; confidence: low; commits: 5c3fd2fbe97b; files: src/secrets/apply.ts)
  • sallyom: Authored merged dotenv startup work referenced by this PR, covering the gateway dotenv loading contract this change follows. (role: adjacent runtime contributor; confidence: medium; commits: 4cbbfc215953; files: src/cli/gateway-cli/pre-bootstrap.ts, src/infra/dotenv-global.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Correct the cleanup claim in both secrets docs.
  • Add the short cross-file lifecycle comment at the retained-key deletion.
  • Obtain maintainer acceptance of retaining a plaintext dotenv source for env SecretRefs.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (12 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-04T22:18:18.608Z sha 201c8879b706f461428fcd829381cdaf5f128d73 :: needs changes before merge. :: [P3] Document why planned env refs bypass cleanup
  • reviewed 2026-08-05T20:48:54.211Z sha 201c8879b706f461428fcd829381cdaf5f128d73 :: needs changes before merge. :: [P3] Document why planned env refs bypass cleanup
  • reviewed 2026-08-05T21:37:03.728Z sha 201c8879b706f461428fcd829381cdaf5f128d73 :: needs changes before merge. :: [P3] Document the durable env-source invariant
  • reviewed 2026-08-07T18:56:55.458Z sha 201c8879b706f461428fcd829381cdaf5f128d73 :: needs changes before merge. :: [P3] Document why planned env refs bypass cleanup
  • reviewed 2026-08-07T19:56:20.372Z sha 201c8879b706f461428fcd829381cdaf5f128d73 :: needs changes before merge. :: [P2] Align the env-reference cleanup docs | [P3] Document why planned env refs bypass cleanup
  • reviewed 2026-08-09T17:45:45.046Z sha 820d811de330dd7e2e8b3d72fd531a928f9a3da8 :: needs changes before merge. :: [P1] Preserve only the value that backs the new env reference | [P2] Do not call retained env plaintext an agent-access completion
  • reviewed 2026-08-11T16:07:27.447Z sha 77dee9b8465222d1b9ad91f09bf9dce621218512 :: needs changes before merge. :: [P1] Retain the external config dotenv source | [P2] Describe dotenv source precedence accurately | [P3] Explain the retained-source lifecycle invariant
  • reviewed 2026-08-13T06:19:30.763Z sha c6d1f394bbcca7cd236fd369ac64975ba2dc2eb5 :: needs changes before merge. :: [P1] Retain the runtime-effective dotenv assignment | [P2] Scope external-config dotenv guidance to gateway startup | [P3] Explain the retained-key consumption at the lifecycle boundary

@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. labels Aug 3, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 7, 2026
@yetval
yetval force-pushed the fix/secrets-apply-env-scrub-self-delete branch from 201c887 to 820d811 Compare August 9, 2026 17:38
@yetval

yetval commented Aug 9, 2026

Copy link
Copy Markdown
Contributor Author

Rebased and addressed the open verdict items. New head 820d811de330dd7e2e8b3d72fd531a928f9a3da8, rebased onto origin/main at 34b8a6515d780e07866b437dfc1a6f12d1fc7f18 with no conflicts.

  • [P2] Align the env-reference cleanup docs: fixed in docs/gateway/secrets.md and docs/gateway/secrets-plan-contract.md. The guide now states that an env SecretRef keeps its backing .env line on purpose, so re-audit still reports it as PLAINTEXT_FOUND, that migrating to env removes the credential from openclaw.json and generated models.json files but not from disk, that a fully clean re-audit requires a file or exec source, and that deleting the reported line leaves the ref unresolvable in every fresh process. The agent-access boundary checklist earlier in the same guide is corrected to match, and the plan contract now documents the retention inside the scrubEnv option description.
  • [P3] Document why planned env refs bypass cleanup: added the invariant comment at the scrub site in src/secrets/apply.ts, naming the lifecycle boundary. Only the applying process inherits the value from its own environment, so scrubbing a variable the same plan just pointed a ref at deauthenticates that provider in every fresh process.
  • [P1] Merge risk, branch behind main: resolved by the rebase above.
  • [P1] Merge risk, docs correction: resolved by the P2 change.

Proof regenerated and pinned to the new head. Same two-child-process run on a real temporary state directory: real loadDotEnv startup hydration, real buildConfigureCandidatesForScope and buildSecretsConfigurePlan with scrubEnv: true, real runSecretsApply, then real runSecretsAudit in a separate process. Base at 34b8a6515d7 empties .env and audits unresolved=1; patched head keeps the line and audits unresolved=0. Full transcript is in the PR body.

Acceptance criteria re-run at this head: vitest run src/secrets/apply.test.ts 38 passed, oxlint clean, oxfmt --check clean across both source files and both docs, check-docs-mdx passed 770 files, docs-list exit 0, and the link audit reports 0 broken links over 6411 internal links.

One item is left for maintainer judgement rather than changed. The Stored data model flag reads serialized state: src/secrets/apply.test.ts, which is test fixture JSON written into a temporary state directory by the added cases, not a persisted schema. This PR changes no on-disk format: .env line syntax, plan JSON shape, and the openclaw.json ref shape are all untouched, so there is no upgrade path to prove.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Aug 9, 2026
@yetval
yetval force-pushed the fix/secrets-apply-env-scrub-self-delete branch from 820d811 to 77dee9b Compare August 11, 2026 16:01
@yetval

yetval commented Aug 11, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto current main and reworked the retention rule. The P1 was correct: name-only exclusion retained a same-named value even when apply had validated a different one inherited from the operator's shell, so a restarted process could authenticate as the stale credential. Retention is now bound to the durable source path and to the resolved value.

scrubEnvFiles keeps an assignment only when all three hold: the file is the state-directory .env, the name is read by one of this same plan's env SecretRef targets, and the value equals the value apply validated that ref against. plannedEnvRefValues maps each source: "env" target id to env[id], which is exactly what validateProjectedSecretsState resolves, since resolveEnvRefs returns params.env[ref.id] unchanged. Every other name, a stale value under the same name, and the config-adjacent copy are all still scrubbed.

The state-directory restriction is the runtime contract, not a guess. loadGlobalRuntimeDotEnvFiles loads resolveConfigDir(process.env)/.env plus ~/.config/openclaw/gateway.env, and loadDotEnv adds the workspace .env, which blocks provider auth keys. The config-adjacent .env that listSecretsDotEnvPaths also scans is never read by a fresh process, so retaining a copy there would only leave plaintext behind that no ref resolves.

Item by item:

  • [P1] Preserve only the value that backs the new env reference - fixed at src/secrets/apply.ts. Retention is path- and value-bound; the mismatched fixture you flagged is gone.
  • [medium] Retained dotenv credential is not bound to the validated ref - same change. The retained value is now, by construction, the value projected validation resolved.
  • Merge risk (P1), migration validated against an inherited credential retains a different state-directory value - closed by the same predicate. New case scrubs a state .env value that does not back the validated env SecretRef asserts the stale line is removed and that a process started without the shell export resolves nothing rather than the stale value.
  • Improve patch quality: bind retained dotenv entries to the validated value and durable source path, with a fresh-process regression - done. The regression builds its env by reading the state .env back with the real readDotEnvFile, then drives the real resolveSecretRefValue, which is what a restarted process does. A second case, scrubs a config-adjacent .env copy while keeping the state .env source, covers the path half.
  • [P2] Do not call retained env plaintext an agent-access completion - fixed at docs/gateway/secrets.md. The checklist item is back to requiring a clean openclaw secrets audit --check. The page now states that an env SecretRef does not satisfy the agent-access boundary: the retained line stays agent-readable, the re-audit keeps reporting PLAINTEXT_FOUND, and completing the boundary requires file or exec refs or an isolated state directory.
  • Merge risk (P1), the checklist can tell operators an agent-access migration is complete - same change.
  • Improve patch quality: correct the agent-access completion guidance - same change.
  • Complete next step (P2) - done; no product-direction decision was needed for either half.
  • PR fixture demonstrates the mismatch - resolved. Four pre-existing scrub assertions that the previous head had to rewire onto a renamed variable are back to their original form and pass unmodified, because a value that does not back the new ref is scrubbed again.
  • Stored data model on src/secrets/apply.test.ts - that file is fixture JSON inside a suite; no on-disk format or schema version changes. The genuine upgrade-visible change is the scrubEnv default, recorded in docs/gateway/secrets-plan-contract.md. Left as an explicit maintainer accept in the PR body.

Reviewed head was 820d811de330; that base is now stale. Still needed on current main: the unconditional scrubEnvRaw(current, scrubbedValues, knownSecretEnvVars) call is unchanged there, and the refreshed proof reproduces the self-delete against pristine main afc644464d9a. #119441 is adjacent, not superseding; it makes a managed gateway restart reload and clear managed dotenv values, which makes the scrubbed credential disappear more definitively, not less.

The refreshed proof in the body runs the real plan builder, real runSecretsApply, then real runSecretsAudit and resolveSecretRefValue in a separate process with the shell export removed, across three trees. On pristine main the provider ends with no credential. On the previous head a stale copy survived and the provider silently authenticated as sk-canary-stale-B1. On this head the matching source survives and the stale copy is removed.

Acceptance criteria: src/secrets/apply.test.ts and src/secrets/audit.test.ts pass (105 with resolve.test.ts), git diff --check clean, docs MDX check passed over 769 files, docs link audit 0 broken over 6430 internal links.

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Aug 11, 2026
@yetval
yetval force-pushed the fix/secrets-apply-env-scrub-self-delete branch from 77dee9b to c6d1f39 Compare August 13, 2026 05:35
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime labels Aug 13, 2026
@yetval

yetval commented Aug 13, 2026

Copy link
Copy Markdown
Contributor Author

Rebased and reworked the retention rule. New head c6d1f394bbcca7cd236fd369ac64975ba2dc2eb5, rebased onto main eda22ae1d578 with no conflicts.

The P1 was correct and the premise behind the previous head was wrong. I had claimed in the last round that "the config-adjacent .env is never read by a fresh process". resolveGatewayRunDotEnvPaths in src/cli/gateway-cli/pre-bootstrap.ts:80-85 disproves that: when resolveConfigDir differs from resolveStateDir it passes the config directory's .env to loadGlobalRuntimeDotEnvFiles as an additional runtime source. So for an external OPENCLAW_CONFIG_PATH the previous head deleted the only credential source, exactly as you described.

Retention now follows runtime precedence instead of a hard-coded path. listSecretsDotEnvPaths returns [stateDir/.env, dirname(configPath)/.env] and the gateway loader consumes [resolveStateDir/.env, resolveConfigDir/.env], the same sequence, and loadParsedDotEnvFiles is first-wins across it. scrubEnvFiles now walks that list with a working retention map and deletes each key once an earlier file has supplied it, so the first assignment a fresh process would actually read survives and every later duplicate is scrubbed.

Item by item:

  • [P1] Retain the external config dotenv source - fixed at src/secrets/apply.ts. Retention is precedence-ordered, not state-directory-only. New case keeps the config-adjacent .env source when the state .env cannot back the env SecretRef is the config-only regression you asked for; it fails on the previous head 77dee9b84652 with expected [ ... ] to not include <configEnvPath> and passes here.
  • [P2] Describe dotenv source precedence accurately - fixed at docs/gateway/secrets.md. New Retained dotenv sources section lists the real load order: inherited process environment first and never overridden by a file, then the state-directory .env, then the active config directory's .env when OPENCLAW_CONFIG_PATH is external. The false "never read by a fresh process" claim is gone, and the guidance is scoped to the retained-source case so operators do not delete a valid source. docs/gateway/secrets-plan-contract.md states the scrubEnv rule in the same precedence terms.
  • [P3] Explain the retained-source lifecycle invariant - answered rather than applied as written, and flagged in the PR body for you to overrule. The invariant is recorded in the plan contract and in the new docs section instead of as an inline comment at scrubEnvFiles. Say the word and I will move it to the call site.
  • Merge risk (P1), external OPENCLAW_CONFIG_PATH can delete the only dotenv assignment - closed by the P1 change and proven below.
  • Merge risk (P1), docs describe the state-directory file as the universal env-reference source - closed by the P2 change.
  • Complete next step (P2) - done; both halves were mechanical once the precedence contract was read.
  • Rank-up moves - all three applied: precedence-ordered retention including the external-config path, a fresh-gateway regression for a config dotenv file with no state-directory credential, and the corrected source-precedence documentation.
  • Stored data model on src/secrets/apply.test.ts - fixture JSON inside a suite; no on-disk format, schema version, or persisted shape changes. The genuine upgrade-visible change is the scrubEnv default, recorded in the plan contract and left as an explicit maintainer accept in the body.
  • Production versus test LOC - production is +40/-2. Named in the body as a maintainer decision rather than argued away; absorbing it into scrubEnvRaw would mean handing that function the file list, which merges two responsibilities instead of removing one.

One correctness point worth calling out, since it is the security-boundary half. The fix retains exactly one assignment per ref, not every matching copy. When both files carry the same value the higher-precedence one survives and the redundant copy is deleted, so this does not widen the plaintext left on disk. Scenario B in the refreshed proof shows that run directly.

Proof regenerated and pinned to the new head. Real buildConfigureCandidatesForScope, buildSecretsConfigurePlan and runSecretsApply in one process, then real loadGlobalRuntimeDotEnvFiles using the same path selection resolveGatewayRunDotEnvPaths makes, plus real resolveSecretRefValue, in a second process with the shell export removed. Across three trees on identical inputs: pristine main eda22ae1d578 and the previous head 77dee9b84652 both end with the provider unresolved, this head resolves it. Full transcript is in the PR body.

Acceptance criteria at this head: node scripts/run-vitest.mjs src/secrets/apply.test.ts 40 passed, run-oxlint clean, oxfmt --check clean across both source files and both docs, check-docs-mdx passed 771 files, docs link audit 0 broken over 6480 internal links, git diff --check clean.

mergeStateStatus currently reads BEHIND because main moved again during the run; mergeable is MERGEABLE with no conflicts. I left it rather than rebase again, because another rebase would move the head off the SHA this proof is pinned to.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Retention selects each dotenv file's runtime-effective assignment for a planned env SecretRef and drops the other assignments of that name in that file, so a same-file duplicate cannot leave a fresh process authenticating with a credential apply never validated.
@yetval
yetval force-pushed the fix/secrets-apply-env-scrub-self-delete branch from c6d1f39 to 2bd3590 Compare August 14, 2026 16:35
@yetval

yetval commented Aug 14, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto main 9386ac096632 (clean, no conflicts) and pushed 2bd3590467904b89e4f8ce79873402257dd4c395. The PR body is refreshed and its proof is pinned to that head. Answering the verdict at c6d1f394bbcc item by item.

[P1] Retain the runtime-effective dotenv assignment - fixed. scrubEnvRaw no longer keeps the first raw match. It builds durableLineByKey in a pre-pass holding the last index whose parsed value equals the value apply validated the ref against, which is the assignment dotenv.parse surfaces for that file, and removes every other assignment of that name in that file. Shadowed and shadowing duplicates both go.

Security: same-file precedence can select a stale credential - fixed by the same change, and reproduced first. Scenario C in the refreshed proof seeds one .env declaring OPENAI_API_KEY twice, validated value first and a rotated-out value second, and runs real runSecretsApply then a real second process using loadGlobalRuntimeDotEnvFiles plus resolveSecretRefValue. Pristine main 9386ac096632 and the reviewed head c6d1f394bbcc both hand the restarted process sk-openai-rotated-out-4a11. This head hands it sk-openai-live-9c2f.

Fresh-process regression - added, table-driven over both orderings: removes a same-file duplicate declared before/after the retained env SecretRef source. Each case loads the post-apply file through readDotEnvFile and resolves the ref from that hydrated env. Both fail on the rebased previous head with expected [ Array(1) ] to include <stateEnvPath>, because the .env was never rewritten and the duplicate survived.

[P2] Scope external-config dotenv guidance to gateway startup - fixed. The docs no longer claim the retained source is read by every fresh CLI and gateway process. Retained dotenv sources now says only openclaw gateway run loads the active config directory's .env, that normal CLI commands load the working-directory and state-directory files instead, and that a ref whose only retained source is the config-directory file therefore resolves in the gateway but not in a fresh CLI such as the post-apply openclaw secrets audit, with the fix being to move that assignment into the state-directory .env.

[P3] Explain the retained-key consumption at the lifecycle boundary - answered, not as a comment. The map is renamed envRefValuesAwaitingSource, so envRefValuesAwaitingSource.delete(retainedKey) reads as consuming a pending ref rather than as ordinary map cleanup, and the invariant is written down in docs/gateway/secrets-plan-contract.md and the new docs section. Root AGENTS.md does ask for an inline comment on cross-path lifecycle ordering; if a maintainer wants it at the code site rather than in the name, say so and it goes in. This is the one item left as an explicit maintainer choice.

Merge risk: production LOC - the production delta is +48/-10, net +38, unchanged from the reviewed head even though the retention predicate is now precedence-correct. The previous collectPlannedEnvRefValues helper was folded into scrubEnvFiles to pay for the new pre-pass.

Merge risk: retaining one plaintext dotenv source by default - still a deliberate tradeoff and still yours to accept or reject. It is recorded in the plan contract doc and in Open maintainer decisions in the body. The agent-access boundary section states plainly that an env SecretRef does not satisfy that boundary and that file or exec refs are required to complete it.

Stored data model - src/secrets/apply.test.ts is fixture JSON inside a suite. No on-disk format, schema version, or persisted shape changes in this PR.

Stale base / stale proof - both cleared by the rebase and the regenerated proof above.

Acceptance criteria run locally: node scripts/run-vitest.mjs src/secrets/apply.test.ts, node scripts/run-oxlint.mjs src/secrets/apply.ts src/secrets/apply.test.ts, node scripts/check-docs-mdx.mjs, node scripts/docs-link-audit.mjs, git diff --check.

@yetval

yetval commented Aug 19, 2026

Copy link
Copy Markdown
Contributor Author

Closing this while it sits in waiting-on-author state. The defect is real and remains open on main; it is now tracked in #126470, which carries the root cause analysis, the scope boundary against #97660, and the repro recipe from this PR.

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

Labels

docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant