Repository navigation
fix(kms): address #1533 review on LUKS migration, setters and handover checks - #1539
Merged
Merged
Conversation
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>
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>
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>
Signed-off-by: Kevin Wang <wy721@qq.com>
kvinwang
force-pushed
the
fix/pr1533-review-decisions
branch
from
November 9, 2026 12:23
c818f54 to
29605ec
Compare
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Follow-up to #1533 review (blocking #1, #3, #4, #7, #8, #9, #11, #12, #13, #14).
luksChangeKey+luksHeaderRestorewith in-placeluksAddKey→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.isKmsAllowed/isAppAllowedalways read epoch 0, matching v0.6.0.*AtEpochstill changes a single row.DstackApp*AtEpochsetters 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 callingadvanceAppEpoch(N)./app/:appIdreturns 404 for an unknown app.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./bootAuth/kmsrequests that report no root epoch, as they already did for apps. The CHANGELOG says to upgrade every KMS before activating a new epoch.DstackApp.isAppAllowedrefuses once the app epoch is nonzero.devicesandosImageslists now allow nothing.DstackKmsandDstackAppsources are kept verbatim undercontracts/test-utils/reference/.Upgrades.validateUpgradeandreferenceContract.LegacyDstackKms.test_ReleasedStorageLayoutsUpgradeToTheCurrentContractsfail, and the unmodified tree passes:allowedComposeHashesandallowedDeviceIdsinDstackApp("RenamedallowedComposeHashestoallowedDeviceIds");DstackKms__gapfrom 45 to 46 ("Bad storage gap resize from 50 to 46");DstackApp__gapfrom 45 to 44 ("Bad storage gap resize from 49 to 44").public_key_handover, the recipient check, and the operations sent. Removing any check or sending a wrong operation fails a test.Test results:
forge test --ffi: 96 passed.cargo test -p dstack-kms: 78 passed.cargo test -p dstack-auth: 9 passed.debian:trixie(cryptsetup 2.7.5): 9 passed.