Repository navigation
fix(secrets): preserve .env assignment backing newly configured env SecretRef - #138750
YusenZhang0601 wants to merge 7 commits into
Conversation
fixes openclaw#126470) When 'secrets configure --apply' writes an env SecretRef, it previously scrubbed all assignments matching the secret value from .env files, destroying the durable source backing the newly configured ref. - Retain exactly one assignment per env SecretRef written in the plan from the first dotenv file where it matches the validated value. - Remove duplicate assignments of that name within the same file to preserve last-assignment-wins semantics. - Add unit tests covering state .env preservation, precedence order, and duplicate line removal. - Update secrets contract and documentation.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
…sertion safety ratchet
…s and align docs - Restrict dotenv source retention in scrubEnvFiles to targets that survive sequential projection in applyConfigTargetMutations, ensuring overwritten env targets have their dotenv plaintext scrubbed. - Add regression tests in apply.test.ts covering overwritten env targets and mixed surviving/overwritten plan targets. - Clarify in secrets.md that Gateway pre-bootstrap deduplicates dotenv loading to the state directory when OPENCLAW_STATE_DIR is explicitly configured. - Align scrub removal guarantees across secrets.md and secrets-plan-contract.md with the migratedValues contract.
|
Codex review: blocked before merge. Reviewed September 5, 2026, 4:59 AM ET / 08:59 UTC. ClawSweeper reviewWhat this changesPreserves dotenv credentials backing newly configured environment secret references, removes competing assignments, and adds migration tests and operator documentation. Merge readiness⛔ Blocked before merge - 4 items remain This remains a useful repair for a source-proven credential-loss bug on current main and the latest release. Earlier code findings are addressed, and the closed, unmerged predecessor does not supersede this work. Priority: P1 Review scores
Verification
How this fits togetherSecrets apply converts configured credentials into references and cleans up plaintext copies. Its dotenv cleanup affects whether a fresh CLI or Gateway process can resolve those references after restart. flowchart TD
A[Migration plan] --> C[Project final credential references]
B[Config and auth stores] --> C
C --> D[Identify surviving environment references]
E[Dotenv files and process environment] --> F[Retain validated sources and scrub copies]
D --> F
F --> G[Fresh process resolves credentials]
F --> H[Audit reports remaining plaintext]
Decision needed
Why: This changes security-owned cleanup semantics, and the contributor's policy explanation does not establish SecOps acceptance. Before merge
Agent review detailsSecurityNone. PR surfaceSource +76, Tests +532, Docs +19. Total +627 across 4 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Keep source retention in the apply owner under a SecOps-approved cleanup contract; canonical destination and file-precedence tracking justify the added production state. Do we have a high-confidence way to reproduce the issue? Yes: migrating a plaintext credential to an environment reference with the same value in a known dotenv key reaches the deletion predicate on current main and v2026.9.1. This review verified the source path without executing the migration. Is this the best way to solve the issue? Yes on the repair boundary: preserving the source during apply avoids downstream fallback logic, while disabling scrubEnv would unnecessarily skip all dotenv cleanup. Final acceptance still requires the security-owner decision and direct parser-contract review. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against ec8d874e38b0. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (5 earlier review cycles)
|
…d duplicate cleanup
… path, and align CLI dotenv docs
…two-stage CLI dotenv hydration
|
This assigned pull request has been automatically marked as stale after being open for 27 days. |
|
Just checking in to keep this PR active and prevent the stale bot from closing it. The implementation and terminal behavior verification remain solid (as verified by ClawSweeper). Whenever you or SecOps have a moment to weigh in on the scoped retention policy decision, please let me know. I'm actively monitoring this and happy to rebase against the latest Thanks! |
|
This assigned pull request has been automatically marked as stale after being open for 27 days. |
Fixes #126470
What Problem This Solves
Resolves an issue where running
openclaw secrets configure --applyto migrate plaintext credentials to anenvSecretRef (for examplemodels.providers.openai.apiKey -> env:default:OPENAI_API_KEY) deletes the backing assignment in.env, leaving the ref unresolvable after restart in fresh processes that lack ambient shell exports.Why This Change Was Made
I updated
scrubEnvRawandscrubEnvFilesinsrc/secrets/apply.tsso that when a plan writes anenvSecretRef, apply retains exactly one durable assignment from the first dotenv file where it matches the validated secret value.Following review iterations and ClawSweeper / SecOps feedback:
src/secrets/apply.ts,getPlanTargetDestinationKeyserializesresolved.pathSegmentsviaJSON.stringify. This preserves explicit segment boundaries, ensuring that provider keys containing dots (such asmodels.providers["openai.headers"].apiKey) do not collide with nested property targets (models.providers.openai.headers.apiKey), while equivalent path spellings continue to share identical destination identity.auth-profile-storetargets,getPlanTargetDestinationKeyresolves the canonical database path viaresolveAuthStoreTargetForAgent(...)(which normalizes the agent directory). Case-variant agent IDs (such asMAINvsmain) resolve to the exact same store path, ensuring sequential overwrites (e.g. anenvref overwritten by afileref for the same profile) correctly scrub superseded dotenv credentials.docs/gateway/secrets.mdto document the complete two-stage CLI hydration order whenOPENCLAW_STATE_DIRis unset andOPENCLAW_CONFIG_PATHis external:loadCliDotEnvinsrc/cli/dotenv.ts:24) explicitly loadspath.join(resolveStateDir(process.env), ".env")(~/.openclaw/.env).maybeLoadDotEnvForConfig) invokesloadDotEnv, loading the config-adjacent.envwithout overriding existing environment keys (override: false).Consequently, if a credential variable is defined in both files, the state-directory assignment from Stage 1 takes precedence over the config-adjacent file.
docs/gateway/secrets.mdanddocs/gateway/secrets-plan-contract.mdthat scrubbing removes values inmigratedValuesacross scrubbed files and duplicate assignments of retained keys in the retention file.User Impact
Operators migrating credentials with
openclaw secrets configure --applycan safely configureenvSecretRefs without losing their backing values on disk upon restart. Overwrittenenvtargets correctly have their plaintext scrubbed, segment boundaries are preserved without key collision, and the retained assignment continues to be reported by audit asPLAINTEXT_FOUNDas intended forenvrefs, maintaining an accurate security posture.Evidence & Executed Test Attributions
fix/secrets-apply-preserve-env-secretrefc365300cb05c47789b7b0af78a4707ab84f88c2c33949781392(132/132 checks passed, 100% green)checks-node-compact-small-13(Job ID:101262379052)Executed runner transcript covering destination collision, retention, duplicate cleanup, and equivalent-path overwrite:
Unit tests in
src/secrets/apply.test.tsalso cover:.envsource backing a newly writtenenvSecretRef..envvalues that do not match the validated ref..envand config-adjacent.env.envtarget is overwritten by a subsequentfiletarget for the same destination.Destination Collision Regression Proof
In
src/secrets/apply.test.ts:736, the regression test verifies that dotted provider keys (models.providers["openai.headers"].apiKey) and nested targets (models.providers.openai.headers.apiKey) do not collide in the survival map:resolved.pathSegments.join(".")):Both targets resolve to identical key
config:models.providers.openai.headers.apiKey. The subsequentfiletarget overwrites theenvtarget insurvivingTargetsByDestination, causingANTHROPIC_API_KEYto be dropped fromsurvivingTargets. InscrubEnvRaw,ANTHROPIC_API_KEYis not marked durable and is deleted from.env, failingexpect(nextEnv).toContain("ANTHROPIC_API_KEY=sk-anthropic-header-plaintext").JSON.stringify(resolved.pathSegments)):Target 1 key:
config:["models","providers","openai","headers","apiKey"]Target 2 key:
config:["models","providers","openai.headers","apiKey"]Because token boundaries are preserved, both targets survive in
survivingTargetsByDestination.ANTHROPIC_API_KEYis retained in.envto back the surviving ref, andOPENAI_API_KEY(migrated to file) is scrubbed.Executed test result in CI:
[shard:core-runtime-secrets] ✓ secrets src/secrets/apply.test.ts > secrets apply > does not collide destinations when provider keys contain dots and preserves distinct env sources 927msSecOps Credential-Retention Policy Alignment
envSecretRef sources whose validated value matches disk.envSecretRefs keep their backing assignment without generating residue.envSecretRefs leave credentials in.envby design and continue to be reported asPLAINTEXT_FOUNDbyopenclaw secrets audit. Full credential isolation outside agent-readable dotenv directories still requiresfileorexecSecretRefs.Terminal & Fresh-Process Audit Trace (Ambient Shell Cleared)
Verified fresh-process CLI behavior with ambient environment cleared (
env -u/env -isimulation), matching exact OpenClaw emitters (src/cli/secrets-cli.ts:397andsrc/secrets/audit.ts:183):