Skip to content

fix(kms): address #1533 review on LUKS migration, setters and handover checks - #1539

Merged
kvinwang merged 31 commits into
feat/kms-epochs-combinedfrom
fix/pr1533-review-decisions
Nov 9, 2026
Merged

kvinwang merged 31 commits into
feat/kms-epochs-combinedfrom
fix/pr1533-review-decisions

Conversation

@kvinwang

@kvinwang kvinwang commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

Follow-up to #1533 review (blocking #1, #3, #4, #7, #8, #9, #11, #12, #13, #14).

  • LUKS migration: replace luksChangeKey + luksHeaderRestore with in-place luksAddKey → token import → luksKillSlot, each one atomic LUKS2 commit. The header is re-backed up and validated after each change, and the disk is opened only with the validated tmpfs copy. Boot tries the current key first, so it can resume after a crash at any step. The initialization label is checked before migration, so an interrupted format gets reformatted. Requires cryptsetup ≥ 2.5.
  • Legacy contract checks: isKmsAllowed / isAppAllowed always read epoch 0, matching v0.6.0.
  • Epoch-less KMS setters (OS image, KMS MR, KMS device) now apply to every row from the current epoch through the latest registered one, so a revocation during a rotation also reaches the serving row. *AtEpoch still changes a single row.
  • App epoch preparation (ratls: Implement quote verification in RA-TLS #7): DstackApp *AtEpoch setters accept the next epoch, and the epoch-less setters change both the current and the next row. App owners can prepare row N+1 before calling advanceAppEpoch(N).
  • Fail closed on unknown app epochs (Add event log in certs and quote api #8):
    • auth-simple: a missing or invalid config fails every request.
    • auth-simple and dstack-auth: /app/:appId returns 404 for an unknown app.
    • DstackKms: currentAppEpoch(address) reverts for an unregistered or undeployed app. Legacy policies are still epoch 0, and the authorization paths still return a rejection instead of reverting.
    • KMS: the env public key RPCs refuse a non-200 answer.
  • Pre-epoch KMS cut-off (Add python client for tappd #9): once a root epoch other than 0 is active, all five backends deny /bootAuth/kms requests that report no root epoch, as they already did for apps. The CHANGELOG says to upgrade every KMS before activating a new epoch.
  • Legacy app check (Add example killswitch #11): DstackApp.isAppAllowed refuses once the app epoch is nonzero.
  • Root policy rows keyed by chain hash (Remove ubuntu-based image making #12): a popped and re-registered epoch starts with empty rows. Epoch 0 keeps the legacy mappings, and the storage layout stays compatible with 0.6.3.
  • dstack-auth (teepod: Support for mapping host port to CVM #13): empty devices and osImages lists now allow nothing.
  • Upgrade safety (Support for running CVM without KMS #14):
    • The v0.5.9 (deployed) and v0.6.0 DstackKms and DstackApp sources are kept verbatim under contracts/test-utils/reference/.
    • All four release → current upgrades are checked with Upgrades.validateUpgrade and referenceContract.
    • The KMS tests now use the real v0.5.9 source instead of LegacyDstackKms.
    • Negative check, run by hand: each of the following makes test_ReleasedStorageLayoutsUpgradeToTheCurrentContracts fail, and the unmodified tree passes:
      • swapping allowedComposeHashes and allowedDeviceIds in DstackApp ("Renamed allowedComposeHashes to allowedDeviceIds");
      • growing the DstackKms __gap from 45 to 46 ("Bad storage gap resize from 50 to 46");
      • shrinking the DstackApp __gap from 45 to 44 ("Bad storage gap resize from 49 to 44").
  • Tests:
    • KMS handover: handler-level tests against a mock auth API cover the self check, the caller check, the key release gate, public_key_handover, the recipient check, and the operations sent. Removing any check or sending a wrong operation fails a test.
    • Auth backends: auth-eth, auth-eth-bun, auth-mock and dstack-auth now assert the forwarded or evaluated operation and both epochs.

Test results:

  • forge test --ffi: 96 passed.
  • cargo test -p dstack-kms: 78 passed. cargo test -p dstack-auth: 9 passed.
  • auth-eth jest: 25 passed. auth-eth-bun vitest: 53 passed. auth-mock vitest: 16 passed. auth-simple vitest: 33 passed.
  • dstack-util LUKS tests in debian:trixie (cryptsetup 2.7.5): 9 passed.

@kvinwang kvinwang changed the title fix(kms): address #1533 review on LUKS migration and legacy checks fix(kms): address #1533 review on LUKS migration, setters and handover checks Nov 9, 2026
isKmsAllowed and isAppAllowed serve pre-epoch KMS binaries only. Read
the legacy epoch-0 storage regardless of the current root epoch so they
behave exactly like v0.6.0.

Signed-off-by: Kevin Wang <wy721@qq.com>
Restoring a re-keyed header copy with luksHeaderRestore bypassed the
LUKS2 crash-consistent metadata commit, and an interrupted format left
a header without its epoch token that every later boot misread as
epoch 0.

- Check the initialization label before any migration, so an
  interrupted format is reformatted.
- Replace luksChangeKey + luksHeaderRestore with luksAddKey, token
  import and luksKillSlot on the device. Each is one atomic LUKS2
  commit; the header is backed up to tmpfs and validated again after
  each change, and the disk is opened only with the validated copy.
- Try the current key first: if it unlocks a keyslot, record the token
  and remove the other slot; otherwise migrate from the token's epochs.
  This resumes after a crash at any step.
- Accept keyslot 0, 1 or both, with the token bound to one existing
  slot and both header copies required to agree.

Signed-off-by: Kevin Wang <wy721@qq.com>
The epoch-less OS image, KMS MR and KMS device setters wrote only the
latest registered row. During a rotation, removeOsImageHash(compromised)
succeeded but left the serving row allowing the image. Writing only the
current row instead would make a prepared pending row miss the change.

Apply them to every row from the current epoch through the latest
registered one. The *AtEpoch setters still change a single row.

Signed-off-by: Kevin Wang <wy721@qq.com>
Exercise handover at the handler level against a recording auth API:
the self check (kms_export_keys), the caller check (kms_import_keys at
the highest exported epoch), the platform key release gate, the
public_key_handover switch on the RPC listener, and the recipient's
check of the source. Removing any of them, or sending a wrong
operation, fails a test.

Signed-off-by: Kevin Wang <wy721@qq.com>
auth-eth and auth-eth-bun: decode or inspect the contract call and
check the forwarded operation hash and both epoch selectors for
authorizeKms and authorizeApp. auth-mock and dstack-auth: cover a
wrong-scope operation and requested root and app epochs beyond the
current ones; auth-simple already covers these.

Signed-off-by: Kevin Wang <wy721@qq.com>
…off"

This reverts commit b67fed0.

Signed-off-by: Kevin Wang <wy721@qq.com>
…cing

DstackApp accepted *AtEpoch writes only up to the current epoch, so the
next row could be filled only after advanceAppEpoch, and a CVM that
restarted in between was denied.

Accept writes to the current epoch + 1, and apply the epoch-less
setters to the current and next rows, mirroring the DstackKms
semantics for pending root epochs. Document preparing the next row
before advancing.

Signed-off-by: Kevin Wang <wy721@qq.com>
The env public key RPCs read the app epoch from `/app/:appId` alone.
Three backends reported epoch 0 when they could not tell: auth-simple
on a missing or invalid config, dstack-auth for an unknown app, and
DstackKms.currentAppEpoch for an unregistered or undeployed app. A key
for epoch 0 could then be issued to an app that has advanced.

- auth-simple: a missing or invalid config fails every request (503 on
  `/app/:appId` and the authorize endpoints, denial on `/bootAuth`)
  instead of reading as an empty policy; an unknown app returns 404.
- dstack-auth: `/app/:appId` returns 404 for an unknown app.
- DstackKms: currentAppEpoch reverts for an unregistered or undeployed
  app, so the Ethereum backends answer non-200. A registered legacy
  policy without IAppEpochAuth is still epoch 0, and the authorization
  paths still report their rejection instead of reverting.
- KMS already rejects a non-200 answer; cover both env public key RPCs.

Signed-off-by: Kevin Wang <wy721@qq.com>
Every backend exempted KMS checks without a root epoch from the
current-epoch rule, so a KMS binary predating root epochs kept passing
its self check after a rotation. It could still sign env public keys
with the rotated epoch-0 root.

Apply the app rule to KMS checks too in auth-eth, auth-eth-bun,
auth-simple, auth-mock and dstack-auth: a request without a root epoch
is served only while epoch 0 is current. Before any rotation, old KMS
binaries behave as before. Note the required upgrade order.

Signed-off-by: Kevin Wang <wy721@qq.com>
DstackApp.isAppAllowed read the current app epoch row, but its callers
(a DstackKms predating app epochs, or other IAppAuth consumers) derive
epoch-zero keys from the bool. After an advance, an identity approved
only at epoch N would receive the epoch-0 keys the owner is retiring.

Refuse once the app epoch is nonzero, as DstackKms.isAppAllowed does,
so the result does not depend on which contract is upgraded first. At
epoch 0 it still reads row 0, as in v0.6.0.

Signed-off-by: Kevin Wang <wy721@qq.com>
The OS image, KMS MR and KMS device rows of epochs from 1 were keyed by
epoch number, and popRootEpoch cannot clear a mapping. Policy prepared
for a popped epoch therefore applied to whatever keys were registered
under the same number next.

Key those rows by the epoch's chain hash instead, so policy belongs to
the registered keys and a replacement registration starts empty.
Epoch 0 keeps the legacy mappings. The per-epoch storage is new in
this branch and occupies the same slots, so no migration is needed;
the layout stays compatible with 0.6.3.

Signed-off-by: Kevin Wang <wy721@qq.com>
…othing

An empty `devices` list allowed any device even with `allowAnyDevice`
false, and an empty `osImages` list skipped the OS image check. The
comment claimed this matched auth-simple, which denies in that case.

Allow any device only with `allowAnyDevice`, and deny apps when the OS
image allowlist is empty. The allowlists dstack-cli generates set
`allowAnyDevice: true` and list the image, so they are unaffected.

Signed-off-by: Kevin Wang <wy721@qq.com>
The upgrade tests only covered the current contracts upgrading to test
V2s, and LegacyDstackKms used Ownable2Step while v0.5.9 is single-step,
so reordering DstackApp's legacy fields or resizing a gap went unnoticed.

Keep the v0.5.9 (deployed) and v0.6.0 DstackKms and DstackApp sources
verbatim under contracts/test-utils/reference, renamed per release so
"DstackKms.sol" stays unambiguous for the deployment scripts, and
validate all four release-to-current upgrades with referenceContract.
Upgrade a v0.5.9 DstackApp proxy and check its allowlist survives, and
migrate the KMS tests from LegacyDstackKms to the real v0.5.9 source.

Signed-off-by: Kevin Wang <wy721@qq.com>
Keep the fallback that lets a new KMS join a v0.5.x source, the only
migration path for a cluster whose KMS cannot upgrade in place, and
document why it is safe: mrAggregated still gates the image, rotation
never takes it, and a v0.5.x source holds only epoch 0, so it is
refused once a later epoch is current.

Move the decision into is_legacy_source and cover it, along with a
pre-epoch source being refused after a rotation, in unit tests.

Signed-off-by: Kevin Wang <wy721@qq.com>
Drop the legacy certificate fallback and its allow_legacy_cert
parameter. It filled a missing OS image hash from the local KMS for
0.5.x sources, but current releases cannot join a 0.5.x cluster anyway,
so it only kept a fail-open branch on the OS image dimension. A source
without an OS image hash is now refused, for joins and rotations alike;
upgrade a 0.5.x cluster to 0.6.x first.

This replaces the scoping of the fallback in the previous commit.

Signed-off-by: Kevin Wang <wy721@qq.com>
The signer whitelist is a flat set, so a signer left in it after a
rotation stays trusted and a holder of the rotated root can sign env
public keys the CLI accepts. Tell operators to remove the old signer
before adding the new one.

Signed-off-by: Kevin Wang <wy721@qq.com>
The guest tries historical env keys from the current epoch down to 0
and skips an epoch the KMS refuses, so env encrypted under an older,
still-approved epoch can migrate. The protocol said it stopped on an
authorization failure.

Signed-off-by: Kevin Wang <wy721@qq.com>
The protocol asked the guest to verify the replacement env locally;
the guest does not, and the round trip through the VMM is covered by
integration tests instead.

Signed-off-by: Kevin Wang <wy721@qq.com>
…ches

The self boot info is cached for an hour, so this KMS's own TCB status
takes effect up to an hour late; the comment claimed it was judged on
every self check. Document the scope of enforce_self_authorization,
the dev auth API and public_key_handover separately.

Signed-off-by: Kevin Wang <wy721@qq.com>
The original allowlist getters and material events describe epoch 0,
as the legacy interfaces do; say so in their natspec and point to the
*AtEpoch getters and EpochPolicyChanged for other epochs.

Signed-off-by: Kevin Wang <wy721@qq.com>
…tion

Rotation onboarding does not require a source token, and need not: the
new epoch takes effect only once governance registers and activates
it, and Admin.GetKmsKey also requires an attested client certificate.
Also note that every join, not only rotation, now needs the source's
OS image hash.

Signed-off-by: Kevin Wang <wy721@qq.com>
The v2 report data bound the epoch number but not the preceding chain
hash, and nothing tested either format. Neither needs binding: the
epoch number comes from the on-chain registration order, joins check
the prefix against the registry, and a mismatch only fails
`servable_epoch`. Use the released v1 encoding for every epoch, so the
owner and external tools have one check, and pin it with a test vector.
Document the verification steps before registration.

Signed-off-by: Kevin Wang <wy721@qq.com>
The registry is not strictly append-only: a pending epoch can be popped
and the owner can update evidenceUrl. Only a registered epoch's keys and
chain hash are immutable, and the evidence proves itself, so changing
its URL only moves where it is stored.

Signed-off-by: Kevin Wang <wy721@qq.com>
Keys::store created epochs/<n>/ with fs::create_dir_all, so safe_write
found it present and never fsynced its parent. After a power loss the
directory could vanish while the top-level keys remained: the node
refuses to onboard again and cannot load its keyring. Let safe_write
create the directory, which flushes every parent it creates.

Not unit tested: losing unsynced directory entries requires a power
cut, which a test cannot simulate.

Signed-off-by: Kevin Wang <wy721@qq.com>
The comment claimed the lock is held across a fetch so each epoch is
fetched once. It is released before fetching, and only successes are
cached, so concurrent first requests and refused epochs each reach the
KMS. That is harmless (an app can call the KMS directly anyway), but
the comment must not suggest deduplication.

Signed-off-by: Kevin Wang <wy721@qq.com>
Wallets from toViemAccount, toKeypair and their Python counterparts are
a function of the KMS root: a leaked root yields their private keys,
and moving funds after a rotation or an app epoch advance is a race
against its holder. Recommend smart-account signers or a sealed random
key for assets, and rejecting old root epochs for signatures.

Signed-off-by: Kevin Wang <wy721@qq.com>
GetAppEnvEncryptPubKey and GetSealedEnvPubKey need no client
certificate, yet each call queried the auth backend's /app/:appId
uncached, two chain RPC calls on auth-eth-bun. A flood could exhaust
the RPC provider's quota and fail authorization for everyone.

Cache each app's epoch for one second in a bounded cache (10,000
entries), as for the other auth API reads; failures are not cached.
Random app IDs still pass through, so document per-source rate
limiting in front of the KMS.

Signed-off-by: Kevin Wang <wy721@qq.com>
A migration that crashed after luksAddKey, before the token import or
the old keyslot's removal, leaves two keyslots. If the CVM does not
boot again until another rotation, the current key unlocks neither,
and sync_luks_epochs refused any disk with two keyslots it could not
unlock, so every later boot failed.

When the current key unlocks no keyslot, migrate from the slot the
token records (slot 0 for a disk without a token). Confirm the
recorded epochs' key unlocks it first, so a denied epoch or a wrong
key leaves both keyslots in place, then remove the other slot to make
room for the current key.

Signed-off-by: Kevin Wang <wy721@qq.com>
@kvinwang
kvinwang force-pushed the fix/pr1533-review-decisions branch from c818f54 to 29605ec Compare November 9, 2026 12:23
@kvinwang
kvinwang merged commit e4a3c54 into feat/kms-epochs-combined Nov 9, 2026
3 checks passed
@kvinwang
kvinwang deleted the fix/pr1533-review-decisions branch November 9, 2026 12:25
kvinwang added a commit that referenced this pull request Nov 9, 2026
…leases

Rebased onto #1539, whose handover tests construct RpcHandler and call
handover_keys directly. Pass the remote endpoint and the release kind
there, and assert that a successful handover counts one release on its
listener while a refused one counts none.

Signed-off-by: Kevin Wang <wy721@qq.com>
kvinwang added a commit that referenced this pull request Nov 9, 2026
…result

Rebased onto #1539, whose tests still used the old shapes: qualified
DstackKms.AuthorizationRequest/Result types, the isAllowed field, the
three-argument DstackApp.authorizeApp, and backend answers without the
latest root epoch fields. Move them to the shared types, `authorized`,
the authorizeAt helper and complete answers.

test_AuthorizeAppOwnsOperationScopeAndAppEpoch now prepares row 0 with
the *AtEpoch setters: since #1539 the epoch-less setters also write the
next row, so the current row would no longer be empty after advancing.

Signed-off-by: Kevin Wang <wy721@qq.com>
kvinwang added a commit that referenced this pull request Nov 9, 2026
…tation

DiskMigration now models the two-keyslot migration of #1539 (luksAddKey,
token bound to its keyslot, luksKillSlot) instead of luksHeaderRestore, and
lets the KMS rotate at any point of a boot. All invariants hold for epochs
0-3; the torn-restore script and the configs for the replaced scheme go.

KmsRotation checks the latest registered epoch's chain hash on handover, as
onboard_service.rs does since #1542, so HandoverAgreesWithRegistry now holds
and joins the main config.

EnvUpdate gains FailClosed for the guest of #1546, which holds with a lossy
host API; the lossy config keeps the earlier guest as a counterexample.

The README records the mutations each model catches.

Signed-off-by: Kevin Wang <wy721@qq.com>
kvinwang added a commit that referenced this pull request Nov 9, 2026
…tation

DiskMigration now models the two-keyslot migration of #1539 (luksAddKey,
token bound to its keyslot, luksKillSlot) instead of luksHeaderRestore, and
lets the KMS rotate at any point of a boot. All invariants hold for epochs
0-3; the torn-restore script and the configs for the replaced scheme go.

KmsRotation checks the latest registered epoch's chain hash on handover, as
onboard_service.rs does since #1542, so HandoverAgreesWithRegistry now holds
and joins the main config.

EnvUpdate gains FailClosed for the guest of #1546, which holds with a lossy
host API; the lossy config keeps the earlier guest as a counterexample.

The README records the mutations each model catches.

Signed-off-by: Kevin Wang <wy721@qq.com>
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.

1 participant