Skip to content

feat: encryption key rotation without export and import - #1919

Merged
bplatz merged 10 commits into
mainfrom
feat/encryption-key-rotation
Sep 26, 2026
Merged

bplatz merged 10 commits into
mainfrom
feat/encryption-key-rotation

Conversation

@bplatz

@bplatz bplatz commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Rotates the at-rest encryption key without export and import: configure a key set, make the new key current, run a sweep that re-envelopes every blob on the old key in place, verify, then drop the old key. The sweep is resumable across restarts and leadership changes and can run over days while serving traffic.

Four commits, one per layer.

Configuration and builder

  • AES256Keys: a list of {keyId, AES256Key} nodes (each with the usual envVar indirection) plus AES256CurrentKey, in both the JSON-LD and flat parsers. The single AES256Key still means one key with id 0. Both parsers reject mixing the forms, duplicate ids, and a current id outside the set.
  • MultiKeyProvider in the crypto crate; KeyProvider::key_ids() for reporting. FlureeBuilder::with_encryption_keys() and encryption_key_ids().

Storage admin surface

  • core::EncryptionAdmin, reachable from any StorageRead via encryption_admin(): key ids, current id, key_id_at(address) from a header-only range read (no decryption; absent or non-envelope bytes classify as None), and reencrypt(address), an in-place rewrite under the current key that reads itself back before reporting success. Addresses are hashes of plaintext, so nothing else changes.

The sweep (fluree-db-api/src/key_rotation.rs)

  • Units in a fixed order: each ledger branch's prefix, each ledger's shared dictionaries, graph sources. Position is a unit plus the last address processed. A progress record at @maintenance/key-rotation.json in the same storage is checkpointed every thousand blobs or thirty seconds and doubles as the heartbeat; it is a cache of position, never the truth, which stays in the envelope headers.
  • A Running record from another holder is refused while fresh and taken over when stale (ten minutes). resume_pending_key_rotation continues a record after a restart or election. release_key_rotation clears the heartbeat on leadership loss so the next leader takes over at once.
  • Failed blobs are counted and named (first hundred) and left for the next pass. After the sweep a verification pass counts the whole store by header: zero stamps completed, otherwise swept. Nothing removes a key. Dry runs count only and touch no record. A byte-rate cap throttles rewrites.

Server

  • Reads, any node: GET /encryption (held key ids), GET /encryption/rotate/status.
  • Admin-gated, leader-forwarded writes: POST /encryption/rotate, /rotate/pause, /rotate/cancel, /rotate/verify.
  • A standalone server resumes a pending record at startup; under Raft a leader task resumes it on election and releases it on abort. Discovery and OpenAPI updated.

CLI

fluree encryption {status, rotate, resume, pause, cancel, verify, generate-key} with --remote <name> or --connection-config <path>, --wait polling that flags a stalled record, and --json.

Docs

docs/security/encryption.md rotation section: key set config, the two-phase rollout order across nodes, commands and endpoints, status semantics, and the rule that only a verified zero count licenses removing a key. Connection-config reference updated.

Not in this PR

The cluster-wide preflight that refuses to start until every node reports the current key. Per-node key ids are on the status endpoint and the docs give the order; enforcement across nodes is a follow-up.

Follow-up: #1951 (stream the address listing instead of holding it in memory)
Follow-up: #1952 (enforce the cross-node key rollout order)
Follow-up: #1953 (resume automatically after a restart, a leader crash or a missed release)
Follow-up: #1954 (CLI: dry-run counts, --rate on resume, exit status)
Follow-up: #1955 (server rebuild staging setting; Raft log and snapshots)

