Repository navigation
fix(cli): make key-gen --force rotation atomic across both key files (#844) - #887
Conversation
…844) `decdn key-gen --force` rotated the two on-disk secrets sequentially with no rollback: it archived + regenerated `node.secret` first, then generated the eth keystore. If keystore generation failed (disk full, encryption error), the node identity had already been replaced while the keystore was stale/archived — a half-rotated, mismatched key pair on the very rotation path the archiving exists to make safe. Split each "generate + persist" into a STAGE step (RNG, scrypt encryption, temp-file write, chmod — all into a temp file, touching nothing canonical) and a COMMIT step (archive-old + atomic rename, fast metadata ops). The CLI now stages both secrets and only commits after both stages succeed, so a generation failure leaves both canonical files untouched. The new staged handles are RAII: an uncommitted handle removes its temp on drop, so a failure in the second stage cleans up the first stage's temp. - common/identity.rs: split `write_atomic` into reusable `write_temp` + rename; add `StagedNodeKey` + `stage_node_key` (`load_or_generate` and the `decdn run` startup path are unchanged). - incentive/eth_identity.rs: add `StagedKeystore` + `stage_keystore`; `generate_and_persist` is now a thin wrapper over stage+commit, which also fixes its own archive-before-encrypt ordering. - cli/key_gen.rs: stage-both-then-commit-both. The residual inter-commit window is narrow but not crash-only — if the node key commits and the keystore commit then fails, the keystore error is annotated with the half-rotated state and the recovery path so the operator isn't misled. Tests: 5 existing key-gen e2e tests preserved; +2 regression tests pinning the no-mutation-before-commit contract (incl. 0o600 on staged temps and that commit installs exactly the staged identity). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces a two-phase key rotation mechanism (staging and committing) for both the Ed25519 node key and the Ethereum keystore to prevent half-rotated states during generation or encryption failures. The review feedback highlights that if the final rename operation fails after the original file has been moved aside, the system could be left without any active key or keystore. It is recommended to attempt to restore the backup files if the rename fails, and to ensure that the staged data is persisted to disk using sync_all() before renaming.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
There was a problem hiding this comment.
Pull request overview
This PR fixes #844 by making decdn key-gen --force key rotation safer: it stages both the node key (node.secret) and Ethereum keystore (keystore.json) into temp files first, and only then commits them, avoiding half-rotation on generation/encryption failures.
Changes:
- Introduces staged/RAII temp-file workflows for the node key and ETH keystore (stage → commit).
- Updates
decdn key-gento stage both secrets before committing either. - Adds E2E regression tests to ensure staging doesn’t mutate canonical files and that commit installs the staged identity.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
| crates/common/src/identity.rs | Adds StagedNodeKey + stage_node_key, and refactors atomic writes into write_temp + rename. |
| crates/incentive/src/eth_identity.rs | Adds StagedKeystore + stage_keystore, refactors generate_and_persist to stage+commit. |
| crates/cli/src/commands/key_gen.rs | Switches CLI rotation flow to stage-both-then-commit-both and improves operator-facing error context. |
| crates/cli/tests/key_gen_e2e.rs | Adds regression tests for staging non-mutation, temp cleanup, and stage/commit identity consistency. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Coverage reportTotal: 86.17% (was 86.17%, ● 0.00%) — 35527/41230 lines
History
|
) Address external review (Gemini, Copilot): if `commit()`'s install rename fails *after* `move_aside` archived the prior file, the canonical path was left empty (only the `.bak.*` remained) — a fail-unsafe outcome on the rotation path this PR hardens. Both `StagedNodeKey::commit` and `StagedKeystore::commit` now restore the archive (best-effort) when the install rename fails, so the old key/keystore stays live at the canonical path rather than the location going missing. If the restore also fails the archive is still on disk for manual recovery (runbook §5); the staged temp is cleaned up by `Drop`. This makes the node-key commit genuinely "clean" on failure, so the CLI comment is updated to match (it previously overstated the guarantee). Not changed: the keystore-temp fsync the review suggested is a pre-existing power-loss durability concern orthogonal to half-rotation; the node-key temp already fsyncs in `write_temp`, and temps are already created 0o600 (asserted by test). The suggested `self.file.sync_all()` doesn't apply — the staged handles hold no open file. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…d; test rollback (#844) Second-pass review (multi-agent) findings: 1. Silent failure (key material): if commit's install rename fails AND the best-effort archive restore ALSO fails, the canonical file is left missing and the operator saw only the original rename error. The error now branches on the restore outcome — naming the surviving `.bak` and that the path is MISSING when restore fails, vs "restored, stays live" when it succeeds. 2. Duplication: the archive→rename→rollback body was hand-copied across the two crates. Extracted to `decdn_common::identity::install_staged`, called by both `StagedNodeKey::commit` and `StagedKeystore::commit`, so the fix above lives in one place. (`common` is not in the public-api snapshot crate, so no surface gate; `committed: bool` kept — the by-value-consume + Drop-on-failure encoding is the minimal one, confirmed in review.) 3. The rollback path IS deterministically testable (my earlier claim was wrong): deleting the staged temp before commit makes the install rename fail ENOENT while the dir stays writable, so the restore succeeds. Added two e2e tests (node + keystore) asserting the prior file is restored byte-for-byte, the `.bak` is consumed, and the error reports the restore. Also: softened the CLI node-key comment (the restore is best-effort, not a guaranteed "old pair intact"), and documented why StagedKeystore's derive(Debug) is secret-safe. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Summary
Fixes #844.
decdn key-gen --forcerotated the two on-disk secrets — the Ed25519 node key (node.secret) and the eth keystore (keystore.json) — sequentially with no rollback: archive + regeneratenode.secretfirst, then generate the keystore. If keystore generation failed (disk full, encryption error), the node identity was already replaced while the keystore was stale/archived — a half-rotated, mismatched key pair on the very rotation path the archiving exists to make safe.Approach
Split each "generate + persist" into:
The CLI now stages both secrets, then commits both — so a generation failure leaves both canonical files untouched. The staged handles are RAII (
#[must_use],commit(self)by value,Dropremoves an uncommitted temp), so a failure in the second stage automatically cleans up the first stage's temp.Changes
common/identity.rs— splitwrite_atomicinto reusablewrite_temp+ rename; addStagedNodeKey+stage_node_key.load_or_generateand thedecdn runstartup path are unchanged.incentive/eth_identity.rs— addStagedKeystore+stage_keystore;generate_and_persistbecomes a thin wrapper over stage+commit (keeps its 11 unit tests green and incidentally fixes its own archive-before-encrypt ordering).cli/key_gen.rs— stage-both-then-commit-both.Scope boundary
The residual two-rename commit window is narrow but not crash-only: if the node key commits and the keystore commit then fails (e.g. a
move_asidearchive collision, or a rename hitting ENOSPC/EXDEV/EACCES), the pair is half-rotated. The fix moves all fallible generation ahead of any mutation (the half-rotation hazard #844 describes); the keystore commit error is now annotated with the half-rotated state and the recovery path (restorenode.secretfrom its.bakper the key-rotation runbook §5, or re-run--force) so the operator isn't misled. A boot-time reconciliation for the crash-in-the-gap case is a separate concern (cf. the seller-side analog #839).Tests
key_gen_e2e.rstests preserved (incl.force_archives_both_prior_keys,errors_when_*_without_force);eth_identity.rsunit tests preserved.0o600on the staged temps), and commit installs exactly the staged identity.Verification
cargo nextest run -p decdn-cli -p decdn-common -p decdn-incentive→ 701 passedcargo clippy --workspace --all-targets→ cleancargo fmt -- --check→ clean0o600;--forcerotates both and archives both priors to*.bak.<ts>, no temp litter.🤖 Generated with Claude Code