Skip to content

fix(cli): make key-gen --force rotation atomic across both key files (#844) - #887

Merged
thiras merged 3 commits into
mainfrom
fix/key-gen-atomic-rotation-844
Jun 13, 2026
Merged

thiras merged 3 commits into
mainfrom
fix/key-gen-atomic-rotation-844

Conversation

@thiras

@thiras thiras commented Jun 12, 2026

Copy link
Copy Markdown
Contributor

Summary

Fixes #844. decdn key-gen --force rotated the two on-disk secrets — the Ed25519 node key (node.secret) and the eth keystore (keystore.json) — sequentially with no rollback: archive + regenerate node.secret first, 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:

  • stage — all the expensive, failure-prone work (RNG, scrypt encryption, temp-file write, chmod) into a temp file, touching nothing canonical, and
  • commit — archive-old + atomic rename (fast metadata ops).

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, Drop removes an uncommitted temp), so a failure in the second stage automatically cleans up the first stage's temp.

Changes

  • 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 becomes 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_aside archive 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 (restore node.secret from its .bak per 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

  • 5 existing key_gen_e2e.rs tests preserved (incl. force_archives_both_prior_keys, errors_when_*_without_force); eth_identity.rs unit tests preserved.
  • +2 regression tests pinning the contract: staging mutates neither canonical file and drops clean (asserting 0o600 on the staged temps), and commit installs exactly the staged identity.

Verification

  • cargo nextest run -p decdn-cli -p decdn-common -p decdn-incentive → 701 passed
  • cargo clippy --workspace --all-targets → clean
  • cargo fmt -- --check → clean
  • Manual: fresh dir creates both at 0o600; --force rotates both and archives both priors to *.bak.<ts>, no temp litter.

🤖 Generated with Claude Code

…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]>
Copilot AI review requested due to automatic review settings June 12, 2026 23:45

@gemini-code-assist gemini-code-assist 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.

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.

Comment thread crates/common/src/identity.rs Resolved
Comment thread crates/incentive/src/eth_identity.rs Resolved

Copilot AI 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.

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-gen to 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.

Comment thread crates/common/src/identity.rs Resolved
Comment thread crates/incentive/src/eth_identity.rs Resolved
Comment thread crates/cli/src/commands/key_gen.rs Resolved
@github-actions

github-actions Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 86.17% (was 86.17%, ● 0.00%) — 35527/41230 lines

File Coverage Lines Δ
crates/cli/src/commands/key_gen.rs 91.11% 41/45 ▼ 1.39%
crates/common/src/identity.rs 87.36% 311/356 ▼ 3.46%
crates/incentive/src/eth_identity.rs 88.06% 317/360 ▲ +2.55%
History
Commit Total Δ vs base
1c0b438 86.15% ▼ 0.01%
7f371a2 86.15% ▼ 0.02%
1dc54c3 (HEAD) 86.17% ● 0.00%

thiras and others added 2 commits June 13, 2026 02:51
)

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]>
@thiras
thiras merged commit aa564a7 into main Jun 13, 2026
20 checks passed
@thiras
thiras deleted the fix/key-gen-atomic-rotation-844 branch June 13, 2026 00:09
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.

cli: key-gen --force regenerates node.secret before the eth keystore with no rollback — failure leaves a mismatched half-rotated key pair

2 participants