Review follow-ups

  • encryption_admin through routers. StorageRead::encryption_admin is now a required method, like permits_plaintext_cache. AddressIdentifierResolverStorage returns its default storage's admin: every write and listing goes there, and routed storages are read-only here with their own keys. TieredStorage routes by address when both tiers share a key set. GET /encryption asks the storage via Fluree::encryption_key_ids instead of reading any config error as "not encrypted". Regression test: rotation through an addressIdentifiers router (fails when the router answers None).
  • Clock-dependent test. The scoped-then-full assertion now checks the new record's scope, not whole-second start times. Rotation tests run on a multi-thread runtime so their deadline can fire.
  • Handover status. A record released by an outgoing leader reports released, not stalled, and the CLI shows RELEASED with the resume hint.
  • Debug. KeyedAes256Key redacts its key; StorageConfig lists the key set by id.
  • Fail closed on ignored keys (found by the docs audit, pre-existing). An AES256Key whose envVar is unset with no defaultVal, a non-string key in the flat config, and a commitStorage key that differs from indexStorage's used to leave the store unencrypted without an error. All three are now config errors. A deployment relying on any of them will now fail to start, which is intended.
  • Docs audit. Every claim in the encryption and rotation pages was checked against the code and corrected, including how resume actually behaves today, the admin-auth default, key id 0 for a single key, and a .flpack migration path to encryption. The server-command lines are left to fix(server): config precedence, boolean switches, and docs for what exists #1944.

Tests

  • Provider, both parsers, and the admin surface through type erasure.
  • End to end on file storage: a ledger written under key 1 reopens with key 2 current, every blob classifies as key 1, re-encrypts in place, and reads back through a client holding key 2 alone.
  • Sweep: dry run, a ledger-scoped run verification reports as swept, a full run (a new, unscoped job) that finishes to completed, a fresh foreign record refused and a stale one taken over, and reads after the old key is gone. Waits carry a deadline so a stall fails rather than hangs.
  • HTTP: a rotation driven to completion through the router, verify, the admin gate, and the unencrypted response.

Verification

After the review follow-ups: workspace clippy (plus raft and CI's wasm32 gate), unit suites for core (native), connection, crypto, indexer, nameservice, nameservice-sync, api and cli; it_key_rotation (5× single-threaded), grp_misc encryption, grp_index, it_import_remote, it_residency_retry, and grp_http rotation tests. The LocalStack S3 tests were not re-run.

Before them:

Clippy and fmt clean on core, crypto, connection, api, server (with and without raft) and cli. Suites above pass, plus the existing encryption integration tests.

@bplatz bplatz added enhancement New feature or request area:storage Storage backends, nameservice, ledger lifecycle, index storage, caches labels Sep 24, 2026
@bplatz
bplatz requested review from aaj3f and zonotope September 24, 2026 13:05
@bplatz
bplatz added this pull request to stack #1918 September 24, 2026 13:05

@aaj3f aaj3f 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.

This is really cool, @bplatz--genuinely! I think it's pretty neat that we can perform these key rotations in this PR without moving blobs, rewriting points, or churning over the index chain. I mean, maybe this is block-and-tackle stuff for data encryption, but as that's not my expertise, I'm impressed by it. That the new-key takeover functions as a "lease" rather than a lock" is also really neat.

There are some suggestions below maybe worth considering (namely (1) re: the use of Vec<String> to materialize every address and (2) re: cluster config preflight). I'll leave it to you whether they get considered now or as follow-up at the tip of the stacked branches/PRs


The two structural facts it rests on (addresses are plaintext hashes so a rewrite doesn't move anything, and the envelope names its own key so the blobs are the truth and the progress record is only a cache) are the right foundations, and you've drawn the consequences out consistently — a cursor that's cheap to be wrong about, a reencrypt that reads itself back, a lease with an explicit release on leadership loss, and above all a completion that is an independent count over the whole store rather than a bookkeeping conclusion. That last one is what makes the whole feature safe to hand an operator, and the docs put it in front of them in the right words. I mutation-checked the foreign-holder guard and it's load-bearing.

Two things before it merges. First, encryption_admin is declared on StorageRead with a "wrappers delegate; routers return an admin that routes" contract that two of our own wrappers don't meet — TieredStorage and AddressIdentifierResolverStorage both picked up permits_plaintext_cache in #1916 but not this one. The second is live: build_client_* wraps the address-identifier router over the encrypted storage, so on any deployment with addressIdentifiers the router answers None, rotation refuses with "storage is not encrypted; nothing to rotate", and — because routes/encryption.rs:48 maps every ApiError::Config to encrypted: false — GET /encryption tells an operator their node doesn't encrypt at rest when it does. I built one to check rather than reasoning about it: key ids [2, 1], 23 of 28 blobs decrypting through the encrypted storage, and both API calls reporting not-encrypted. Second, it_key_rotation.rs:195 asserts full.started_at == scoped.started_at with the message "resumed the swept record", but the full run passes ledger: None against a record scoped to rot-a, so the resume arm at key_rotation.rs:349 doesn't match and a fresh record is created — the assertion passes only when both runs land in the same wall-clock second, and I caught it failing (left: …509, right: …508).

Two more I'd like you to weigh rather than just fix. count_on_key and the per-unit enumeration both materialize every address in the store as a Vec<String> (plus a sort, plus one GET per object in verification, run at the end of every sweep) — that's inside the letter of list_prefix's "admin operations" caveat, but a store that needs a multi-day rotation has millions of leaves in one ledger prefix, so I'd rather we settle the paginated-walk question before a customer does. And the Debug derives on StorageConfig / KeyedAes256Key print raw base64 key material; that's pre-existing for the single-key field, but this PR is the one that puts the whole key set in that struct.

Adherence to repo commitments:

  • Patterns/abstractions: ⚠️ EncryptionAdmin on StorageRead is the right shape and MultiKeyProvider extends the existing KeyProvider rather than paralleling it — but the new trait method's own delegation contract is unmet by two in-repo wrappers, which is what produces the blocking finding.
  • Performance (speed first, memory second): ✔ for the query and write paths — encryption_admin has no caller there, and MultiKeyProvider::key_by_id is a linear scan over one or two entries per decrypt. ⚠️ for the rotation's own enumeration, which is O(store) in memory and round trips, twice per sweep.
  • Testing: ⚠️ Real end-to-end coverage (a ledger written under key 1, reopened with key 2 current, swept, verified, and read back through a client holding only key 2), wired into a [[test]] target and grp_http, running in CI on this exact head, and the takeover guard goes red under mutation. Against that: one assertion is a wall-clock flake that proves the opposite of its message, and I hit a four-minute hang on a cold run I couldn't reproduce.
  • Conventions: ✔ Four commits, one per layer, each with a body that carries the real rationale; clippy/fmt green at ca6b5895c; the CLI docs page and book summary are there; the docs are honest about the follow-up they don't cover.

Verified locally at ca6b5895c: both it_key_rotation tests pass in isolation; --test-threads=1 reproduces the :195 failure; mutating the foreign-holder freshness check turns foreign_running_record_is_refused_… red; a temporary probe with addressIdentifiers + AES256Keys reproduces the "not encrypted" false negative on an encrypted store; both encryption GETs confirmed inside the admin-token bracket in routes/mod.rs:175-178; cargo check -p fluree-db-crypto clean with --no-default-features, default and --all-features. Worktrees restored, git status clean.

None of this is a quarrel with the design — I'd ship this design. Just be sure the wrapper delegation lands before it merges, since the version of this bug that reaches a customer is a compliance script being told the node isn't encrypted.

Comment thread fluree-db-core/src/storage.rs Outdated
/// The encryption administration surface, when this storage encrypts
/// at rest. `None` (the default) for plaintext storages. Wrappers
/// delegate to what they wrap; routers return an admin that routes.
fn encryption_admin(&self) -> Option<Arc<dyn EncryptionAdmin>> {

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.

Blocking — two of the repo's own storage wrappers don't implement encryption_admin, so on any deployment with addressIdentifiers configured the encryption status endpoint reports encrypted: false and rotation refuses to start — on a store that is encrypted.

The doc comment three lines up says "Wrappers delegate to what they wrap; routers return an admin that routes." TieredStorage (fluree-db-api/src/lib.rs:800) and AddressIdentifierResolverStorage (lib.rs:1024) do neither — both picked up permits_plaintext_cache in #1916 but not this one, so they take the None default. AddressIdentifierResolverStorage is the live case: build_client_file, build_client_memory and build_client_s3 all apply encrypt_if_configured and then call wrap_address_identifiers, so the router sits on top and backend.admin_storage_cloned() hands key_rotation.rs:236 a storage that answers None.

I built one to be sure rather than reasoning about it. With a file storage carrying AES256Keys [{1},{2}], AES256CurrentKey: 2, and one addressIdentifiers entry:

builder key ids = [2, 1]
storage.encryption_admin().is_some() = false
status ERR = Invalid configuration: storage is not encrypted; nothing to rotate
rotate ERR = Invalid configuration: storage is not encrypted; nothing to rotate
readable_through_encrypted_storage=23 unreadable=5

Twenty-three blobs decrypt through the encrypted storage — the data really is enveloped at rest — and the API says the storage isn't encrypted. That gets worse one layer up: fluree-db-server/src/routes/encryption.rs:48-52 maps any ApiError::Config to {"encrypted": false, "key_ids": [], "current_key_id": null}, so GET /encryption — the endpoint an operator or a compliance script asks "does this node encrypt at rest?" — answers no for a node that does. A security-status endpoint returning a reassuring false negative is the part of this I'd most want closed before it ships.

Three pieces to the fix, and I think all three are small:

// TieredStorage — both tiers must agree, same shape as permits_plaintext_cache above.
fn encryption_admin(&self) -> Option<Arc<dyn EncryptionAdmin>> {
    match (self.commit.encryption_admin(), self.index.encryption_admin()) {
        (Some(a), Some(_)) => Some(a),   // or refuse unless the key sets match
        _ => None,
    }
}

For AddressIdentifierResolverStorage, delegating to self.default alone would be wrong — the routed storages each carry their own AES256Key, so a sweep driven from the default's admin would silently miss them. A routing admin is the honest answer; if that's more than you want here, an explicit distinct error ("key rotation is not supported with addressIdentifiers") beats the current silent None, because at least it doesn't come back through the status endpoint as "not encrypted."

And the endpoint itself should stop treating every config error as proof of plaintext: only the "storage is not encrypted" case should map to encrypted: false; a "managed storage backend required" or anything else should surface as an error, so an unexpected condition reads as unknown rather than as safe-to-ignore.

Commenting here because fluree-db-api/src/lib.rs:800 and :1024 — the two impls that are missing — are not in this diff; this is the trait method and the delegation contract they don't meet.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 452723c, with one change to the shape you suggested.

  • encryption_admin is now a required method, the same answer as permits_plaintext_cache. The compiler flagged exactly these two wrappers.
  • AddressIdentifierResolverStorage returns its default storage's admin rather than a routing admin. Every write and every listing already goes to the default, so the sweep only ever sees and rewrites the default. The routed storages are read-only from this node and carry their own keys, so a routing admin would rewrite blobs in storage this node only reads. The docs now say routed storages are rotated from the deployment that writes them.
  • TieredStorage returns an admin that routes by address when both tiers are encrypted under the same key set, and None otherwise. In-repo builds encrypt above the tiers, so this isn't the live path.
  • GET /encryption now asks the storage directly through Fluree::encryption_key_ids() and never reads an error as "not encrypted". The only case without admin storage is IPFS, which can't be encrypted since fix(storage): apply AES256Key on every encryptable build path and keep the disk cache free of decrypted artifacts #1916.
  • Test: rotation_through_an_address_identifier_router turns your reproduction into a test: status reports the keys and a rotation completes. It fails with the router answering None.

Comment thread fluree-db-api/tests/it_key_rotation.rs Outdated
// Full run resumes the swept record and finishes: everything rewritten.
let full = run_to_end(&fluree, opts(1)).await;
assert_eq!(full.state, KeyRotationState::Completed);
assert_eq!(

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.

Blocking (test correctness) — this assertion is a wall-clock flake, and the thing it claims to prove is the opposite of what the code does.

assert_eq!(full.started_at, scoped.started_at, "resumed the swept record"). The swept record was written with ledger_scope: Some("rot-a"); the full run passes ledger: None. start_key_rotation's resume arm requires rec.ledger_scope == opts.ledger (key_rotation.rs:349), so it does not match, and control falls to the _ arm, which builds a fresh KeyRotationProgress with started_at: now_secs(). The assertion therefore passes if and only if the scoped run and the full run happen to land inside the same wall-clock second — started_at is whole seconds (key_rotation.rs:169-174).

It fails as soon as a second boundary intervenes. I caught it:

test rotation_dry_run_scoped_run_full_run_and_verify ... FAILED
assertion `left == right` failed: resumed the swept record
  left: 1790353509
 right: 1790353508

This also means the PR body's "a full run that resumes it to completed" isn't what the test exercises — widening the scope starts a new job, which is a defensible design (the record's counters are scoped to one job definition) but isn't what the assertion says. Two ways out, and I'd take whichever matches your intent: assert the opposite and name the behavior —

assert_ne!(
    full.started_at, scoped.started_at,
    "a widened scope is a new job, not a resumption of the scoped record"
);

— or, if a full run should subsume a scoped one, loosen the match at key_rotation.rs:349 so opts.ledger == None resumes a scoped record (and keep the assertion as written). Either way this shouldn't merge asserting something the code doesn't do, since the next person to read it will believe it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 452723c. Widening the scope is a new job, and that's the right behavior: the scoped record's counters describe its own units. But assert_ne! on started_at would be flaky the other way, since two runs in the same second compare equal. The test now asserts full.ledger_scope == None, which a resumed scoped record can't satisfy, so the clock plays no part. It passed 5× single-threaded. The PR body no longer says the full run resumes the scoped one.

key_id: u32,
) -> Result<u64> {
let root = format!("fluree:{}://", storage.storage_method());
let addresses = storage.list_prefix(&root).await?;

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.

Optional, but I think it matters before the first real run — the sweep and the verification pass both materialize every address in the store in memory, on a feature whose own docs say it "can run over days."

count_on_key lists the entire store root into one Vec<String> and then issues one ranged GET per address; run_sweep does the same per unit and additionally sorts the whole list (:663-666). The trait's own doc is explicit about this (fluree-db-core/src/storage.rs:215-221: "This can be expensive for large prefixes. Use only for: Development/debugging, Admin operations, Small, bounded prefixes"). A rotation is an admin operation, so it's inside the letter of that — but a store big enough to need a multi-day sweep has millions of index leaves in a single ledger prefix, which is a gigabyte-scale Vec of address strings plus a full sort, and then the verification pass repeats the whole enumeration across every unit at the end of every sweep and again on each explicit verify.

list_prefix_paginated already exists on the S3 and file backends (it's how the nameservice walks), so a streaming walk looks reachable, though I appreciate it isn't on Arc<dyn Storage> today so it's not a one-liner. I don't think this blocks — nothing is wrong — but I'd rather we decide it now than find out on a customer's bucket. At minimum a line in the docs about expected memory and request count for a store of size N would set the right expectation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed this should be decided rather than found. Filed #1951 with the design constraint: list_prefix_paginated isn't reachable from Arc<dyn Storage>, but the sweep's cursor (last address processed) already fits a start-after listing. Verification's one ranged read per blob is inherent, so pagination bounds memory, not requests. The docs now state the cost: verification lists the whole store at once, so budget roughly 100–150 bytes per blob, plus one ranged read per blob for each verification pass.

checkpoint(&storage, &shared, &mut progress).await;
// Clear the heartbeat after the checkpoint so the record is
// stale to the next holder without losing the cursor.
progress.updated_at = 0;

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.

Optional — a handed-off rotation reports stalled: true during the handover, which reads as an alarm.

release_key_rotation deliberately writes updated_at = 0 so the next leader treats the record as stale and takes over at once — that's a nice trick and the comment explains it. But key_rotation_status computes stalled as Running && age > STALE_AFTER (:494-499), and now - 0 is very much greater, so between the outgoing leader releasing and the new leader resuming, fluree encryption status says "stalled", which the docs define as "nobody is advancing it." During a leader election that's exactly wrong — someone is about to. A sentinel check (p.updated_at != 0) in the stalled computation, or a distinct released flag, would keep the takeover behavior and stop the false alarm. This is minor and non-blocking — but if you agree it's right, I'd rather see it folded in now than lost in the backlog.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed. The status now reports such a record as released instead of stalled, and the CLI shows RELEASED with the resume hint. I went with a flag rather than only excluding it from stalled, because the docs audit found the new leader checks just once: a release that lands after that check, or a crashed leader, leaves the record unadvanced. Hiding it would make that case look healthy. The retry itself is #1953.

/// One entry of a rotation key set: a base64 AES-256 key and the id the
/// envelope header records for it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyedAes256Key {

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.

Optional — KeyedAes256Key and StorageConfig derive Debug over raw base64 key material, and this PR turns one key into a list of them.

#[derive(Debug, Clone, PartialEq, Eq)] pub struct KeyedAes256Key { pub id: u32, pub key: Arc<str> } — key is the decoded-from-envVar base64 secret, printed in full by {:?}. Same for StorageConfig.aes256_key at :145 and now aes256_keys at :149, and ConnectionConfig derives Debug over index_storage, and FlureeBuilder derives Debug over config. So {:?} on a builder prints every key the deployment holds.

This is pre-existing for the single-key field — #1916's commit body says the ConfiguredKey newtype closed the builder's Debug leak, and it closed that field, not this path — so I'm not pinning it on this PR. But this PR widens it from one secret to the whole key set, which is the one place a rotation deployment has all of its keys in one struct. I checked and nothing logs a config today, so it's latent, one ?config on a future tracing call away. A manual Debug on both types redacting the key strings is a dozen lines and closes it for good. Your call whether it lands here or as its own change.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done here. KeyedAes256Key has a hand-written Debug that prints the id and <redacted>, and StorageConfig's Debug (from #1916) now lists the key set by id. debug_never_prints_secrets covers both.

.expect("a sweep ran")
}

async fn run_to_end(fluree: &Fluree, opts: KeyRotationOptions) -> KeyRotationProgress {

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.

Optional, and I want to be honest about how well I can pin this — on the very first cold run of this target, foreign_running_record_is_refused_while_fresh_and_taken_over_when_stale hung past four minutes with the process idle, and the test's own 60-second SWEEP_DEADLINE never fired.

I could not reproduce it on any subsequent run, so I can't hand you a recipe — and I want to flag that several other fluree-db-* test binaries were running on this machine at the time, which matters because support::build_and_publish_index uses IndexerConfig::default(), i.e. the process-and-machine-shared $TMPDIR/fluree-index. A cross-process collision there is a plausible cause and would be pre-existing, not yours. CI is unaffected either way, since nextest runs each test in its own process.

The part I do think is worth a look regardless: tokio::time::timeout(SWEEP_DEADLINE, …) not firing on a #[tokio::test] (current-thread runtime) means something blocked the runtime thread rather than yielding — a timer can't fire if nothing polls it. So the deadline you added to make a stall fail rather than hang doesn't actually protect against the blocking-call class of stall. A #[tokio::test(flavor = "multi_thread")] would let the timer fire and turn any recurrence into a clean failure with a message. Worth two characters of config even if the hang never comes back.

@bplatz bplatz Sep 26, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Switched all three rotation tests to flavor = "multi_thread", so the deadline can fire even if something blocks a worker. On the shared $TMPDIR/fluree-index: rebuild staging is per-session since #1917, so a cross-process collision there shouldn't recur.

progress.cursor = None;
checkpoint(&storage, &shared, &mut progress).await;
}
progress.unit = None;

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.

Praise — making completion an independent count over the whole store rather than a conclusion drawn from "I finished my unit list" is the right instinct, and it's the property the entire feature rests on.

A unit enumeration that missed a prefix, or a ledger created mid-sweep, surfaces as Swept with a non-zero remainder instead of a false Completed — and since Completed is the only thing licensing key deletion, that's the difference between a safe failure and an unreadable ledger. The docs say it too ("Only completed … licenses removing the retiring key"), which is the right thing to put in front of an operator.

let plaintext = self.decrypt(&envelope)?;
let rewritten = self.encrypt(&plaintext)?;
self.inner.write_bytes(address, &rewritten).await?;

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.

Praise — reading the blob back and comparing both the key id and the decrypted plaintext before reporting success is more than most rewrite loops bother with, and on a background path it costs nothing that matters.

let mut keys = Vec::new();
for entry in graph.resolve_all(raw) {
let id = resolve_u64(graph, entry, vocab::FIELD_KEY_ID)
.ok_or_else(|| ConnectionError::invalid_config("AES256Keys entry requires keyId"))?;

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.

Praise — one validate_aes256_key_set shared by the JSON-LD and flat parsers, rejecting the mixed form, duplicate ids and an out-of-set current id.

And the error messages tell the operator what to do rather than what went wrong ("list the single key in AES256Keys"). That's the kind of thing that stops a support ticket.

(worker, handle)
}

/// Leader-scope key rotation task: resume a pending sweep, then hold. The

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.

Praise — ReleaseOnDrop inside the leader task, so an abort on leadership loss releases the record rather than stranding it until the lease expires, is a nice piece of plumbing and the comment says exactly why it exists.

@bplatz
bplatz force-pushed the feat/encryption-key-rotation branch from ca6b589 to 466908e Compare September 25, 2026 23:14
Base automatically changed from fix/index-build-staging-guard to main September 25, 2026 23:28
…in surface

Foundation for key rotation without export and import.

- MultiKeyProvider holds several keys by id with one current; every held
  key decrypts, the current one encrypts. KeyProvider gains key_ids() for
  reporting (ids only, never material). key_id_of_header classifies a
  blob from its first bytes without decrypting.
- Storage config accepts AES256Keys (a list of keyId + AES256Key entries,
  each with the usual environment indirection) and AES256CurrentKey, in
  both the JSON-LD and flat parsers. The single AES256Key form still means
  one key with id 0. Both parsers reject a mix of the two forms, duplicate
  ids, and a current id outside the set.
- FlureeBuilder carries the set through ConfiguredKey (now over
  MultiKeyProvider), with with_encryption_keys() and encryption_key_ids().
- Core gains the EncryptionAdmin trait, reachable from any StorageRead via
  encryption_admin(): key ids, current id, key_id_at(address) from the
  envelope header alone, and reencrypt(address), an in-place rewrite under
  the current key that verifies its own read-back. EncryptedStorage
  implements it; absent or non-envelope bytes classify as None.

Tests cover the provider, both parsers, and an end-to-end reopen of a
ledger written under key 1 with key 2 current: old blobs read, every blob
classifies as key 1, re-encrypts in place, and reads back through a client
holding key 2 alone.
Fluree::start_key_rotation runs a background sweep that re-envelopes every
blob on a retiring key under the current key, in place. Units are listed
in a fixed order — each ledger branch, each ledger's shared dictionaries,
graph sources — so position is a unit plus the last address processed,
and a restart resumes from the checkpoint by re-reading a few headers.

The progress record lives at @maintenance/key-rotation.json in the same
storage; it is a cache of position and counters, never the truth, which
stays in the envelope headers. Checkpoints every thousand blobs or thirty
seconds double as a heartbeat: a Running record from another holder is
refused while fresh and taken over when stale. resume_pending_key_rotation
lets a restarted process or a new leader continue without an operator.

Blobs that fail are counted, named (first hundred), and left for the next
pass; a listing failure stops the sweep as Failed. After the sweep a
verification pass counts the whole store by header: zero stamps
Completed, otherwise Swept. verify_key_rotation runs that pass alone.
Nothing here removes a key. Dry runs count only and touch no record; a
byte-rate cap throttles rewrites; pause and cancel act on the local task.

Tests: dry run, a ledger-scoped run that verification reports as Swept,
a full run that resumes it to Completed, a fresh foreign record refused
and a stale one taken over, and reads through a client holding only the
new key.
GET /encryption reports the key ids a node holds (never material) and
whether the storage is encrypted; GET /encryption/rotate/status returns
the progress record, which any node reads from storage. POST
/encryption/rotate, /pause, /cancel and /verify are admin-gated writes
in the leader-forwarded block, so under Raft one node holds the sweep.

A sweep left Running by a previous run resumes without an operator: a
standalone server resumes it at startup, and under Raft a leader task
resumes it on election and releases it on leadership loss (the record
stays Running with a cleared heartbeat, so the next leader takes over at
once instead of waiting for staleness).

Discovery advertises the key ids and rotation support; the OpenAPI
document lists the routes. Tests drive a rotation to completion over the
router, verify it, and pin the admin gate and the unencrypted response.
`fluree encryption` — status, rotate, resume, pause, cancel, verify and
generate-key — runs against a server (`--remote`) or directly against
the storage a connection config describes (`--connection-config`); the
CLI's own local store is never encrypted, so there is no third mode.
`rotate --wait` and `resume --wait` poll status and print one line per
change, marking a stalled record; a local sweep is always awaited, since
exiting would abandon it. `--json` prints the raw response for scripts.
The remote client gains the six calls behind the commands.

Docs: the encryption page's rotation section now describes the key set
configuration, the two-phase rollout across nodes, the commands and
endpoints, what the status fields mean, and that only a verified zero
count licenses removing a key. The connection-config reference lists
AES256Keys and AES256CurrentKey for every storage type.

The rotation tests wait with a deadline so a stalled sweep fails the
test instead of hanging it.
The CLI docs gate requires a docs/cli page per command, indexed in the
README and the book summary. The page mirrors the command tree and
points at the rotation runbook for the cross-node rollout order.
…llow-ups

StorageRead::encryption_admin is now required, like
permits_plaintext_cache. With a `None` default, AddressIdentifierResolverStorage
and TieredStorage answered "not encrypted" over encrypted storage: with
addressIdentifiers configured, rotation refused to start and GET /encryption
reported encrypted: false on a node that encrypts at rest.

- AddressIdentifierResolverStorage returns its default storage's admin.
  Every write and listing goes to the default, so it is all this node can
  rotate; routed storages are read-only here and carry their own keys.
- TieredStorage returns an admin that routes by address when both tiers
  encrypt under the same key set.
- GET /encryption asks the storage through Fluree::encryption_key_ids
  instead of treating every config error as "not encrypted".
- key_rotation_status no longer reports a released record (updated_at 0,
  mid leader handover) as stalled.
- KeyedAes256Key's Debug redacts the key, and StorageConfig's Debug lists
  the key set by id.

Tests: rotation through an addressIdentifiers router (fails with the router
answering None); a released record is not stalled; the scoped-then-full
assertion checks the new record's scope instead of comparing whole-second
start times, which passed only when both runs fell in the same second. The
rotation tests run on a multi-thread runtime so their deadline can fire.
A configured key that does not take effect used to leave the store
unencrypted without an error:

- AES256Key given as {"envVar": ...} with the variable unset or empty
  and no defaultVal resolved to nothing, and the storage was built
  plaintext. It is now a config error. AES256Keys entries already failed
  closed.
- In the flat config form a non-string AES256Key (such as an envVar
  object) was skipped. It is now a config error naming the JSON-LD form.
- Only indexStorage's key is read, and it encrypts commit storage too, so
  a key on commitStorage alone left commits and indexes plaintext. A
  commitStorage key that differs from indexStorage's is now rejected;
  repeating the index key (for example by naming the same node) is fine.

Key rotation status also reports a record released by an outgoing leader
as `released` instead of hiding it: a release nobody picked up was
otherwise indistinguishable from a healthy running sweep. The CLI shows
RELEASED with the `resume` hint.
…code

Every claim in the encryption and key rotation pages was checked against
the code and corrected where it did not hold:

- security/encryption.md: key set Rust API; where the key goes
  (indexStorage; commitStorage and envVar keys now fail closed); moving
  from a single AES256Key keeps id 0; admin gating covers all six
  endpoints and is enforced only with --admin-auth-mode required; how a
  sweep resumes after a restart or leader change, and when it does not
  (#1953); --rate is not kept on resume (#1954); dry runs, --ledger scope,
  local runs and stalled-while-verifying; the full status fields;
  integrity is per blob; what the nameservice holds, the Raft log,
  presigned import staging, and rebuild staging on the server (#1955);
  troubleshooting strings that match the code; and a migration to
  encryption through .flpack archives, which keep history.
- cli/encryption.md: resume, pause and cancel semantics, --rate format,
  --wait, exit status and --json shapes, single-key rotation.
- connection-config-jsonld, operations/storage, operations/ipfs-storage,
  getting-started/rust-api, design/storage-traits, reference/crate-map and
  cli/config: the required trait methods, the IPFS and build_with
  exceptions, key placement, and the CLI's real storage_path key.

The `fluree create --remote` help text no longer says --from is rejected:
.flpack archives restore on the server, and source files import there
when the server offers source uploads.
@bplatz

bplatz commented Sep 26, 2026

Copy link
Copy Markdown
Contributor Author

@aaj3f heads-up: this has changed since you approved ca6b5895c. Beyond your threads (replied inline), two things are new and worth a look.

rotation_through_an_address_identifier_router ended `swept` instead of
`completed` in CI. The seeding client is built from a connection config
with background indexing on, and the default reindex threshold is 100
bytes, so every seeding insert queued a background index build under
the old key. That build could still be writing after the seeding client
went out of scope, so the sweep missed blobs that verification then
found. All three tests shared the race; the router test lost it first.

The tests build and publish their indexes explicitly, so their configs
now turn background indexing off. Without the change, 1 of 40 parallel
runs failed locally; with it, 120 of 120 pass.
@bplatz
bplatz merged commit 4002cf6 into main Sep 26, 2026
16 checks passed
@bplatz
bplatz deleted the feat/encryption-key-rotation branch September 26, 2026 00:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:storage Storage backends, nameservice, ledger lifecycle, index storage, caches enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants