diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000000..49ad1be77a --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,69 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +# Weekly version updates, one grouped PR per directory for minor and patch +# bumps; major bumps arrive as their own PRs. The cooldown keeps freshly +# published releases out for a week. Security updates bypass both. +version: 2 + +updates: + - package-ecosystem: cargo + directories: ["/dstack", "/sdk/rust"] + schedule: + interval: weekly + cooldown: + default-days: 7 + groups: + cargo: + update-types: ["minor", "patch"] + + - package-ecosystem: gomod + directories: ["/sdk/go", "/sdk/go/*"] + schedule: + interval: weekly + cooldown: + default-days: 7 + groups: + gomod: + update-types: ["minor", "patch"] + + - package-ecosystem: bun + directories: ["/sdk/js", "/dstack/kms/auth-eth"] + schedule: + interval: weekly + cooldown: + default-days: 7 + groups: + bun: + update-types: ["minor", "patch"] + + - package-ecosystem: npm + directories: ["/dstack/vmm/ui", "/sdk/verifier-wasm"] + schedule: + interval: weekly + cooldown: + default-days: 7 + groups: + npm: + update-types: ["minor", "patch"] + + - package-ecosystem: pip + directories: ["/sdk/python", "/dstack/vmm", "/dstack/python/ct_monitor"] + schedule: + interval: weekly + cooldown: + default-days: 7 + groups: + pip: + update-types: ["minor", "patch"] + + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + cooldown: + default-days: 7 + groups: + github-actions: + update-types: ["minor", "patch"] diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock new file mode 100644 index 0000000000..9bb8607152 --- /dev/null +++ b/.github/workflows/actions.lock @@ -0,0 +1,401 @@ +# This file is machine-generated by `gh actions-lock`. +# Do not edit by hand; run `gh actions-lock` to update. +# Docs: https://gh.io/actions-lockfile +version: 'v0.0.3' +workflows: + '.github/workflows/docker-build-check.yml': + - 'actions/checkout@v5' + - 'docker/build-push-action@v5' + - 'docker/setup-buildx-action@v3' + - 'foundry-rs/foundry-toolchain@v1' + '.github/workflows/foundry-test.yml': + - 'actions/checkout@v5' + - 'foundry-rs/foundry-toolchain@v1' + '.github/workflows/gateway-cluster-tests.yml': + - 'actions/cache@v4' + - 'actions/checkout@v5' + - 'actions/upload-artifact@v4' + - 'dtolnay/rust-toolchain@v1' + '.github/workflows/gateway-e2e-tests.yml': + - 'actions/cache@v4' + - 'actions/checkout@v5' + - 'actions/upload-artifact@v4' + - 'dtolnay/rust-toolchain@v1' + '.github/workflows/gateway-proxy-tests.yml': + - 'actions/cache@v4' + - 'actions/checkout@v5' + - 'actions/upload-artifact@v4' + - 'dtolnay/rust-toolchain@v1' + '.github/workflows/gateway-release.yml': + - 'actions/attest-build-provenance@ef244123eb79f2f7a7e75d99086184180e6d0018' + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9' + - 'docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f' + - 'softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65' + '.github/workflows/go-sdk-release.yml': + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff' + - 'dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8' + - 'softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65' + - 'swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0' + '.github/workflows/guest-os.yml': + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093' + - 'actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02' + '.github/workflows/halmos.yml': + - 'actions/checkout@v5' + - 'foundry-rs/foundry-toolchain@v1' + '.github/workflows/js-sdk-release.yml': + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444' + - 'oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6' + - 'softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65' + '.github/workflows/key-recovery-release.yml': + - 'actions/attest-build-provenance@ef244123eb79f2f7a7e75d99086184180e6d0018' + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'docker/build-push-action@ca052bb54ab0790a636c9b5f226502c73d547a25' + - 'docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9' + - 'docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f' + - 'softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65' + '.github/workflows/kms-auth-eth.yml': + - 'actions/attest-build-provenance@ef244123eb79f2f7a7e75d99086184180e6d0018' + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8' + - 'docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9' + - 'docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f' + - 'oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6' + '.github/workflows/kms-release.yml': + - 'actions/attest-build-provenance@ef244123eb79f2f7a7e75d99086184180e6d0018' + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9' + - 'docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f' + - 'foundry-rs/foundry-toolchain@908c540300062bd5a7e473851cdb4282204cee09' + - 'softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65' + '.github/workflows/lean.yml': + - 'actions/checkout@v5' + - 'leanprover/lean-action@v1' + '.github/workflows/local-key-provider-release.yml': + - 'actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8' + - 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1' + - 'docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a' + - 'docker/login-action@dbcb813823bdd20940b903addbd779551569679f' + - 'docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e' + - 'softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64' + '.github/workflows/mkosi-build.yml': + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093' + - 'actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1' + - 'actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02' + - 'docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9' + '.github/workflows/plumber-check.yml': + - 'actions/checkout@v5' + - 'getplumber/plumber@v0.7.23' + '.github/workflows/prek-check.yml': + - 'actions/checkout@v5' + - 'actions/setup-go@v5' + - 'actions/setup-python@v5' + - 'dtolnay/rust-toolchain@v1' + '.github/workflows/python-sdk-release.yml': + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065' + - 'pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086' + - 'softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65' + '.github/workflows/qemu-acpi-differential.yml': + - 'actions/checkout@v5' + - 'actions/upload-artifact@v4' + - 'dtolnay/rust-toolchain@v1' + '.github/workflows/rust-sdk-release.yml': + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'rust-lang/crates-io-auth-action@3268eb413133e2960fa4ae0e963ca76380c54cd9' + '.github/workflows/rust.yml': + - 'actions/checkout@v5' + - 'dtolnay/rust-toolchain@v1' + - 'swatinem/rust-cache@v2' + '.github/workflows/sdk-compat.yaml': + - 'actions/checkout@v5' + - 'actions/setup-go@v5' + - 'actions/setup-node@v5' + - 'actions/setup-python@v5' + - 'dtolnay/rust-toolchain@v1' + - 'swatinem/rust-cache@v2' + '.github/workflows/sdk.yaml': + - 'actions/checkout@v5' + - 'actions/setup-python@v5' + - 'dtolnay/rust-toolchain@v1' + - 'swatinem/rust-cache@v2' + '.github/workflows/simulator-release.yml': + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8' + - 'softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65' + - 'swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6' + '.github/workflows/spdx-check.yml': + - 'actions/checkout@v5' + - 'fsfe/reuse-action@v5' + '.github/workflows/verifier-release.yml': + - 'actions/attest-build-provenance@ef244123eb79f2f7a7e75d99086184180e6d0018' + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9' + - 'docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f' + - 'softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65' + '.github/workflows/verifier-wasm-release.yml': + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444' + - 'softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65' + '.github/workflows/verifier-wasm.yml': + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093' + - 'actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444' + - 'actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02' + - 'oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6' + '.github/workflows/vmm-ui.yml': + - 'actions/checkout@v5' + - 'actions/setup-node@v5' + - 'actions/setup-python@v5' +dependencies: + 'actions/attest-build-provenance@36fa7d009e22618ca7cd599486979b8150596c74': + ref: 'predicate@1.1.4' + commit: 'sha1-36fa7d009e22618ca7cd599486979b8150596c74' + owner_id: 44036562 + repo_id: 760702757 + 'actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8': + ref: 'v4.2.2' + commit: 'sha1-4d101475d8b20a2381f78447822ac1eab6504dd8' + owner_id: 44036562 + repo_id: 760702757 + uses: + - 'actions/attest@508db95dd578ae2727ebd6217d5ba78e4fbda05d' + 'actions/attest-build-provenance@ef244123eb79f2f7a7e75d99086184180e6d0018': + ref: 'v1.4.4' + commit: 'sha1-ef244123eb79f2f7a7e75d99086184180e6d0018' + owner_id: 44036562 + repo_id: 760702757 + uses: + - 'actions/attest-build-provenance@36fa7d009e22618ca7cd599486979b8150596c74' + - 'actions/attest@67422f5511b7ff725f4dbd6fb9bd2cd925c65a8d' + 'actions/attest@508db95dd578ae2727ebd6217d5ba78e4fbda05d': + ref: 'v4.2.1' + commit: 'sha1-508db95dd578ae2727ebd6217d5ba78e4fbda05d' + owner_id: 44036562 + repo_id: 760701061 + 'actions/attest@67422f5511b7ff725f4dbd6fb9bd2cd925c65a8d': + ref: 'v1.4.1' + commit: 'sha1-67422f5511b7ff725f4dbd6fb9bd2cd925c65a8d' + owner_id: 44036562 + repo_id: 760701061 + 'actions/cache@caa296126883cff596d87d8935842f9db880ef25': + ref: 'v5.1.0' + commit: 'sha1-caa296126883cff596d87d8935842f9db880ef25' + owner_id: 44036562 + repo_id: 215566462 + 'actions/cache@v4': + ref: 'v4' + commit: 'sha1-0057852bfaa89a56745cba8c7296529d2fc39830' + owner_id: 44036562 + repo_id: 215566462 + 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1': + ref: 'v7.0.1' + commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1' + owner_id: 44036562 + repo_id: 197814629 + 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09': + ref: 'v5.1.0' + commit: 'sha1-fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + owner_id: 44036562 + repo_id: 197814629 + 'actions/checkout@v5': + ref: 'v5' + commit: 'sha1-fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + owner_id: 44036562 + repo_id: 197814629 + 'actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093': + ref: 'v4.3.0' + commit: 'sha1-d3f86a106a0bac45b974a628896c90dbdf5c8093' + owner_id: 44036562 + repo_id: 192626254 + 'actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff': + ref: 'v5.6.0' + commit: 'sha1-40f1582b2485089dde7abd97c1529aa768e1baff' + owner_id: 44036562 + repo_id: 192624594 + 'actions/setup-go@v5': + ref: 'v5' + commit: 'sha1-40f1582b2485089dde7abd97c1529aa768e1baff' + owner_id: 44036562 + repo_id: 192624594 + 'actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444': + ref: 'v5.0.0' + commit: 'sha1-a0853c24544627f65ddf259abe73b1d18a591444' + owner_id: 44036562 + repo_id: 189476904 + 'actions/setup-node@v5': + ref: 'v5' + commit: 'sha1-a0853c24544627f65ddf259abe73b1d18a591444' + owner_id: 44036562 + repo_id: 189476904 + 'actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065': + ref: 'v5.6.0' + commit: 'sha1-a26af69be951a213d495a4c3e4e4022e16d87065' + owner_id: 44036562 + repo_id: 192625525 + 'actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405': + ref: 'v6.2.0' + commit: 'sha1-a309ff8b426b58ec0e2a45f0f869d46889d02405' + owner_id: 44036562 + repo_id: 192625525 + 'actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1': + ref: 'v6.3.0' + commit: 'sha1-ece7cb06caefa5fff74198d8649806c4678c61a1' + owner_id: 44036562 + repo_id: 192625525 + 'actions/setup-python@v5': + ref: 'v5' + commit: 'sha1-a26af69be951a213d495a4c3e4e4022e16d87065' + owner_id: 44036562 + repo_id: 192625525 + 'actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9': + ref: 'v7.0.2' + commit: 'sha1-cf430e030ddbb5b0abf93d22962f4752f3646cd9' + owner_id: 44036562 + repo_id: 192625955 + 'actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02': + ref: 'v4.6.2' + commit: 'sha1-ea165f8d65b6e75b540449e92b4886f43607fa02' + owner_id: 44036562 + repo_id: 192625955 + 'actions/upload-artifact@v4': + ref: 'v4' + commit: 'sha1-ea165f8d65b6e75b540449e92b4886f43607fa02' + owner_id: 44036562 + repo_id: 192625955 + 'docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8': + ref: 'v6.19.2' + commit: 'sha1-10e90e3645eae34f1e60eeb005ba3a3d33f178e8' + owner_id: 5429470 + repo_id: 241092383 + 'docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a': + ref: 'v7.3.0' + commit: 'sha1-53b7df96c91f9c12dcc8a07bcb9ccacbed38856a' + owner_id: 5429470 + repo_id: 241092383 + 'docker/build-push-action@ca052bb54ab0790a636c9b5f226502c73d547a25': + ref: 'v5.4.0' + commit: 'sha1-ca052bb54ab0790a636c9b5f226502c73d547a25' + owner_id: 5429470 + repo_id: 241092383 + 'docker/build-push-action@v5': + ref: 'v5' + commit: 'sha1-ca052bb54ab0790a636c9b5f226502c73d547a25' + owner_id: 5429470 + repo_id: 241092383 + 'docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9': + ref: 'v3.7.0' + commit: 'sha1-c94ce9fb468520275223c153574b00df6fe4bcc9' + owner_id: 5429470 + repo_id: 287743349 + 'docker/login-action@dbcb813823bdd20940b903addbd779551569679f': + ref: 'v4.6.0' + commit: 'sha1-dbcb813823bdd20940b903addbd779551569679f' + owner_id: 5429470 + repo_id: 287743349 + 'docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e': + ref: 'v4.3.0' + commit: 'sha1-37fe631027851001ddb9b187196cc803df7f5f0e' + owner_id: 5429470 + repo_id: 288485773 + 'docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f': + ref: 'v3.12.0' + commit: 'sha1-8d2750c68a42422c14e847fe6c8ac0403b4cbd6f' + owner_id: 5429470 + repo_id: 288485773 + 'docker/setup-buildx-action@v3': + ref: 'v3' + commit: 'sha1-8d2750c68a42422c14e847fe6c8ac0403b4cbd6f' + owner_id: 5429470 + repo_id: 288485773 + 'dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8': + ref: 'v1' + commit: 'sha1-683b588c487a69d01f6c6ddf40f036ff682cc2c8' + owner_id: 1940490 + repo_id: 260749683 + 'dtolnay/rust-toolchain@v1': + ref: 'v1' + commit: 'sha1-683b588c487a69d01f6c6ddf40f036ff682cc2c8' + owner_id: 1940490 + repo_id: 260749683 + 'foundry-rs/foundry-toolchain@908c540300062bd5a7e473851cdb4282204cee09': + ref: 'v1.9.1' + commit: 'sha1-908c540300062bd5a7e473851cdb4282204cee09' + owner_id: 99892494 + repo_id: 448072613 + 'foundry-rs/foundry-toolchain@v1': + ref: 'v1' + commit: 'sha1-dba66c27052e63476d886f22216e119ba7e615bf' + owner_id: 99892494 + repo_id: 448072613 + 'fsfe/reuse-action@v5': + ref: 'v5' + commit: 'sha1-bb774aa972c2a89ff34781233d275075cbddf542' + owner_id: 27927890 + repo_id: 244390200 + 'getplumber/plumber@v0.7.23': + ref: 'v0.7.23' + commit: 'sha1-ec8cb3a7edd6a324b33e85109b627b2df6023d94' + owner_id: 255179076 + repo_id: 1137327132 + uses: + - 'actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9' + - 'github/codeql-action@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee' + 'github/codeql-action@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee': + ref: 'v4.39.0' + commit: 'sha1-6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee' + owner_id: 9919 + repo_id: 259445878 + 'leanprover/lean-action@v1': + ref: 'v1' + commit: 'sha1-ba3fdfe5c4476c925da13bf11a005ddb47e47aee' + owner_id: 7233018 + repo_id: 795738301 + uses: + - 'actions/cache@caa296126883cff596d87d8935842f9db880ef25' + 'oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6': + ref: 'v2.2.0' + commit: 'sha1-0c5077e51419868618aeaa5fe8019c62421857d6' + owner_id: 108928776 + repo_id: 512644635 + 'pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086': + ref: 'v1.14.3' + commit: 'sha1-7245906fb61fa33a13554f9d5fb856fe61758086' + owner_id: 647025 + repo_id: 178055147 + uses: + - 'actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405' + 'rust-lang/crates-io-auth-action@3268eb413133e2960fa4ae0e963ca76380c54cd9': + ref: 'v1.0.6' + commit: 'sha1-3268eb413133e2960fa4ae0e963ca76380c54cd9' + owner_id: 5430905 + repo_id: 1008931044 + 'softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65': + ref: 'v2.6.2' + commit: 'sha1-3bb12739c298aeb8a4eeaf626c5b8d85266b0e65' + owner_id: 2242 + repo_id: 204253808 + 'softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64': + ref: 'v3.0.3' + commit: 'sha1-efb35369e0ad2afab669f228072c1b0d510eae64' + owner_id: 2242 + repo_id: 204253808 + 'swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6': + ref: 'v2.9.2' + commit: 'sha1-6323deb102c322ba6fcbdcafc7e3dddab59af2b6' + owner_id: 580492 + repo_id: 298565987 + 'swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0': + ref: 'v2.9.3' + commit: 'sha1-d1527c8f67ef9af357290475d4af4b0fab8f12e0' + owner_id: 580492 + repo_id: 298565987 + 'swatinem/rust-cache@v2': + ref: 'v2' + commit: 'sha1-d1527c8f67ef9af357290475d4af4b0fab8f12e0' + owner_id: 580492 + repo_id: 298565987 diff --git a/.github/workflows/docker-build-check.yml b/.github/workflows/docker-build-check.yml index 318df35a80..7711e07268 100644 --- a/.github/workflows/docker-build-check.yml +++ b/.github/workflows/docker-build-check.yml @@ -29,6 +29,9 @@ on: - '.github/workflows/gateway-release.yml' - '.github/workflows/verifier-release.yml' +permissions: + contents: read + env: DSTACK_REV: ${{ github.event.pull_request.head.sha || github.sha }} DSTACK_SRC_URL: ${{ github.event.pull_request.head.repo.clone_url || format('{0}/{1}', github.server_url, github.repository) }} @@ -52,6 +55,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 + with: + persist-credentials: false - name: Test release build orchestration run: python3 -m unittest discover -s dstack/build/shared/tests -v @@ -59,6 +64,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 + with: + persist-credentials: false - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 @@ -105,6 +112,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 + with: + persist-credentials: false - name: Checkout KMS contract dependencies run: | @@ -166,6 +175,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 + with: + persist-credentials: false - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 diff --git a/.github/workflows/foundry-test.yml b/.github/workflows/foundry-test.yml index 674e610813..cb6ae7cf3c 100644 --- a/.github/workflows/foundry-test.yml +++ b/.github/workflows/foundry-test.yml @@ -30,6 +30,8 @@ jobs: working-directory: dstack/kms/auth-eth steps: - uses: actions/checkout@v5 + with: + persist-credentials: false - name: Checkout contract dependencies working-directory: . @@ -57,7 +59,11 @@ jobs: id: build - name: Install OpenZeppelin upgrades validator - run: npm install --no-save --package-lock=false @openzeppelin/upgrades-core@^1.37.0 + # The upgrade-safety tests run `npx @openzeppelin/upgrades-core@^1.37.0`; + # warm the npx cache with that spec once so parallel tests reuse it. + # `npm install` here would also resolve the webhook server's + # package.json, which is managed by Bun. + run: npx --yes @openzeppelin/upgrades-core@^1.37.0 --help > /dev/null - name: Run Forge tests # The upgrade-safety validator rejects a contract found in more than one diff --git a/.github/workflows/gateway-cluster-tests.yml b/.github/workflows/gateway-cluster-tests.yml index 74acca7f37..fb9cf58ed8 100644 --- a/.github/workflows/gateway-cluster-tests.yml +++ b/.github/workflows/gateway-cluster-tests.yml @@ -62,10 +62,13 @@ jobs: timeout-minutes: 60 steps: - uses: actions/checkout@v5 + with: + persist-credentials: false - name: Install Rust - uses: dtolnay/rust-toolchain@1.92.0 + uses: dtolnay/rust-toolchain@v1 with: + toolchain: 1.92.0 targets: x86_64-unknown-linux-musl - name: Install musl toolchain diff --git a/.github/workflows/gateway-e2e-tests.yml b/.github/workflows/gateway-e2e-tests.yml index 38aa838fe5..4e65ddbfed 100644 --- a/.github/workflows/gateway-e2e-tests.yml +++ b/.github/workflows/gateway-e2e-tests.yml @@ -68,10 +68,13 @@ jobs: timeout-minutes: 45 steps: - uses: actions/checkout@v5 + with: + persist-credentials: false - name: Install Rust - uses: dtolnay/rust-toolchain@1.92.0 + uses: dtolnay/rust-toolchain@v1 with: + toolchain: 1.92.0 # run-e2e.sh builds a static gateway so the image can be alpine. targets: x86_64-unknown-linux-musl diff --git a/.github/workflows/gateway-proxy-tests.yml b/.github/workflows/gateway-proxy-tests.yml index 86413a4c1e..43569e41ee 100644 --- a/.github/workflows/gateway-proxy-tests.yml +++ b/.github/workflows/gateway-proxy-tests.yml @@ -71,10 +71,13 @@ jobs: timeout-minutes: 45 steps: - uses: actions/checkout@v5 + with: + persist-credentials: false - name: Install Rust - uses: dtolnay/rust-toolchain@1.92.0 + uses: dtolnay/rust-toolchain@v1 with: + toolchain: 1.92.0 # The container image is built around a static binary. targets: x86_64-unknown-linux-musl diff --git a/.github/workflows/gateway-release.yml b/.github/workflows/gateway-release.yml index b3017ded01..5a5ba067a6 100644 --- a/.github/workflows/gateway-release.yml +++ b/.github/workflows/gateway-release.yml @@ -43,11 +43,22 @@ jobs: echo "VERSION=$VERSION" >> "$GITHUB_ENV" echo "RELEASE_TAG=gateway-v$VERSION" >> "$GITHUB_ENV" + - name: Reclaim runner disk space + run: | + sudo rm -rf \ + /opt/ghc \ + /opt/hostedtoolcache/CodeQL \ + /usr/local/.ghcup \ + /usr/local/lib/android \ + /usr/share/dotnet + df -h / + # Manual runs rebuild an existing release tag, not the selected branch. - name: Checkout repository uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: ref: ${{ github.event_name == 'workflow_dispatch' && env.RELEASE_TAG || github.sha }} + persist-credentials: false - name: Log in to GitHub Container Registry uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3 @@ -98,7 +109,7 @@ jobs: "https://ghcr.io/v2/dstack-tee/dstack-gateway/manifests/$IMAGE_DIGEST" - name: Generate artifact attestation - uses: actions/attest-build-provenance@92c65d2898f1f53cfdc910b962cecff86e7f8fcc # v1 + uses: actions/attest-build-provenance@ef244123eb79f2f7a7e75d99086184180e6d0018 # v1 with: subject-name: "ghcr.io/dstack-tee/dstack-gateway" subject-digest: ${{ steps.build-and-push.outputs.digest }} diff --git a/.github/workflows/go-sdk-release.yml b/.github/workflows/go-sdk-release.yml new file mode 100644 index 0000000000..99b3bbfc01 --- /dev/null +++ b/.github/workflows/go-sdk-release.yml @@ -0,0 +1,217 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: Publish Go SDK +on: + push: + # sdk/go/v0.6.1 is special: it tags the package-less deprecation stub and + # must be pushed before the carved-out modules get theirs. + tags: ['sdk/go/dstack/v*', 'sdk/go/ratls/v*', 'sdk/go/v0.6.1'] + workflow_dispatch: + inputs: + module: + description: 'Module to (re)index on pkg.go.dev' + required: true + default: 'sdk/go/dstack' + type: choice + options: + - sdk/go + - sdk/go/dstack + - sdk/go/ratls + version: + description: 'Version, with the leading v (e.g. v0.6.1)' + required: true + +permissions: + contents: read + +jobs: + test: + # workflow_dispatch is only for re-indexing pkg.go.dev after a release, so + # it skips the gate. + if: github.event_name == 'push' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + + - name: Install Rust + uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # v1 + with: + toolchain: 1.92.0 + + # The simulator is built from the dstack workspace; without the cache + # this build is most of the job's wall time. + - name: Cache cargo + uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 + with: + workspaces: dstack + + - name: Install Go + uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5 + with: + # The `go` directive in the released sdk/go/dstack/go.mod. sdk/go/ratls + # and sdk/go/tappd ask for 1.24, so this one toolchain covers all + # three modules. + go-version: '1.25' + + - name: Go SDK tests against the simulator + run: | + set -Eeuo pipefail + source sdk/simulator/lifecycle.sh + trap 'simulator_print_logs' ERR + trap simulator_stop EXIT INT TERM + simulator_start + + unformatted=$(gofmt -l sdk/go) + if [ -n "$unformatted" ]; then + echo "::error::unformatted Go files: $unformatted" + exit 1 + fi + + # Each of the three directories under sdk/go is its own module + # (dstack, tappd, ratls), so they are vetted and tested separately. + pushd sdk/go/dstack + go vet ./... + go test -v . + popd + + pushd sdk/go/tappd + go vet ./... + go test -v . + popd + + pushd sdk/go/ratls + go vet ./... + # Compiling is as far as this goes: the test binary links against + # libdcap_qvl, which no CI job installs (run-tests.sh and the compat + # runner don't exercise ratls either). + go build ./... + popd + + release: + needs: test + # Without a status function the condition gets an implicit `success()`, + # which is false once `test` is skipped on workflow_dispatch. + if: ${{ !cancelled() && (github.event_name == 'workflow_dispatch' || needs.test.result == 'success') }} + runs-on: ubuntu-latest + permissions: + # The GitHub Release step creates the release. + contents: write + steps: + - name: Resolve module and version + id: meta + env: + MODULE_INPUT: ${{ github.event.inputs.module }} + VERSION_INPUT: ${{ github.event.inputs.version }} + run: | + if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then + module="$MODULE_INPUT" + version="$VERSION_INPUT" + else + tag="${GITHUB_REF_NAME}" + case "$tag" in + sdk/go/dstack/v*) module="sdk/go/dstack" ;; + sdk/go/ratls/v*) module="sdk/go/ratls" ;; + sdk/go/v0.6.1) module="sdk/go" ;; + *) + echo "::error::unexpected tag $tag, expected sdk/go/dstack/v*, sdk/go/ratls/v*, or sdk/go/v0.6.1" + exit 1 + ;; + esac + version="v${tag##*/v}" + # sdk/go/dstack requires the package-less sdk/go v0.6.1 to defuse + # ambiguous imports for importers pinned to sdk/go v0.6.0, so that + # tag must be indexed on the proxy first. ratls does not require + # the stub and is not gated on it. + if [ "$module" = "sdk/go/dstack" ] && ! curl -fsSL --retry 3 --retry-delay 5 --retry-all-errors \ + -o /dev/null "https://proxy.golang.org/github.com/!dstack-!t!e!e/dstack/sdk/go/@v/v0.6.1.mod"; then + echo "::error::sdk/go v0.6.1 is not on the module proxy; tag sdk/go/v0.6.1 first" + exit 1 + fi + fi + if ! [[ "$version" =~ ^v[0-9]+\.[0-9]+\.[0-9]+([-+][0-9A-Za-z.-]+)?$ ]]; then + echo "::error::invalid version $version" + exit 1 + fi + echo "module=$module" >> "$GITHUB_OUTPUT" + echo "version=$version" >> "$GITHUB_OUTPUT" + + - name: GitHub Release + if: github.event_name == 'push' + uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2 + with: + name: "Go SDK ${{ steps.meta.outputs.version }}" + body: | + ## Go module + + **Module**: `github.com/Dstack-TEE/dstack/${{ steps.meta.outputs.module }}` + **Version**: `${{ steps.meta.outputs.version }}` + + ```bash + go get github.com/Dstack-TEE/dstack/${{ steps.meta.outputs.module }}@${{ steps.meta.outputs.version }} + ``` + + **Docs**: https://pkg.go.dev/github.com/Dstack-TEE/dstack/${{ steps.meta.outputs.module }}@${{ steps.meta.outputs.version }} + + # pkg.go.dev and the module proxy both crawl on demand, and the crawl + # takes minutes after a tag push. A plain curl right after the release + # races the crawl and 404s. Pull the version through the proxy first + # (that request is what indexes the proxy), then poll pkg.go.dev until + # its own crawl finishes. + - name: Index the module on pkg.go.dev + run: | + module="${{ steps.meta.outputs.module }}" + module_path="github.com/Dstack-TEE/dstack/$module" + version="${{ steps.meta.outputs.version }}" + # Go module proxy escaping applies to both the path and the version: + # every uppercase letter becomes "!" + its lowercase form (BSD sed + # has no \L, so loop in bash). A raw uppercase prerelease like + # v0.6.1-RC1 is rejected by the proxy as an invalid escaped version. + escape() { + local s="$1" out="" c i + for ((i = 0; i < ${#s}; i++)); do + c="${s:i:1}" + if [[ "$c" =~ [A-Z] ]]; then + out+="!${c,,}" + else + out+="$c" + fi + done + echo "$out" + } + proxy_path=$(escape "$module_path") + proxy_version=$(escape "$version") + deadline=$((SECONDS + 240)) + until curl -fsSL --max-time 30 -o /dev/null "https://proxy.golang.org/${proxy_path}/@v/${proxy_version}.info"; do + if [ "$SECONDS" -ge "$deadline" ]; then + echo "::error::module proxy never served ${module_path}@${version}" + exit 1 + fi + sleep 10 + done + echo "proxy serves ${module_path}@${version}" + if [ "$module" = "sdk/go" ]; then + # The package-less deprecation stub is never indexed by + # pkg.go.dev (observed: 404 for 50+ minutes while the proxy + # serves it). It only needs the proxy, where `go get` resolves + # it for importers pinned to v0.6.0. + echo "sdk/go is a package-less stub; skipping pkg.go.dev" + exit 0 + fi + deadline=$((SECONDS + 480)) + until curl -fsSL --max-time 30 -o /dev/null "https://pkg.go.dev/${module_path}@${version}"; do + if [ "$SECONDS" -ge "$deadline" ]; then + echo "::error::pkg.go.dev never indexed ${module_path}@${version}" + exit 1 + fi + sleep 10 + done + echo "pkg.go.dev indexed ${module_path}@${version}" + # Best effort: the unversioned page can lag minutes behind the + # versioned one, and a transient error here says nothing about the + # indexing above. + curl -fsSL --max-time 30 -o /dev/null "https://pkg.go.dev/${module_path}" || \ + echo "::warning::unversioned pkg.go.dev page not refreshed yet" diff --git a/.github/workflows/guest-os.yml b/.github/workflows/guest-os.yml index 503159a7e1..09fdbe41e0 100644 --- a/.github/workflows/guest-os.yml +++ b/.github/workflows/guest-os.yml @@ -23,13 +23,15 @@ jobs: contents: read steps: - name: Checkout - uses: actions/checkout@v5 + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false - name: Build production guest OS (deprecated Yocto backend) run: make os-image-yocto - name: Upload artifacts - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: name: guest-images path: | @@ -47,12 +49,12 @@ jobs: contents: write steps: - name: Checkout default branch - uses: actions/checkout@v5 + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: ref: ${{ github.event.repository.default_branch }} - name: Download artifacts - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 with: name: guest-images path: os/yocto/repro-build/dist diff --git a/.github/workflows/halmos.yml b/.github/workflows/halmos.yml new file mode 100644 index 0000000000..5c839fc761 --- /dev/null +++ b/.github/workflows/halmos.yml @@ -0,0 +1,62 @@ +# SPDX-FileCopyrightText: © 2025 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: KMS Auth-ETH Halmos + +on: + push: + paths: + - 'dstack/kms/auth-eth/**' + - '.github/workflows/halmos.yml' + pull_request: + paths: + - 'dstack/kms/auth-eth/**' + - '.github/workflows/halmos.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + halmos: + name: ${{ matrix.contract }} + runs-on: ubuntu-latest + timeout-minutes: 40 + strategy: + fail-fast: false + matrix: + contract: + - DstackAppSymbolicTest + - DstackAppEpochSymbolicTest + - DstackKmsSymbolicTest + - DstackKmsEpochSymbolicTest + defaults: + run: + working-directory: dstack/kms/auth-eth + env: + # Halmos does not support the vm.deployCode that dynamic test linking emits. + FOUNDRY_DYNAMIC_TEST_LINKING: 'false' + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + + - name: Checkout contract dependencies + working-directory: . + run: | + git submodule update --init --recursive --depth 1 -- \ + dstack/kms/auth-eth/lib/forge-std \ + dstack/kms/auth-eth/lib/openzeppelin-contracts-upgradeable \ + dstack/kms/auth-eth/lib/openzeppelin-foundry-upgrades + + - name: Install Foundry + uses: foundry-rs/foundry-toolchain@v1 + with: + version: v1.8.4 + + - name: Install Halmos + run: pipx install halmos==0.3.3 + + - name: Run Halmos + run: halmos --contract ${{ matrix.contract }} diff --git a/.github/workflows/js-sdk-release.yml b/.github/workflows/js-sdk-release.yml index 97148f3905..ec4679ca08 100644 --- a/.github/workflows/js-sdk-release.yml +++ b/.github/workflows/js-sdk-release.yml @@ -26,16 +26,18 @@ jobs: publish: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false - - uses: actions/setup-node@v5 + - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5 with: node-version: '20' registry-url: 'https://registry.npmjs.org' - name: Upgrade npm for trusted publishers support run: | - npm install -g npm@latest + npm install -g npm@11.21.1 echo "npm: $(npm --version)" - name: Verify OIDC token availability @@ -63,13 +65,22 @@ jobs: fi echo "Repositories match" + # bun.lock is the only lockfile in sdk/js; installing from it keeps the + # dependency tree of this credentialed job fixed. `--ignore-scripts` + # because Bun otherwise runs install scripts for its default-trusted + # packages (bufferutil, utf-8-validate here), and the build needs none. + # npm is still used to publish, for trusted publishing. + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + bun-version: 1.4.4 + - name: Install dependencies working-directory: sdk/js - run: npm install + run: bun install --frozen-lockfile --ignore-scripts - name: Build working-directory: sdk/js - run: npm run build + run: bun run build - name: Determine version and npm dist-tag id: tag @@ -104,7 +115,7 @@ jobs: - name: GitHub Release if: github.event_name == 'push' - uses: softprops/action-gh-release@v2 + uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2 with: name: "JS SDK v${{ steps.tag.outputs.version }}" body: | diff --git a/.github/workflows/key-recovery-release.yml b/.github/workflows/key-recovery-release.yml new file mode 100644 index 0000000000..3974914bc9 --- /dev/null +++ b/.github/workflows/key-recovery-release.yml @@ -0,0 +1,106 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: Key Recovery Release + +on: + workflow_dispatch: + inputs: + version: + description: Existing release tag version without the key-recovery-v prefix + required: true + type: string + push: + tags: + - 'key-recovery-v*' + +permissions: + attestations: write + id-token: write + contents: write + packages: write + +jobs: + build-and-release: + runs-on: ubuntu-latest + steps: + - name: Parse and check version + env: + DISPATCH_VERSION: ${{ inputs.version }} + run: | + if [ "$GITHUB_EVENT_NAME" = workflow_dispatch ]; then + VERSION=$DISPATCH_VERSION + else + case "$GITHUB_REF" in + refs/tags/key-recovery-v*) VERSION=${GITHUB_REF#refs/tags/key-recovery-v} ;; + *) echo "Expected a key-recovery-v* tag" >&2; exit 1 ;; + esac + fi + if [[ ! "$VERSION" =~ ^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$ ]]; then + echo "Version must be a valid Docker tag" >&2 + exit 1 + fi + echo "VERSION=$VERSION" >> "$GITHUB_ENV" + echo "RELEASE_TAG=key-recovery-v$VERSION" >> "$GITHUB_ENV" + + - name: Checkout repository + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + ref: ${{ github.event_name == 'workflow_dispatch' && env.RELEASE_TAG || github.sha }} + persist-credentials: false + + - name: Log in to GitHub Container Registry + uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Resolve the revision to build + run: echo "GIT_REV=$(git rev-parse HEAD)" >> "$GITHUB_ENV" + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3 + + - name: Build and push + id: build + uses: docker/build-push-action@ca052bb54ab0790a636c9b5f226502c73d547a25 # v5 + with: + context: dstack/tools/key-recovery + file: dstack/tools/key-recovery/Dockerfile + push: true + provenance: true + sbom: true + build-args: | + DSTACK_REV=${{ env.GIT_REV }} + tags: | + ghcr.io/dstack-tee/dstack-key-recovery:${{ env.VERSION }} + ghcr.io/dstack-tee/dstack-key-recovery:latest + + - name: Generate artifact attestation + uses: actions/attest-build-provenance@ef244123eb79f2f7a7e75d99086184180e6d0018 # v1 + with: + subject-name: ghcr.io/dstack-tee/dstack-key-recovery + subject-digest: ${{ steps.build.outputs.digest }} + push-to-registry: true + + - name: GitHub Release + uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2 + with: + tag_name: ${{ env.RELEASE_TAG }} + name: "Key Recovery v${{ env.VERSION }}" + body: | + ## Docker Image + + **Image**: `ghcr.io/dstack-tee/dstack-key-recovery:${{ env.VERSION }}` + + **Digest (SHA256)**: `${{ steps.build.outputs.digest }}` + + **Verification**: [Verify on Sigstore](https://search.sigstore.dev/?hash=${{ steps.build.outputs.digest }}) + + Build from source: + + ```bash + docker build -f tools/key-recovery/Dockerfile -t dstack-key-recovery dstack + ``` diff --git a/.github/workflows/kms-auth-eth.yml b/.github/workflows/kms-auth-eth.yml new file mode 100644 index 0000000000..26aed2e9a3 --- /dev/null +++ b/.github/workflows/kms-auth-eth.yml @@ -0,0 +1,182 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: KMS auth-eth + +# The auth-eth webhook ships on its own cadence, separate from the KMS +# image: a `kms-auth-eth-v*` tag publishes +# ghcr.io/dstack-tee/dstack-kms-auth-eth:. Pull requests and +# pushes that touch the backend run the checks and build the image without +# pushing it. +on: + workflow_dispatch: + inputs: + version: + description: Existing release tag version without the kms-auth-eth-v prefix + required: true + type: string + push: + branches: [ next, 'release/**' ] + tags: + - 'kms-auth-eth-v*' + # Top-level files only: the server lives next to the Foundry project, whose + # contracts/, lib/, test/ and script/ are covered by foundry-test.yml. + paths: + - 'dstack/kms/auth-eth/*' + - '.github/workflows/kms-auth-eth.yml' + pull_request: + branches: [ next, 'release/**', 'feat/**' ] + paths: + - 'dstack/kms/auth-eth/*' + - '.github/workflows/kms-auth-eth.yml' + +permissions: + contents: read + +env: + IMAGE: ghcr.io/dstack-tee/dstack-kms-auth-eth + BACKEND_DIR: dstack/kms/auth-eth + +jobs: + check: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + ref: ${{ github.event_name == 'workflow_dispatch' && format('kms-auth-eth-v{0}', inputs.version) || github.sha }} + persist-credentials: false + + - name: Set up Bun + uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + # Keep in step with the base image in the Dockerfile. + bun-version: 1.4.4 + # A release build must not restore a cache an untrusted run wrote. + no-cache: true + + - name: Install dependencies + working-directory: ${{ env.BACKEND_DIR }} + run: bun install --frozen-lockfile + + - name: Audit dependencies + working-directory: ${{ env.BACKEND_DIR }} + run: bun audit --audit-level=moderate + + - name: Lint + working-directory: ${{ env.BACKEND_DIR }} + run: bun run lint + + - name: Test + working-directory: ${{ env.BACKEND_DIR }} + run: bun run test:run + + image: + needs: check + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + attestations: write + id-token: write + steps: + - name: Decide whether to publish + env: + DISPATCH_VERSION: ${{ inputs.version }} + run: | + VERSION= + if [ "$GITHUB_EVENT_NAME" = workflow_dispatch ]; then + VERSION=$DISPATCH_VERSION + else + case "$GITHUB_REF" in + refs/tags/kms-auth-eth-v*) VERSION=${GITHUB_REF#refs/tags/kms-auth-eth-v} ;; + esac + fi + if [ -n "$VERSION" ]; then + if [[ ! "$VERSION" =~ ^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$ ]]; then + echo "version must be a valid Docker tag" >&2 + exit 1 + fi + echo "PUBLISH=1" >> "$GITHUB_ENV" + echo "IMAGE_REF=$IMAGE:$VERSION" >> "$GITHUB_ENV" + else + echo "PUBLISH=" >> "$GITHUB_ENV" + echo "IMAGE_REF=$IMAGE:check" >> "$GITHUB_ENV" + fi + + # Manual runs rebuild an existing release tag, not the selected branch. + - name: Checkout repository + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + ref: ${{ github.event_name == 'workflow_dispatch' && format('kms-auth-eth-v{0}', inputs.version) || github.sha }} + persist-credentials: false + + - name: Resolve the revision to build + run: | + echo "GIT_REV=$(git rev-parse HEAD)" >> "$GITHUB_ENV" + echo "SOURCE_DATE_EPOCH=$(git show -s --format=%ct HEAD)" >> "$GITHUB_ENV" + + - name: Log in to GitHub Container Registry + if: env.PUBLISH == '1' + uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3 + with: + driver-opts: image=moby/buildkit:v0.20.2@sha256:c457984bd29f04d6acc90c8d9e717afe3922ae14665f3187e0096976fe37b1c8 + + - name: Build and push Docker image + id: build + uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6 + with: + context: ${{ env.BACKEND_DIR }} + platforms: linux/amd64 + outputs: type=image,push=${{ env.PUBLISH == '1' }},oci-mediatypes=true,rewrite-timestamp=true + provenance: false + tags: ${{ env.IMAGE_REF }} + build-args: | + GIT_REV=${{ env.GIT_REV }} + SOURCE_DATE_EPOCH=${{ env.SOURCE_DATE_EPOCH }} + labels: | + org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }} + org.opencontainers.image.revision=${{ env.GIT_REV }} + org.opencontainers.image.description=dstack KMS auth webhook backed by the DstackKms contract + + - name: Verify anonymous pull access + if: env.PUBLISH == '1' + env: + IMAGE_DIGEST: ${{ steps.build.outputs.digest }} + run: | + token=$(curl -fsSL \ + "https://ghcr.io/token?scope=repository:dstack-tee/dstack-kms-auth-eth:pull" \ + | jq -er .token) + curl -fsSL -o /dev/null \ + -H "Authorization: Bearer $token" \ + -H "Accept: application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json" \ + "https://ghcr.io/v2/dstack-tee/dstack-kms-auth-eth/manifests/$IMAGE_DIGEST" + + - name: Generate artifact attestation + if: env.PUBLISH == '1' + uses: actions/attest-build-provenance@ef244123eb79f2f7a7e75d99086184180e6d0018 # v1 + with: + subject-name: ${{ env.IMAGE }} + subject-digest: ${{ steps.build.outputs.digest }} + push-to-registry: true + + - name: Summarize + if: env.PUBLISH == '1' + env: + IMAGE_DIGEST: ${{ steps.build.outputs.digest }} + run: | + { + echo "**Image**: \`$IMAGE_REF\`" + echo + echo "**Pinned**: \`$IMAGE@$IMAGE_DIGEST\`" + echo + echo "**Revision**: \`$GIT_REV\`" + } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/kms-release.yml b/.github/workflows/kms-release.yml index eedb5d66a0..b1ad81a439 100644 --- a/.github/workflows/kms-release.yml +++ b/.github/workflows/kms-release.yml @@ -43,11 +43,22 @@ jobs: echo "VERSION=$VERSION" >> "$GITHUB_ENV" echo "RELEASE_TAG=kms-v$VERSION" >> "$GITHUB_ENV" + - name: Reclaim runner disk space + run: | + sudo rm -rf \ + /opt/ghc \ + /opt/hostedtoolcache/CodeQL \ + /usr/local/.ghcup \ + /usr/local/lib/android \ + /usr/share/dotnet + df -h / + # Manual runs rebuild an existing release tag, not the selected branch. - name: Checkout repository uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: ref: ${{ github.event_name == 'workflow_dispatch' && env.RELEASE_TAG || github.sha }} + persist-credentials: false - name: Checkout contract dependencies run: | @@ -105,7 +116,7 @@ jobs: "https://ghcr.io/v2/dstack-tee/dstack-kms/manifests/$IMAGE_DIGEST" - name: Generate artifact attestation - uses: actions/attest-build-provenance@92c65d2898f1f53cfdc910b962cecff86e7f8fcc # v1 + uses: actions/attest-build-provenance@ef244123eb79f2f7a7e75d99086184180e6d0018 # v1 with: subject-name: "ghcr.io/dstack-tee/dstack-kms" subject-digest: ${{ steps.build-and-push.outputs.digest }} diff --git a/.github/workflows/lean.yml b/.github/workflows/lean.yml new file mode 100644 index 0000000000..ea25f71e7f --- /dev/null +++ b/.github/workflows/lean.yml @@ -0,0 +1,31 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: Lean proofs + +on: + push: + branches: [ next, 'release/**' ] + paths: [ 'formal/**', '.github/workflows/lean.yml' ] + pull_request: + branches: [ next, 'release/**', 'feat/**' ] + paths: [ 'formal/**', '.github/workflows/lean.yml' ] + +permissions: + contents: read + +jobs: + build: + runs-on: ${{ vars.CI_RUNNER || 'ubuntu-latest' }} + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + + - name: Reject axioms and unchecked code + run: "! grep -rnE '^\\s*(axiom|unsafe|@\\[implemented_by|@\\[extern)|native_decide' --include='*.lean' formal" + + - uses: leanprover/lean-action@v1 + with: + lake-package-directory: formal diff --git a/.github/workflows/local-key-provider-release.yml b/.github/workflows/local-key-provider-release.yml index 49d39d4103..8372b9acd6 100644 --- a/.github/workflows/local-key-provider-release.yml +++ b/.github/workflows/local-key-provider-release.yml @@ -49,6 +49,7 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: ${{ github.event_name == 'workflow_dispatch' && env.RELEASE_TAG || github.sha }} + persist-credentials: false - name: Log in to GitHub Container Registry uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4 @@ -91,7 +92,7 @@ jobs: "https://ghcr.io/v2/dstack-tee/local-key-provider/manifests/$IMAGE_DIGEST" - name: Generate artifact attestation - uses: actions/attest-build-provenance@8beda2b7ed98355c0e97c0a63bec38ae472e66c4 # v4 + uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4 with: subject-name: "ghcr.io/dstack-tee/local-key-provider" subject-digest: ${{ steps.build-and-push.outputs.digest }} @@ -116,7 +117,7 @@ jobs: echo "MRSIGNER=$MRSIGNER" >> "$GITHUB_ENV" - name: GitHub Release - uses: softprops/action-gh-release@5113cdc90fd4d541c801c55356214017bf5ae34b # v3 + uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3 with: name: "Local Key Provider Release v${{ env.VERSION }}" tag_name: ${{ env.RELEASE_TAG }} diff --git a/.github/workflows/mkosi-build.yml b/.github/workflows/mkosi-build.yml index 2f4f273fc1..5c23ea147d 100644 --- a/.github/workflows/mkosi-build.yml +++ b/.github/workflows/mkosi-build.yml @@ -42,6 +42,8 @@ jobs: contents: read steps: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false # Runs in seconds and covers the whole os/mkosi static contract, so it # gates every change rather than waiting for a manual dispatch. - name: Check the static contract @@ -64,6 +66,9 @@ jobs: bare_sha256: ${{ steps.hashes.outputs.bare_sha256 }} uki_sha256: ${{ steps.hashes.outputs.uki_sha256 }} kernel_devel_sha256: ${{ steps.hashes.outputs.kernel_devel_sha256 }} + mrtd: ${{ steps.hashes.outputs.mrtd }} + uki_auth: ${{ steps.hashes.outputs.uki_auth }} + aws_pcr: ${{ steps.hashes.outputs.aws_pcr }} steps: # GitHub-hosted runners have enough CPU and memory for this build, but @@ -88,6 +93,7 @@ jobs: uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: fetch-depth: 0 + persist-credentials: false - name: Set up Python for mkosi uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 @@ -222,6 +228,9 @@ jobs: echo "bare_sha256=$bare_sha256" echo "uki_sha256=$uki_sha256" echo "kernel_devel_sha256=$kernel_devel_sha256" + echo "mrtd=$mrtd" + echo "uki_auth=$uki_auth" + echo "aws_pcr=$aws_pcr" } >> "$GITHUB_OUTPUT" # os_image_hash is the value operators need most, so surface it in the @@ -258,24 +267,11 @@ jobs: echo '' } >> "$GITHUB_STEP_SUMMARY" - { - echo "os_image_hash $os_image_hash" - echo "git_revision $git_revision" - echo "tdx_mrtd $mrtd" - echo "gcp_uki_auth $uki_auth" - echo "aws_boot_pcr $aws_pcr" - echo "$bare_sha256 dstack-$version.tar.gz" - echo "$uki_sha256 dstack-$version-uki.tar.gz" - echo "$kernel_devel_sha256 dstack-$version-kernel-devel.tar.gz" - } | tee "$DIST_DIR/image-hashes.txt" - - name: Upload guest images uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: name: mkosi-guest-images - path: | - ${{ steps.build.outputs.dist_dir }}/dstack-*.tar.gz - ${{ steps.build.outputs.dist_dir }}/image-hashes.txt + path: ${{ steps.build.outputs.dist_dir }}/dstack-*.tar.gz retention-days: 30 if-no-files-found: error @@ -294,6 +290,8 @@ jobs: steps: - name: Checkout uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false - name: Download guest images uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 @@ -336,6 +334,8 @@ jobs: steps: - name: Checkout uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false - name: Download guest images uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 @@ -388,6 +388,9 @@ jobs: BARE_SHA256: ${{ needs.build.outputs.bare_sha256 }} UKI_SHA256: ${{ needs.build.outputs.uki_sha256 }} KERNEL_DEVEL_SHA256: ${{ needs.build.outputs.kernel_devel_sha256 }} + MRTD: ${{ needs.build.outputs.mrtd }} + UKI_AUTH: ${{ needs.build.outputs.uki_auth }} + AWS_PCR: ${{ needs.build.outputs.aws_pcr }} run: | set -euo pipefail { @@ -400,13 +403,13 @@ jobs: echo '| --- | --- |' echo "| \`os_image_hash\` | \`$OS_IMAGE_HASH\` |" echo "| Git revision | \`$GITHUB_SHA\` |" + echo "| TDX \`MRTD\` | \`$MRTD\` |" + echo "| GCP \`uki_auth\` | \`$UKI_AUTH\` |" + echo "| AWS \`boot_pcr_digest\` | \`$AWS_PCR\` |" echo "| \`dstack-$VERSION.tar.gz\` | \`$BARE_SHA256\` |" echo "| \`dstack-$VERSION-uki.tar.gz\` | \`$UKI_SHA256\` |" echo "| \`dstack-$VERSION-kernel-devel.tar.gz\` | \`$KERNEL_DEVEL_SHA256\` |" echo - echo "\`image-hashes.txt\` additionally records the TDX \`MRTD\`, the GCP" - echo "\`uki_auth\` hash and the AWS \`boot_pcr_digest\` for this image." - echo echo "To build out-of-tree kernel modules, use" echo "\`ghcr.io/dstack-tee/dstack-kernel-builder:$VERSION\`; see" echo "[docs/building-guest-os.md](https://github.com/${GITHUB_REPOSITORY}/blob/${TAG}/docs/building-guest-os.md#kernel-headers-for-out-of-tree-modules)." @@ -426,7 +429,6 @@ jobs: "dist/dstack-$VERSION.tar.gz" \ "dist/dstack-$VERSION-uki.tar.gz" \ "dist/dstack-$VERSION-kernel-devel.tar.gz" \ - dist/image-hashes.txt \ --title "dstack OS v$VERSION" \ --notes-file release-notes.md \ --verify-tag \ diff --git a/.github/workflows/plumber-check.yml b/.github/workflows/plumber-check.yml new file mode 100644 index 0000000000..fdb972a012 --- /dev/null +++ b/.github/workflows/plumber-check.yml @@ -0,0 +1,55 @@ +# SPDX-FileCopyrightText: © 2026 Thibaud Van den Berghe +# +# SPDX-License-Identifier: Apache-2.0 + +name: Plumber check + +# Checks the workflows themselves: token scopes, checkouts that keep the +# token, action references and the lockfile. Not a required status check, so +# a workflow-level filter is safe here: what it reads cannot change unless +# something under `.github/` or the Plumber configuration does. +on: + push: + branches: [ next ] + paths: + - '.github/**' + - '.plumber.yaml' + pull_request: + branches: [ next ] + paths: + - '.github/**' + - '.plumber.yaml' + +permissions: + contents: read + +jobs: + plumber: + runs-on: ubuntu-latest + permissions: + contents: read + # Workflow states and one run log, to prove each job's token scope. + actions: read + # Lists the findings under code scanning. + security-events: write + # Needed by score-push, no secret or token to store. + id-token: write + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + + - name: Run Plumber + uses: getplumber/plumber@v0.7.23 + with: + # Pull requests from forks get a read-only token, so the code + # scanning upload is skipped there. The report stays a workflow + # artifact. + upload-sarif: ${{ github.event.pull_request.head.repo.fork != true }} + # Fail under 85 points. The default gate is 100, where any finding + # fails. + min-points: 85 + # Publish the score and the repository name on score.getplumber.io, + # where the README badge reads them. Only pushes to next publish, a + # pull request never does. + score-push: ${{ github.event_name == 'push' }} diff --git a/.github/workflows/prek-check.yml b/.github/workflows/prek-check.yml index 267f21c55b..6f42422305 100644 --- a/.github/workflows/prek-check.yml +++ b/.github/workflows/prek-check.yml @@ -8,7 +8,7 @@ on: push: branches: [ next, 'release/**' ] pull_request: - branches: [ next, 'release/**' ] + branches: [ next, 'release/**', 'feat/**' ] permissions: contents: read @@ -23,9 +23,10 @@ jobs: - uses: actions/checkout@v5 with: fetch-depth: 0 + persist-credentials: false - name: Install Rust - uses: dtolnay/rust-toolchain@master + uses: dtolnay/rust-toolchain@v1 with: toolchain: 1.92.0 components: rustfmt diff --git a/.github/workflows/python-sdk-release.yml b/.github/workflows/python-sdk-release.yml index 3aec79f1de..5fc1e19f00 100644 --- a/.github/workflows/python-sdk-release.yml +++ b/.github/workflows/python-sdk-release.yml @@ -25,18 +25,25 @@ jobs: publish: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false - - uses: actions/setup-python@v5 + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 with: python-version: '3.11' - - name: Install PDM - run: pip install pdm + # Build with the pinned, hash-checked backend alone: pdm-backend has no + # dependencies on Python >= 3.10, so nothing else is resolved in this + # credentialed job. + - name: Install build backend + run: | + echo 'pdm-backend==2.5.0 --hash=sha256:5b8746b567a16a1fd506ce66ee28e89d46374526f52238aa1b96cc2c08245c63' > "$RUNNER_TEMP/build-requirements.txt" + pip install --require-hashes --no-deps -r "$RUNNER_TEMP/build-requirements.txt" - name: Build distribution working-directory: sdk/python - run: pdm build + run: python -c "from pdm.backend import build_sdist, build_wheel; build_sdist('dist'); build_wheel('dist')" - name: Parse and verify version id: version @@ -66,20 +73,20 @@ jobs: - name: Publish to PyPI if: github.event_name == 'push' || github.event.inputs.target == 'pypi' - uses: pypa/gh-action-pypi-publish@release/v1 + uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 with: packages-dir: sdk/python/dist - name: Publish to TestPyPI if: github.event_name == 'workflow_dispatch' && github.event.inputs.target == 'testpypi' - uses: pypa/gh-action-pypi-publish@release/v1 + uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 with: repository-url: https://test.pypi.org/legacy/ packages-dir: sdk/python/dist - name: GitHub Release if: github.event_name == 'push' - uses: softprops/action-gh-release@v2 + uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2 with: name: "Python SDK v${{ steps.version.outputs.version }}" body: | diff --git a/.github/workflows/qemu-acpi-differential.yml b/.github/workflows/qemu-acpi-differential.yml index de8dea2221..5dae1c9631 100644 --- a/.github/workflows/qemu-acpi-differential.yml +++ b/.github/workflows/qemu-acpi-differential.yml @@ -35,9 +35,13 @@ jobs: REFERENCE_IMAGE: kvin/dstack-acpi-tables@sha256:54e692d8c68c6f02dd7c655bf6de6e7f3ad7a43fded6ca00d8e998918108a3b4 steps: - uses: actions/checkout@v5 + with: + persist-credentials: false - name: Install Rust - uses: dtolnay/rust-toolchain@1.92.0 + uses: dtolnay/rust-toolchain@v1 + with: + toolchain: 1.92.0 - name: Build Rust ACPI generator run: cargo build -p qemu-acpi --example dump diff --git a/.github/workflows/rust-sdk-release.yml b/.github/workflows/rust-sdk-release.yml index 207c2bee9c..96127c21b5 100644 --- a/.github/workflows/rust-sdk-release.yml +++ b/.github/workflows/rust-sdk-release.yml @@ -16,7 +16,9 @@ jobs: id-token: write contents: write steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false - name: Extract version from tag id: ver @@ -69,7 +71,7 @@ jobs: sys.exit(1) PY - - uses: rust-lang/crates-io-auth-action@v1 + - uses: rust-lang/crates-io-auth-action@3268eb413133e2960fa4ae0e963ca76380c54cd9 # v1.0.6 id: auth - name: Publish dstack-sdk-types diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 0cb18deec0..d3e490306c 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -8,7 +8,10 @@ on: push: branches: [ next, 'release/**' ] pull_request: - branches: [ next, 'release/**' ] + branches: [ next, 'release/**', 'feat/**' ] + +permissions: + contents: read env: CARGO_TERM_COLOR: always @@ -24,6 +27,7 @@ jobs: with: # The change detection below diffs against the base commit. fetch-depth: 0 + persist-credentials: false # Which files changed, decided here rather than with a workflow-level # `paths:` filter. @@ -53,8 +57,9 @@ jobs: fi - name: Install Rust - uses: dtolnay/rust-toolchain@1.92.0 + uses: dtolnay/rust-toolchain@v1 with: + toolchain: 1.92.0 components: clippy, rustfmt # The largest job in the repository was compiling the workspace from nothing @@ -78,6 +83,12 @@ jobs: if: steps.changes.outputs.relevant == 'true' run: cargo fmt --check --all + # The LUKS tests in dstack-util skip and pass when cryptsetup is missing. + # Fail here instead, so a runner without it cannot hide them. + - name: Require cryptsetup + if: steps.changes.outputs.relevant == 'true' + run: cryptsetup --version + - name: Run tests if: steps.changes.outputs.relevant == 'true' run: ./run-tests.sh diff --git a/.github/workflows/sdk-compat.yaml b/.github/workflows/sdk-compat.yaml index 2fdc127a6c..3dfa22ab30 100644 --- a/.github/workflows/sdk-compat.yaml +++ b/.github/workflows/sdk-compat.yaml @@ -60,9 +60,13 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 + with: + persist-credentials: false - name: Install Rust - uses: dtolnay/rust-toolchain@1.92.0 + uses: dtolnay/rust-toolchain@v1 + with: + toolchain: 1.92.0 - name: Cache cargo uses: Swatinem/rust-cache@v2 @@ -108,9 +112,12 @@ jobs: # objects behind them, so take the whole history: the clone is a # rounding error next to the Rust build in this job. fetch-depth: 0 + persist-credentials: false - name: Install Rust - uses: dtolnay/rust-toolchain@1.92.0 + uses: dtolnay/rust-toolchain@v1 + with: + toolchain: 1.92.0 # Restore only. The `simulator` job above populated this key; a leg that # saved as well would race its twin for the same entry and gain nothing, diff --git a/.github/workflows/sdk.yaml b/.github/workflows/sdk.yaml index 550806ff97..a101b5a135 100644 --- a/.github/workflows/sdk.yaml +++ b/.github/workflows/sdk.yaml @@ -11,7 +11,7 @@ on: push: branches: [next, 'release/**'] pull_request: - branches: [next, 'release/**'] + branches: [next, 'release/**', 'feat/**'] env: CARGO_TERM_COLOR: always @@ -24,6 +24,7 @@ jobs: with: # The change detection below diffs against the base commit. fetch-depth: 0 + persist-credentials: false # Which files changed, decided here rather than with a workflow-level # `paths:` filter. @@ -61,8 +62,9 @@ jobs: fi - name: Install Rust - uses: dtolnay/rust-toolchain@1.92.0 + uses: dtolnay/rust-toolchain@v1 with: + toolchain: 1.92.0 components: clippy, rustfmt # This additional target is needed for wasm32 compatibility check. targets: wasm32-unknown-unknown, thumbv6m-none-eabi @@ -84,6 +86,14 @@ jobs: # the entries that are actually shared. save-if: ${{ github.event_name == 'push' }} + # Pin the interpreter: the runner image's system Python can be newer than + # the PyO3 versions in the Python SDK's locked dependencies support. + - name: Install Python + if: steps.changes.outputs.relevant == 'true' + uses: actions/setup-python@v5 + with: + python-version: '3.13' + - name: SDK tests if: steps.changes.outputs.relevant == 'true' run: cd sdk && ./run-tests.sh diff --git a/.github/workflows/simulator-release.yml b/.github/workflows/simulator-release.yml index 01ab59d2a8..2acf998816 100644 --- a/.github/workflows/simulator-release.yml +++ b/.github/workflows/simulator-release.yml @@ -26,6 +26,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false - name: Resolve version and tag run: | @@ -46,8 +48,9 @@ jobs: sudo apt-get install -y musl-tools - name: Set up Rust toolchain - uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable + uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # v1 with: + toolchain: stable targets: ${{ env.TARGET_TRIPLE }} - name: Cache Rust build artifacts diff --git a/.github/workflows/spdx-check.yml b/.github/workflows/spdx-check.yml index dc24dfd081..19f4366cda 100644 --- a/.github/workflows/spdx-check.yml +++ b/.github/workflows/spdx-check.yml @@ -8,7 +8,10 @@ on: push: branches: [ next, 'release/**' ] pull_request: - branches: [ next, 'release/**' ] + branches: [ next, 'release/**', 'feat/**' ] + +permissions: + contents: read jobs: reuse-lint: @@ -17,6 +20,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@v5 + with: + persist-credentials: false - name: REUSE Compliance Check uses: fsfe/reuse-action@v5 diff --git a/.github/workflows/verifier-release.yml b/.github/workflows/verifier-release.yml index f3ca48f792..e9d65289c0 100644 --- a/.github/workflows/verifier-release.yml +++ b/.github/workflows/verifier-release.yml @@ -43,11 +43,22 @@ jobs: echo "VERSION=$VERSION" >> "$GITHUB_ENV" echo "RELEASE_TAG=verifier-v$VERSION" >> "$GITHUB_ENV" + - name: Reclaim runner disk space + run: | + sudo rm -rf \ + /opt/ghc \ + /opt/hostedtoolcache/CodeQL \ + /usr/local/.ghcup \ + /usr/local/lib/android \ + /usr/share/dotnet + df -h / + # Manual runs rebuild an existing release tag, not the selected branch. - name: Checkout repository uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: ref: ${{ github.event_name == 'workflow_dispatch' && env.RELEASE_TAG || github.sha }} + persist-credentials: false - name: Log in to GitHub Container Registry uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3 @@ -100,7 +111,7 @@ jobs: "https://ghcr.io/v2/dstack-tee/dstack-verifier/manifests/$IMAGE_DIGEST" - name: Generate artifact attestation - uses: actions/attest-build-provenance@92c65d2898f1f53cfdc910b962cecff86e7f8fcc # v1 + uses: actions/attest-build-provenance@ef244123eb79f2f7a7e75d99086184180e6d0018 # v1 with: subject-name: "ghcr.io/dstack-tee/dstack-verifier" subject-digest: ${{ steps.build-and-push.outputs.digest }} diff --git a/.github/workflows/verifier-wasm-release.yml b/.github/workflows/verifier-wasm-release.yml new file mode 100644 index 0000000000..fda7ee473e --- /dev/null +++ b/.github/workflows/verifier-wasm-release.yml @@ -0,0 +1,130 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: Publish TDX lite verifier wasm to npm +on: + push: + tags: ['verifier-wasm-v*'] + workflow_dispatch: + inputs: + npm_tag: + description: 'npm dist-tag (beta, latest)' + required: true + default: 'beta' + type: choice + options: + - beta + - latest + +permissions: + id-token: write + contents: write + +jobs: + publish: + runs-on: ubuntu-latest + defaults: + run: + working-directory: sdk/verifier-wasm + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + + - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5 + with: + node-version: '22' + registry-url: 'https://registry.npmjs.org' + + - name: Upgrade npm for trusted publishers support + run: | + npm install -g npm@11.21.1 + echo "npm: $(npm --version)" + + - name: Verify OIDC token availability + run: | + if [ -n "${ACTIONS_ID_TOKEN_REQUEST_URL}" ] && [ -n "${ACTIONS_ID_TOKEN_REQUEST_TOKEN}" ]; then + echo "OIDC token available" + else + echo "OIDC token NOT available" + echo "Check workflow permissions include 'id-token: write'" + exit 1 + fi + + - name: Verify repository configuration + run: | + echo "Checking repository consistency..." + GIT_REPO=$(git remote get-url origin | sed 's/.*github.com[/:]//; s/.git$//') + PKG_REPO=$(node -e "console.log(require('./package.json').repository?.url || '')" | sed 's|https://github.com/||; s|git+||; s|.git$||') + echo "Git remote: $GIT_REPO" + echo "package.json: $PKG_REPO" + if [ "$GIT_REPO" != "$PKG_REPO" ]; then + echo "Repository mismatch!" + echo "This will cause 422 error during publish" + exit 1 + fi + echo "Repositories match" + + - name: Build wasm package + working-directory: . + env: + REPRO_CHECK: '1' + run: bash sdk/verifier-wasm/scripts/build-in-container.sh + + - name: Run Node tests + run: npm test + + - name: Determine version and npm dist-tag + id: tag + run: | + PKG_VERSION=$(node -e "console.log(require('./package.json').version)") + PRERELEASE=false + if echo "$PKG_VERSION" | grep -qiE '(beta|alpha|rc|preview)'; then + PRERELEASE=true + fi + + if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then + VERSION="$PKG_VERSION" + REQUESTED="${{ github.event.inputs.npm_tag }}" + if [ "$PRERELEASE" = true ] && [ "$REQUESTED" = "latest" ]; then + echo "::error::prerelease $PKG_VERSION cannot be published with dist-tag latest" + exit 1 + fi + echo "tag=$REQUESTED" >> "$GITHUB_OUTPUT" + else + TAG_VERSION="${GITHUB_REF_NAME#verifier-wasm-v}" + if [ "$TAG_VERSION" != "$PKG_VERSION" ]; then + echo "::error::tag version ($TAG_VERSION) does not match package.json version ($PKG_VERSION)" + exit 1 + fi + VERSION="$TAG_VERSION" + if [ "$PRERELEASE" = true ]; then + echo "tag=beta" >> "$GITHUB_OUTPUT" + else + echo "tag=latest" >> "$GITHUB_OUTPUT" + fi + fi + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + + - name: Publish to npm + run: | + NPM_TAG="${{ steps.tag.outputs.tag }}" + echo "Publishing with dist-tag: $NPM_TAG" + npm publish --access public --provenance --tag "$NPM_TAG" + + - name: GitHub Release + if: github.event_name == 'push' + uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2 + with: + name: "verifier-wasm v${{ steps.tag.outputs.version }}" + body: | + ## npm Package + + **Package**: `@phala/dstack-verifier-wasm@${{ steps.tag.outputs.version }}` + + **Install**: `npm install @phala/dstack-verifier-wasm@${{ steps.tag.outputs.version }}` + + **Dist-tag**: `${{ steps.tag.outputs.tag }}` + + **Registry**: https://www.npmjs.com/package/@phala/dstack-verifier-wasm/v/${{ steps.tag.outputs.version }} diff --git a/.github/workflows/verifier-wasm.yml b/.github/workflows/verifier-wasm.yml new file mode 100644 index 0000000000..4060ab2a9b --- /dev/null +++ b/.github/workflows/verifier-wasm.yml @@ -0,0 +1,206 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: TDX lite verifier wasm + +on: + push: + branches: [ next, 'release/**' ] + tags: ['verifier-wasm-v*'] + pull_request: + types: [opened, synchronize, reopened, labeled, unlabeled] + branches: [ next, 'release/**' ] + workflow_dispatch: + inputs: + runtimes: + description: Run Electron and browser jobs + type: boolean + default: true + +permissions: + contents: read + +jobs: + changes: + runs-on: ubuntu-latest + outputs: + relevant: ${{ steps.changes.outputs.relevant }} + runtimes: ${{ steps.changes.outputs.runtimes }} + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Detect relevant changes + id: changes + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + BEFORE_SHA: ${{ github.event.before }} + EVENT_NAME: ${{ github.event_name }} + REF: ${{ github.ref }} + HAS_LABEL: ${{ contains(github.event.pull_request.labels.*.name, 'verifier-wasm-runtimes') }} + DISPATCH_RUNTIMES: ${{ github.event_name == 'workflow_dispatch' && inputs.runtimes }} + run: | + relevant=false + if [ "$EVENT_NAME" = "workflow_dispatch" ] || [[ "$REF" == refs/tags/* ]]; then + relevant=true + echo "dispatch or tag: running" + else + if [ -n "$BASE_SHA" ]; then + changed=$(git diff --name-only "$BASE_SHA...HEAD") + elif [ -n "$BEFORE_SHA" ] && [ "$BEFORE_SHA" != "0000000000000000000000000000000000000000" ]; then + changed=$(git diff --name-only "$BEFORE_SHA...HEAD") + else + changed=$(git diff --name-only HEAD~1...HEAD) + fi + echo "$changed" + # Keep in sync with the workspace crates dstack-verifier-wasm depends on + # (`cargo metadata --filter-platform wasm32-unknown-unknown`). + if echo "$changed" | grep -qE '^(sdk/verifier-wasm/|dstack/crates/dstack-verifier-wasm/|dstack/dstack-mr/|dstack/crates/qemu-acpi/|dstack/dstack-types/|dstack/cc-eventlog/|dstack/size-parser/|dstack/verifier/fixtures/|dstack/Cargo\.(toml|lock)|\.github/workflows/verifier-wasm\.yml)'; then + relevant=true + else + echo "nothing this job covers changed" + fi + fi + + runtimes=false + if [ "$relevant" = true ]; then + if [ "$DISPATCH_RUNTIMES" = "true" ]; then + runtimes=true + elif [ "$EVENT_NAME" = "push" ] && { [ "$REF" = "refs/heads/next" ] || [[ "$REF" == refs/tags/* ]]; }; then + runtimes=true + elif [ "$HAS_LABEL" = "true" ]; then + runtimes=true + fi + fi + + echo "relevant=$relevant" >> "$GITHUB_OUTPUT" + echo "runtimes=$runtimes" >> "$GITHUB_OUTPUT" + echo "relevant=$relevant runtimes=$runtimes" + + build: + needs: changes + if: needs.changes.outputs.relevant == 'true' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + + - name: Build wasm in pinned container + env: + # The release workflow always checks reproducibility; PRs build once. + REPRO_CHECK: ${{ github.event_name == 'pull_request' && '0' || '1' }} + run: bash sdk/verifier-wasm/scripts/build-in-container.sh + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: verifier-wasm-bytes + path: sdk/verifier-wasm/src/wasm-bytes.js + if-no-files-found: error + + node: + needs: [changes, build] + if: needs.changes.outputs.relevant == 'true' + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node: ['20.19.0', '22', '24'] + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: verifier-wasm-bytes + path: sdk/verifier-wasm/src + - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5 + with: + node-version: ${{ matrix.node }} + - name: Run cases + working-directory: sdk/verifier-wasm + run: npm test + + bun: + needs: [changes, build] + if: needs.changes.outputs.relevant == 'true' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: verifier-wasm-bytes + path: sdk/verifier-wasm/src + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + bun-version: latest + - name: Run cases + working-directory: sdk/verifier-wasm + run: bun test/run-cases.mjs + + electron: + needs: [changes, build] + if: needs.changes.outputs.relevant == 'true' && needs.changes.outputs.runtimes == 'true' + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + electron: ['31', 'latest'] + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: verifier-wasm-bytes + path: sdk/verifier-wasm/src + - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5 + with: + node-version: '22' + - name: Install Electron + run: | + mkdir -p "$RUNNER_TEMP/electron" + cd "$RUNNER_TEMP/electron" + npm init -y >/dev/null + npm install "electron@${{ matrix.electron }}" + echo "ELECTRON_BIN=$RUNNER_TEMP/electron/node_modules/.bin/electron" >> "$GITHUB_ENV" + ELECTRON_RUN_AS_NODE=1 "$RUNNER_TEMP/electron/node_modules/.bin/electron" -e 'console.log(process.versions.electron)' + - name: Run cases as Node + working-directory: sdk/verifier-wasm + run: ELECTRON_RUN_AS_NODE=1 "$ELECTRON_BIN" test/run-cases.mjs + - name: Install xvfb + run: sudo apt-get update && sudo apt-get install -y xvfb + - name: Run cases in Electron main + working-directory: sdk/verifier-wasm + run: xvfb-run -a "$ELECTRON_BIN" --no-sandbox test/electron-main.mjs + + browser: + needs: [changes, build] + if: needs.changes.outputs.relevant == 'true' && needs.changes.outputs.runtimes == 'true' + runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + browser: [chromium, firefox, webkit] + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: verifier-wasm-bytes + path: sdk/verifier-wasm/src + - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5 + with: + node-version: '20' + - name: Install Playwright and run cases + working-directory: sdk/verifier-wasm + run: | + npm install --no-save --no-package-lock playwright@1.65.0 + npx playwright install --with-deps ${{ matrix.browser }} + node test/browser/playwright.mjs ${{ matrix.browser }} diff --git a/.github/workflows/vmm-ui.yml b/.github/workflows/vmm-ui.yml index 2598655418..5e79081267 100644 --- a/.github/workflows/vmm-ui.yml +++ b/.github/workflows/vmm-ui.yml @@ -7,18 +7,24 @@ name: VMM UI build permissions: contents: read -# Only the VMM's web UI is built here. Not a required status check, so a -# workflow-level filter is safe. +# The VMM's web UI and vmm-cli are built and tested here. Not a required +# status check, so a workflow-level filter is safe. on: push: branches: [ next, 'release/**' ] paths: - 'dstack/vmm/ui/**' + - 'dstack/vmm/src/vmm-cli.py' + - 'dstack/vmm/src/tests/test_vmm_cli.py' + - 'dstack/vmm/requirements.txt' - '.github/workflows/vmm-ui.yml' pull_request: - branches: [ next, 'release/**' ] + branches: [ next, 'release/**', 'feat/**' ] paths: - 'dstack/vmm/ui/**' + - 'dstack/vmm/src/vmm-cli.py' + - 'dstack/vmm/src/tests/test_vmm_cli.py' + - 'dstack/vmm/requirements.txt' - '.github/workflows/vmm-ui.yml' jobs: @@ -26,6 +32,8 @@ jobs: runs-on: ${{ vars.CI_RUNNER || 'ubuntu-latest' }} steps: - uses: actions/checkout@v5 + with: + persist-credentials: false - name: Install Node.js uses: actions/setup-node@v5 @@ -47,3 +55,28 @@ jobs: git status --porcelain exit 1 fi + + # `--if-present`: the UI test script is not on every branch yet. + - name: Test vmm UI + run: npm run test --if-present + working-directory: dstack/vmm/ui + + vmm-cli: + runs-on: ${{ vars.CI_RUNNER || 'ubuntu-latest' }} + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + + - name: Install Python + uses: actions/setup-python@v5 + with: + python-version: '3.12' + + - name: Install vmm-cli dependencies + run: pip install -r requirements.txt + working-directory: dstack/vmm + + - name: Test vmm-cli + run: python3 -m unittest -v tests/test_vmm_cli.py + working-directory: dstack/vmm/src diff --git a/.plumber.yaml b/.plumber.yaml new file mode 100644 index 0000000000..0bf9475a0e --- /dev/null +++ b/.plumber.yaml @@ -0,0 +1,25 @@ +# SPDX-FileCopyrightText: © 2026 Thibaud Van den Berghe +# +# SPDX-License-Identifier: Apache-2.0 + +# Plumber configuration: the built-in defaults plus what this repository needs. +extends: plumber:default +version: "2.0" + +github: + controls: + githubActionMustComeFromAuthorizedSources: + includePlumberDefaults: true + # Third-party actions the workflows use, on top of the default trust list. + trustedGithubActions: + - dtolnay/rust-toolchain # installs the Rust toolchain + - Swatinem/rust-cache # cargo cache of the Rust jobs + - softprops/action-gh-release # creates the GitHub releases + - foundry-rs/foundry-toolchain # forge, for the KMS contracts + - leanprover/lean-action # builds the Lean proofs + # dtolnay/rust-toolchain downloads the rustup installer only when rustup + # is missing, and ubuntu-latest ships rustup. The four jobs that take + # their runner from `vars.CI_RUNNER` would run that download on a runner + # without it. + actionsMustNotExecuteMutableRemoteCode: + enabled: false diff --git a/CHANGELOG.md b/CHANGELOG.md index d4acc7c906..cf4eefcee5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,687 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Upgrade notes + +- **`secure_time` refuses a clock the host controls.** `secure_time` is on + unless the app compose sets it to `false`, so this applies to every app + that leaves it out. Such an app no longer boots on AWS, nor when the + clocksource is not `tsc`. On AMD SEV-SNP the VMM launches it with Secure + TSC, which needs QEMU >= 11.2 (not released yet), host kernel >= 6.18 and a + CPU that supports it; an older QEMU exits at startup on the unknown + `secure-tsc` property. Such a guest also needs a KMS and verifier of this + release. Apps with `secure_time: false` launch as before. + +### Added + +- **Landlock in the guest kernel.** `CONFIG_SECURITY_LANDLOCK` is now built in, + so unprivileged sandboxes that rely on Landlock run inside CVMs. This + changes the guest kernel and therefore the OS image measurements. +- **Secure TSC for AMD SEV-SNP guests.** The VMM launches an SNP guest with + Secure TSC when `secure_time` is on, so the host cannot skew the guest + clock. +- `vmm-cli compose --init-script` sets `init_script` in the app compose file. +- **`allowed_envs` entries can constrain values.** An entry may be `NAME: spec`, + such as `PORT: int(1..=65535)` or `NETWORK: /mainnet|testnet/`, and the guest + refuses to boot when a value does not match. `dstack-util validate-env` + applies the same specs from an `init_script`, and `dstack-util import-env` + takes variables from `.user-config` under them. `vmm-cli compose --env-spec` + and the VMM web UI set them, and the VMM rejects malformed `int` and + `float` specs at deployment. See + [Environment value specs](docs/security/cvm-boundaries.md#environment-value-specs). +- **The KMS auth-eth server can require several RPC providers to agree.** + `ETH_RPC_URLS` with `ETH_RPC_QUORUM=n/m` answers a read only with what n of + the m endpoints return alike, and `ETH_MAX_BLOCK_AGE`, required with several + endpoints, rejects a stale block. + `dstack-app/deploy-to-vmm.sh` reads the endpoints from `rpc.json` and keeps + API keys out of the measured compose file. See [Multiple RPC providers](dstack/kms/auth-eth/README.md#multiple-rpc-providers). +- **`key_provider: tdx-seal` derives keys from TDX hardware sealing.** The + guest derives its seed with `TDG.MR.KEY.GET`, bound to the OS, VM + configuration and app identity, so a CVM on a TDX host can recover its disk + without a KMS or SGX. See [TDX Hardware Key Provider](docs/tdx-seal-key-provider.md). + +### Security + +- **A new `sev-snp` disk is sealed to the running TCB.** The guest used + sealing parameters the host had already stored in `.instance_info`, so a host + could seal a new disk to an older TCB that stays able to derive its key. +- **Sysbox is updated to 0.7.2.** It fixes read-only bind mounts being made + writable from inside a Sysbox container, and host files being reachable + through symlinks while Sysbox syncs special volumes. See the + [upstream release](https://github.com/nestybox/sysbox/releases/tag/v0.7.2) + for the advisories. + +### Changed + +- **TDX quotes go to QGS over vsock first.** When `/etc/tdx-attest.conf` + sets a port, `tdx-attest` asks QGS directly and falls back to configfs only + if that fails, or uses configfs alone when `DCAP_TDX_QUOTE_CONFIGFS_PATH` is + set. The kernel's configfs path polls once a second, so a quote took about + 1 s there and takes about 5 ms over vsock. +- **Breaking:** guest: a data disk left at older KMS key epochs is no longer + migrated after a key rotation; boot stops instead. Start such apps from a + fresh data disk. Migration keeps the volume key, which the old root and any + copy of the old LUKS header reveal, so a migrated disk stays readable and + writable by whoever holds them. `requirements.unsafe_allow_disk_migration` + restores migration and is strongly discouraged; it has to be set in a new + compose approved in the old and the current app epoch rows. +- **`vmm-cli update --compose` takes an app compose file.** It sends the + `app-compose.json` written by `vmm-cli compose` unchanged instead of a Docker + Compose file patched into the stored one, and `--prelaunch-script` and + `--swap` are gone from `update`: run `compose` again to change them. + `update --env-file` no longer rewrites `allowed_envs` or `launch_token_hash` + and refuses variables the compose does not allow or an `APP_LAUNCH_TOKEN` it + does not pin; render them with `compose --env-file`, which now also writes + `launch_token_hash`, changing the compose hash when the env file sets + `APP_LAUNCH_TOKEN`. `update-env` and + `update-app-compose` are removed in favor of `update --env-file` and + `update --compose`. + `update --kms-encrypt-url` encrypts `--env-file` without replacing the VM's + KMS URLs, which `--kms-url` does. +- **`app-compose.service` rejects environment variables outside + `allowed_envs`.** It used to pass on whatever `.decrypted-env.json` held, so + an `init_script` that adds variables to that file must now have them listed + in `allowed_envs`. An `allowed_envs` entry that contains a `:` must now be + a valid `NAME: spec`; such an entry used to be a name no variable could + have, and now stops the boot. +- **The KMS auth-eth server pins contract reads to a block hash.** Each + request reads the block it resolved by hash (EIP-1898) rather than by number, + so the RPC endpoint must accept a block hash in `eth_call`, which the server + checks at startup. HTTP redirects from the endpoint are refused. The server + no longer falls back to `http://localhost:8545`: it exits unless + `ETH_RPC_URL` or `ETH_RPC_URLS` is set. +- A failing `init_script` is reported to the VMM as a boot error. +- **Go SDK module moves to `github.com/Dstack-TEE/dstack/sdk/go/dstack`.** + `go get` now targets the module rooted at the `dstack` package, so pkg.go.dev + lists it under its product name instead of "go". The `dstack` package import + path is unchanged — importers only update the module line in `go.mod`. The + retired tappd client becomes its own module at its unchanged path + (`sdk/go/tappd`), frozen and deprecated. The old `sdk/go` module is + deprecated and contains no packages from v0.6.1; both new modules require + that version, so `go get` upgrades an existing v0.6.0 pin instead of failing + with an ambiguous import. A consumer importing both `dstack` and `tappd` + must `go get` both new modules; the frozen tappd gets a one-time + `sdk/go/tappd/v0.6.1` tag for exactly that. Releases tag `sdk/go/dstack/v*` + or `sdk/go/ratls/v*`, gated by a new release workflow that also warms + pkg.go.dev indexing. +- **AMD SEV-SNP on bare metal is no longer experimental.** The docs list it + next to Intel TDX, GPU workloads included: the measured, fail-closed GPU gate + gives SNP the same boot-time guarantee, and an SNP verifier checks the GPU + requirement in the policy bound by `compose_hash` instead of the + `gpu-attestation` event. SEV-SNP in public clouds stays unsupported. + +### Fixed + +- The guest agent answers legacy `Info` without a quote on TDX guests whose + kernel exposes the TSM measurement sysfs, so `Info` no longer queues behind + quote callers. Callers that wait more than 10 seconds for the attestation + queue receive HTTP 503 and can retry. + +## [0.6.6] - 2026-11-20 + +### Upgrade notes + +- **KMS state moves to `/var/lib/kms`.** The root keys of every epoch move out + of `cert_dir` into the new `core.keyring_dir` (default + `/var/lib/kms/keyring`), as `epochs//` with `root-epoch` marking the + newest. `cert_dir` and the default listener TLS paths move from + `/etc/kms/certs` to `/var/lib/kms/certs`. A deployment that persists + `/etc/kms/certs` and relies on the defaults must persist `/var/lib/kms` or + set both paths. The on-disk layout is not read from older versions, so + upgrade by onboarding a new KMS, as before. + +- **SEV-SNP verification fetches AMD's CRL.** Every SNP verification now + needs AMD KDS, or the configured mirror, to serve `/crl`, including + evidence that carries its own certificates and used to verify offline. A + mirror that serves only `cert_chain` and VCEKs fails every SNP verification + as unavailable collateral until it serves the CRL too. + +- **SEV-SNP needs a published TCB list.** The KMS judges an SEV-SNP TCB + against the minimum TCB governance publishes for its CPU, and refuses an + SEV-SNP request, its own self-authorization included, while it cannot: + upgrade `DstackKms` and the auth API, then publish the list with + `setSevSnpTcbRequirements` (or `sevSnpTcbRequirements` for `dstack-auth`) + before upgrading the KMS. A KMS can cover the CPUs governance leaves out + with `core.attestation.sev_snp_tcb_requirements_file`, and `dstack-verifier` + judges against the same JSON in `attestation.sev_snp_tcb_requirements_file`. A host whose firmware still emits version 2 + reports, which do not name the CPU, is refused. See + [AMD SEV-SNP](docs/amd-sev-snp.md). + +- **`DstackKms` deploys apps through `appImplementation`.** The app proxy is + now created by `DstackApp.deployProxy` and initialized by `DstackKms`, which + keeps the proxy's creation code out of `DstackKms`, close to the 24 KB + contract size limit. After upgrading `DstackKms`, point `setAppImplementation` + at a current `DstackApp`, as `Upgrade.s.sol:UpgradeKms` now does. With a + released `DstackApp` there, `deployAndRegisterApp` reverts. + +- **Gateway WireGuard key proofs are off until you turn them on.** A CVM now + proves it holds the WireGuard key it registers. Old CVMs and gateways keep + working, and a missing proof is only logged, so the logs show when the fleet + is ready; then require proofs with `SetWgKeyProofConfig`. The squatting it + stops is closed only once every gateway node runs 0.6.6 and proofs are + required (#1615). + +- **The guest agent logs every API request to the serial console**: socket, + caller pid and uid, method, status and latency, never the arguments. Whoever + can read the console sees which internal APIs an app calls and how often + (#1626). + +### Added + +- Guest agent: v0 `GetKey` takes optional `root_epoch` and `app_epoch` and + reports the epochs it derived from, so an app can still reach a v0 key from + before a KMS key rotation. Unset means the current epochs, as before. + `Tappd.DeriveK256Key` shares `GetKeyArgs` and honours them too. The 0.5 line + gets the same in 0.5.16 (#1630, #1631). +- `dstack-key-recovery`, a tool that recovers an application key from an older + KMS root epoch for guests that cannot select one (#1632, #1633). +- KMS and verifier: the SEV-SNP TCB is judged against per-CPU minimums taken + from the AMD security bulletins, published through the auth API or loaded + from a JSON file (#1621, #1627, #1628). +- Gateway: CVMs prove possession of their WireGuard key at registration + (#1615). +- Guest agent: an access log line per API request on the serial console + (#1626). +- `formal/`: Lean 4 models and machine-checked proofs of KMS, gateway and guest + OS logic, built in CI (#1597). + +### Changed + +- KMS: each root epoch keeps the attestation produced when its keys were + generated (`epochs//root-attestation`), and key handover carries it in + `KmsKeys.attestation`, so joined and rotated nodes keep the evidence of every + epoch. The receiver archives it without verifying it; relying parties verify + it. `bootstrap-info.json` is gone: `GetMeta.bootstrap_info` reports the served + epoch's attestation. Auto-bootstrap now records the attestation too (#539). +- **Breaking:** SDKs: the SealedEnv helpers take the app epoch with no + default. `sealEnv`/`seal_env`/`SealEnv` and + `verifySealedEnvPublicKey`/`verify_sealed_env_public_key`/`VerifySealedEnvPublicKey` + take `root_epoch, app_epoch` in that order, and Go's `SealEnvAtEpochs` and + `VerifySealedEnvPublicKeyAtEpochs` and Rust's `seal_env_at_epochs` and + `verify_sealed_env_public_key_at_epochs` are folded into them. The app epoch + used to default to 0, so a key fetched after an app key rotation produced an + envelope the guest could not decrypt at boot. Pass both epochs + `GetSealedEnvPubKey` returns. +- sdk/rust (breaking): `TcbInfo` fields `mrtd` and `rtmr0`-`rtmr3` changed from `String` to `Option` because the server emits null on non-TDX backends; new public fields on `TlsKeyConfig`, `EventLog` and `InfoResponse` break struct-literal construction +- sdk/rust (breaking): `TappdTcbInfo` fields `mrtd` and `rtmr0`-`rtmr3` are now + `Option` to support non-TDX guests. Persisted Borsh values must be + decoded with the old layout before re-encoding. Rust v0 now requires an + agent with the `Version` RPC (dstack 0.5.7 or newer) to request Ed25519 keys, + certificate validity overrides, or application info in TLS certificates. + Default requests are unchanged. +- sdk/js (breaking): v0 and Tappd `TcbInfo` measurement fields `mrtd` and + `rtmr0`-`rtmr3` are typed as `string | null`, matching non-TDX responses. + Check for `null` before using them as hex strings. +- sdk/python (breaking): `TcbInfo` fields `mrtd` and `rtmr0`-`rtmr3` are now `Optional[str]` +- sdk/rust (breaking): v0 and v1 `get_key` take a `GetKeyConfig` built with + `GetKeyConfig::builder()`, which also carries the optional `root_epoch` and + `app_epoch`, and for v0 the `algorithm`. Replace v0 `get_key(Some(path), None)` with + `get_key(GetKeyConfig::builder().path(path).build())`, and v1 + `get_key(domain, algorithm)` with + `get_key(GetKeyConfig::builder().domain(domain).algorithm(algorithm).build())`. +- SDKs: the Python, JS and Go compose-hash helpers follow one rule, taken from + the `dstack-types` serde attributes, and agree on every app-compose vmm-cli + and the VMM UI emit. Go's hash of such files changes, since it used to differ + from the other SDKs. Hand-built inputs holding `null` or `false` values can + hash differently than before: Python and Go now keep a top-level `null`, + and JS drops `requirements.health_check: false` and similar defaults (#1508). +- SDKs: a v1 `GetKey` that selects an epoch fails if the response omits it, as + the v0 clients do: an agent older than the epoch fields ignores the + selectors (#1508). +- sdk/go: `ratls` verifies the versioned attestation current dstack writes, + replays V2 runtime events, accepts only TDX quotes, and gains a `WithVerify` + policy hook (#1508). +- sdk/go (breaking): `AppCompose.InitScript` and `AppCompose.SwapSize` changed to the named types `*InitScripts` and `*SwapSize`. Explicit empty compose slices now encode as `[]`; use nil to reproduce hashes that omitted them. + +### Removed + +- **Breaking:** Go and Rust SDKs: `GetKeyAtRootEpoch` and + `get_key_at_root_epoch`. Use `GetKeyAtEpochs(ctx, domain, algorithm, + &rootEpoch, nil)` or `get_key` with `GetKeyConfig::builder().root_epoch(n)`. + +### Fixed + +- Guest agent: the watchdog probe no longer reuses an idle connection the + agent may be closing, which logged `Connection reset by peer` every few + minutes on 0.6.5 (#1625). +- KMS: refuses to serve from an empty keyring instead of serving epoch + `u32::MAX` (#1618). +- VMM: a dropped start request no longer leaves two QEMUs; stop, power-off and + load recheck their state under the launch lock; the VM manifest and state + are written atomically; a reload no longer tears down a VM created while it + scans; and a VM that fails to load at startup is kept running instead of + stopped as an orphan (#1609-#1614, #1616, #1617). +- Gateway: a lock or lease that is no longer held cannot delete a successor's + or commit writes, and one stamped beyond the clock drift bound counts as + expired; an IP stays allocated while another instance holds it; a peer + gateway address inside this node's pool is warned about; wavekv 2.2 fixes two + replication divergences (#1598-#1601, #1605, #1606). +- Guest: warns on an `instance_id_seed` that is not 20 bytes (#1607). +- SDKs: Tappd clients call only routes `tappd.sock` serves, and Python's + `tdx_quote` pads short raw report data instead of failing; JS validates hex + and handles truncated responses; Python and Rust decode `Info` with null + registers (#1508). + +### Security + +- sev-snp-qvl: binds a supplied VCEK to the chip and TCB the report claims, + and rejects ASKs revoked by AMD's CRL (#1620, #1622). +- cc-eventlog: rejects V1 runtime event names containing `:`, whose digests + were not injective (#1596). +- Gateway: SNI sniffing honours the declared record lengths, and a CVM can no + longer register with a gateway node's WireGuard key (#1602, #1603, #1604). + +## [0.6.5] - 2026-11-15 + +### Upgrade notes + +- **The contracts are not compatible with 0.6.4.** `AuthorizationRequest` gains + `launchTicketHash` (see Changed), which changes the selectors of + `authorizeApp` and `authorizeKms` and the `IAppEpochAuth` interface ID + (`0xd33835bd` to `0xc396c1b0`). Upgrade `DstackKms`, every `DstackApp` proxy + (and `setAppImplementation`) and auth-eth together: a 0.6.4 auth-eth with a + 0.6.5 `DstackKms`, or the reverse, denies every request, and a 0.6.5 + `DstackKms` treats a 0.6.4 `DstackApp` as a legacy policy, limited to app + epoch 0 through `isAppAllowed`. +- **Upgrade the auth backend before the KMS.** A joining KMS needs the auth + backend's `GET /` to report `rootCaPubkey` and an `https://` source URL. +- **Upgrade every KMS instance before `setRequireKmsLaunchTicket(true)`.** + Older instances authorize serving through `isKmsAllowed`, which a required + ticket refuses, so they stop serving every app. +- **KMS refuses its old listener settings.** Move `[rpc]`, `[core.admin]`, + `[core.onboard]` `address`/`port`/`tls`, `[default]` and top-level Rocket + settings to `[listeners.*]` (see Changed) when upgrading the KMS image. +- **Gateway refuses its old listener settings.** A hand-written `gateway.toml` + must move its top-level listener settings, `[tls]`, `[core.admin]` and + `[core.debug]` (see Changed) when upgrading the gateway. + +### Added + +- KMS: an optional `[listeners.public]` listener, off by default, serving only + `GetMeta`, `GetAppEnvEncryptPubKey` and `GetSealedEnvPubKey`, so the guest + listener, which releases keys, can be restricted to CVMs (#1580). +- KMS, gateway: `proxy_protocol = true` on a listener requires a PROXY v1/v2 + header on every connection and logs its source address as the client. The + header is trusted as sent, so the listener must be reachable only through the + proxy. prpc request logs now carry the client address as `remote` (#1582). +- Launch tickets: key release can require a secret ticket the host presents at + launch, checked by the contract before the KMS releases anything, without + changing the compose hash. `DstackApp.setRequireLaunchTicket`, + `addLaunchTicket(hash, label)`, `removeLaunchTicket` and `launchTickets()` + gate `GetAppKey` and `SignCert` at every app epoch; `DstackKms` has the same + for KMS instances, gating only `kms_import_keys`. The hash is + `sha256("dstack-launch-ticket/v1:" || ticket)`. The VMM stores the ticket, + writes it to the guest's sys-config at every boot and returns only + `VmInfo.launch_ticket_hash`; `vmm-cli launch-ticket new|hash`, `deploy + --launch-ticket-file`, `update --launch-ticket-file|--no-launch-ticket`, + `dstack-util get-keys --launch-ticket-file` and the web UI set it. A joining + KMS takes its ticket in `Onboard`. Guests need OS 0.6.5, or 0.5.15 or later + on 0.5.x. See `dstack/kms/README.md#launch-tickets` (#1577). +- auth-eth, dstack-auth: `GET /` reports `rootCaPubkey`, the CA key of the + current root epoch (#1577). +- KMS: refused `GetAppKey`, `SignCert` and `GetKmsKey` requests are logged as + `key release denied` on `dstack_kms::audit`, with the app, instance, caller + and error, and `GetAppEnvEncryptPubKey`/`GetSealedEnvPubKey` as `env public + key served` or `refused` (#1583). +- Gateway: every state-changing admin RPC and every CVM registration logs one + line on `dstack_gateway::audit` with the operation, caller and subject + (#1588), and every proxied connection one line on `dstack_gateway::access` + with client, SNI, route, app, bytes and duration; disable it with + `RUST_LOG=info,dstack_gateway::access=off` (#1589). +- vmm-cli: `DSTACK_VMM_KMS_WHITELIST_PATH` overrides the KMS whitelist path, + `~/.dstack-vmm/kms-whitelist.json` by default (#1591). +- `dstack-verifier-wasm` (`@phala/dstack-verifier-wasm`): the TDX lite OS check + as a self-contained wasm package for JS/TS verifiers, released separately as + `verifier-wasm-v*` (#1555). + +### Changed + +- **Breaking:** KMS: listener settings move to `[listeners.*]`: + `[listeners.default]` (`tls`, `proxy_protocol`, Rocket settings, inherited + by every listener), `[listeners.guest]` (was `[rpc]`), `[listeners.admin]` + (was `[core.admin]`, credentials included), `[listeners.public]` and + `[listeners.onboard]` (`address`/`port`, was in `[core.onboard]`). The KMS + refuses a config that still sets an old location, naming the new one. The + old `[default]` section was never read; only `ident` moves, so responses now + carry `Server: DStack KMS` (#1585). +- **Breaking:** gateway: listener settings move to `[listeners.*]`: + `[listeners.default]` (Rocket settings and `proxy_protocol`, was the top + level, now inherited by the admin and debug listeners too), + `[listeners.guest]` (`address`, `tls`, was the top level), `[listeners.admin]` + (was `[core.admin]`) and `[listeners.debug]` (`enabled`, was `[core.debug] + insecure_enable_debug_rpc`). `insecure_localhost_backend` moves to + `[core.proxy]`. The gateway refuses a config that still sets an old location, + naming the new one; the gateway image's entrypoint writes the new one (#1587). +- **Breaking:** `IAppEpochAuth.AuthorizationRequest` gains `launchTicketHash`, + forwarded by auth-eth and checked by dstack-auth. A required ticket refuses + the legacy `isAppAllowed` and `isKmsAllowed` (#1577). +- KMS: onboarding pins the source's RPC certificate to the current root CA + from its own auth backend and refuses `http://` sources, so the ticket and + `source_token` are sent only to a KMS holding the registered roots (#1577). +- VMM: VM work directories are created with mode 0700 (#1577). +- verifier: `details.acpi_tables_verified` is `false` on an MR mismatch; + `is_valid` is unchanged (#1555). +- mkosi OS releases no longer publish `image-hashes.txt`; MRTD, `uki_auth` and + `boot_pcr_digest` are in the release notes table (#1573). +- dstack-auth is documented as development, testing and evaluation only: the + host operator controls its policy file (#1576). + +### Fixed + +- dstack-util: `get-keys` verifies the KMS with the guest's collateral service + and trust anchors, as system setup does, instead of the production defaults + (#1565). +- VMM: a guest with `simulated_tee = dstack-tdx` gets the vm_config and + measurement document of a TDX guest, so a KMS no longer refuses it with an + MRTD mismatch (#1590). +- auth-eth: bump hono to 4.13.16 for GHSA-4m76-xfj5-7975, GHSA-h7mg-cq63-vhpq, + GHSA-46wx-v44x-9hh2 and GHSA-4h7h-rv7c-7m2v (#1578). + +## [0.6.4] - 2026-11-12 + +### Upgrade notes + +- **Deployment order for key epochs:** upgrade the `DstackKms` and `DstackApp` + proxies and the auth backend, register the existing roots as root epoch 0 + (`registerRootEpoch`), then roll out the KMS nodes, then guests. Keep root and + app epochs at 0 until every KMS and guest is upgraded. See + `dstack/kms/README.md` and `docs/deployment.md`. +- **Auth backends must serve `GET /app/:appId`**, which reports an app's current + app epoch. The KMS reads it for `GetAppEnvEncryptPubKey` and + `GetSealedEnvPubKey`. `auth-eth` and `dstack-auth` serve it; custom webhook + backends must add it. +- **Upgrade KMS before guests.** 0.6.4 guests mint self-issued RA-TLS client + certificates for KMS calls and need a 0.6.4 KMS that accepts them. +- **KMS needs a key handover path to start:** configure the admin listener + with TLS and an admin token, or set `core.onboard.public_key_handover = true` + (see Changed). + +### Added + +- DstackKms, DstackApp: TEE platform allowlists. `AuthorizationRequest` of + `IAppEpochAuth` (the epoch-aware policy interface) carries `teeVariant`, the + platform name the KMS reports (`dstack-tdx`, `dstack-amd-sev-snp`, ...), + passed through unchanged by auth-eth. Each contract allows any platform until + its owner calls `setAllowAnyTeeVariant(false)`; it then allows only the names + set by `setAllowedTeeVariants`, from the platforms `TeeVariantPolicy` knows + (setting an unknown one reverts). The policy covers every epoch, and a + restricted one refuses unknown platforms and the legacy `isAppAllowed` and + `isKmsAllowed`, whose callers report no platform. auth-eth requires + `teeVariant` on `/authorizeKms` and `/authorizeApp`. +- KMS root and application key epochs, epoch-scoped authorization, SealedEnv + HPKE encryption, automatic environment migration, and epoch-aware SDK key + selection. +- dstack-auth: opt-in `allowedTcbStatuses` and `allowedAdvisoryIds` allowlists, + applied to app and KMS requests on `/authorize*` and `/bootAuth/*`. When set, + a `tcbStatus` outside the list, or any advisory ID outside the list, denies; + when absent, neither is checked. `GET /` reports the configured `chainId` and + `appImplementation`, and each decision is logged with the device ID, + measurements and TCB status. +- guest: `key_provider: sev-snp` derives a hardware-bound seed inside an AMD + SEV-SNP guest, so a KMS CVM on an AMD host can recover its disk and stored + root keys after restart without SGX (#1526). + +### Changed + +- KMS: a KMS requires a key handover path and otherwise refuses to start, + before onboarding or bootstrap, naming the missing setting: unless + `core.onboard.public_key_handover = true`, set `[core.admin] enabled = true` + and `[core.admin.tls]` with `key` and `certs`. There is no opt-out, dev auth + included. The built-in config now enables the admin listener with TLS on the + RPC key and certificate, so a KMS on it needs an admin token to start: + `core.admin.auth_token`, `DSTACK_KMS_ADMIN_TOKEN`, or the new + `core.admin.auth_token_hash` (hex SHA-256), which keeps the token out of a + public app compose; the hash is then public, so use a high-entropy random + token such as `openssl rand -hex 32`. When upgrading, add the admin TLS and a token, or enable + the public handover. The `dstack-app` composes and `dstackup` generate the + token and configure its hash; the deploy scripts publish the admin listener + when `KMS_ADMIN_ADDR` is set. +- KMS: `core.onboard.public_key_handover` defaults to `false`, so + `KMS.GetKmsKey` is no longer served on the public port. Onboard through the + source's admin listener with `source_token`; a source that still onboards + 0.5.x KMS nodes must set the option to `true` until they are upgraded. +- KMS: onboarding refuses a source whose certificate carries no OS image hash, + which drops the fallback for KMS 0.5.x sources. Join only from a 0.6+ source; + upgrade a 0.5.x cluster to 0.6.x first. +- dstack-auth: an empty `devices` list no longer allows any device; set + `allowAnyDevice: true` for that. An empty `osImages` list now denies every + app instead of skipping the OS image check. Allowlists generated by + `dstack-cli` already set both explicitly. +- Auth backends: once a root epoch other than 0 is activated, `/bootAuth/kms` + denies a KMS that reports no root epoch, as `/bootAuth/app` already did, so + KMS binaries predating root epochs stop serving at activation. Upgrade every + KMS before activating a new root epoch. +- auth-eth: policy is read at the `finalized` block by default instead of + `latest`, so on-chain changes, including revocations, take effect only once + finalized. Set `ETH_BLOCK_TAG=latest` (or `safe`) to override; an OP-stack + chain read through the Helios light client requires `latest`. Only + `finalized` protects policy from reorgs: with `latest` or `safe`, a reorg can + roll back an activation or a revocation the KMS has already acted on. The + server refuses to start if the RPC cannot serve the configured tag. + `ETH_FINALITY_CONFIRMATIONS` now counts back from that block. +- DstackKms, DstackApp: material approvals are per epoch. A request is decided + on the row of the epoch it selects, so a value is revoked only once every row + allowing it is cleared. Material setters name their rows: + `*AtEpochs(from, to, value)` writes a range, and in `DstackApp` + `*AtEpoch(epoch, value)` one epoch (in `DstackKms`, pass the epoch twice); + `remove*AtEpochs(0, latest root epoch, value)` in `DstackKms` and + `remove*AtEpochs(0, currentAppEpoch, value)` in `DstackApp` revoke a value + everywhere. `DstackApp` reports its setters as the new ERC-165 interface + `IAppEpochManagement` (`0x8c0524c4`). The `Manage.s.sol` scripts require + `ROOT_EPOCH` or `APP_EPOCH`, or a `FROM_*`/`TO_*` range. `DstackApp`'s + `allowAnyDevice` stays a single switch: `setAllowAnyDevice(bool)` covers every + app epoch, so dropping the device restriction cannot leave an older epoch + open to any host. +- App contracts deployed before app epochs (v0.5.x, v0.6.0) keep working with + the upgraded `DstackKms` and KMS, which authorize them for app epoch 0 only. + `Manage.s.sol` detects them by interface ID and calls their epoch-less + setters. Upgrading one to the current `DstackApp` keeps its compose hashes and + devices as app epoch 0, and its `allowAnyDevice` for every app epoch. +- DstackKms, DstackApp: ownership transfers take two steps for proxies upgraded + from v0.5.9: `transferOwnership` nominates, and the new owner must call + `acceptOwnership`. +- dstack-auth: `kms_export_keys` and `kms_import_keys` accept a registered + pending root epoch, so KMS nodes can onboard a new epoch before + `currentRootEpoch` is raised, as with the contract backend. Key-issuing + operations stay limited to the current epoch. +- KMS: retain `GetTempCaCert`, temporary CA files and legacy handover fields so + KMS nodes can be upgraded before existing OS images. +- dstack-util, cert-client: guests mint self-issued RA-TLS client + certificates for KMS calls instead of fetching the temp CA and minting from + it; the KMS authenticates the quote inside the certificate, not its issuer. + Guests fetch the root CA with the key response and bind it to the attested + RPC certificate, without a metadata preflight. Provider pins and the + `key-provider` launch event (RTMR3/PCR14) retain the root identity binding. + The new flow requires an attested KMS that accepts self-issued certificates. +- dstack-types: `KeyProvider::Kms` drops `tmp_ca_key` and `tmp_ca_cert`, so + `.appkeys.json` no longer carries them. Files written by older images still + parse, but out-of-tree readers that require those fields fail on new files. +- KMS: `auth-eth-bun` is renamed to `auth-eth`. The Bun webhook server moves + from `dstack/kms/auth-eth-bun` into `dstack/kms/auth-eth`, next to the + contracts. New releases are tagged `kms-auth-eth-v*` and published as + `ghcr.io/dstack-tee/dstack-kms-auth-eth`; images already published as + `ghcr.io/dstack-tee/dstack-kms-auth-eth-bun` remain available. Update image + references and source paths in deployments. +- **Breaking:** DstackKms: reverts with custom errors such as + `UnknownRootEpoch()` instead of revert strings, to stay under the EIP-170 + size limit. This includes `registerApp`, `setAppImplementation` and + `deployAndRegisterApp`, whose v0.6.0 strings (`Invalid app ID`, `Invalid + implementation address`, `DstackApp implementation not set`, `Invalid owner + address`) become `InvalidAppId()`, `InvalidImplementationAddress()`, + `AppImplementationNotSet()` and `InvalidOwnerAddress()`; tooling that + matches the strings must decode the errors. Authorization rejection reasons + are unchanged. + +### Removed + +- DstackKms: the epoch-less `addOsImageHash`, `removeOsImageHash`, + `addKmsAggregatedMr`, `removeKmsAggregatedMr`, `addKmsDevice` and + `removeKmsDevice`. Use the `*AtEpochs` forms; before any rotation, + `addOsImageHashAtEpochs(0, 0, hash)` is the old call. +- **Breaking:** DstackApp: the epoch-less `addComposeHash`, `removeComposeHash`, + `addDevice` and `removeDevice`, and with them + `IAppAuthBasicManagement`: an upgraded app no longer reports interface ID + `0x8fd37527`, and calls to those functions revert. Use the `*AtEpoch` or + `*AtEpochs` forms (`IAppEpochManagement`); at app epoch 0, + `addComposeHashAtEpoch(0, hash)` is the old call. +- DstackKms: `setKmsInfo`, `setKmsQuote` and `setKmsEventlog`. Root keys are + set with `registerRootEpoch`, and each epoch's attestation lives at its + `evidenceUrl`. +- KMS: the `auth-mock` webhook backend. For development, use the built-in + `[core.auth_api] type = "dev"`, which allows everything. +- `auth-simple` (`dstack/kms/auth-simple`). Use `dstack-auth`, which reads the + same config file. Differences: the TCB status and advisories are not checked + unless `allowedTcbStatuses` / `allowedAdvisoryIds` are set (auth-simple + defaulted to `["UpToDate"]` and `[]`); `/authorize*` requires + `kmsContractAddr`; KMS requests are not matched against `osImages`; the + config path and port are `--config` / `--port` flags instead of + `AUTH_CONFIG_PATH` / `PORT`, and it binds to `127.0.0.1` by default. See + `docs/dstack-auth-operations.md#migrating-from-auth-simple`. +- KMS: the Node `auth-eth` webhook server (`dstack/kms/auth-eth/src`) is + removed. Use the Bun server (formerly `auth-eth-bun`, now in the same + directory, see Changed), which serves the same webhook API and reads the + same environment variables, except that it binds all interfaces and ignores + `HOST`, and `PORT` defaults to 3000 from source (8000 in its image). The + `DstackKms`/`DstackApp` contracts, Foundry tests and deployment scripts stay + in `dstack/kms/auth-eth`. `kms/dstack-app/compose-dev.yaml` now builds + the Bun server. + +### Fixed + +- kms: onboarding with or without `source_token` verifies the source's + attestation on the connection that returns the root keys and checks local + policy before using them. Legacy sources requiring temp-CA-issued clients + must be upgraded. +- ra-rpc: check the TLS handshake signature when CA verification is skipped; + `tls_no_check` is renamed to `tls_skip_ca_verification` (#1522). +- vmm: write `.instance_info` atomically, so a failed write or power loss can no + longer drop the instance ID seed and lose the VM's disk key (#1553). +- KMS, Gateway, Verifier, auth-eth images: set explicit file modes and + normalize timestamps so image digests no longer depend on the clone-time + umask (#1512). + +## [0.6.3] - 2026-11-01 + +### Upgrade notes + +- **Upgrade every Gateway node before deploying the new guest image.** The + guest-agent external API now requires scoped access. Older Gateways cannot + authenticate health probes and drop new guests from rotation; mixed-version + clusters can also lose guest tokens during replication. See + [Guest Agent API access control](docs/guest-api-auth.md). +- **New guest image.** Register the 0.6.3 `os_image_hash` on chain before + deploying it. The guest kernel, rootfs, and their measurements have changed. +- **KMS always verifies the OS image hash.** The `[core.image] verify` option + has been removed; a leftover key is ignored (#1497). + +### Security + +- guest OS: disable automatic GPT partition discovery and host-supplied system + credentials on the measured kernel command line. Remove production systemd + generators that act on host-controlled, unmeasured input; pin the allowed + generator set and assert the hardening configuration during builds. Includes + the unreleased 0.6.2 fixes for GHSA-c79w-3x5w-gmm5. +- guest-agent: gate every external API route by scopes granted through signed + Ed25519 JWTs or `[cvm.guest_agent_api].anonymous_scopes`. No scopes are + anonymous by default; app SDKs keep using the internal Unix socket. The + measured `public_logs`, `public_sysinfo`, and `public_tcbinfo` settings still + control what may leave the TEE (#1469). +- KMS: always verify `os_image_hash`, including its policy and identity-event + bindings (#1497). +- TPM: bound allocations and loops driven by TPM replies, reject undersized + response headers, and handle non-progressing handle enumeration (#1477, + #1481). +- guest OS, service images, KMS auth backends, and SDK locks: update CA trust + stores and TLS dependencies for emSign distrust; remove the obsolete KMS + compose file that pinned vulnerable images (#1463–#1467, #1470, #1492). +- guest OS: update the mkosi kernel to 6.18.59; update Rust and npm dependencies + for published security advisories (#1473, #1493–#1496, #1502). + +### Added + +- guest: `requirements.ephemeral_data_disk` starts every boot with an empty + data disk, formatted before app code runs (#1461). +- guest OS: ship the kernel build tree under `/usr/src/linux-headers-` + with `/lib/modules//build` pointing to it (#1501). +- guest OS: enable transparent huge pages with the `madvise` default, read-only + file THP, opt-in Multi-Gen LRU and BBR, and deferred page initialization + (#1503, #1504). +- guest OS: enable EROFS, ublk, and alternative streamed container-layer + backends (#1509). +- KMS: publish the Bun-based auth-eth backend image (#1452). + +### Fixed + +- guest: keep verity volumes out of data-disk discovery, including volumes + created by older releases, and use distinct partition labels (#1459). +- guest OS: update Sysbox to 0.7.1 and use idmapped overlay mounts so container + rootfs writes persist across restarts and failed starts do not corrupt + ownership (#1489). +- SEV-SNP: coalesce concurrent endorsement-certificate fetches and return HTTP + 503 for unavailable AMD endorsements rather than declaring quotes invalid + (#1484). +- KMS: recover onboarding after repeated clicks or lost provisioning responses, + clear measurement cache entries by their actual filenames, and increase the + Bun auth webhook idle timeout (#1453, #1460, #1471). +- guest-agent: saturate oversized log durations instead of overflowing (#1478). +- vmm/verifier: measure guest NUMA nodes without PXB expanders; validate image + names before writing VM manifests (#1458, #1476). +- gateway: require canonical port numbers in SNI; validate gateway WireGuard + fields before rendering configuration (#1451, #1472). +- TDX: add read/write timeouts for QGS vsock requests (#1454). +- Go SDK: match compose hashing for U+2028 and U+2029 (#1479). + +### Changed + +- vmm: enable the QMP socket by default for newly started CVMs; set + `qmp_socket = false` to opt out (#1450). +- vmm: disable GPU `sanitize_on_attach` by default (#1455). +- guest OS: decompress squashfs file data directly into the page cache using + per-CPU decompressors (#1506). +- gateway: use a guest-issued, ten-year API token that remains valid while + registration is unavailable (#1499, #1500). +- dependencies: update dcap-qvl to 0.7.0; build JS and Python SDK releases from + locked dependencies (#1480, #1498). + +## [0.6.1] - 2026-10-12 + +dstack 0.6.1 is a security release. Upgrade the guest OS, KMS, and verifier. + +### Upgrade notes + +- **New guest image.** Register the 0.6.1 `os_image_hash` on chain before + deploying 0.6.1 images + +### Security + +- guest-agent: `/logs/` rejects names that are not valid Docker + container names, so a crafted name can no longer reach a different Docker + API endpoint (#1442) +- KMS and verifier: a request `vm_config` must match the attested copy, and a + config has one layout. On AMD SEV-SNP the competing copies let a `SignCert` + request pass authorization with one `os_image_hash` and obtain a certificate + claiming another (#1430) + +### Added + +- verifier: measure multi-node NUMA layouts of hugepage VMs through + `vm_config.numa_nodes`; the VMM orders guest NUMA nodes by host node and + records the memory QEMU actually allocates, so such VMs now verify (#1418) +- verifier: `vm_config.extra_root_devices` describes root-bus devices that a + `qemu_path` wrapper appends, so their DSDT entries can be measured (#1424) +- vmm: `passt` networking is back. Each passt runs as a sidecar of the VM + launcher and talks to QEMU over a socketpair; see + `docs/passt-networking.md` (#1422, #1423) +- vmm: per-VM `annotations` for host-side tooling, stored in the VM manifest + and never passed to the guest or measured (#1419, #1421) + +### Changed + +- sdk/simulator: use the GHCR openssh installer image (#1417) +- dependency updates: rustls 0.23.45 in the Rust SDK, hickory-resolver 0.26.2, + and npm packages in KMS auth-eth and the VMM UI (#1429, #1432, #1434, #1436, + #1438, #1439, #1440) + ## [0.6.0] - 2026-09-28 > [!IMPORTANT] @@ -1655,7 +2336,8 @@ New contributors in this release: * @Leechael made their first contribution * @nanometerzhu made their first contribution * @h4x3rotab made their first contribution -[unreleased]: https://github.com/Dstack-TEE/dstack/compare/v0.6.0..HEAD +[unreleased]: https://github.com/Dstack-TEE/dstack/compare/v0.6.1..HEAD +[0.6.1]: https://github.com/Dstack-TEE/dstack/compare/v0.6.0..v0.6.1 [0.6.0]: https://github.com/Dstack-TEE/dstack/compare/v0.5.11..v0.6.0 [0.5.5]: https://github.com/Dstack-TEE/dstack/compare/v0.5.4..v0.5.5 [0.5.4]: https://github.com/Dstack-TEE/dstack/compare/v0.5.3..v0.5.4 diff --git a/CLAUDE.md b/CLAUDE.md index 6fdcf51741..a42d3f073c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -70,22 +70,24 @@ cargo clippy -- -D warnings --allow unused_variables ```bash cd dstack/kms/auth-eth -npm install # Install Node.js dependencies for bootAuth server -forge install # Install Foundry dependencies (submodules) +git submodule update --init --recursive lib/forge-std \ + lib/openzeppelin-contracts-upgradeable lib/openzeppelin-foundry-upgrades +# Upgrade-safety validator called by `forge test --ffi` +npx --yes @openzeppelin/upgrades-core@^1.37.0 --help > /dev/null # Build forge build # Compile smart contracts -npm run build # Build TypeScript server # Test -forge test --ffi # Run Foundry contract tests -npm test # Run TypeScript server tests -npm run test:coverage # Run TypeScript tests with coverage +forge clean && forge test --ffi # Run Foundry contract tests # Local development anvil # Start local Ethereum node ``` +The KMS webhook server for these contracts lives in the same directory +(`bun install && bun run check`). + ### Python SDK ```bash @@ -130,7 +132,7 @@ cargo test --all-features -- --show-output --test-threads=1 cd dstack/kms/auth-eth # Run all Foundry tests -forge test +forge test --ffi # Run with verbosity forge test -vv diff --git a/README.md b/README.md index 27b55eedf4..e001b84c3f 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ [![GitHub Stars](https://img.shields.io/github/stars/dstack-tee/dstack?style=flat-square&logo=github)](https://github.com/Dstack-TEE/dstack/stargazers) [![License](https://img.shields.io/github/license/dstack-tee/dstack?style=flat-square)](https://github.com/Dstack-TEE/dstack/blob/next/LICENSE) [![REUSE status](https://api.reuse.software/badge/github.com/Dstack-TEE/dstack)](https://api.reuse.software/info/github.com/Dstack-TEE/dstack) +[![Plumber Score](https://score.getplumber.io/github.com/Dstack-TEE/dstack.svg?style=flat-square)](https://score.getplumber.io/github.com/Dstack-TEE/dstack) [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/Dstack-TEE/dstack) [![Telegram](https://img.shields.io/badge/Telegram-2CA5E0?style=flat-square&logo=telegram&logoColor=white)](https://t.me/+UO4bS4jflr45YmUx) @@ -29,7 +30,7 @@ AI providers ask users to trust them with sensitive data. But trust doesn't scal | Platform | Status | Attestation | |----------|--------|-------------| | **Bare metal TDX** | Available | TDX | -| **Bare metal AMD SEV-SNP** | Host support; requires an SNP-capable guest image | SEV-SNP | +| **Bare metal AMD SEV-SNP** | Available | SEV-SNP | | **[Phala Cloud](https://cloud.phala.network)** | Available | TDX | | **GCP Confidential VMs** | Available | TDX + TPM | | **AWS Nitro Enclaves** | Available | NSM | @@ -139,7 +140,7 @@ Apps communicate with the guest agent via HTTP over `/var/run/dstack.sock`. Use | Python | `pip install dstack-sdk` | [README](./sdk/python/README.md) | | TypeScript | `npm install @phala/dstack-sdk` | [README](./sdk/js/README.md) | | Rust | `cargo add dstack-sdk` | [README](./sdk/rust/README.md) | -| Go | `go get github.com/Dstack-TEE/dstack/sdk/go` | [README](./sdk/go/README.md) | +| Go | `go get github.com/Dstack-TEE/dstack/sdk/go/dstack` | [README](./sdk/go/README.md) | ## Documentation @@ -151,6 +152,7 @@ Apps communicate with the guest agent via HTTP over `/var/run/dstack.sock`. Use **For Operators** - [Hardware Enablement](./docs/hardware-enablement.md) - Prepare a TDX or AMD SEV-SNP host - [AMD SEV-SNP](./docs/amd-sev-snp.md) - Image, attestation, and key-release requirements +- [TDX Hardware Key Provider](./docs/tdx-seal-key-provider.md) - Recover a CVM's keys from TDX sealing without a KMS - [Self-hosted Quick Onboarding](./docs/onboarding.md) - First app on one host - [Build the Guest OS](./docs/building-guest-os.md) - Build and verify bootable images from source - [Deployment](./docs/deployment.md) - Self-hosting on TDX or AMD SEV-SNP hardware @@ -161,6 +163,7 @@ Apps communicate with the guest agent via HTTP over `/var/run/dstack.sock`. Use **Reference** - [Guest Agent API v1](./docs/guest-api-v1.md) - Key derivation, signature chains, and the versioned guest API - [Guest Agent API v0](./docs/guest-api-v0.md) - The frozen legacy surface, for clients that still speak the unversioned API +- [Guest Agent API access control](./docs/guest-api-auth.md) - Scopes, tokens, and anonymous access on port 8090 - [App Compose Format](./docs/normalized-app-compose.md) - Compose file specification - [Intel TDX Attestation](./docs/attestation-tdx.md) - Measurement and runtime-event verification - [Native TEE Interfaces](./docs/native-tee-interfaces.md) - Advanced compatibility with Linux TEE devices and configfs-tsm @@ -219,7 +222,7 @@ Yes. dstack runs on supported TEE-capable servers, including Intel TDX-capable h - **GCP**: Intel TDX (Confidential VMs) - **AWS**: Nitro Enclaves (NSM attestation) -- **Bare metal**: Intel TDX (4th/5th Gen Xeon) and AMD SEV-SNP on supported dstack OS images. Intel TDX is the production path; AMD SEV-SNP is new and experimental. +- **Bare metal**: Intel TDX (4th/5th Gen Xeon) and AMD SEV-SNP (Milan, Genoa, Turin) with dstack OS 0.6.6 or later - **GPUs**: NVIDIA Confidential Computing (H100, Blackwell) diff --git a/REUSE.toml b/REUSE.toml index 68c0740195..6e7e20c645 100644 --- a/REUSE.toml +++ b/REUSE.toml @@ -13,6 +13,7 @@ path = [ "docs/**/*.md", "dstack/**/*.md", "examples/**/*.md", + "formal/**/*.md", "sdk/**/*.md", "tools/**/*.md", "os/README.md", @@ -34,18 +35,17 @@ path = [ "**/tsconfig.json", "**/tsconfig.node.json", "**/tsconfig.browser.json", - "dstack/kms/auth-eth-bun/.oxlintrc.json", + "dstack/kms/auth-eth/.oxlintrc.json", "dstack/kms/auth-eth/slither.config.json", "**/package-lock.json", "dstack/kms/auth-eth/.openzeppelin/unknown-2035.json", - "dstack/kms/auth-mock/.oxlintrc.json", - "dstack/kms/auth-simple/.oxlintrc.json", - "dstack/kms/auth-simple/auth-config.example.json", "tools/sca/examples/heartbeat/config.json", "tools/sca/examples/hello-c/config.json", "tools/sca/examples/heartbeat/rootfs/etc/heartbeat/interval", "sdk/simulator/*.json", - "sdk/go/go.sum", + "sdk/fixtures/sealed-env/*.json", + "sdk/tests/compose-hash-fixture.json", + "sdk/go/dstack/go.sum", "sdk/go/ratls/go.sum", "dstack/kms/dstack-app/builder/shared/builder-pinned-packages.txt", "dstack/kms/dstack-app/builder/shared/pinned-packages.txt", @@ -72,6 +72,9 @@ path = [ "dstack/**/.npmignore", "docs/**/.gitignore", "examples/**/.gitignore", + "formal/.gitignore", + "formal/lake-manifest.json", + "formal/lean-toolchain", "os/common/**/.gitignore", "os/image/**/.gitignore", "sdk/**/.gitignore", @@ -96,6 +99,8 @@ path = [ "dstack_Technical_Charter_Final_10-17-2025.pdf", "sdk/simulator/quote.hex", "sdk/simulator/attestation.bin", + "sdk/go/ratls/tdx-lite-v0-get-tls-key.pem", + "sdk/go/ratls/tdx-lite-v1-issue-cert.pem", "dstack/ra-tls/assets/tdx_quote", "dstack/cc-eventlog/samples/ccel.bin", "dstack/cc-eventlog/samples/tpm_eventlog.bin", @@ -106,6 +111,7 @@ path = [ "dstack/dstack-attest/tests/sev_snp_attestation.bin", "dstack/dstack-attest/tests/sev_snp_ask.pem", "dstack/dstack-attest/tests/sev_snp_vcek.pem", + "dstack/sev-snp-qvl/testdata/amd-milan.crl", "dstack/nsm-attest/tests/nitro_attestation.bin", "dstack/nsm-qvl/tests/nitro_attestation.bin", "dstack/nsm-qvl/certs/AWS_NitroEnclaves_Root-G1.pem", @@ -194,11 +200,6 @@ precedence = "override" # Generated files -[[annotations]] -path = "dstack/kms/auth-eth/typechain-types/**" -SPDX-FileCopyrightText = "NONE" -SPDX-License-Identifier = "CC0-1.0" - [[annotations]] path = "**/*.lock" SPDX-FileCopyrightText = "NONE" diff --git a/docs/amd-sev-snp.md b/docs/amd-sev-snp.md index d2ebe8139a..569fb5d8a0 100644 --- a/docs/amd-sev-snp.md +++ b/docs/amd-sev-snp.md @@ -1,8 +1,9 @@ # AMD SEV-SNP Support This document describes how dstack uses AMD SEV-SNP on self-hosted bare-metal -systems. AMD SEV-SNP support is currently **experimental**; Intel TDX remains -the production bare-metal path. +systems. SEV-SNP instances in public clouds are not supported yet: dstack +recomputes the launch measurement itself, which needs control of the launch, +and AWS signs its reports with a VLEK, which the verifier rejects. For platform firmware, kernel, QEMU, and OVMF preparation, start with [Hardware Enablement](./hardware-enablement.md). This document covers the @@ -25,7 +26,7 @@ Guest OS releases are split at the monorepo boundary: under tags such as `guest-os-v0.6.0`. The 0.5.x images are legacy TDX images, not the current unified SEV-SNP image -line. Use a 0.6.0-or-later image for SEV-SNP. The image must include +line. Use a 0.6.6-or-later image for SEV-SNP. The image must include `digest.txt`, `sha256sum.txt`, and the SNP measurement material. ## Host requirements @@ -50,20 +51,55 @@ preflight does not replace firmware, kernel, QEMU, or OVMF validation. ## Install dstack on an SNP host -Pull a current unified image and select the platform explicitly: +Use a release containing the `sev-snp` key provider in the guest OS and VMM. The +KMS container and client attestation verifiers must recognize the new provider +metadata. Set `VERSION` to the OS release version and `KMS_IMAGE` to the KMS +container reference, then install: ```bash -VERSION=0.6.0 sudo dstackup image pull --version "$VERSION" -sudo dstackup install --platform amd-sev-snp --image "dstack-$VERSION" +sudo dstackup install --platform amd-sev-snp \ + --image "dstack-$VERSION" --kms-image "$KMS_IMAGE" sudo dstackup status ``` -The default `--platform auto` mode also selects SEV-SNP when the host CPU flags -advertise `sev_snp`. Explicit selection is preferable while commissioning a -host because it fails immediately when the required SNP device is absent. +Confirm that installation reports `booted` for the KMS CVM. `dstackup` selects +the `sev-snp` provider for the KMS CVM on AMD hosts. The default +`--platform auto` also detects SEV-SNP from the host CPU flags. Explicit +selection checks for the required SNP device before installation. Review the +[KMS key-release policy](#kms-key-release-policy) before serving applications. -Unlike the TDX path, SEV-SNP does not use the local SGX key provider. +## Run KMS with persistent local keys + +The `sev-snp` provider lets a KMS CVM recover its encrypted disk and stored KMS +roots after restart on the same AMD hardware. For a manually managed KMS CVM, +set this field in its app-compose document: + +```json +{"key_provider": "sev-snp"} +``` + +The deployment CLI also accepts `dstack deploy --key-provider sev-snp`. Application +CVMs continue using `key_provider: kms` and the existing KMS API. + +The guest derives a seed through `SNP_GET_DERIVED_KEY` using legacy VCEK at +VMPL0. The seed binds to launch measurement, guest policy, HOST_DATA, launch +identity, and a pinned TCB. The guest requires debugging disabled and encrypted +storage, and verifies the configuration binding before deriving the seed. + +Before initializing a new disk, the guest persists public derivation parameters +in `.instance_info` through the host API. Preserve this file, the encrypted +disk, and the original launch configuration together. Missing parameters for +an existing disk, unknown versions, or derivation/unlock failures stop startup. + +Recovery requires the original hardware and bound launch inputs. For OS or +compose changes, or hardware replacement, preserve KMS roots through the +existing onboarding/replication flow. Firmware updates must support the stored +derivation TCB and satisfy attestation policy. + +The entire KMS CVM, including its OS, is trusted. Protect KMS root and sealing +keys by keeping the KMS OS and workload under operator control. Application +key release continues to follow the existing KMS authorization policy. ## Attestation and image identity @@ -82,23 +118,87 @@ Verification is fail-closed and includes: 5. the unified OS image identity, `sha256(sha256sum.txt)`, which must match `digest.txt` and the SNP measurement document. -For a GPU VM, the optional `MrConfigV3.gpu_policy_hash` field contains -`SHA-256(JCS(requirements.gpu_policy))`. The signed SNP report binds the exact -MrConfigV3 document through `HOST_DATA`, so a verifier can validate the report -and document binding and then compare this field with the expected GPU policy -digest. If the field is absent, this optional check is not asserted. This binds -the GPU policy, but not the later `gpu-attestation` runtime event or the -boot-time GPU evidence returned by `/v1/Attest`: the current SEV-SNP path has -no quote-bound runtime measurement register. +GPU workloads get the same boot-time guarantee as on TDX. Before key +provisioning, the guest attests every attached NVIDIA GPU, applies the app's +`requirements.gpu_policy`, and stops boot if either fails. The SNP report proves +this gate ran under that policy: the launch `MEASUREMENT` covers the OS that +runs it, and `HOST_DATA` binds the MrConfigV3 `compose_hash` that fixes the +policy. GPU launches also carry the policy digest, +`SHA-256(JCS(requirements.gpu_policy))`, as `MrConfigV3.gpu_policy_hash`. + +SEV-SNP has no quote-bound runtime register, so the per-boot `gpu-attestation` +event and the boot-time GPU evidence returned by `/v1/Attest` are not bound to +the report. A verifier that needs a GPU present, or a specific GPU count, must +find that requirement in the measured policy rather than in the event. See +[GPU Threat Model and Lifetime](./security/security-model.md#gpu-threat-model-and-lifetime). The verifier supports the AMD Milan, Genoa, and Turin KDS product families. Bergamo and Siena are handled through AMD's canonical Genoa KDS product path. -`BootInfo.tcb_status` is `UpToDate` only when the current, reported, committed, -and launch TCB versions agree; otherwise it is `OutOfDate`. Authorization -policy should remain strict for non-up-to-date TCB values. The verifier -currently reports an explicit empty advisory-ID list because the SNP report -and VCEK evidence do not directly carry an advisory list. +The verifier also fetches the product family's CRL from KDS +(`//crl`). It requires the CRL to be signed by the pinned ARK +and current, and rejects a revoked ASK. This applies whether the evidence +carries its certificates or the verifier fetches them, so a KDS mirror must +serve the CRL too. The verifier does not yet check the validity periods of the +ASK and VCEK certificates +([#1140](https://github.com/Dstack-TEE/dstack/issues/1140)). + +AMD publishes no TCB status for SNP, so a report is judged against a list of +minimum TCBs, one per CPU. An entry names the CPU by CPUID Fn0000_0001 EAX, as +AMD's security bulletins print it, and gives the highest SVNs those bulletins +require of it; family 1Ah (Turin) entries also set `fmc`. This one is Milan +after AMD-SB-3020 and AMD-SB-3027: + +```json +[{"cpuid":"00a00f11","bootloader":0,"tee":0,"snp":27,"microcode":222}] +``` + +A product family is too coarse a key: Milan (`00a00f11`) and Milan-X +(`00a00f12`) differ only in stepping and carry different microcode SVNs, as do +Genoa (`00a10f11`), Genoa-X (`00a10f12`) and Bergamo/Siena (`00aa0f02`). A +bulletin that lists only a microcode patch level implies the SVN: it is the +level's low byte, as the bulletins that state both show. + +`BootInfo.tcb_status` is `UpToDate` when the reported, committed and launch +TCBs all meet the entry for the report's CPU, and `OutOfDate` when one does +not. The reported TCB is the one the VCEK certifies, and the committed TCB +bounds a firmware rollback. SEV-SNP reports no advisory IDs. `DstackKms` +accepts only `UpToDate` from a KMS instance, as does `DstackApp` with +`requireTcbUpToDate`. + +The KMS reads the list from its auth API when it authorizes an SEV-SNP +attestation, reusing it for a second. Its verdict on its own attestation is +reused for an hour, like the rest of its boot info. Publish the list where the +auth API reads it: + +- With on-chain governance, publish it in `DstackKms` with + `setSevSnpTcbRequirements` (see [On-chain governance](./onchain-governance.md)). +- With `dstack-auth`, list the entries under `sevSnpTcbRequirements` (see + [dstack-auth operations](./dstack-auth-operations.md)). + +A KMS can cover CPUs governance does not list: `sev_snp_tcb_requirements_file` +under `[core.attestation]` names a file with the same JSON, read at startup. +The published list takes precedence: the file decides only for a CPU the +published list has no entry for, and cannot raise or lower a published minimum. +Governance does not see the file, so a KMS that carries one vouches by itself +for the CPUs governance leaves out, its own included. Write the file in the +KMS's compose file, like `kms.toml`, so that it is part of the measurement +governance allows. + +The KMS refuses a request it cannot judge, with the reason, instead of calling +the TCB out of date: when the auth API does not serve the list, when the list +does not parse, when neither list has an entry for the report's CPU, and when +the report predates the CPUID fields (version 2). The dev backend publishes +none, which leaves the KMS's own list. + +`dstack-verifier` does not read the auth API: give it the same JSON in the file +`attestation.sev_snp_tcb_requirements_file` names, which a compose file can +carry inline (see the [verifier README](../dstack/verifier/README.md)). It +reads the file at startup, and reports an empty status without one and for a +CPU without an entry. + +No report field shows firmware that was downgraded and upgraded again +while the guest ran, as long as the committed TCB stayed at the minimum. ## KMS key-release policy @@ -129,9 +229,10 @@ for production TEE deployments. ## AMD KDS collateral -The verifier obtains AMD certificate collateral from the built-in AMD KDS URL -when the attestation evidence does not already contain the required chain. An -operator can set an AMD-KDS-compatible mirror or cache: +The verifier obtains the ASK and VCEK from the built-in AMD KDS URL when the +attestation evidence does not already contain them, and always fetches the +product family's CRL from it. An operator can set an AMD-KDS-compatible mirror +or cache, which must also serve `/crl`: ```toml [core] @@ -150,11 +251,15 @@ AMD signatures. - **The guest resets before Linux starts:** verify that the selected QEMU, OVMF, and unified dstack OS image all support SNP. Do not debug KMS policy until the guest boots reliably. -- **Image identity files are missing:** use a 0.6.0-or-later unified image. +- **Image identity files are missing:** use a 0.6.6-or-later unified image. `dstackup install` rejects an SNP image without `digest.txt`. - **KDS requests fail:** check host time, DNS, outbound HTTPS, and KDS or mirror availability. Do not disable certificate or signature verification. - **Attestation succeeds but key release fails:** check both the external auth response and `core.sev_snp_key_release`; either gate can deny the request. -- **TCB is `OutOfDate`:** update platform firmware and re-evaluate the reported, - committed, current, and launch TCB versions before changing auth policy. +- **TCB is `OutOfDate`:** the TCB is below the minimum published for its CPU. + Update the platform firmware before changing the auth policy. +- **`no minimum TCB is listed for CPUID ...`:** publish an entry for that CPU. + The error names the `cpuid` the entry needs. +- **`failed to read the SEV-SNP TCB requirements from the auth API`:** the auth + API predates the route, or the contract predates `sevSnpTcbRequirements`. diff --git a/docs/app-key-epochs.md b/docs/app-key-epochs.md new file mode 100644 index 0000000000..5cf3b052b0 --- /dev/null +++ b/docs/app-key-epochs.md @@ -0,0 +1,208 @@ +# Application key epochs + +Application owners can rotate their app's derived keys without rotating KMS root +keys or other apps. This extends SealedEnv (#1528); the PR dependency order is +#1519 → #1517 → #1520 → #1521 → #1528 → application epochs. + +## Authorization and rotation + +`authorizeApp` returns `currentAppEpoch` together with the current root +epoch and its chain hash. `requestedRootEpoch` and `requestedAppEpoch` are +independent `OptionalUint256` values: omitted selects current, explicit zero selects +historical epoch zero. Future epochs are denied through `rejectionReason`. +`authorizeKms` remains separate and uses app epoch zero. + +`DstackApp.currentAppEpoch` starts at zero. Its owner calls +`advanceAppEpoch(expectedCurrentEpoch)` to increment it. The expected value +prevents a stale or retried transaction from advancing twice. Epochs cannot be +rolled back and are limited to uint32. Prepare the next row before advancing, as +with a pending root epoch: approve its materials with `*AtEpoch(N + 1, ...)`, +then call `advanceAppEpoch(N)`, so guests that restart after the advance are +authorized at once. `AdvanceAppEpoch` in `Manage.s.sol` exposes +this operation; `GetAppEpoch` in `Query.s.sol` reads it. Upgrade the app policy +implementation before advancing, and upgrade the KMS/auth backend and guests +before using nonzero epochs. Once the app epoch is nonzero, the legacy +`isAppAllowed` of both `DstackApp` and `DstackKms` refuses, since its callers +derive epoch-zero keys, so the KMS contract calling the app policy must support +epochs before the app epoch advances. The ERC-165 `IAppEpochAuth` capability combines +`currentAppEpoch()` and `authorizeApp(AuthorizationRequest)` in one interface; the +policy returns the same `AuthorizationResult` struct as `DstackKms`. The request +also carries `teeVariant`, the platform name the KMS reports, which +`allowAnyTeeVariant` and `allowedTeeVariants` in `DstackApp` and `DstackKms` +restrict to the platforms listed in `TeeVariantPolicy.sol`; listing a new +platform takes a contract upgrade. Like `allowAnyDevice`, the policy covers every +epoch: which platforms may hold an app's keys is a trust decision, not a property +of a key generation. Legacy policies +without this capability remain at zero; failures of an advertised getter propagate. + +The Ethereum auth backends query the policy through the KMS contract. The simple +backend reads `apps[appId].currentAppEpoch` (default zero); operators must preserve +its monotonicity. Public encryption-key lookup uses `GET /app/:appId` to read this +value. With `APP_AUTH_URL` unset, auth-eth reads it at the `latest` block, so a +new app gets its key at once and an advanced epoch never hands out the retired +key. When `APP_AUTH_URL` is set, that service answers `GET /app/:appId` and owns +the epoch's freshness, and key release takes the app epoch from the delegate's +`currentAppEpoch` — the KMS only range-checks a requested epoch against it — +not from a value read at the policy block. The monotonicity requirement moves +with it: auth-eth only range-checks the delegate's epoch, so a delegate that +goes back an epoch, through a restore or a bug, makes environment public-key +lookups and default boots use a retired epoch's keys; delegate operators must +preserve its monotonicity. On the chain path, key release still reads the +policy block, so an +environment sealed to a just-advanced epoch boots only once the advance reaches +that block. Legacy boot authorization and +legacy environment public-key issuance are rejected once the app epoch is nonzero, +preventing old clients from silently continuing with epoch-zero keys. + +## Epoch-scoped allowlists + +Material approvals are an exact `epoch × material` matrix, not a maximum epoch. +Authorization checks only the selected row, with O(1) add, removal and lookup: + +- `DstackKms`: OS images, KMS aggregated measurements and KMS device IDs are + indexed by **root epoch**. OS image limits also apply to app key requests. +- `DstackApp`: compose hashes and device IDs are indexed by **app epoch**. Each + required material must be allowed in the selected row. `allowAnyDevice` is a + single switch over every app epoch: which hosts may run the app is not a + property of a key generation, and a per-epoch switch could leave an older + epoch open to any host after the current one is restricted. + +There is no implicit access in either direction. Rotating keys starts an empty +row; approving a new row neither copies old approvals nor grants historical keys. +Root and app selectors remain independent. Omitted selectors select the current +epochs. For an image handover, explicitly approve the new image in the old row so +it can migrate old keys, approve it in the new row, and remove the old image from +the old row after the handover. The old image never needs access to the new row. + +A request may select any epoch up to the current one and is decided on that +epoch's row, so a value is revoked only once every row allowing it is cleared. +Neither contract has epoch-less material setters: +`*AtEpochs(fromEpoch, toEpoch, material)` changes every row in the range, and in +`DstackApp` `*AtEpoch(epoch, material)` one row (in `DstackKms`, pass the epoch +twice). One transaction revokes a value from all rows, with +`remove*AtEpochs(0, latest, …)` in `DstackKms` and +`remove*AtEpochs(0, currentAppEpoch, …)` in `DstackApp`. `DstackKms` writes +registered root epochs (before any is registered, only epoch zero); `DstackApp` +writes app epochs up to the next one. +`DstackApp` reports these setters as the ERC-165 interface +`IAppEpochManagement` and no longer reports `IAppAuthBasicManagement` +(`0x8fd37527`), whose epoch-less setters it removed. The scripts in +`Manage.s.sol` take `ROOT_EPOCH` or `APP_EPOCH` for one row, or +`FROM_ROOT_EPOCH`/`TO_ROOT_EPOCH` and `FROM_APP_EPOCH`/`TO_APP_EPOCH` for a range, +and fail without them. + +App policies deployed before app epochs (v0.5.x, v0.6.0) keep working with an +upgraded `DstackKms` and KMS: they report no `IAppEpochAuth`, so `authorizeApp` +asks their `isAppAllowed` and only for app epoch zero, and `currentAppEpoch` +reports zero for them. Their owners keep the epoch-less setters until they +upgrade, which `Manage.s.sol` detects and uses with no epoch or `APP_EPOCH=0`. +Upgrading keeps their allowlists as app epoch zero. See +[onchain-governance.md](./onchain-governance.md#apps-deployed-before-app-epochs). + +Disk and environment migration after a root rotation fetches the keys of the +recorded epoch, so a new image migrating old data must be allowed in that old +row too. Without it the guest stops with an error naming the root and app epoch +it could not get keys for. + +The `*AtEpoch` getters read the selected row, including legacy epoch zero. +`EpochPolicyChanged` events include the row and the resulting permission. Legacy +bool getters and events describe **epoch zero only**; changing a nonzero row does +not change its legacy bool or emit a misleading legacy material event. The +exception is `allowAnyDevice` and its `AllowAnyDeviceSet` event, which cover every +app epoch. +Root policy rows from epoch 1 belong to the epoch's registration, so a row can +be written only once the epoch is registered (register, prepare the row, then +activate). A popped epoch's rows do not carry over: the next registration of the +number starts with empty rows, even with the same keys, which must be prepared +again before activation. Epoch 0 keeps the legacy mappings. + +### KMS keyring handover + +Keyring handover is deliberately different from app key access: approval in the +**highest exported root epoch** authorizes the entire keyring, including all older +roots. The KMS passes that epoch explicitly to `authorizeKms`, so approval in the +current row cannot accidentally authorize a newer pending keyring. A registered +pending root may be authorized for KMS handover before activation; app key requests +still cannot select it. KMS self-authorization without a selector continues to +check the active root epoch. The source checks `kms_import_keys` for the recipient, and the recipient +checks `kms_export_keys` for the source, both at the highest transferred epoch. +This permits staged key distribution without changing which epoch the KMS serves. + +### Upgrading existing proxies + +The original bool mappings and `allowAnyDevice` retain their storage locations and +are used directly as row zero. New storage consumes storage-gap slots in each +contract (seven in `DstackKms`, four in `DstackApp`); no entries are copied and no reinitializer is required. Existing +owners, pending owners, policy flags, root registries and app epoch counters are +preserved. Even if the pre-upgrade counter is nonzero, old global material +approvals grant only row zero after upgrading: explicitly populate the intended +nonzero rows. `allowAnyDevice` keeps covering every app epoch. + +Upgrade the KMS policy before app policies, then approve the intended rows before +restarting guests or activating a new root. `DstackApp` advertises the optional +ERC-165 `IAppEpochAuth` capability. `DstackKms.authorizeApp` first applies the +checks it owns (operation scope, registered root epoch, requested root epoch not +beyond the current one, app registration, OS image at the selected root epoch, +deployed contract), then forwards the request unchanged to the policy's +`authorizeApp`. The policy validates the operation and the requested app epoch and +fills `authorized`, `rejectionReason` and `currentAppEpoch`; the KMS then sets +`gatewayAppId` and the current and latest root epoch fields. The decision and +its app epoch therefore come from one policy call. Its interface ID is the XOR of +both method selectors; policies advertising only either former single-method +interface must upgrade to the combined interface. Policies without that capability can only +authorize app epoch zero; failures of an advertised method propagate instead of +falling back. +Direct legacy app checks use the current app epoch; legacy KMS app authorization +still rejects nonzero app epochs. + +These material matrices are implemented by the Solidity policies. Config-file auth +backends such as dstack-auth retain their own policy model; dstack-auth applies the +same epoch limits, accepting a registered pending root epoch for KMS handover and +only active epochs for key-issuing operations. + +## Derivation and lifetime + +Every key is identified by `(root_epoch, app_epoch)`. App epoch zero keeps existing derived keys and app-key signatures. Nonzero app epochs append +`"app-epoch-v1:" || app_epoch[4, big-endian]` to the existing derivation context +for disk, environment, SealedEnv, app CA and secp256k1 keys. + +The root signature for a nonzero app secp256k1 key signs Keccak256 of +`"dstack-kms-issued-v2:" || app_id[20] || app_epoch[4, big-endian] || public_key[33]`. +Relying parties must verify this format against the trusted root key for the +returned root epoch. Epoch zero keeps the original `dstack-kms-issued` format. + +Restart CVMs after advancing the policy. A running CVM continues to use its boot +key pair; omitted guest-agent GetKey selectors mean that CVM's boot epochs, not a +fresh chain lookup. Explicit historical requests select each dimension +independently and cache by the complete pair. Historical requests must be approved +in the selected root/app rows. Revoking one row does not revoke other rows or +keys already delivered. Supplied `trusted_ca` always pins the KMS connection, +regardless of epoch selection; historical responses cannot replace that pin. + +The guest migrates disk headers and environment ciphertext if either dimension +changes and rejects future epochs in either dimension. Disk migration also +requires `requirements.unsafe_allow_disk_migration` in the app compose, which is +strongly discouraged; see +[the emergency rotation protocol](kms-emergency-key-rotation-protocol.md#5-os-slot-migration-and-luks-header-metadata). LUKS tokens record both +epochs (missing app epoch means zero). Rekeying replaces the keyslot wrapping key; +it does not rotate the volume encryption key or erase host snapshots. Once a disk +header carries an epoch token, older guest images reject that header as malformed; +reverting the VM image therefore requires migrating the disk with a compatible +image or restoring a compatible header backup. App rotation isolates future app +keys from an exposed old derived key, but cannot recover from compromise of the +KMS root or revoke already disclosed secrets. + +## SDK selection + +Both selectors are optional; specify zero explicitly to recover an old key. +For example, Python `client.get_key("storage", "secp256k1", root_epoch=3, +app_epoch=0)` selects exactly that pair. JavaScript uses +`client.getKey("storage", "secp256k1", 3, 0)`. Rust uses +`client.get_key(GetKeyConfig::builder().domain("storage").algorithm("secp256k1").root_epoch(3).app_epoch(0).build())`. +Go provides `GetKeyAtEpochs` with pointer selectors. Responses report both epochs. + +Sealing helpers (`seal_env`, `SealEnv`, `sealEnv`) and the SealedEnv public-key +verifiers take both epochs, with no default: they work offline and cannot know +the current epochs, so pass the ones `GetSealedEnvPubKey` returned with the key. See [SealedEnv](sealed-env.md) for the wire and signature +formats. The VMM UI and CLI use the epochs returned with the encryption key. SealedEnv +uses a single version-1 format that always includes both epochs. diff --git a/docs/auth-simple-operations.md b/docs/auth-simple-operations.md deleted file mode 100644 index 6b8826d8f9..0000000000 --- a/docs/auth-simple-operations.md +++ /dev/null @@ -1,302 +0,0 @@ -# auth-simple Operations Guide - -> **This guide is for self-hosted deployments** on your own TDX hardware. For cloud deployments, see [Quickstart](./quickstart.md). - -This guide covers day-to-day operations for managing apps and devices with auth-simple. - -For initial deployment setup, see [Deployment Guide](./deployment.md). - -## Overview - -auth-simple uses a JSON config file to whitelist: -- **OS images** - Which guest OS versions can boot -- **KMS nodes** - Which KMS instances can onboard (mrAggregated, devices) -- **Apps** - Which applications can boot (appId, composeHash, devices) - -The config is re-read on each request, so changes take effect immediately without restart. - ---- - -## Config File Structure - -```json -{ - "osImages": ["0x..."], - "gatewayAppId": "0x...", - "kms": { - "mrAggregated": ["0x..."], - "devices": ["0x..."], - "allowAnyDevice": true - }, - "apps": { - "0x": { - "composeHashes": ["0x..."], - "devices": ["0x..."], - "allowAnyDevice": true - } - } -} -``` - -> **Note:** `osImages` is always required. For KMS authorization, you must also populate `kms.mrAggregated`; if it is left empty, auth-simple denies all KMS boots. Add `gatewayAppId` after deploying the Gateway. Add `apps` entries as you deploy applications. - ---- - -## Adding an App - -### Step 1: Generate App ID - -App IDs are typically the contract address (for on-chain) or a unique identifier you choose. - -For auth-simple, you can use any unique hex string (40 characters / 20 bytes): - -```bash -# Generate a random app ID -openssl rand -hex 20 -# Output: 7a3b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b -``` - -### Step 2: Get Compose Hash - -The compose hash is computed from the normalized docker-compose file. The VMM displays it when deploying: - -``` -Docker compose file: -... -Compose hash: 0x700a50336df7c07c82457b116e144f526c29f6d8... -``` - -Or query from a running CVM: - -```bash -curl -s --unix-socket /var/run/dstack.sock http://localhost/Info | \ - jq -r '"0x" + (.tcb_info | fromjson | .compose_hash)' -``` - -> **Note:** The VMM normalizes YAML to JSON before hashing. For exact hash, use the value shown during deployment. - -### Step 3: Add to Config - -Edit your `auth-config.json`: - -```json -{ - "apps": { - "0x7a3b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b": { - "composeHashes": [ - "0x700a50336df7c07c82457b116e144f526c29f6d8..." - ], - "devices": [], - "allowAnyDevice": true - } - } -} -``` - -### Step 4: Deploy via VMM - -Use the App ID when deploying through VMM: - -```bash -./vmm-cli.py deploy \ - --app-id 7a3b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b \ - --compose docker-compose.yaml \ - ... -``` - ---- - -## Updating an App - -When you change your docker-compose.yaml, a new compose hash is generated. - -### Add New Hash (Keep Old Running) - -Add the new hash to the `composeHashes` array: - -```json -{ - "apps": { - "0x": { - "composeHashes": [ - "0x", - "0x" - ] - } - } -} -``` - -### Replace Hash (Force Upgrade) - -Remove the old hash to prevent old versions from booting: - -```json -{ - "apps": { - "0x": { - "composeHashes": [ - "0x" - ] - } - } -} -``` - ---- - -## Device Management - -Devices are identified by their TDX device ID (hardware-specific). - -### Get Device ID - -The `deviceId` is sent by the booting app/KMS in its auth request. Check auth-simple logs: - -``` -app boot auth request: { appId: '0x...', deviceId: '0x...', ... } -``` - -> **Tip:** Use `allowAnyDevice: true` initially, then restrict to specific devices after capturing IDs from logs. - -### Restrict App to Specific Devices - -```json -{ - "apps": { - "0x": { - "composeHashes": ["0x..."], - "devices": [ - "0xe5a0c70bb6503de2d31c11d85914fe3776ed5b33a078ed856327c371a60fe0fd" - ], - "allowAnyDevice": false - } - } -} -``` - -### Allow Any Device - -For initial testing or when device restriction isn't needed: - -```json -{ - "apps": { - "0x": { - "allowAnyDevice": true - } - } -} -``` - ---- - -## Removing an App - -Delete the app entry from the `apps` object: - -```json -{ - "apps": { - // "0x": { ... } <- deleted - } -} -``` - -Running instances will continue until restarted. New boot requests will be rejected. - ---- - -## Setting the Gateway App (After Gateway Deployment) - -The `gatewayAppId` field is **optional** during initial KMS deployment. Add it after deploying the Gateway. - -The Gateway is a special app that routes traffic to other apps. Once deployed, add its App ID to your config: - -```json -{ - "gatewayAppId": "0x75537828f2ce51be7289709686A69CbFDbB714F1", - "apps": { - "0x75537828f2ce51be7289709686A69CbFDbB714F1": { - "composeHashes": ["0x..."], - "allowAnyDevice": true - } - } -} -``` - -The `gatewayAppId` is returned in boot responses and used by KMS for key derivation. - -To trust several gateways, join their App IDs with commas (`"0xaaa...,0xbbb..."`). CVMs accept a gateway whose App ID is contained in this value. - ---- - -## KMS Onboarding (Multi-Node) - -To allow additional KMS nodes to onboard (receive root keys from the primary KMS), whitelist their `mrAggregated` value. - -### Get mrAggregated - -The `mrAggregated` is sent by the booting KMS in its auth request. To get this value: - -1. **From auth-simple logs**: When a KMS boots, auth-simple logs the mrAggregated: - ``` - KMS boot auth request: { osImageHash: '0x...', mrAggregated: '0x...', ... } - ``` - -2. **Initial setup**: capture the first KMS measurement with `Onboard.GetAttestationInfo` or from auth logs, then add it to `kms.mrAggregated` before bootstrap. An empty array now denies all KMS boots. - -### Add to Config - -```json -{ - "kms": { - "mrAggregated": ["0x"], - "allowAnyDevice": true - } -} -``` - -> **Note:** All KMS nodes using the same OS image and compose will have the same mrAggregated, so you only need to capture it once. - ---- - -## Verification - -### Check Config is Valid - -```bash -curl -s http://localhost:3001/ | jq -``` - -Returns current config status including `gatewayAppId`. - -### Test Boot Authorization - -```bash -# Test app boot -curl -s -X POST http://localhost:3001/bootAuth/app \ - -H "Content-Type: application/json" \ - -d '{ - "appId": "0x", - "composeHash": "0x", - "osImageHash": "0x", - "deviceId": "0x", - "mrAggregated": "0x...", - "instanceId": "0x...", - "tcbStatus": "UpToDate" - }' | jq -``` - -Expected responses: -- `{"isAllowed": true, ...}` - App is authorized -- `{"isAllowed": false, "reason": "app not registered", ...}` - App ID not in config -- `{"isAllowed": false, "reason": "compose hash not allowed", ...}` - Hash not whitelisted - ---- - -## See Also - -- [Deployment Guide](./deployment.md) - Initial setup -- [auth-simple README](../dstack/kms/auth-simple/README.md) - Developer reference -- [On-Chain Governance](./onchain-governance.md) - Smart contract-based alternative diff --git a/docs/aws-attested-instance-security-evaluation.md b/docs/aws-attested-instance-security-evaluation.md index 7dbbb38412..42703390b4 100644 --- a/docs/aws-attested-instance-security-evaluation.md +++ b/docs/aws-attested-instance-security-evaluation.md @@ -38,11 +38,11 @@ NitroTPM path meets them today. | P4 | Runtime application identity is cryptographically bound | RTMR3 `compose-hash`, `app-id`, `instance-id`, `key-provider`; event log replay | SHA384 `PCR14` event-log replay is the authoritative binding (RTMR3 analogue; non-resettable). Launch events: `system-preparing`, `app-id`, `compose-hash`, zero or more ordered `init-script-hash` events, `instance-id`, `boot-mr-done`, `key-provider`, `storage-fs`, `storage-encrypted`, `system-ready` (`dstack/dstack-util/src/system_setup.rs`). GPU launches also include `gpu-policy-hash` before `instance-id`, and `gpu-attestation` after `boot-mr-done` and before `key-provider`. `dstack-attest`, `dstack-verifier`, and KMS reject missing/mismatched PCR14 and bad replay. Optionally, the guest extends the raw `MrConfig` V2 `config_id` into `PCR8` once (`PCR8 = sha384(0^48 || config_id)`) so a lightweight third-party verifier can check compose hash + key provider without event-log replay; dstack's own verifier and KMS do not check PCR8. | | P5 | Challenge/liveness and caller key binding | `report_data` challenge or RA-TLS public key hash in quote | RA-TLS binds `report_data` to the TLS certificate public key. KMS key release is bound to the live RA-TLS handshake; external `/verify` callers supply and check their own `report_data` challenge. The low-level NitroTPM document verifier also rejects stale or far-future document timestamps. | | P6 | Secret release only to attested code | dstack KMS verifies attestation, checks auth policy, derives per-app keys | dstack KMS verifies the NitroTPM attestation, runs the same `verify_os_image_hash_for_aws_nitro_tpm` binding check as the verifier, builds `BootInfo` from verified boot PCRs plus PCR14 launch events, and checks auth policy before deriving app keys (`dstack/kms/src/main_service.rs`). AWS NitroTPM key release is gated behind the opt-in `aws_nitro_tpm_key_release` flag (default false in `kms.toml`). | -| P7 | Key-release policy is not controlled by the untrusted account admin | KMS runs inside TEE; policy from auth API/contracts; KMS identity measured | Satisfied with dstack KMS or another verifiable secret authority outside the untrusted AWS account admin's control. A NitroTPM-backed dstack KMS keeps root material out of account-admin snapshots and clones. The policy backend (auth-simple in a trusted control plane, or on-chain `DstackKms`/`DstackApp`) must be outside the workload account admin's control. Same-account AWS KMS fails this property if the admin can change key policy, create grants, or call secret-bearing operations through a policy they control. | +| P7 | Key-release policy is not controlled by the untrusted account admin | KMS runs inside TEE; policy from auth API/contracts; KMS identity measured | Satisfied with dstack KMS or another verifiable secret authority outside the untrusted AWS account admin's control. A NitroTPM-backed dstack KMS keeps root material out of account-admin snapshots and clones. The policy backend (on-chain `DstackKms`/`DstackApp` or an equivalent service; dstack-auth is for development, testing and evaluation only) must be outside the workload account admin's control. Same-account AWS KMS fails this property if the admin can change key policy, create grants, or call secret-bearing operations through a policy they control. | | P8 | Operator cannot inject boot-time or runtime inputs that affect secrets without detection | Host-shared files are measured or independently authenticated; KMS URLs not trusted, KMS key identity measured | App TPM access is enforced by measurement, not by a container sandbox: `init_script`, `pre_launch_script`, and the docker-compose are measured into the app-compose hash, hence into the governed app identity, and replayed into non-resettable `PCR14`, so an operator cannot alter app inputs without changing the measured identity and being denied key release. Production dstack-os AWS images exclude SSH, cloud-init, SSM, EC2 Instance Connect, and serial login (checked by `audit-aws-ec2-image-hardening.sh`). IMDS/operator-provided config must not be a secret-affecting input unless measured or authenticated. | | P9 | Persistent state confidentiality from account admin | dstack disk key derived after attestation; encrypted env vars decrypted only inside CVM | The local TPM key provider seals the disk seed under a SHA384 PCR policy over `[4, 7, 8, 12, 14]` (`AWS_NITRO_PCRS` in `dstack/tpm-attest/src/lib.rs`), so the sealed seed survives same-instance stop/start but does not transfer with cloned EBS volumes to another instance. EBS snapshots and volumes remain account-admin visible at the AWS control plane, so persisted confidential state must stay encrypted inside the instance and AMIs must contain no secrets. | | P10 | Network and TLS endpoint identity is attestation-bound | RA-TLS / Zero Trust HTTPS / gateway attestation; TLS keys generated in TEE | The Rust RA-TLS verifier exposes `verify_der`/`verify_pem`, which extract the certificate's embedded attestation, verify it with the platform verifier (including AWS NitroTPM), and require `report_data = QuoteContentType::RaTlsCert(SubjectPublicKeyInfo)`. `dstack-verifier --verify-cert` provides an operator/relying-party certificate evidence path that also binds `os_image_hash`. AWS attestation alone does not protect DNS, load balancers, or admin-controlled proxies; clients must require this RA-TLS check, signed responses, or an attested gateway. | -| P11 | Upgrade governance is explicit and non-bypassable | DstackApp/DstackKms whitelists compose hashes, OS images, KMS aggregate MRs | auth-simple and the unchanged on-chain `DstackKms`/`DstackApp` contracts pin OS image hash, app compose hash, device ID, and KMS identity. KMS auth pins the early `mrAggregated` (the `boot-mr-done` launch-event snapshot). AWS reuses the standard gate via `tcbStatus = "UpToDate"` normalization with no AWS-specific on-chain field, plus the opt-in `aws_nitro_tpm_key_release` KMS flag. Secure Boot PCR7 certificate policies need explicit rotation/revocation handling so old AMIs do not remain authorized. | +| P11 | Upgrade governance is explicit and non-bypassable | DstackApp/DstackKms whitelists compose hashes, OS images, KMS aggregate MRs | dstack-auth and the unchanged on-chain `DstackKms`/`DstackApp` contracts pin OS image hash, app compose hash, device ID, and KMS identity. KMS auth pins the early `mrAggregated` (the `boot-mr-done` launch-event snapshot). AWS reuses the standard gate via `tcbStatus = "UpToDate"` normalization (dstack-auth enforces it once `allowedTcbStatuses: ["UpToDate"]` is set) with no AWS-specific on-chain field, plus the opt-in `aws_nitro_tpm_key_release` KMS flag. Secure Boot PCR7 certificate policies need explicit rotation/revocation handling so old AMIs do not remain authorized. | | P12 | Verifier is independent and complete | `dstack-verifier`, DCAP/QVL, RTMR replay, KMS/app/governance checks | `dstack-verifier` verifies the NitroTPM document against the AWS Nitro PKI, enforces the required `aws_measurement`/`boot_pcr_digest` binding against the unified `os_image_hash`, replays the PCR14 launch-event chain, and emits the canonical auth-policy object as `details.boot_info` for the same policy logic used by `/bootAuth/app` and `/bootAuth/kms`. The relying-party deployment workflow is `docs/aws-ec2-production-verifier-runbook.md`; each deployment must instantiate it with real OS-image, PCR, and compose-hash allowlists. | ## Sources diff --git a/docs/aws-ec2-production-verifier-runbook.md b/docs/aws-ec2-production-verifier-runbook.md index d43fc37195..de64f1481f 100644 --- a/docs/aws-ec2-production-verifier-runbook.md +++ b/docs/aws-ec2-production-verifier-runbook.md @@ -18,8 +18,9 @@ and endpoint identity. - The dstack monorepo sources pinned at the exact release revision, for the reproducible rebuild. - A dstack verifier built from this repository. -- The production auth policy backend: `auth-simple`, auth-eth contracts, or an - equivalent verifier-controlled service. +- The production auth policy backend: auth-eth contracts or an equivalent + verifier-controlled service. `dstack-auth` is for development, testing and + evaluation only. - For public services, the endpoint's RA-TLS certificate. ## 1. Verify Release Evidence @@ -198,7 +199,7 @@ The relying party should then check `details.boot_info` against its auth policy. For AWS NitroTPM, the policy must require: -- accepted `tcbStatus` (`UpToDate` by default, matching the normalized value); +- accepted `tcbStatus` (`UpToDate`, matching the normalized value); - accepted `osImageHash` (unified `sha256(sha256sum.txt)`; `aws_measurement` is required and must bind the attested boot PCRs); - accepted app `composeHash` and `appId`; @@ -209,6 +210,33 @@ For AWS NitroTPM, the policy must require: `instance-id`, `key-provider`); - a `report_data` challenge for external verifier flows that need liveness. +When evaluating with `dstack-auth`, note that the TCB status and advisories are +checked only when the allowlist sets them, so set both explicitly: + +```json +{ + "allowedTcbStatuses": ["UpToDate"], + "allowedAdvisoryIds": [], + "osImages": ["0x"], + "kms": { + "mrAggregated": ["0x"], + "devices": [], + "allowAnyDevice": true + }, + "apps": { + "0x": { + "composeHashes": ["0x"], + "devices": [], + "allowAnyDevice": true + } + } +} +``` + +dstack-auth authorizes the canonical `BootInfo` the KMS derives after verifying +the NitroTPM evidence; it does not verify raw NitroTPM evidence itself. See +[dstack-auth operations](./dstack-auth-operations.md) for the remaining fields. + For GPU workloads, PCR14 also contains `gpu-policy-hash` immediately after `compose-hash`. Its 32-byte payload must equal `SHA-256(JCS(requirements.gpu_policy))`, using `{}` when the policy is omitted. diff --git a/docs/building-guest-os.md b/docs/building-guest-os.md index 4521380ebb..0388596c1c 100644 --- a/docs/building-guest-os.md +++ b/docs/building-guest-os.md @@ -105,8 +105,7 @@ The bare-metal archive includes the kernel, initramfs, OVMF firmware, partitioned dm-verity rootfs, platform measurement CBOR files, `sha256sum.txt`, `digest.txt`, and `metadata.json`. The UKI archive includes the bootable `disk.raw` plus its identity and measurement files. The -kernel-devel archive is the build tree for out-of-tree modules; it is not part -of the image identity (see below). +kernel-devel archive holds the build trees for out-of-tree modules (see below). Inspect and verify an archive with: @@ -132,13 +131,20 @@ and records `"is_dev": true` in `metadata.json`. ## Kernel headers for out-of-tree modules -Each release publishes the guest kernel's build tree for building out-of-tree -modules: - -- `dstack--kernel-devel.tar.gz`, the exported build tree, and -- `ghcr.io/dstack-tee/dstack-kernel-builder:`, the same tree plus a +The guest rootfs ships the kernel's build tree at +`/usr/src/linux-headers-`, linked from +`/lib/modules//build`, so tools that compile against the running +kernel (for example eBPF tooling) find it at the usual Debian location when it +is bind-mounted into a container. Beside it, `/usr/src/nvidia-` holds +the interface headers and `Module.symvers` of the NVIDIA open modules the image +loads, in the open-gpu-kernel-modules layout, for modules that call into +`nvidia.ko`. Both trees are also published for building out-of-tree modules +outside the CVM: + +- `dstack--kernel-devel.tar.gz`, the exported trees, and +- `ghcr.io/dstack-tee/dstack-kernel-builder:`, the same trees plus a compiler from the pinned Debian snapshot the kernel was built with, with - `KDIR` set. + `KDIR` and `NVIDIA_HEADERS` set. ```dockerfile FROM ghcr.io/dstack-tee/dstack-kernel-builder: AS kmod @@ -149,11 +155,16 @@ FROM alpine COPY --from=kmod /src/mymod.ko /opt/ ``` +A module that calls into `nvidia.ko` also takes its include directories from +`$NVIDIA_HEADERS` and passes +`KBUILD_EXTRA_SYMBOLS=$NVIDIA_HEADERS/kernel-open/Module.symvers`, without which +modpost rejects its references to the driver's symbols. + To build the image locally from a release archive, run `os/image/kernel-builder/build.sh `. -Neither artifact is part of `sha256sum.txt`, so they do not affect -`os_image_hash`. A module loaded by an application (which needs +The in-image trees are part of the dm-verity rootfs and therefore of +`os_image_hash`; the two release artifacts are not in `sha256sum.txt`. A module loaded by an application (which needs `CAP_SYS_MODULE`) is covered by the container image digest and therefore the compose hash, but it is not measured separately and dstack does not enforce module signatures. diff --git a/docs/confidential-ai.md b/docs/confidential-ai.md index f418b805fd..56fd3c1130 100644 --- a/docs/confidential-ai.md +++ b/docs/confidential-ai.md @@ -12,7 +12,7 @@ The key difference from self-hosting: users don't have to trust you. They can cr ## What Makes It Confidential -Four things need to be true for the system to be actually confidential: +Four protections keep data confidential: **TLS terminates inside the VM.** Your HTTPS connection ends inside the Confidential VM, not at some load balancer outside. The operator never sees plaintext traffic. @@ -22,7 +22,31 @@ Four things need to be true for the system to be actually confidential: **Disk is encrypted.** Anything written to storage uses keys derived from the TEE. The storage backend only sees ciphertext. -When all four are in place, data stays encrypted from network ingress to egress. +Attestation lets you verify which application handles that data. You can use CPU attestation to check that the deployed application configuration matches the one you reviewed. See [how attestation works](#how-attestation-works). + +## How Attestation Works + +The application runs in a confidential VM and uses the NVIDIA driver inside that VM to send work to the GPUs. CPU attestation lets you check the VM's software, including that driver, and the application configuration. GPU attestation describes the hardware and its confidential-computing state at the time of the check. + +```mermaid +graph LR + CPU["Confidential VM
Application and NVIDIA driver"] -->|submits work| GPU["Confidential GPUs"] + CPUProof["CPU attestation"] -.->|covers software and configuration| CPU + GPUProof["Boot-time GPU attestation"] -.->|covers hardware and protection state| GPU + GPUProof -.->|recorded in launch log| CPUProof +``` + +In a multi-GPU VM, the boot-time check covers every attached GPU. Together, the CPU and GPU evidence let you verify which software submits the work and the GPU protections in place at launch. The check does not prove that the same GPUs stay attached for the VM's lifetime. + +For the guarantees and their limits, see [GPU Security for AI Workloads](./security/security-model.md#gpu-security-for-ai-workloads). + +### Verifying the Whole Deployment + +A service can show "CPU verified" and "GPU verified" while sending your prompts to an unchecked GPU. For example, the CPU quote could come from a genuine confidential VM and the GPU report from a separate test machine. Even if both reports answer the same fresh challenge (nonce), each still describes its own environment. + +With the default policy, the dstack OS makes GPUs available to the workload only after every attached GPU passes the boot-time check. A failed check stops startup before the workload can receive prompts. On Intel TDX, the result is recorded in the VM's launch log, which the signed CPU quote covers. See [Verification](#verification) for how to check it. + +Your data also needs a protected path to the application you reviewed. If an untrusted proxy terminates TLS outside the VM, it can read your prompts before forwarding them to the confidential workload. Verify where TLS terminates and review how the application handles your data. See [Verification](#verification) and [Phala Cloud domain attestation](https://docs.phala.com/phala-cloud/networking/domain-attestation). ## Private Inference @@ -212,35 +236,14 @@ Full example: [dstack-examples/ai/agents](https://github.com/Dstack-TEE/dstack-e ## Verification -Attestation proves the hardware is genuine and shows what code is running. But it doesn't automatically prove the code is safe—you need to audit it yourself. +You can verify a running deployment before sending it sensitive data. Start by reviewing the application code and configuration. Then verify the CPU attestation and compare the measured application configuration with the one you reviewed. -```mermaid -graph LR - App[Your App] -->|quote| Verifier - Verifier -->|valid + compose_hash| You - You -->|compare| Compose[docker-compose.yaml] - Compose -->|audit| Code[Source Code] -``` - -The verification flow: - -```python -import requests - -# Get attestation with a nonce to prevent replay -attestation = requests.get( - "https://your-app/attestation", - params={"nonce": "random-challenge"} -).json() - -# Compare compose hash against what you reviewed -expected_hash = "sha256:abc123..." # From your audited docker-compose -assert attestation["compose_hash"] == expected_hash -``` +On Intel TDX, the signed CPU quote lets you verify the launch record, including the application configuration hash and dstack's boot-time GPU check. Follow the [Intel TDX attestation guide](./attestation-tdx.md). For other platforms, see the [verification overview](./verification.md#platform-specific-verification). -For visual verification, paste the quote into [proof.t16z.com](https://proof.t16z.com), Phala's TEE attestation explorer that parses TDX quotes and displays the verification status, measurements, and TCB info in a readable format. +For a GPU workload, check two more things, because the default policy also accepts a launch with no GPU: -The compose hash only tells you *what* is running. You still need to verify that code does what you expect—no secret logging, no data exfiltration, proper access controls. +- The reviewed configuration keeps GPU attestation enabled: `requirements.gpu_policy.attest_gpu` is not `false`. A `rego` rule in the same policy can require the expected GPU count. +- The launch record contains exactly one `gpu-attestation` event, and its `devices` count is above zero and matches your deployment. ## Performance diff --git a/docs/deployment.md b/docs/deployment.md index 4f66566684..06872f0c61 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -122,28 +122,39 @@ Production KMS requires: #### Auth Server Options -> **Note:** the boot-authorization webhook below (auth-simple / auth-eth) is a *different* mechanism from the KMS admin-API authentication. The webhook allowlists which CVMs may boot and receive keys; the admin API (`[core.admin]` in `kms.toml`) guards operator RPCs. See [dstack-kms admin authentication](../dstack/kms/README.md#admin-api-authentication). +> **Note:** the boot-authorization webhook below (dstack-auth / auth-eth) is a *different* mechanism from the KMS admin-API authentication. The webhook allowlists which CVMs may boot and receive keys; the admin API (`[listeners.admin]` in `kms.toml`) guards operator RPCs. See [dstack-kms admin authentication](../dstack/kms/README.md#admin-api-authentication). | Server | Use Case | Configuration | |--------|----------|---------------| -| [auth-simple](../dstack/kms/auth-simple/) | Config-file-based whitelisting | JSON config file | -| [auth-eth](../dstack/kms/auth-eth/) | On-chain governance via smart contracts | Ethereum RPC + contract | +| [dstack-auth](./dstack-auth-operations.md) | Config-file-based whitelisting for development, testing and evaluation only | JSON config file | +| [auth-eth](../dstack/kms/auth-eth/) | On-chain governance via the `DstackKms`/`DstackApp` contracts in the same directory | Ethereum RPC + contract | | Custom | Your own authorization logic | Implement webhook interface | All auth servers implement the same webhook interface: -- `GET /` - Health check -- `POST /bootAuth/app` - App boot authorization -- `POST /bootAuth/kms` - KMS boot authorization -#### Using auth-simple (Config-Based) +- `GET /` - Health check and current root epoch +- `POST /authorizeApp` - Application key and certificate authorization +- `POST /authorizeKms` - KMS self-authorization and key handover -auth-simple validates boot requests against a JSON config file. +The legacy `/bootAuth/app` and `/bootAuth/kms` routes remain available for older +clients and KMS bootstrap/onboarding checks. + +#### Using dstack-auth (Config-Based) + +dstack-auth validates requests against a JSON config file. Build it: + +```bash +cd dstack +cargo build --release -p dstack-auth +``` Create `auth-config.json` for initial KMS deployment: ```json { "osImages": ["0x"], + "allowedTcbStatuses": ["UpToDate"], + "allowedAdvisoryIds": [], "kms": { "mrAggregated": ["0x"], "allowAnyDevice": true @@ -152,22 +163,46 @@ Create `auth-config.json` for initial KMS deployment: } ``` -> **Important:** `auth-simple` now treats an empty `kms.mrAggregated` allowlist as deny-all for KMS. Capture the current KMS measurement with `Onboard.GetAttestationInfo` and add it before bootstrap. +> **Important:** an empty `kms.mrAggregated` allowlist denies every KMS. Capture the current KMS measurement with `Onboard.GetAttestationInfo` and add it before bootstrap. -Run auth-simple: +`allowedTcbStatuses` and `allowedAdvisoryIds` are opt-in: without them the TCB +status and advisories are not checked. Keep them unless you operate and trust +the host yourself; see [TCB and advisory policy](./dstack-auth-operations.md#tcb-and-advisory-policy). + +Bootstrap needs only the fields above. Before the KMS serves keys, set +`kmsContractAddr` to the KMS CVM's app ID and register its root keys as +`rootEpochs` (see [Rotating KMS Root Keys](#rotating-kms-root-keys)); every +other operation is denied until both are set. + +Run dstack-auth on the operator host: ```bash -cd dstack/kms/auth-simple -bun install -PORT=3001 AUTH_CONFIG_PATH=/path/to/auth-config.json bun run start +./target/release/dstack-auth --config /path/to/auth-config.json --port 3001 ``` -For adding Gateway, apps, and other config fields, see [auth-simple Operations Guide](./auth-simple-operations.md). +It binds to `127.0.0.1`, which a KMS CVM on QEMU user-mode networking reaches as +`http://10.0.2.2:3001`. Add `--address 0.0.0.0` if the KMS reaches the host over +a real network. + +For adding Gateway, apps, and other config fields, see [dstack-auth Operations Guide](./dstack-auth-operations.md). #### Using auth-eth (On-Chain) For decentralized governance via smart contracts, see [On-Chain Governance](./onchain-governance.md). +auth-eth reads policy at the block `ETH_BLOCK_TAG` names, `finalized` by +default. Only `finalized` protects policy from reorgs. With `latest` (required +for an OP-stack chain read through Helios) or `safe`, a reorg can revert both +activations and revocations: a removed image or compose hash is authorized +again, and a rolled-back root epoch activation makes every KMS restart onto the +previous epoch. `ETH_FINALITY_CONFIRMATIONS=N` hides reorgs shallower than N +blocks but delays every policy change, emergency revocations included, by N +blocks. See [reorgs and the block tag](../dstack/kms/auth-eth/README.md#reorgs-and-the-block-tag). + +Optional `APP_AUTH_URL` leaves KMS policy on `DstackKms` and forwards +`/authorizeApp` and `GET /app/:appId` to another service. The default, leaving +it unset, is unchanged. See [delegated app authorization](../dstack/kms/auth-eth/README.md#delegated-app-authorization). + #### Getting OS Image Hash The OS image hash is in the `digest.txt` file inside the guest image tarball: @@ -179,15 +214,15 @@ cat dstack-0.5.5/digest.txt # Output: 0b327bcd642788b0517de3ff46d31ebd3847b6c64ea40bacde268bb9f1c8ec83 ``` -Add `0x` prefix for auth-simple config: `0x0b327bcd...` +Add `0x` prefix for the dstack-auth config: `0x0b327bcd...` #### Deploy KMS CVM Choose the deployment script based on your auth server: -**For auth-simple (external webhook):** +**For dstack-auth (external webhook):** -auth-simple runs on your infrastructure, outside the CVM. +dstack-auth runs on your infrastructure, outside the CVM. ```bash cd dstack/kms/dstack-app/ @@ -197,7 +232,7 @@ Edit `.env.simple`: ```bash VMM_RPC=http://127.0.0.1:9080 -AUTH_WEBHOOK_URL=http://your-auth-server:3001 +AUTH_WEBHOOK_URL=http://10.0.2.2:3001 KMS_RPC_ADDR=0.0.0.0:9201 GUEST_AGENT_ADDR=127.0.0.1:9205 OS_IMAGE=dstack-0.5.5 @@ -286,7 +321,7 @@ OS_IMAGE=dstack-0.5.5 **Note on hex formats:** - Gateway `.env` file: Use raw hex without `0x` prefix (e.g., `GATEWAY_APP_ID=32467b43...`) -- auth-simple config: Use `0x` prefix (e.g., `"0x32467b43..."`). The server normalizes both formats. +- dstack-auth config: Use `0x` prefix (e.g., `"0x32467b43..."`). The server normalizes both formats. Run the script again: @@ -306,7 +341,7 @@ Continue? [y/N] ``` **Before pressing 'y'**, add the compose hash to your auth server whitelist: -- For auth-simple: Add to `composeHashes` array in `auth-config.json` +- For dstack-auth: Add to `composeHashes` array in `auth-config.json` - For auth-eth: Use Foundry scripts (see [On-Chain Governance](./onchain-governance.md#register-gateway-app)) Then return to the first terminal and press 'y' to deploy. @@ -470,19 +505,40 @@ Additional KMS instances can onboard from an existing KMS to share the same root **How it works:** 1. New KMS starts in onboard mode (empty `auto_bootstrap_domain`) -2. New KMS calls `GetTempCaCert` on source KMS -3. New KMS generates RA-TLS certificate with TDX quote -4. New KMS calls `GetKmsKey` with mTLS authentication -5. Source KMS verifies attestation via `bootAuth/kms` webhook -6. If approved, source KMS returns root keys +2. New KMS generates an RA-TLS client certificate with its attestation: self-issued with an admin token, or signed by the source temporary CA for tokenless legacy onboarding +3. New KMS calls `GetKmsKey` over mTLS: `Admin.GetKmsKey` with the token, or the explicitly enabled public `KMS.GetKmsKey` without one +4. Source KMS verifies the attestation and authorizes handover via `/authorizeKms` +5. If approved, source KMS returns root keys +6. New KMS verifies the source's attestation on that same connection and checks it against its own policy before using the keys 7. Both KMS instances now derive identical keys +**Configure the source KMS for key handover:** + +Every KMS needs this, or `core.onboard.public_key_handover = true`: without a handover path it refuses to start, before onboarding or bootstrap, naming the missing setting. In a public config such as an app compose, set `auth_token_hash` (the token's SHA-256) instead of `auth_token`, with a high-entropy random token (`openssl rand -hex 32`), since the hash can be brute-forced offline. + +`Admin.GetKmsKey` only works on an admin listener with TLS (`[listeners.default.tls]`, or `[listeners.admin.tls]` to override it): without TLS the listener speaks plain HTTP, so the new KMS can present no RA-TLS certificate and the call fails with `No attestation provided`. The admin listener binds to `127.0.0.1` by default; bind it to an address the new KMS can reach and restrict access to the KMS nodes at the network layer. + +```toml +[listeners.admin] +enabled = true +address = "0.0.0.0" # reachable by the new KMS; firewall it to KMS nodes only +port = 8001 +auth_token = "" + +[listeners.default.tls] +key = "/var/lib/kms/certs/rpc.key" +certs = "/var/lib/kms/certs/rpc.crt" +# No `mutual` section: client certificates are verified by their attestation. +``` + **Configure new KMS for onboarding:** ```toml [core.onboard] enabled = true auto_bootstrap_domain = "" # Empty = onboard mode + +[listeners.onboard] address = "0.0.0.0" port = 9203 # HTTP port for onboard UI ``` @@ -492,7 +548,7 @@ port = 9203 # HTTP port for onboard UI ```bash curl -X POST http://:9203/prpc/Onboard.Onboard?json \ -H "Content-Type: application/json" \ - -d '{"source_url": "https://:9202/prpc", "source_token": "", "domain": "kms2.example.com"}' + -d '{"source_url": "https://:8001/prpc", "source_token": "", "domain": "kms2.example.com"}' ``` **Finish and restart:** @@ -509,9 +565,77 @@ curl http://:9203/finish > > If you skip this, `Onboard.Onboard` or later trusted RPCs will fail with KMS authorization errors. -> **Admin authentication.** The KMS *admin* RPCs (for example `ClearImageCache`) are served on a dedicated `[core.admin]` listener behind the shared HTTP authenticator, just like the VMM and gateway: set `[core.admin] enabled = true` with an `auth_token` (or the `DSTACK_KMS_ADMIN_TOKEN` / `ADMIN_API_TOKEN` env vars), and clients send `Authorization: Bearer ` or `X-Admin-Token`. Enabled with neither `auth_token` nor `htpasswd_file` (and `insecure_no_auth = false`) fails closed — the KMS refuses to start. See [dstack-kms admin authentication](../dstack/kms/README.md#admin-api-authentication). +> **Admin authentication.** The KMS *admin* RPCs (for example `ClearImageCache`) are served on a dedicated `[listeners.admin]` listener behind the shared HTTP authenticator, just like the VMM and gateway: set `[listeners.admin] enabled = true` with an `auth_token` (or the `DSTACK_KMS_ADMIN_TOKEN` / `ADMIN_API_TOKEN` env vars), and clients send `Authorization: Bearer ` or `X-Admin-Token`. Enabled with neither `auth_token` nor `htpasswd_file` (and `insecure_no_auth = false`) fails closed — the KMS refuses to start. See [dstack-kms admin authentication](../dstack/kms/README.md#admin-api-authentication). +> +> **Source pinning.** Before sending anything secret, the new KMS requires the source's RPC certificate, at the TLS handshake, to be a `kms:rpc` leaf signed by the current root CA its own auth API reports (`rootCaPubkey` in `GET /`), so `source_url` must be `https://`. A source without the registered roots never sees the launch ticket or `source_token`; onboarding fails if the auth API reports no root CA key. Right after a root epoch is activated, a source still serving the RPC certificate of the previous one fails the handshake until it restarts; onboarding attempts do not trigger that restart, so restart the source. Upgrade the auth backend before the KMS: a custom webhook must report `rootCaPubkey`. A KMS with `auth_api.type = "dev"` registers no roots and pins nothing. +> +> **Launch ticket.** When the KMS contract requires one (`setRequireKmsLaunchTicket`), pass this instance's ticket as `launch_ticket` in the onboarding request; the source checks its hash against `kmsLaunchTickets()` before handing over the keys. Remove the ticket from the contract once the instance has joined. See [launch tickets](../dstack/kms/README.md#launch-tickets). > -> **Key handover.** It is served as `Admin.GetKmsKey` on the `[core.admin]` listener, which needs `[core.admin.tls]` so it can verify the onboarding KMS's RA-TLS certificate. Pass the source admin URL and its token (`source_token`) in the onboarding request. `core.onboard.public_key_handover = true` keeps the legacy public `KMS.GetKmsKey`. +> **Key handover.** It is served as `Admin.GetKmsKey` on the `[listeners.admin]` listener, which needs TLS so it can verify the onboarding KMS's RA-TLS certificate. Pass the source admin URL (`https://`) and its token (`source_token`) in the onboarding request; the token is required unless the source enables the public handover. The legacy public `KMS.GetKmsKey` is off by default; set `core.onboard.public_key_handover = true` on the source only when an onboarding KMS cannot use the admin listener, such as a 0.5.x KMS or an onboarding request without `source_token`. + +#### Rotating KMS Root Keys + +KMS root keys are versioned by epoch; epoch 0 is the original roots. Every KMS +keeps all epochs so CVMs can migrate from any of them, and serves the epoch +governance made current. See the [rotation design](./kms-emergency-key-rotation-protocol.md) +for the full procedure; the KMS steps are: + +1. If epochs were never registered, publish the attestation the KMS produced at + bootstrap (served as `bootstrap_info` by `KMS.GetMeta`) and + register the current root public keys as epoch 0: + `DstackKms.registerRootEpoch(caPubkey, k256Pubkey, evidenceUrl)`, via + `script/Manage.s.sol:RegisterRootEpoch`, or a `rootEpochs` entry in the + dstack-auth config. Epoch 0 is current once registered, and must be the + `kmsInfo` keys when those are set. A deployment whose `kmsInfo` holds a + legacy `quote` and `eventlog` instead of an attestation converts them with + `dstack-kms legacy-attestation --quote --eventlog ` and publishes + the result first: from then on `kmsInfo` follows the current epoch's keys and + its quote and event log are cleared. +2. Onboard a fresh KMS with `"rotate": true` (the **Rotate** checkbox in the + onboard UI) from a KMS at the current epoch N-1. It imports epochs 0..N-1, + generates epoch N, and returns the new public keys with an attestation whose + report data is + `keccak256("dstack-kms-genereted-keys-v1:{ca_pubkey_hex};{k256_pubkey_hex};")` + zero-padded to 64 bytes, the same encoding as the original bootstrap (the + spelling is part of the format). It binds both public keys; the epoch number + comes from the on-chain registration order. +3. Before registering, verify the attestation with + [dstack-verifier](../dstack/verifier/README.md) (`POST /verify`): check the + quote, the approved KMS image and measurements, and that its report data + equals the value recomputed from the returned public keys. Then publish it + and register epoch N with its URL. The cluster keeps serving N-1. +4. Onboard the other KMS nodes from the rotated one; they import 0..N and keep + serving N-1. A join checks the source's keyring against the latest registered + epoch as well as the current one, so a source holding an unregistered or + different epoch N is refused. +5. Activate epoch N (`ActivateRootEpoch`, or `currentRootEpoch` for + dstack-auth). Each KMS restarts onto N on its next uncached authorization + check; a KMS that does not hold N waits + until it is onboarded again. + If the nodes holding N are lost before N is activated, drop it with + `PopRootEpoch` (or remove the `rootEpochs` entry) and rotate again; nodes + that imported the dropped N must be onboarded again. On chain, the policy + rows prepared for the dropped N do not apply to the new one; approve them + again before activating it. +6. Boot CVMs on an OS that supports root epochs. At boot they re-key their data + disk from the epoch recorded in its LUKS header to the current one. If an + encrypted environment still uses an older epoch, the CVM re-encrypts it during + boot and the VMM replaces the ciphertext only if it was not changed concurrently. + See [SealedEnv](./sealed-env.md) for the new format, file precedence, and rollback requirements. + +Each `authorizeKms` or `authorizeApp` result carries the current epoch and its chain hash, +and the latest registered epoch (`latestRootEpoch`, `latestRootEpochHash`), which may be +pending activation, including when authorization is denied. KMS verifies these against its keyring; +there is no cached serving epoch. An optional `requestedRootEpoch` selects historical +keys, and omission selects the returned current epoch. Requests for future +epochs are denied. No registered epoch returns a rejection with +`rejectionReason: "Root epoch not registered"` and a zero hash. + +RPC certificates still require a listener restart when their root CA changes; +callers retry after the certificate is refreshed. Register epoch 0 before normal +key release. Bootstrap keeps using scoped KMS authorization so it can generate +the first roots before registration. See the +[authorization protocol](../dstack/kms/README.md#authorization-protocol). --- @@ -522,7 +646,7 @@ After setup, deploy apps via the VMM dashboard or CLI. ### Register App Before deploying, register your app in your auth server: -- For auth-simple: See [auth-simple Operations Guide](./auth-simple-operations.md#adding-an-app) +- For dstack-auth: See [dstack-auth Operations Guide](./dstack-auth-operations.md#adding-an-app) - For auth-eth: See [On-Chain Governance](./onchain-governance.md#register-apps-on-chain) ### Deploy via UI diff --git a/docs/design-and-hardening-decisions.md b/docs/design-and-hardening-decisions.md index b6ffbb9cd2..cfb883a1e8 100644 --- a/docs/design-and-hardening-decisions.md +++ b/docs/design-and-hardening-decisions.md @@ -57,7 +57,9 @@ See [here](https://intel.github.io/ccc-linux-guest-hardening-docs/security-spec. **Implementation**: dstack OS enforces the guest kernel uses TSC as the only timer source by appending `tsc=reliable no-kvmclock` to the kernel cmdline. It also enforces the use of NTS with built-in [trusted servers](../os/yocto/layers/meta-dstack/recipes-core/chrony/files/chrony.conf) to synchronize system time. -**Behavior**: When `secure_time` is enabled in the app-compose.json configuration, the system ensures time synchronization is completed before requesting application keys. If `secure_time` is disabled, time synchronization is not enforced before application launch. +On AMD SEV-SNP the hypervisor controls the guest TSC unless the guest is launched with Secure TSC. The VMM enables it whenever `secure_time` is on in app-compose.json (the default), which needs QEMU >= 11.2, host kernel >= 6.18 and a CPU that supports Secure TSC. + +**Behavior**: When `secure_time` is enabled in the app-compose.json configuration, the system ensures time synchronization is completed before requesting application keys. It first checks that the host cannot move the clock between syncs and refuses to boot otherwise: the clocksource must be `tsc`, an AMD SEV-SNP guest must run with Secure TSC, and AWS is not supported. If `secure_time` is disabled, time synchronization is not enforced before application launch. **Rationale**: Time synchronization is provided as an optional feature because the process typically requires tens of seconds to complete. Applications can function without the `secure_time` option enabled and may implement their own time synchronization mechanisms if required. diff --git a/docs/dstack-auth-operations.md b/docs/dstack-auth-operations.md new file mode 100644 index 0000000000..216f59af84 --- /dev/null +++ b/docs/dstack-auth-operations.md @@ -0,0 +1,476 @@ +# dstack-auth Operations Guide + +> **This guide is for self-hosted deployments** on your own TDX hardware. For cloud deployments, see [Quickstart](./quickstart.md). + +> [!WARNING] +> `dstack-auth` is intended for development, testing and evaluation only. Do not +> use it to protect production keys; use [auth-eth](../dstack/kms/auth-eth/) or +> an equivalent production-grade authorization service instead. + +`dstack-auth` is the file-based KMS authorization webhook. It allowlists OS +images, KMS instances and apps in one JSON file. For on-chain governance, use +[auth-eth](../dstack/kms/auth-eth/) instead +(see [On-Chain Governance](./onchain-governance.md)). + +This guide covers running `dstack-auth` and managing apps and devices with it. +For initial deployment setup, see [Deployment Guide](./deployment.md). + +## Overview + +The allowlist file whitelists: +- **OS images** - Which guest OS versions can boot +- **KMS nodes** - Which KMS instances can bootstrap, serve and onboard (`mrAggregated`, devices) +- **Apps** - Which applications can boot (appId, composeHash, devices) +- **Platform state (opt-in)** - Which TCB statuses and security advisories are acceptable + +The file is re-read on every request, so changes take effect immediately without restart. +A missing or invalid file denies every request. + +--- + +## Running dstack-auth + +### Installed by dstackup + +`dstackup` installs `dstack-auth` as the `dstack-auth.service` systemd unit, +listening on `127.0.0.1:8001`, and writes the allowlist to +`auth-allowlist.json` in its config directory. `dstack run` adds the compose +hash of each app it deploys. Edit that file to change the policy. + +### Running the binary yourself + +Build it from the repository: + +```bash +cd dstack +cargo build --release -p dstack-auth +./target/release/dstack-auth --config /path/to/auth-config.json --port 3001 +``` + +| Option | Default | Description | +|--------|---------|-------------| +| `--config` | `/var/lib/dstack/auth-allowlist.json` | Allowlist JSON file | +| `--address` | `127.0.0.1` | Bind address | +| `--port` | `8001` | Bind port | + +A KMS CVM on QEMU user-mode networking reaches the host loopback at `10.0.2.2`, +so the default address is enough for a KMS on the same host: point the KMS at +`http://10.0.2.2:`. Bind `--address 0.0.0.0` only when the KMS reaches the +host over a real network, and restrict access to that port. + +Point the KMS at it in `kms.toml`: + +```toml +[core.auth_api] +type = "webhook" + +[core.auth_api.webhook] +url = "http://10.0.2.2:3001" +``` + +--- + +## Config File Structure + +```json +{ + "osImages": ["0x..."], + "gatewayAppId": "0x...", + "kmsContractAddr": "0x", + "kms": { + "mrAggregated": ["0x..."], + "devices": ["0x..."], + "allowAnyDevice": true + }, + "apps": { + "0x": { + "composeHashes": ["0x..."], + "devices": ["0x..."], + "allowAnyDevice": true + } + }, + "rootEpochs": [{"caPubkey": "0x...", "k256Pubkey": "0x..."}], + "currentRootEpoch": 0 +} +``` + +> **Note:** `osImages` is always required for apps. For KMS authorization, you must also populate `kms.mrAggregated`; if it is left empty, dstack-auth denies all KMS boots. Add `gatewayAppId` after deploying the Gateway. Add `apps` entries as you deploy applications. + +Hex values are compared case-insensitively, with or without a `0x` prefix. + +### Configuration Fields + +| Field | Required | Description | +|-------|----------|-------------| +| `osImages` | Yes | Allowed OS image hashes (from `digest.txt`). Empty denies every app. | +| `gatewayAppId` | No | Gateway app ID (add after Gateway deployment). Several gateways: join their IDs with commas. | +| `kmsContractAddr` | For `/authorize*` | The attested app ID of the KMS. Every operation except `kms_bootstrap` is denied while it is unset, and a caller is accepted only on the endpoint matching its app ID (`/authorizeKms` for this ID, `/authorizeApp` for any other). Reported by `GET /`. | +| `chainId` | No | Informational, reported by `GET /` (default `0`). | +| `appImplementation` | No | Informational, reported by `GET /` as `appImplementation` and `appAuthImplementation`. | +| `allowedTcbStatuses` | No | When set, deny unless the verifier-derived `tcbStatus` is listed; `[]` denies everything. **Absent: not checked.** See [TCB and advisory policy](#tcb-and-advisory-policy). | +| `allowedAdvisoryIds` | No | When set, deny any reported advisory ID that is not listed; `[]` denies any advisory. **Absent: not checked.** | +| `sevSnpTcbRequirements` | No | The minimum TCB of each CPU the KMS judges an SEV-SNP TCB against, as the entries described in [AMD SEV-SNP](./amd-sev-snp.md). **Absent: a KMS judges a CPU only against its own list, and refuses one neither lists.** | +| `kms.mrAggregated` | Yes | Allowed KMS early aggregate MR values (boot-mr-done). Empty denies every KMS. | +| `kms.devices` | No | Allowed KMS device IDs. Empty denies all unless `kms.allowAnyDevice` is true. | +| `kms.allowAnyDevice` | No | If true, skip the device ID check for KMS | +| `apps..composeHashes` | No | Allowed compose hashes for this app | +| `apps..devices` | No | Allowed device IDs for this app. Empty denies all unless `allowAnyDevice` is true. | +| `apps..allowAnyDevice` | No | If true, skip the device ID check for this app | +| `apps..currentAppEpoch` | No | Current app key epoch (default `0`), served by `GET /app/`. A non-zero epoch denies the legacy `/bootAuth/app` route. | +| `rootEpochs` | No | KMS root public keys of each root epoch, indexed by epoch, `[{"caPubkey": "0x...", "k256Pubkey": "0x..."}]`. Epoch 0 is the original roots. Append only. `GET /` reports the current epoch as `rootEpoch` with its chain hash as `rootEpochHash`; the last entry is reported as `latestRootEpoch`, and entries beyond `currentRootEpoch` are pending activation. | +| `currentRootEpoch` | No | Root epoch KMS instances serve (default 0). Key-issuing operations (`kms_serve`, `app_get_key`, `app_get_cert`) may request up to this epoch; KMS key handover (`kms_export_keys`, `kms_import_keys`) may request any registered epoch, so the other KMS nodes can onboard from the rotated one while the new epoch is pending. Raise it only once every KMS node holds that epoch. | + +### Validation Logic + +KMS (`/authorizeKms`, `/bootAuth/kms`): + +1. `tcbStatus` must be in `allowedTcbStatuses`, if set +2. Every `advisoryIds` entry must be in `allowedAdvisoryIds`, if set +3. `mrAggregated` must be in `kms.mrAggregated` +4. `deviceId` must be in `kms.devices` unless `kms.allowAnyDevice` is true + +Apps (`/authorizeApp`, `/bootAuth/app`): + +1. `tcbStatus` must be in `allowedTcbStatuses`, if set +2. Every `advisoryIds` entry must be in `allowedAdvisoryIds`, if set +3. `osImageHash` must be in `osImages` +4. `appId` must exist in `apps` +5. `composeHash` must be in the app's `composeHashes` +6. `deviceId` must be in the app's `devices` unless `allowAnyDevice` is true + +KMS requests are not matched against `osImages`: `mrAggregated` already pins +the OS image measurements. The `/authorize*` endpoints and legacy `/bootAuth/*` +routes also enforce root epochs, see the +[KMS authorization protocol](../dstack/kms/README.md#authorization-protocol). + +--- + +## TCB and Advisory Policy + +By default `dstack-auth` does not check the platform TCB status or security +advisories. In the single-operator model the operator controls and trusts the +host, and real TDX hosts routinely report a non-`UpToDate` TCB when microcode or +the TDX module lags behind, so a hard TCB gate there adds friction without +adding trust. + +Deployments where the host operator is not the party relying on the policy +(a KMS serving other users, AWS, SEV-SNP) should enforce it explicitly: + +```json +{ + "allowedTcbStatuses": ["UpToDate"], + "allowedAdvisoryIds": [], + "osImages": ["0x..."], + "kms": { "mrAggregated": ["0x..."], "allowAnyDevice": true }, + "apps": {} +} +``` + +With this, any status other than `UpToDate` and any advisory ID denies. To +accept a known state temporarily, list it explicitly, for example +`"allowedTcbStatuses": ["UpToDate", "SWHardeningNeeded"]` or +`"allowedAdvisoryIds": ["INTEL-SA-00837"]`. + +AWS NitroTPM has no TDX/SNP-style TCB advisory surface, so the KMS normalizes a +verified NitroTPM attestation to `tcbStatus: "UpToDate"` before calling the +webhook; the policy above works unchanged there. + +--- + +## Migrating from auth-simple + +`auth-simple` (the Bun/TypeScript server in `dstack/kms/auth-simple`) has been +removed. `dstack-auth` reads the same config file format, so an existing +`auth-config.json` loads unchanged. To switch: + +1. Keep auth-simple's strict platform defaults by adding them explicitly, unless + your config already sets them: + + ```json + "allowedTcbStatuses": ["UpToDate"], + "allowedAdvisoryIds": [] + ``` + + Without these fields, dstack-auth accepts any TCB status and advisory. +2. Set `kmsContractAddr` to the attested KMS app ID if it is not set. auth-simple + defaulted it to the zero address and did not check it; dstack-auth denies + every `/authorize*` operation except `kms_bootstrap` without it. +3. Replace the start command. `PORT` and `AUTH_CONFIG_PATH` become flags, and + auth-simple listened on all interfaces while dstack-auth binds to loopback + by default: + + ```bash + # before + PORT=3001 AUTH_CONFIG_PATH=/path/to/auth-config.json bun run start + # after + dstack-auth --config /path/to/auth-config.json --port 3001 + ``` + + Add `--address 0.0.0.0` if the KMS reaches the webhook over a real network + rather than `10.0.2.2`. + +Other differences: KMS requests are no longer matched against `osImages` (see +[Validation Logic](#validation-logic)), `GET /` no longer reports `configPath`, +and rejection reasons are lowercase (for example `root epoch not registered`). + +--- + +## Adding an App + +### Step 1: Generate App ID + +App IDs are typically the contract address (for on-chain) or a unique identifier you choose. + +For dstack-auth, you can use any unique hex string (40 characters / 20 bytes): + +```bash +# Generate a random app ID +openssl rand -hex 20 +# Output: 7a3b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b +``` + +### Step 2: Get Compose Hash + +The compose hash is computed from the normalized docker-compose file. The VMM displays it when deploying: + +``` +Docker compose file: +... +Compose hash: 0x700a50336df7c07c82457b116e144f526c29f6d8... +``` + +Or query from a running CVM: + +```bash +curl -s --unix-socket /var/run/dstack.sock http://localhost/Info | \ + jq -r '"0x" + (.tcb_info | fromjson | .compose_hash)' +``` + +> **Note:** The VMM normalizes YAML to JSON before hashing. For exact hash, use the value shown during deployment. + +### Step 3: Add to Config + +Edit your allowlist file: + +```json +{ + "apps": { + "0x7a3b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b": { + "composeHashes": [ + "0x700a50336df7c07c82457b116e144f526c29f6d8..." + ], + "devices": [], + "allowAnyDevice": true + } + } +} +``` + +### Step 4: Deploy via VMM + +Use the App ID when deploying through VMM: + +```bash +./vmm-cli.py deploy \ + --app-id 7a3b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b \ + --compose docker-compose.yaml \ + ... +``` + +--- + +## Updating an App + +When you change your docker-compose.yaml, a new compose hash is generated. + +### Add New Hash (Keep Old Running) + +Add the new hash to the `composeHashes` array: + +```json +{ + "apps": { + "0x": { + "composeHashes": [ + "0x", + "0x" + ] + } + } +} +``` + +### Replace Hash (Force Upgrade) + +Remove the old hash to prevent old versions from booting: + +```json +{ + "apps": { + "0x": { + "composeHashes": [ + "0x" + ] + } + } +} +``` + +--- + +## Device Management + +Devices are identified by their TDX device ID (hardware-specific). + +### Get Device ID + +The `deviceId` is sent by the booting app/KMS in its auth request. dstack-auth +logs it with each decision (`journalctl -u dstack-auth` when installed by +`dstackup`): + +``` +authorize AppGetKey app=7a3b... compose=700a... mr=... os=0b32... device=e5a0... tcb=UpToDate advisories=[] -> authorized=true () +``` + +> **Tip:** Use `allowAnyDevice: true` initially, then restrict to specific devices after capturing IDs from logs. + +### Restrict App to Specific Devices + +```json +{ + "apps": { + "0x": { + "composeHashes": ["0x..."], + "devices": [ + "0xe5a0c70bb6503de2d31c11d85914fe3776ed5b33a078ed856327c371a60fe0fd" + ], + "allowAnyDevice": false + } + } +} +``` + +### Allow Any Device + +For initial testing or when device restriction isn't needed: + +```json +{ + "apps": { + "0x": { + "allowAnyDevice": true + } + } +} +``` + +--- + +## Removing an App + +Delete the app entry from the `apps` object. Running instances continue until +restarted; new key requests are rejected. + +--- + +## Setting the Gateway App (After Gateway Deployment) + +The `gatewayAppId` field is **optional** during initial KMS deployment. Add it after deploying the Gateway. + +The Gateway is a special app that routes traffic to other apps. Once deployed, add its App ID to your config: + +```json +{ + "gatewayAppId": "0x75537828f2ce51be7289709686A69CbFDbB714F1", + "apps": { + "0x75537828f2ce51be7289709686A69CbFDbB714F1": { + "composeHashes": ["0x..."], + "allowAnyDevice": true + } + } +} +``` + +The `gatewayAppId` is returned in authorization responses and used by KMS for key derivation. + +To trust several gateways, join their App IDs with commas (`"0xaaa...,0xbbb..."`). CVMs accept a gateway whose App ID is contained in this value. + +--- + +## KMS Onboarding (Multi-Node) + +To allow additional KMS nodes to onboard (receive root keys from the primary KMS), whitelist their `mrAggregated` value. + +### Get mrAggregated + +1. **Initial setup**: capture the first KMS measurement with `Onboard.GetAttestationInfo` and add it to `kms.mrAggregated` before bootstrap. An empty array denies all KMS boots. +2. **From dstack-auth logs**: every KMS request is logged with its measurement: + ``` + authorize KmsBootstrap app=... compose=... mr= os=... device=... -> authorized=false (kms mrAggregated not allowed) + ``` + +### Add to Config + +```json +{ + "kms": { + "mrAggregated": ["0x"], + "allowAnyDevice": true + } +} +``` + +> **Note:** All KMS nodes using the same OS image and compose will have the same mrAggregated, so you only need to capture it once. + +--- + +## Verification + +### Check Config is Valid + +```bash +curl -s http://127.0.0.1:3001/ | jq +``` + +Returns `status`, `gatewayAppId`, `kmsContractAddr` and, once `rootEpochs` is +configured, `rootEpoch` and `rootEpochHash`. An invalid `rootEpochs` +configuration returns HTTP 503. + +### Test Boot Authorization + +```bash +curl -s -X POST http://127.0.0.1:3001/bootAuth/app \ + -H "Content-Type: application/json" \ + -d '{ + "appId": "0x", + "composeHash": "0x", + "osImageHash": "0x", + "deviceId": "0x", + "tcbStatus": "UpToDate", + "advisoryIds": [] + }' | jq +``` + +Expected responses: +- `{"isAllowed": true, ...}` - App is authorized +- `{"isAllowed": false, "reason": "app not registered", ...}` - App ID not in config +- `{"isAllowed": false, "reason": "compose hash not allowed", ...}` - Hash not whitelisted +- `{"isAllowed": false, "reason": "tcb status not allowed", ...}` - `tcbStatus` not in `allowedTcbStatuses` + +--- + +## API Endpoints + +| Endpoint | Description | +|----------|-------------| +| `GET /` | Health check and info (`kmsContractAddr`, `gatewayAppId`, `chainId`, `appImplementation`, `rootEpoch`, `rootEpochHash`) | +| `POST /authorizeKms`, `POST /authorizeApp` | Epoch-aware authorization; return an `AuthorizationResult`. See the [KMS authorization protocol](../dstack/kms/README.md#authorization-protocol). | +| `GET /app/` | `{"currentAppEpoch": N}`; 404 for an app that is not configured | +| `POST /bootAuth/kms`, `POST /bootAuth/app` | Legacy boot authorization for older KMS binaries; return `{isAllowed, reason, gatewayAppId}` | + +--- + +## See Also + +- [Deployment Guide](./deployment.md) - Initial setup +- [On-Chain Governance](./onchain-governance.md) - Smart contract-based alternative diff --git a/docs/dstack-gateway.md b/docs/dstack-gateway.md index 7ae1319197..5b4c60ad94 100644 --- a/docs/dstack-gateway.md +++ b/docs/dstack-gateway.md @@ -32,7 +32,7 @@ The base domain is not set here: it is the ZT domain you add in Step 3. Two more sections matter for certificates: ```toml -[core.admin] +[listeners.admin] enabled = true address = "127.0.0.1:9016" auth_token = "" @@ -55,7 +55,7 @@ Start the gateway. ## Step 3: Give the gateway its ACME configuration -Open the admin dashboard at `http://` and fill in **Certbot +Open the admin dashboard at `http://` and fill in **Certbot Configuration**, **DNS Credentials** and **ZT-Domains**, or do the same over the admin API: @@ -150,10 +150,10 @@ Note: The `s` and `g` suffixes cannot be used together ## Admin API authentication -The gateway exposes a separate admin API (used for sync, WireGuard peer management, and other operator RPCs). Configure it in the `core.admin` section of `gateway.toml`: +The gateway exposes a separate admin API (used for sync, WireGuard peer management, and other operator RPCs). Configure it in the `listeners.admin` section of `gateway.toml`: ```toml -[core.admin] +[listeners.admin] enabled = true address = "0.0.0.0:9016" # generate with: openssl rand -hex 32 @@ -173,10 +173,51 @@ The admin server is fail-closed: if it is enabled with no `auth_token` and no `h Clients authenticate by sending `Authorization: Bearer ` or the `X-Admin-Token: ` header. +## PROXY protocol on the gateway's own listeners + +Behind a TCP proxy such as HAProxy, the gateway's RPC and admin listeners see +the proxy's address. Set `proxy_protocol = true` in `[listeners.default]`, or in +one listener's section (`[listeners.guest]`, `[listeners.admin]`, +`[listeners.debug]`), to read the client address from a PROXY protocol (v1 or +v2) header; the RPC request logs then carry it as `remote`. With it on, the listener drops connections that send +no header within five seconds, and trusts the header as sent, so make it +reachable only through the proxy (HAProxy `send-proxy-v2`, plus +`check-send-proxy` for health checks). This is separate from +`[core.proxy] inbound_pp_enabled`, which covers the app traffic the gateway +proxies. It works on TCP listeners only: a listener bound to a Unix socket +(`address = "unix:..."`) fails to start with it, so set `proxy_protocol = false` +in that listener's section when `[listeners.default]` turns it on. + +## WireGuard key proof on registration + +A CVM registers its WireGuard public key with `RegisterCvm`. Without a proof +the gateway takes that key on trust, so a CVM that learned another CVM's public +key could claim it while the other CVM's record is recycled, and keep it once +that CVM comes back. Newer CVMs read the node's WireGuard key from `Info` and +attach a proof that they hold the matching private key, bound to their attested +app and instance ids. + +Whether registrations with a missing or invalid proof are refused is one +cluster-wide switch stored in the replicated KV, read with +`GetWgKeyProofConfig` and toggled at runtime with `SetWgKeyProofConfig` +(admin RPCs). It is off until set. Off, a missing or invalid proof is accepted, +and an invalid one is logged as a warning. On, both are refused. +Turn it on only after every CVM sends a proof and every node is upgraded: a node +verifies only the registrations it receives, and its peers accept whatever it +replicates. If the stored policy cannot be decoded, nodes fail closed and +require proofs until it is overwritten. The proof is checked at registration +and not stored, so records written before the policy was turned on are not +re-checked. + +A proof is made for one node's key, so if the CVM's gateway URL is a balancer, +it must keep a connection on one node (`Info` and `RegisterCvm` share it). A +balancer that routes each request separately can split the two, and that node +then refuses the proof. + ## Metrics The admin server exposes Prometheus metrics at `GET /metrics`. It is part of the -admin API, so it is only reachable when `core.admin.enabled` is true and it +admin API, so it is only reachable when `listeners.admin.enabled` is true and it requires the same credentials — unless `insecure_no_auth` is set, which exposes it along with the rest of the admin API. The series name domains, node ids and instance counts, which is topology that should not be readable without @@ -186,7 +227,7 @@ authentication. scrape_configs: - job_name: dstack-gateway static_configs: - - targets: [""] + - targets: [""] authorization: credentials: "" ``` diff --git a/docs/encrypted-env-spec.md b/docs/encrypted-env-spec.md index c204a16e57..c56afa1ce3 100644 --- a/docs/encrypted-env-spec.md +++ b/docs/encrypted-env-spec.md @@ -170,9 +170,7 @@ Path inside TEE: `/dstack/.host-shared/.appkeys.json` "key_provider": { "Kms": { "url": "https://kms.example.com/prpc", - "pubkey": "...", - "tmp_ca_key": "-----BEGIN PRIVATE KEY-----\n...", - "tmp_ca_cert": "-----BEGIN CERTIFICATE-----\n..." + "pubkey": "..." } } } @@ -200,11 +198,15 @@ Rust externally tagged enum — an object with exactly one key: {"None": {"key": ""}} {"Local": {"key": "", "mr": ""}} {"Tpm": {"key": "", "pubkey": ""}} -{"Kms": {"url": "...", "pubkey": "", "tmp_ca_key": "", "tmp_ca_cert": ""}} +{"Kms": {"url": "...", "pubkey": ""}} ``` The tag is one of `"None"` / `"Local"` / `"Tpm"` / `"Kms"`. +`Kms` carried `tmp_ca_key` / `tmp_ca_cert` before guests switched to self-issued +RA-TLS client certificates. Readers ignore the extra fields, so files written by +older guest images still parse. + ## Runtime File/Path Contract (dstack) For dstack runtime integration, treat these names/locations as protocol-level diff --git a/docs/formal/key-rotation/DiskMigration.cfg b/docs/formal/key-rotation/DiskMigration.cfg new file mode 100644 index 0000000000..5ef9caddc3 --- /dev/null +++ b/docs/formal/key-rotation/DiskMigration.cfg @@ -0,0 +1,12 @@ +\* SPDX-FileCopyrightText: © 2026 Phala Network +\* SPDX-License-Identifier: Apache-2.0 + +SPECIFICATION Spec +CONSTANTS + MaxEpoch = 3 +INVARIANTS + TypeOK + NoBootFailure + DataRecoverable + NoFormatOverData + RunningIsMigrated diff --git a/docs/formal/key-rotation/DiskMigration.tla b/docs/formal/key-rotation/DiskMigration.tla new file mode 100644 index 0000000000..23b3cf56fc --- /dev/null +++ b/docs/formal/key-rotation/DiskMigration.tla @@ -0,0 +1,186 @@ +\* SPDX-FileCopyrightText: © 2026 Phala Network +\* SPDX-License-Identifier: Apache-2.0 + +---------------------------- MODULE DiskMigration ---------------------------- +(***************************************************************************) +(* Data disk setup and LUKS key migration across KMS key epochs, as *) +(* implemented by dstack-util (system_setup.rs: setup_data_disk, *) +(* luks_setup, open_encrypted_volume; system_setup/luks.rs: *) +(* sync_luks_epochs). *) +(* *) +(* A key epoch abstracts the (root, app) epoch pair: the disk key differs *) +(* per epoch and the KMS serves every epoch up to the current one. A boot *) +(* fetches its keys once, so it targets the epoch current at its start; *) +(* the KMS may rotate at any time. *) +(* *) +(* The header has two keyslots and a token recording a keyslot and its *) +(* epoch. Each cryptsetup command on the device (luksFormat, luksAddKey, *) +(* luksKillSlot, token import, config --label) is atomic: it writes a new *) +(* keyslot area before the header copies, each synced, and an outdated *) +(* copy is repaired from the newer one on the next load. A crash can stop *) +(* the boot between any two commands. *) +(***************************************************************************) +EXTENDS Integers + +CONSTANTS MaxEpoch + +Slots == {0, 1} +NoKey == -1 +NoToken == [slot |-> -1, epoch |-> -1] +Tokens == {NoToken} \cup [slot: Slots, epoch: 0..MaxEpoch] + +VARIABLES + current, \* current key epoch on chain + target, \* epoch whose keys this boot fetched + luks, \* the device holds a LUKS header + slots, \* keyslots: Slots -> key epoch or NoKey + token, \* the dstack-kms token + init, \* the header carries the initializing label + pc, \* boot step + oldSlot, \* sync_luks_epochs: the recorded keyslot being migrated from + slot, \* sync_luks_epochs: the keyslot holding the target key + hasData \* applications have written data to the volume + +vars == <> +boot == <> + +Keyslots == {s \in Slots: slots[s] # NoKey} +StoredEpoch == IF token = NoToken THEN 0 ELSE token.epoch +\* unlocked_keyslot: the first keyslot the target key opens. +Unlocked == {s \in Slots: slots[s] = target} +First(S) == IF 0 \in S THEN 0 ELSE 1 + +Init == + /\ current \in 0..MaxEpoch + /\ target = 0 + /\ luks = FALSE + /\ slots = [s \in Slots |-> NoKey] + /\ token = NoToken + /\ init = FALSE + /\ pc = "off" + /\ oldSlot = 0 /\ slot = 0 + /\ hasData = FALSE + +Rotate == + /\ current < MaxEpoch + /\ current' = current + 1 + /\ UNCHANGED <> + +\* setup_data_disk: an initialized disk is opened; an interrupted +\* initialization or a blank disk is formatted. +Boot == + /\ pc = "off" + /\ target' = current + /\ pc' = IF luks /\ ~init THEN "sync" ELSE "format" + /\ UNCHANGED <> + +\* luks_setup: luksFormat with the initializing label, key in keyslot 0. +Format == + /\ pc = "format" + /\ luks' = TRUE /\ init' = TRUE + /\ slots' = [s \in Slots |-> IF s = 0 THEN target ELSE NoKey] + /\ token' = NoToken + /\ pc' = IF target > 0 THEN "formatToken" ELSE "sync" + /\ UNCHANGED <> + +FormatToken == + /\ pc = "formatToken" + /\ token' = [slot |-> 0, epoch |-> target] + /\ pc' = "sync" + /\ UNCHANGED <> + +\* sync_luks_epochs, entry. +Sync == + /\ pc = "sync" + /\ LET old == IF token = NoToken THEN 0 ELSE token.slot IN + CASE StoredEpoch > target -> pc' = "fail" /\ UNCHANGED <> + [] Unlocked # {} -> pc' = "record" /\ slot' = First(Unlocked) /\ UNCHANGED oldSlot + [] StoredEpoch = target -> pc' = "fail" /\ UNCHANGED <> + \* The recorded keyslot must exist and open with the recorded epoch. + [] old \notin Keyslots \/ slots[old] # StoredEpoch -> + pc' = "fail" /\ UNCHANGED <> + [] OTHER -> pc' = "dropStale" /\ oldSlot' = old /\ UNCHANGED slot + /\ UNCHANGED <> + +\* Drop the keyslot whose epochs were never recorded, to make room. +DropStale == + /\ pc = "dropStale" + /\ slots' = [s \in Slots |-> IF s = oldSlot THEN slots[s] ELSE NoKey] + /\ pc' = "addKey" + /\ UNCHANGED <> + +AddKey == + /\ pc = "addKey" + /\ slots' = [slots EXCEPT ![1 - oldSlot] = target] + /\ slot' = 1 - oldSlot + /\ pc' = "record" + /\ UNCHANGED <> + +\* Record the target epoch for the keyslot that holds it; a legacy disk at +\* epoch 0 keeps no token. +Record == + /\ pc = "record" + /\ LET legacy == target = 0 /\ token = NoToken IN + token' = IF legacy THEN token ELSE [slot |-> slot, epoch |-> target] + /\ pc' = "killOld" + /\ UNCHANGED <> + +KillOld == + /\ pc = "killOld" + /\ slots' = [s \in Slots |-> IF s = slot THEN slots[s] ELSE NoKey] + /\ pc' = "open" + /\ UNCHANGED <> + +\* luksOpen with the target key, from the header loaded after the changes. +Open == + /\ pc = "open" + /\ pc' = CASE slots[slot] # target -> "fail" + [] init -> "mkfs" + [] OTHER -> "running" + /\ UNCHANGED <> + +\* mkfs on the volume, then cryptsetup config --label= on the device. +Mkfs == + /\ pc = "mkfs" + /\ init' = FALSE + /\ pc' = "running" + /\ UNCHANGED <> + +WriteData == + /\ pc = "running" /\ ~hasData + /\ hasData' = TRUE + /\ UNCHANGED <> + +\* Shutdown, a crash at any step, or a restart after a failed boot. +Stop == + /\ pc # "off" + /\ pc' = "off" + /\ UNCHANGED <> + +Next == + \/ Rotate \/ Boot \/ Format \/ FormatToken \/ Sync \/ DropStale \/ AddKey + \/ Record \/ KillOld \/ Open \/ Mkfs \/ WriteData \/ Stop + +Spec == Init /\ [][Next]_vars + +----------------------------------------------------------------------------- +TypeOK == + /\ current \in 0..MaxEpoch /\ target \in 0..current + /\ slots \in [Slots -> {NoKey} \cup (0..MaxEpoch)] + /\ token \in Tokens + +\* A boot never fails: a failed boot fails again on every retry. +NoBootFailure == pc # "fail" + +\* Data, once written, stays under a key the KMS still serves. +DataRecoverable == hasData => (luks /\ \E s \in Keyslots: slots[s] <= current) + +\* Reinitialization never runs over data. +NoFormatOverData == pc = "format" => ~hasData + +\* A running disk is keyed by its boot's epoch alone, and records it. +RunningIsMigrated == + pc = "running" => + /\ Keyslots = {slot} /\ slots[slot] = target + /\ IF token = NoToken THEN target = 0 ELSE token = [slot |-> slot, epoch |-> target] +============================================================================= diff --git a/docs/formal/key-rotation/EnvUpdate.cfg b/docs/formal/key-rotation/EnvUpdate.cfg new file mode 100644 index 0000000000..bf77ce3ce2 --- /dev/null +++ b/docs/formal/key-rotation/EnvUpdate.cfg @@ -0,0 +1,12 @@ +\* SPDX-FileCopyrightText: © 2026 Phala Network +\* SPDX-License-Identifier: Apache-2.0 + +SPECIFICATION Spec +CONSTANTS + MaxEpoch = 2 + MaxOwnerWrites = 2 + Lossy = TRUE + FailClosed = TRUE +INVARIANTS + OwnerUpdateKept + NoAppEnv diff --git a/docs/formal/key-rotation/EnvUpdate.tla b/docs/formal/key-rotation/EnvUpdate.tla new file mode 100644 index 0000000000..69a0cd06c4 --- /dev/null +++ b/docs/formal/key-rotation/EnvUpdate.tla @@ -0,0 +1,112 @@ +\* SPDX-FileCopyrightText: © 2026 Phala Network +\* SPDX-License-Identifier: Apache-2.0 + +------------------------------ MODULE EnvUpdate ------------------------------ +(***************************************************************************) +(* Environment re-encryption at boot (dstack-util unseal_env_vars) and the *) +(* VMM's once-per-boot update window (vmm app.rs update_sealed_env and the *) +(* boot.progress handler). *) +(* *) +(* An env value records which owner write it carries, the key epoch it is *) +(* encrypted to, and who stored it. The VMM opens the window when it *) +(* launches the VM, recording the stored env; the first update closes it *) +(* and is applied only over that env; boot progress reaching application *) +(* code also closes it. Owner updates (UpdateVm) can happen at any time. *) +(* *) +(* Lossy lets either host notification, or the answer to the guest's *) +(* update, be lost. With FailClosed (#1546) the guest starts applications *) +(* only once the host answered its update, retrying or stopping the boot *) +(* otherwise; without it, an unanswered update is only logged. *) +(***************************************************************************) +EXTENDS Naturals + +CONSTANTS MaxEpoch, MaxOwnerWrites, Lossy, FailClosed + +None == [owner |-> 0, epoch |-> 0, by |-> "none"] + +VARIABLES + current, \* current key epoch + store, \* env stored by the VMM + ownerWrites, \* number of owner updates so far + window, \* env recorded when the window opened, or None when closed + vm, \* guest step + seen \* env the guest read at boot + +vars == <> + +Init == + /\ current = 0 + /\ store = [owner |-> 0, epoch |-> 0, by |-> "owner"] + /\ ownerWrites = 0 + /\ window = None + /\ vm = "off" + /\ seen = None + +\* The VMM applies an update from the guest: once per boot, only over the +\* env the boot started with. +Deliver(env, empty) == + /\ window' = None + /\ store' = IF window # None /\ ~empty /\ store = window THEN env ELSE store + +Launch == + /\ vm = "off" + /\ vm' = "booting" + /\ window' = store + /\ seen' = store + /\ UNCHANGED <> + +\* Re-encrypt to the current epoch if needed and send it, empty otherwise. +\* An unanswered update, whether lost on the way or after the VMM applied +\* it, is retried under FailClosed; the boot may also stop (Stop). +GuestPush == + /\ vm = "booting" + /\ LET env == [owner |-> seen.owner, epoch |-> current, by |-> "guest"] + empty == seen.epoch = current + unanswered == IF FailClosed THEN "booting" ELSE "pushed" + IN \/ Deliver(env, empty) /\ vm' = "pushed" + \/ Lossy /\ Deliver(env, empty) /\ vm' = unanswered + \/ Lossy /\ UNCHANGED <> /\ vm' = unanswered + /\ UNCHANGED <> + +\* boot.progress "init-script": application code starts after this. +Progress == + /\ vm = "pushed" + /\ vm' = "app" + /\ \/ window' = None + \/ Lossy /\ UNCHANGED window + /\ UNCHANGED <> + +\* Application code calls the host API with an env of its choosing. +AppUpdate == + /\ vm = "app" + /\ Deliver([owner |-> seen.owner, epoch |-> current, by |-> "app"], FALSE) + /\ UNCHANGED <> + +OwnerUpdate == + /\ ownerWrites < MaxOwnerWrites + /\ ownerWrites' = ownerWrites + 1 + /\ store' = [owner |-> ownerWrites + 1, epoch |-> current, by |-> "owner"] + /\ UNCHANGED <> + +Stop == + /\ vm # "off" + /\ vm' = "off" + /\ window' = None + /\ UNCHANGED <> + +Rotate == + /\ vm = "off" /\ current < MaxEpoch + /\ current' = current + 1 + /\ UNCHANGED <> + +Next == Launch \/ GuestPush \/ Progress \/ AppUpdate \/ OwnerUpdate \/ Stop \/ Rotate + +Spec == Init /\ [][Next]_vars + +----------------------------------------------------------------------------- +\* The latest owner update is never replaced by an older one. +OwnerUpdateKept == store.owner = ownerWrites + +\* Application code never replaces the env. +NoAppEnv == store.by # "app" +============================================================================= diff --git a/docs/formal/key-rotation/EnvUpdateLossy.cfg b/docs/formal/key-rotation/EnvUpdateLossy.cfg new file mode 100644 index 0000000000..679e7c6431 --- /dev/null +++ b/docs/formal/key-rotation/EnvUpdateLossy.cfg @@ -0,0 +1,12 @@ +\* SPDX-FileCopyrightText: © 2026 Phala Network +\* SPDX-License-Identifier: Apache-2.0 + +SPECIFICATION Spec +CONSTANTS + MaxEpoch = 2 + MaxOwnerWrites = 2 + Lossy = TRUE + FailClosed = FALSE +INVARIANTS + OwnerUpdateKept + NoAppEnv diff --git a/docs/formal/key-rotation/EpochPolicy.cfg b/docs/formal/key-rotation/EpochPolicy.cfg new file mode 100644 index 0000000000..18cb9cfe48 --- /dev/null +++ b/docs/formal/key-rotation/EpochPolicy.cfg @@ -0,0 +1,20 @@ +\* SPDX-FileCopyrightText: © 2026 Phala Network +\* SPDX-License-Identifier: Apache-2.0 + +SPECIFICATION Spec +CONSTANTS + Values = {v1, v2} + Keys = {1, 2} + MaxEpoch = 2 + MaxRegistrations = 5 + KeyByChainHash = FALSE + Composes = {c1} + MaxAppEpoch = 2 + LegacyIgnoresAppEpoch = FALSE +CHECK_DEADLOCK FALSE +INVARIANTS + TypeOK + RevocationIsTotal + AppKeyMatchesSelectedRow +PROPERTIES + RegistrationStartsEmpty diff --git a/docs/formal/key-rotation/EpochPolicy.tla b/docs/formal/key-rotation/EpochPolicy.tla new file mode 100644 index 0000000000..0a33a423e6 --- /dev/null +++ b/docs/formal/key-rotation/EpochPolicy.tla @@ -0,0 +1,166 @@ +\* SPDX-FileCopyrightText: © 2026 Phala Network +\* SPDX-License-Identifier: Apache-2.0 + +----------------------------- MODULE EpochPolicy ----------------------------- +(***************************************************************************) +(* Epoch-scoped policy of DstackKms and DstackApp, and key release decided *) +(* on the selected rows. *) +(* *) +(* Root side (DstackKms): one row of allowed values (OS images; KMS MRs *) +(* and devices alike) per root epoch, written by *AtEpochs over a range *) +(* of registered rows. A pending epoch can be popped and registered again, *) +(* with the same or other keys. Rows are keyed by registration *) +(* (RootEpoch.registration); KeyByChainHash = TRUE models the earlier *) +(* contract, which keyed them by chain hash. *) +(* *) +(* App side (DstackApp): one row of allowed compose hashes per app epoch, *) +(* written over a range up to the next epoch. An app policy predating app *) +(* epochs (v0.5.x, v0.6.0) has only its flat mapping, which is row 0, and *) +(* epoch-less setters writing it; DstackKms authorizes it through *) +(* isAppAllowed for app epoch 0 only. Its owner may upgrade it at any *) +(* time, keeping the mapping as row 0. LegacyIgnoresAppEpoch = TRUE drops *) +(* the app epoch 0 check of that fallback. *) +(***************************************************************************) +EXTENDS Naturals, Sequences + +CONSTANTS Values, Keys, MaxEpoch, MaxRegistrations, KeyByChainHash, + Composes, MaxAppEpoch, LegacyIgnoresAppEpoch + +VARIABLES + keys, \* keys of the registered root epochs, epoch e at index e + 1 + regs, \* registration of each registered root epoch + nextReg, \* registrations so far + cur, \* current root epoch + rows, \* <> pairs allowed + revoked, \* values removed from every registered row, not added since + legacy, \* the app policy predates app epochs + appCur, \* current app epoch + appRows, \* <> pairs allowed + appRevoked, \* compose hashes removed from every app row, not added since + leaked, \* a key released for a revoked value or compose hash + mismatched \* an app key released for an app epoch whose row disallows it + +vars == <> +rootVars == <> +appVars == <> +ghostVars == <> + +Latest == Len(keys) - 1 +RowKey(ks, rs, e) == IF KeyByChainHash THEN SubSeq(ks, 1, e + 1) ELSE <> +Row(e) == {v \in Values: <> \in rows} +AppRow(a) == {c \in Composes: <> \in appRows} + +Init == + /\ \E k \in Keys: keys = <> + /\ regs = <<0>> /\ nextReg = 1 /\ cur = 0 + /\ rows = {} /\ revoked = {} + /\ legacy \in BOOLEAN /\ appCur = 0 /\ appRows = {} /\ appRevoked = {} + /\ leaked = {} /\ mismatched = FALSE + +\* ---- DstackKms ---- +Register(k) == + /\ Latest < MaxEpoch /\ nextReg < MaxRegistrations + /\ keys' = Append(keys, k) + /\ regs' = Append(regs, nextReg) + /\ nextReg' = nextReg + 1 + /\ UNCHANGED <> + +Activate == + /\ cur < Latest + /\ cur' = cur + 1 + /\ UNCHANGED <> + +Pop == + /\ Latest > cur + /\ keys' = SubSeq(keys, 1, Latest) + /\ regs' = SubSeq(regs, 1, Latest) + /\ UNCHANGED <> + +\* add*AtEpochs / remove*AtEpochs(from, to, v); one row is from = to. +Write(from, to, v, allowed) == + /\ from <= to /\ to <= Latest + /\ LET written == {<>: e \in from..to} + IN rows' = IF allowed THEN rows \cup written ELSE rows \ written + /\ revoked' = IF allowed THEN revoked \ {v} + ELSE IF from = 0 /\ to = Latest THEN revoked \cup {v} + ELSE revoked + /\ UNCHANGED <> + +\* ---- DstackApp ---- +AppWrite(from, to, c, allowed) == + /\ ~legacy /\ from <= to /\ to <= appCur + 1 + /\ LET written == {<>: a \in from..to} + IN appRows' = IF allowed THEN appRows \cup written ELSE appRows \ written + /\ appRevoked' = IF allowed THEN appRevoked \ {c} + ELSE IF from = 0 /\ to = appCur + 1 THEN appRevoked \cup {c} + ELSE appRevoked + /\ UNCHANGED <> + +\* The epoch-less setters of a legacy policy write its only row. +LegacyWrite(c, allowed) == + /\ legacy + /\ appRows' = IF allowed THEN appRows \cup {<<0, c>>} ELSE appRows \ {<<0, c>>} + /\ appRevoked' = IF allowed THEN appRevoked \ {c} ELSE appRevoked \cup {c} + /\ UNCHANGED <> + +Upgrade == + /\ legacy /\ legacy' = FALSE + /\ UNCHANGED <> + +Advance == + /\ ~legacy /\ appCur < MaxAppEpoch + /\ appCur' = appCur + 1 + /\ UNCHANGED <> + +\* ---- Key release ---- +\* kms_serve releases keys of the current epoch at most; the key handover +\* may carry a registered pending one. +KmsRelease(op, e, v) == + /\ e <= (IF op = "kms_export_keys" THEN Latest ELSE cur) + /\ v \in Row(e) + /\ leaked' = IF v \in revoked THEN leaked \cup {<<"root", e, v>>} ELSE leaked + /\ UNCHANGED <> + +\* app_get_key for root epoch e <= current and app epoch a. A legacy policy +\* is asked through isAppAllowed, which reads its only row. +AppRelease(e, a, v, c) == + /\ e <= cur /\ v \in Row(e) + /\ IF legacy + THEN (a = 0 \/ LegacyIgnoresAppEpoch) /\ c \in AppRow(0) + ELSE a <= appCur /\ c \in AppRow(a) + /\ leaked' = leaked \cup (IF v \in revoked THEN {<<"root", e, v>>} ELSE {}) + \cup (IF c \in appRevoked THEN {<<"app", a, c>>} ELSE {}) + /\ mismatched' = (mismatched \/ c \notin AppRow(a)) + /\ UNCHANGED <> + +Next == + \/ Activate \/ Pop \/ Upgrade \/ Advance + \/ \E k \in Keys: Register(k) + \/ \E from, to \in 0..MaxEpoch, v \in Values, allowed \in BOOLEAN: Write(from, to, v, allowed) + \/ \E from, to \in 0..MaxAppEpoch + 1, c \in Composes, allowed \in BOOLEAN: AppWrite(from, to, c, allowed) + \/ \E c \in Composes, allowed \in BOOLEAN: LegacyWrite(c, allowed) + \/ \E op \in {"kms_serve", "kms_export_keys"}, e \in 0..MaxEpoch, v \in Values: KmsRelease(op, e, v) + \/ \E e \in 0..MaxEpoch, a \in 0..MaxAppEpoch, v \in Values, c \in Composes: AppRelease(e, a, v, c) + +Spec == Init /\ [][Next]_vars + +----------------------------------------------------------------------------- +TypeOK == cur <= Latest /\ Latest <= MaxEpoch /\ Len(regs) = Len(keys) /\ appCur <= MaxAppEpoch + /\ (legacy => appCur = 0) + +\* A value or compose hash removed from every row gets no key of any root or +\* app epoch, for any operation, until it is added again; including through a +\* root epoch popped and registered again, and across the upgrade of a legacy +\* app policy. +RevocationIsTotal == leaked = {} + +\* An app key of app epoch a is released only when row a allows the compose +\* hash; for a legacy policy, only app epoch 0, its flat mapping. +AppKeyMatchesSelectedRow == ~mismatched + +\* A root epoch registration starts with an empty row, whatever its keys. +RegistrationStartsEmpty == + [][Len(keys') > Len(keys) => + \A v \in Values: <> \notin rows']_vars +============================================================================= diff --git a/docs/formal/key-rotation/EpochPolicyChainHash.cfg b/docs/formal/key-rotation/EpochPolicyChainHash.cfg new file mode 100644 index 0000000000..58751f4fb8 --- /dev/null +++ b/docs/formal/key-rotation/EpochPolicyChainHash.cfg @@ -0,0 +1,16 @@ +\* SPDX-FileCopyrightText: © 2026 Phala Network +\* SPDX-License-Identifier: Apache-2.0 + +SPECIFICATION Spec +CONSTANTS + Values = {v1, v2} + Keys = {1, 2} + MaxEpoch = 2 + MaxRegistrations = 5 + KeyByChainHash = TRUE + Composes = {c1} + MaxAppEpoch = 2 + LegacyIgnoresAppEpoch = FALSE +CHECK_DEADLOCK FALSE +INVARIANTS + RevocationIsTotal diff --git a/docs/formal/key-rotation/EpochPolicyLegacyAppEpoch.cfg b/docs/formal/key-rotation/EpochPolicyLegacyAppEpoch.cfg new file mode 100644 index 0000000000..b96abd94a7 --- /dev/null +++ b/docs/formal/key-rotation/EpochPolicyLegacyAppEpoch.cfg @@ -0,0 +1,16 @@ +\* SPDX-FileCopyrightText: © 2026 Phala Network +\* SPDX-License-Identifier: Apache-2.0 + +SPECIFICATION Spec +CONSTANTS + Values = {v1, v2} + Keys = {1, 2} + MaxEpoch = 2 + MaxRegistrations = 5 + KeyByChainHash = FALSE + Composes = {c1} + MaxAppEpoch = 2 + LegacyIgnoresAppEpoch = TRUE +CHECK_DEADLOCK FALSE +INVARIANTS + AppKeyMatchesSelectedRow diff --git a/docs/formal/key-rotation/KmsRotation.cfg b/docs/formal/key-rotation/KmsRotation.cfg new file mode 100644 index 0000000000..e1956460a7 --- /dev/null +++ b/docs/formal/key-rotation/KmsRotation.cfg @@ -0,0 +1,13 @@ +\* SPDX-FileCopyrightText: © 2026 Phala Network +\* SPDX-License-Identifier: Apache-2.0 + +SPECIFICATION Spec +CONSTANTS + Nodes = {n1, n2, n3} + MaxRoots = 4 +SYMMETRY Symmetry +CHECK_DEADLOCK FALSE +INVARIANTS + ReleasedFromRegisteredRoots +PROPERTIES + HandoverAgreesWithRegistry diff --git a/docs/formal/key-rotation/KmsRotation.tla b/docs/formal/key-rotation/KmsRotation.tla new file mode 100644 index 0000000000..3a78bada7f --- /dev/null +++ b/docs/formal/key-rotation/KmsRotation.tla @@ -0,0 +1,123 @@ +\* SPDX-FileCopyrightText: © 2026 Phala Network +\* SPDX-License-Identifier: Apache-2.0 + +----------------------------- MODULE KmsRotation ----------------------------- +(***************************************************************************) +(* KMS root epochs: the DstackKms registry, KMS keyrings, onboarding and *) +(* key release, as implemented by the contract and dstack-kms *) +(* (main_service.rs servable_epoch/authorized_epoch, onboard_service.rs *) +(* ensure_handover_registered). *) +(* *) +(* A root is an opaque fresh value; a keyring is the sequence of roots of *) +(* epochs 0..latest. A node serves the current epoch when its keyring *) +(* holds it and the chain hash over epochs 0..current matches the *) +(* registry, which is equality of the prefixes. *) +(* *) +(* The owner registers whatever a generating node attests (the evidence *) +(* binds the epoch and keys, not the earlier roots) and activates an epoch *) +(* once some node can serve it. Operators may wipe a node to re-onboard. *) +(***************************************************************************) +EXTENDS Naturals, Sequences, TLC + +CONSTANTS Nodes, MaxRoots + +VARIABLES + reg, \* registered roots, epoch e at index e + 1 + cur, \* current epoch + kr, \* keyring of each node; <<>> before bootstrap or onboarding + fresh, \* next fresh root + released \* <> pairs whose derived keys were released + +vars == <> + +Prefix(s, n) == SubSeq(s, 1, n) +Latest(n) == Len(kr[n]) - 1 + +\* servable_epoch: the keyring holds the current epoch with its chain hash. +Serves(n) == Len(reg) > 0 /\ Len(kr[n]) > cur /\ Prefix(kr[n], cur + 1) = Prefix(reg, cur + 1) + +Init == + /\ reg = <<>> /\ cur = 0 /\ kr = [n \in Nodes |-> <<>>] + /\ fresh = 1 /\ released = {} + +Bootstrap(n) == + /\ kr[n] = <<>> /\ fresh <= MaxRoots + /\ kr' = [kr EXCEPT ![n] = <>] + /\ fresh' = fresh + 1 + /\ UNCHANGED <> + +\* Handover from src (onboard_service.rs ensure_handover_registered): src +\* passes its kms_export_keys self-check (it serves the current epoch) and +\* holds nothing beyond the latest registered epoch. Epochs past the current +\* one are checked only through the latest registered epoch's chain hash, +\* so a source holding some of them must hold the latest one and match it. +\* A rotation starts from the current epoch with nothing pending. +CanHandOver(src, rotate) == + LET held == Latest(src) + latest == Len(reg) - 1 + IN /\ Serves(src) + /\ held <= latest + /\ ~(held > cur /\ held < latest) + /\ held = latest => kr[src] = reg + /\ rotate => held = cur /\ latest = cur + +Join(dst, src) == + /\ kr[dst] = <<>> /\ CanHandOver(src, FALSE) + /\ kr' = [kr EXCEPT ![dst] = kr[src]] + /\ UNCHANGED <> + +RotationJoin(dst, src) == + /\ kr[dst] = <<>> /\ CanHandOver(src, TRUE) /\ fresh <= MaxRoots + /\ kr' = [kr EXCEPT ![dst] = Append(kr[src], fresh)] + /\ fresh' = fresh + 1 + /\ UNCHANGED <> + +\* registerRootEpoch with the keys node n generated for the next epoch. +Register(n) == + /\ Len(kr[n]) = Len(reg) + 1 + /\ reg' = Append(reg, kr[n][Len(reg) + 1]) + /\ UNCHANGED <> + +Activate == + /\ Len(reg) > cur + 1 + /\ \E n \in Nodes: Len(kr[n]) > cur + 1 /\ Prefix(kr[n], cur + 2) = Prefix(reg, cur + 2) + /\ cur' = cur + 1 + /\ UNCHANGED <> + +Pop == + /\ Len(reg) > cur + 1 + /\ reg' = SubSeq(reg, 1, Len(reg) - 1) + /\ UNCHANGED <> + +Wipe(n) == + /\ kr[n] # <<>> + /\ kr' = [kr EXCEPT ![n] = <<>>] + /\ UNCHANGED <> + +\* GetAppKey for epoch e <= current, current or historical. +Release(n, e) == + /\ Serves(n) /\ e <= cur + /\ released' = released \cup {<>} + /\ UNCHANGED <> + +Next == + \/ Activate \/ Pop + \/ \E n \in Nodes: Bootstrap(n) \/ Register(n) \/ Wipe(n) \/ \E e \in 0..cur: Release(n, e) + \/ \E d, s \in Nodes: d # s /\ (Join(d, s) \/ RotationJoin(d, s)) + +Spec == Init /\ [][Next]_vars + +Symmetry == Permutations(Nodes) + +----------------------------------------------------------------------------- +\* Keys are only ever released from the registered root of their epoch, so +\* no two roots are ever used for one epoch. +ReleasedFromRegisteredRoots == + \A r \in released: r[1] <= cur /\ reg[r[1] + 1] = r[2] + +Agrees(k) == \A e \in 1..Len(k): e <= Len(reg) => k[e] = reg[e] + +\* An ordinary handover only passes on roots the registry agrees with, so a +\* recipient can serve every registered epoch it received once activated. +HandoverAgreesWithRegistry == [][\A d, s \in Nodes: Join(d, s) => Agrees(kr[s])]_vars +============================================================================= diff --git a/docs/formal/key-rotation/README.md b/docs/formal/key-rotation/README.md new file mode 100644 index 0000000000..b5e8cfede8 --- /dev/null +++ b/docs/formal/key-rotation/README.md @@ -0,0 +1,74 @@ + + +# Key rotation models + +TLA+ models of the [KMS key rotation protocol](../../kms-emergency-key-rotation-protocol.md) +as implemented, checked exhaustively with TLC within the stated bounds. + +| Model | Covers | Implementation | +| --- | --- | --- | +| `KmsRotation.tla` | Root epoch registry, KMS keyrings, onboarding, key release | `DstackKms.sol`, `kms/src/main_service.rs`, `kms/src/onboard_service.rs` | +| `DiskMigration.tla` | Data disk setup and LUKS key migration, with crashes and rotations | `dstack-util/src/system_setup.rs`, `system_setup/luks.rs` | +| `EnvUpdate.tla` | Env re-encryption at boot and the VMM update window | `dstack-util/src/system_setup.rs`, `vmm/src/app.rs` | +| `EpochPolicy.tla` | Root and app epoch policy rows, range setters, pop and re-registration, legacy app policies, key release on the selected rows | `DstackKms.sol`, `DstackApp.sol` | + +## Running + +```bash +java -cp tla2tools.jar tlc2.TLC -config DiskMigration.cfg DiskMigration.tla +``` + +| Config | Bounds | Result | +| --- | --- | --- | +| `KmsRotation.cfg` | 3 nodes, 4 roots | `ReleasedFromRegisteredRoots` and `HandoverAgreesWithRegistry` hold (4,423 states); also with 4 nodes, 5 roots (57,889 states) | +| `DiskMigration.cfg` | epochs 0-3 | all invariants hold (828 states) | +| `EnvUpdate.cfg` | epochs 0-2, 2 owner updates, lossy host API, fail-closed guest | `OwnerUpdateKept` and `NoAppEnv` hold (267 states) | +| `EnvUpdateLossy.cfg` | same, guest only logs an unanswered update | `NoAppEnv` violated | +| `EpochPolicy.cfg` | root epochs 0-2, 5 registrations, 2 choices of keys, 2 values; app epochs 0-2, 1 compose hash | `RevocationIsTotal`, `AppKeyMatchesSelectedRow` and `RegistrationStartsEmpty` hold (6,104,564 states) | +| `EpochPolicyChainHash.cfg` | same, rows keyed by chain hash | `RevocationIsTotal` violated | +| `EpochPolicyLegacyAppEpoch.cfg` | same, legacy app fallback ignores the requested app epoch | `AppKeyMatchesSelectedRow` violated | + +Checked with TLC 2026.11.06 on OpenJDK 21. `EnvUpdate.cfg` models the guest of +#1546; `EnvUpdateLossy.cfg` the guest before it. + +Each model was checked against mutations of the implementation, each of which +produces a counterexample: + +- `DiskMigration`: requiring a single keyslot when the current key unlocks none + (a migration interrupted before a later rotation then fails every boot); + opening without removing the old keyslot; treating a disk that still carries + the initializing label as initialized. +- `KmsRotation`: skipping the latest registered epoch's chain hash check on + handover, which lets an ordinary join pass on a losing pending root. +- `EnvUpdate`: starting applications after an unanswered update. +- `EpochPolicy`: the two configs above; and treating a removal from the + current epoch through the latest as a revocation, as the epoch-less setters + before #1561 did, which lets a historical row still release the key. + +## Abstractions + +- A key epoch in `DiskMigration` and `EnvUpdate` stands for the (root, app) + epoch pair; the KMS serves every epoch up to the current one. Authorization + is assumed to allow the instance at each of them; `EpochPolicy` models the + rows that decide it, and a migrating instance must be allowed in the old + rows too. +- In `KmsRotation`, keys are released for epochs up to the current one and + handed over up to the latest registered one, the operation bounds of + `kms_serve`/`app_get_key` and `kms_export_keys`/`kms_import_keys`. +- `EpochPolicy` merges the root materials (OS image, KMS MR and device) into + one row per epoch, and the app materials into compose hashes; a release + needs one allowed value in each selected row. It has one app and no KMS + nodes; `KmsRotation` covers the keyrings. +- A boot fetches its keys once; the KMS may rotate at any point of + `DiskMigration`, and between boots in `EnvUpdate`. +- Each cryptsetup command on the device is atomic: it writes a new keyslot + area before the header copies, syncs each, and repairs an outdated copy on + the next load. A crash may stop a boot between any two commands. +- Roots are unique values; chain hash comparison is prefix equality. +- The owner registers what a generating node attests and activates an epoch once + some node can serve it. Governance and attestation are trusted. +- `EnvUpdate` does not model a VMM without `UpdateSealedEnv`, which has no + update window. diff --git a/docs/guest-api-auth.md b/docs/guest-api-auth.md new file mode 100644 index 0000000000..0531145a5a --- /dev/null +++ b/docs/guest-api-auth.md @@ -0,0 +1,182 @@ +# Guest Agent API access control + +The guest agent's external listener (port 8090) is reachable by anyone who can +route to the CVM. It refuses callers it cannot identify: every request names a +scope, and a scope is granted either by a signed token or by the host's +configuration. + +This is an exposure control, not a confidentiality one. It decides who may +*ask*. Whether the answer may leave the TEE is decided by the app's measured +`public_logs` / `public_sysinfo` / `public_tcbinfo` switches, and a token can +only narrow what those allow. See +[the two gates](#the-two-gates) below. + +## Scopes + +| Scope | Grants | +|---|---| +| `guest:version` | `Worker.Version` on either pRPC surface | +| `guest:health` | `Worker.Health` (`/prpc/v1`) | +| `guest:info` | `Worker.Info` on either surface, and the identity block on the dashboard | +| `guest:attest-app-key` | the frozen `Worker.GetAttestationForAppKey` | +| `guest:dashboard` | the dashboard page itself | +| `guest:containers` | the container table on the dashboard | +| `guest:logs` | `/logs/`, when the app sets `public_logs` | +| `guest:metrics` | `/metrics`, and the sysinfo block on the dashboard | + +`/prpc`, `/prpc/v0` and `/prpc/v1` are matched after percent-decoding and +segment normalisation, so `/prpc/Worker.Info`, `/prpc/v0/Info` and +`/%70rpc/Info` all need `guest:info`. + +The check fails closed: a path the table does not name is answered with 401, +not passed to the router. + +## Default: nothing anonymous + +With no `[cvm.guest_agent_api]` block, an anonymous caller is granted nothing: +the dashboard, its identity block, `/metrics` and the log views all need a +token. The gateway still works, because it is issued one internally. The app's +own SDKs are unaffected: they use the internal Unix socket, which is +unauthenticated and reachable only by the application. + +The sample `vmm.toml` ships the block filled in with what an unconfigured 8090 +used to serve, so a host that copies the sample keeps the page it had: + +| Scope | Effect | +|---|---| +| `guest:version` | `Worker.Version` answers | +| `guest:health` | `Worker.Health` answers | +| `guest:info` | the identity block renders | +| `guest:dashboard` | the page loads at all | + +Everything else is about the app's *contents* and stays behind a token even in +that sample: the container table, `/metrics`, the log views and +`Worker.GetAttestationForAppKey`. + +The dashboard does not fetch `Info` unless a block would show it, so an +anonymous visitor granted only `guest:dashboard` costs the TEE no attestation. + +## Configuring anonymous access + +Anonymous access is a host decision, made in sys-config. The VMM writes it from +`[cvm.guest_agent_api]`: + +```toml +[cvm.guest_agent_api] +anonymous_scopes = ["guest:dashboard", "guest:version", "guest:health", "guest:info"] +``` + +The same block in the guest's `/dstack/.host-shared/.sys-config.json`: + +```json +{ + "guest_agent_api": { + "anonymous_scopes": ["guest:dashboard", "guest:version", "guest:health", "guest:info"] + } +} +``` + +The list is whole, not additive, and there is no built-in default to fall back +on: omitting `anonymous_scopes`, or leaving the list empty, closes the listener +to anonymous callers. Removing the block entirely does the same. + +Listing `guest:dashboard` without `guest:containers`, `guest:info`, `guest:logs` +or `guest:metrics` gives an anonymous visitor the page with every block hidden. +Scopes are independent: each one adds exactly its own block. + +An unknown name is a boot error rather than a permission that silently never +matches. + +## External issuers + +Other than its own token, the agent accepts tokens from issuers the host names: + +```toml +[[cvm.guest_agent_api.external_issuers]] +name = "ops" +public_keys = ["2f8d...c1"] # hex Ed25519 public keys, 32 bytes each +``` + +`name` is the exact `iss` claim a token must carry; `public_keys` is a list so a +key can be rotated by publishing the new one beside the old, waiting until the +tokens it signed have expired, then dropping the old one. The agent does not +cap token lifetimes; there is no revocation list, so `exp` is the issuer's +only exposure control. + +Tokens must be Ed25519. `alg: none`, HMAC, and headers carrying key material +(`jku`, `x5u`, `jwk`) are not rejected by policy -- the header is a constant, +so they cannot be expressed. + +### Where the internal issuer comes from + +The gateway does not hold the app root key; the CVM mints its token and hands +it over on registration, bound to the app id: + +1. The agent and `dstack-util`, both inside the CVM, derive the same Ed25519 + key: `derive_app_key(app_root_key, "dstack:guest-api:issuer:v1", Ed25519)`. + That domain string is final: it is a wire contract between `dstack-util` and + the agent, which are upgraded together but may briefly disagree, so it is + never versioned again. +2. `dstack-util` signs a token with `iss = "dstack:guest-api:"`, + `aud = `, only the `guest:health` scope, `iat` rounded down to the + year and `exp` ten years later. Every registration within a year carries + the same token, and it never lapses while registration is down. +3. Registration carries it to the gateway, which presents it on the v1 `Health` + poll. + +The host cannot mint an internal token: the signing key is derived from the app +root key, which KMS releases only after the boot measurement is verified. The +host can still name its own [external issuer](#external-issuers) and grant +itself any scope; that is the same exposure as listing the scope in +`anonymous_scopes`, and still bounded by the measured switches. + +### Trust inside the CVM + +The CVM is one trust domain; the agent does not sandbox the processes in it. The +issuer key is an ordinary v1 application key, so any process that can reach +`dstack.sock` can obtain it with +`GetKey(domain = "dstack:guest-api:issuer:v1", algorithm = ed25519)` and mint a +token with any scope. That is by design -- the same process can already read +the data those scopes expose -- and it is also how an app issues tokens of its +own. Do not mount `dstack.sock` into a container you would not trust with +that. + +## The two gates + +Two independent checks decide what a caller sees, and both must pass: + +| Gate | Source | Measured | Answers | +|---|---|---|---| +| `public_logs`, `public_sysinfo`, `public_tcbinfo` | app-compose | yes | may this data leave the TEE at all? | +| scopes | sys-config | no | may this caller ask? | + +They combine with `&&`. A token cannot reveal logs the app kept private -- with +`public_logs = false` the route is not even mounted -- and an anonymous caller +cannot see a block it was not granted, however public the app made it. + +Scope configuration is deliberately unmeasured. Host-supplied sys-config is not +part of the attestation, so a host could grant a caller more than the operator +intended. That grants nothing beyond what anonymous 8090 access already granted +before this change: the data is still gated by the measured switches, which a +host cannot alter without changing the app id. + +## Compatibility + +A guest with this change answers 401 to an old gateway that presents no token. +The gateway counts that as unreachable and drops the instance after +`failure_threshold` consecutive polls, so a mixed cluster rebalances away from +new guests until the gateway is upgraded. + +During the rollout, either upgrade the gateway first, or leave the host open: + +```toml +[cvm.guest_agent_api] +anonymous_scopes = ["guest:version", "guest:health", "guest:info", "guest:dashboard"] +``` + +The reverse direction is quieter. A new guest registers with an old gateway +node that does not store `agent_token`; when that record syncs to an upgraded +node, the missing token means the upgraded node's health probe is refused too. +The instance drops out of rotation while `order_by_stickiness` keeps routing +user traffic to it. Upgrade every gateway node in the cluster before rolling +guests, not just the one the VMM talks to. diff --git a/docs/guest-api-v0.md b/docs/guest-api-v0.md index 50861e12ba..9dfacba919 100644 --- a/docs/guest-api-v0.md +++ b/docs/guest-api-v0.md @@ -48,6 +48,11 @@ the agent's own tests: `get_key_pins_the_frozen_chain_link` in `dstack/guest-agent/src/server.rs` exercise the real mount table rather than a restatement of it. +One addition is sanctioned: the `root_epoch` and `app_epoch` selectors on +`GetKey`, described in [Key epochs](#key-epochs). A KMS key rotation changes +every key this surface derives, and v1 derives different keys altogether, so +without them a v0 key from before a rotation would be unreachable. + Two behaviour changes in 0.6.0 are sanctioned and do not alter the wire shape: `GetQuote` fails on a platform without Intel TDX instead of returning an empty quote, and `GetTlsKey` rejects a `not_before` that is not earlier than @@ -116,13 +121,15 @@ with a two-link signature chain proving where it came from. It is the reason thi document exists: it is the one method on this surface whose output other parties depend on, and until now its bytes lived only in the implementation. -`GetKeyArgs` has three fields. +`GetKeyArgs` has five fields. | Field | Type | Reaches the KDF | |---|---|---| | `path` | string | **yes**, verbatim | | `purpose` | string | no | | `algorithm` | string | no | +| `root_epoch` | optional uint32 | selects the IKM | +| `app_epoch` | optional uint32 | selects the IKM | Only `path` reaches the KDF. `purpose` is echoed into the chain claim of link 0 and has no other effect: two calls differing only in `purpose` return the same @@ -138,7 +145,7 @@ and there is no BIP-32-style hierarchy. The empty string is a valid `path`. ```text salt = "RATLS" (5 bytes, ASCII: 52 41 54 4c 53) -IKM = app root secp256k1 private key (32 bytes, `k256_key` from .appkeys.json) +IKM = app root secp256k1 private key (32 bytes, of the selected key epochs) info = path (the caller's bytes, verbatim) L = 32 @@ -155,6 +162,26 @@ The salt is the constant `LEGACY_SALT` in `dstack/ra-tls/src/kdf.rs`. It is the five ASCII bytes `RATLS`. It is baked into every key deployed before the versioned API and must never change. +### Key epochs + +`root_epoch` and `app_epoch` select the KMS root key epoch and the application +key epoch whose app root key is the IKM. Each defaults to the CVM's current +epoch, which is the app root key in `.appkeys.json`; epoch 0 is the original +keys. A selector newer than the current epoch fails. An older one makes the agent +fetch that epoch's app root key from the KMS, which must still authorize this +instance under the policy of that epoch; the agent keeps it in memory afterwards. + +The epochs change the IKM and nothing else: the KDF, the algorithm handling and +the chain encoding are as below, and link 1 is the KMS signature of the selected +epoch. With no selector set, a CVM that never saw a key rotation derives exactly +the keys v0.5.11 did. + +`GetKeyResponse.root_epoch` and `app_epoch` report the epochs the key was derived +from. An agent older than these fields ignores the selectors and omits them from +its response, so a client that sets a selector must check that the response +carries the epochs it asked for. `Tappd.DeriveK256Key` takes `GetKeyArgs` too and +honours the selectors, but its response has no epoch fields. + ### Algorithm selection `normalize_algorithm` maps the caller's string to a canonical name: `k256` diff --git a/docs/guest-api-v1.md b/docs/guest-api-v1.md index c870ae00b3..652b8fff5e 100644 --- a/docs/guest-api-v1.md +++ b/docs/guest-api-v1.md @@ -458,6 +458,11 @@ The v1 `Worker` has three methods, served at `/prpc/v1`. Nothing here returns key material, and no caller chooses what gets signed or attested. +Every method also needs a scope, granted by a signed token or by the host's +configuration. With no configuration the listener answers only token holders; +see [Guest Agent API access control](./guest-api-auth.md) for the vocabulary and +for how the gateway authenticates its health polls. + ### There is no v1 AttestAppKey The frozen surface has `Worker.GetAttestationForAppKey`, which attests a key the diff --git a/docs/kms-emergency-key-rotation-protocol.md b/docs/kms-emergency-key-rotation-protocol.md new file mode 100644 index 0000000000..350af7558b --- /dev/null +++ b/docs/kms-emergency-key-rotation-protocol.md @@ -0,0 +1,371 @@ +# KMS emergency key rotation protocol + +**Status:** Implemented. + +## 1. Scope and assumptions + +- Threat model: KMS root private keys are exposed, while disk data, LUKS headers, + and provider/host access are not. Repair the KMS environment before rotation. +- Stop all application CVMs and gateways; upgrade their OS and restart together. +- Reuse DstackKms governance and its OS allowlist. Assume configured chain RPCs + are trusted; RPC rollback and malicious-host/data anti-rollback are out of scope. +- Keep existing root-public-key pins. Affected deployments are handled separately. +- Rotate LUKS keyslots only; the underlying volume key remains unchanged. +- Every current KMS stores and hands over the complete root history, epochs 0..N. +- KMS stores no individual migration progress. No JWT, live rotation, or gateway + admission-lease protocol is introduced. + +**Storage boundary:** old root + old LUKS header reveals the unchanged volume +key. If ciphertext is later exposed, this can affect post-rotation data too. +Treat historical headers/snapshots as sensitive and inventory/isolate/dispose of +copies operationally. Full reencryption is future work if host/storage exposure +enters the threat model; slot replacement is not equivalent protection. + +## 2. Behavior summary + +Historical GetAppKey requests return complete epoch material and stay available +without a deadline, so late or restored instances can still migrate. Automatic recovery covers +disk keyslots and environment ciphertext with cloud-platform assistance; +application-owned GetKey data and wallets remain application responsibilities. +Onboarding supports ordinary full-history import and rotation import followed +by local generation of the next epoch. Sections 6-7 specify these flows. + +## 3. Roots, policy, and compatibility + +`api_version` selects protocol behavior; `root_epoch` identifies root material. +Epoch 0 is the existing roots, with existing derivation formulas and outputs +unchanged. Every epoch selector is optional; unset means the current epoch. +The name leaves room for a separate per-app epoch later. Generate +independent fresh CA and secp256k1 roots for each new epoch; existing derivation +formulas can remain unchanged. Never reuse an epoch for different roots. + +DstackKms keeps a registry of each epoch's root public keys, whose keys and +chain hash never change once registered (a pending epoch may be popped), an +`evidenceUrl` locating the attestation that proves where they were generated, and +a chain hash `h_n = keccak256(h_{n-1} || keccak256(caPubkey) || keccak256(k256Pubkey))` +(zero `h_{-1}`) committing to every key up to `n`; the position in the chain +fixes `n`, and hashing each key first keeps the preimage fixed-length. The +contract accepts only the encodings the KMS produces: a 91-byte P-256 DER +SubjectPublicKeyInfo with an uncompressed point, and a 33-byte compressed +secp256k1 key, so one key cannot be registered under two encodings. The +evidence stays off chain (stored on chain it would cost about 720 gas per byte) +and needs no hash: its report data binds the keys, so only availability depends +on the URL, which the owner can update (`setRootEpochEvidenceUrl`) when the +evidence moves. Registering an epoch and +making it current are separate: `registerRootEpoch` appends (epoch 0 becomes +current at once) and `activateRootEpoch(n)` moves the current epoch forward one +step. `popRootEpoch(n, chainHash)` drops the last epoch while it is still pending, for when +the nodes holding it are lost before activation; a re-rotation then registers a +new `n`, whose OS image, KMS MR and device rows start empty because policy rows +are keyed by the epoch's chain hash. Prepare them again before activating. A +current epoch is never popped. `kmsInfo` follows the current epoch: +registering epoch 0 and each activation copy its keys there and clear the legacy +quote and event log; the legacy `setKmsInfo`, `setKmsQuote` and `setKmsEventlog` setters are removed. Epoch 0 must be the `kmsInfo` keys +when those are set; a legacy `kmsInfo` quote and event log are converted off +chain into the standard attestation encoding (`Attestation::from_tdx_quote`) +before publishing. The KMS sends the epoch it serves and its chain hash (`rootEpoch`, +`rootEpochHash`) in every boot check, and the auth backend owns the policy: it +denies a KMS that does not serve the current epoch with the registered keys. +Info responses report the current epoch for KMS startup and onboarding; boot +responses are unchanged, and so is the on-chain `AppBootInfo`. +Governance credentials must remain independent and uncompromised. + +The KMS keyring and backups contain every epoch the node holds, not just the +latest two. Keeping old roots does not authorize issuing old derived keys. There +is no local epoch configuration: a KMS serves the current epoch on chain, +provided its keyring holds it and reproduces its chain hash, and waits +otherwise. When the current epoch moves, the KMS restarts to follow it and +re-signs its RPC certificate under the new root CA. Each epoch is stored under +`epochs//` with the attestation produced when its keys were generated, and +onboarding hands both over; a `root-epoch` marker records the newest stored +epoch. + +Historical epochs are not time-limited. Their roots are already exposed, so +withholding derived keys from authorized CVMs would not reduce what an attacker +can derive, while it would strand instances or backups that miss a deadline. +Old OS images are cut off through the OS allowlist instead. If host-side disk +rollback enters the threat model, a release deadline can be added later. + +Compatibility: keep accepting GetAppKey versions 0/1. An absent selector means +the current epoch, which before any rotation is epoch 0, so old OS images see no +change. After rotation they cannot open migrated disks; remove old OS images +through the existing allowlist and retain OS-image verification. Historical +epoch access never overrides OS/application authorization. + +## 4. GetAppKey additive extension + +Reuse the existing [GetAppKey transport and authorization path](../dstack/kms/src/main_service.rs), +without claiming a new KMS measurement-allowlist check on the guest. Preserve +root-public-key checking through `key_provider_id`; there is no separate guest +epoch pin or chain query. Unpinned deployments retain their existing KMS identity +limitations: this proposal does not create independent replacement-root trust +for them. Changing a pin can change compose/config hashes and related allowlists +or verifier expectations; affected deployments need separate coordinated updates. + +Keep `api_version = 1`; add one epoch selector: + +```protobuf +message GetAppKeyRequest { + uint32 api_version = 1; + string vm_config = 2; + // Unset = the current epoch, N = epoch N. + optional uint32 root_epoch = 3; +} +// Add to AppKeyResponse; preserve fields 1-8 and their types. +uint32 root_epoch = 9; +``` + +Unset resolves to current once for this request; unknown epochs are rejected. +Response `root_epoch` and all epoch-dependent material in fields 1-8 belong to +the resolved epoch. There is no separate source disk field. Every epoch up to +current uses the same normal authorization. A guest asks for an older epoch by +number only when it needs one, so a boot with nothing to migrate makes a single +request. + +An allowed historical request returns the complete historical AppKeyResponse, +including env and application keys, to preserve legacy compatibility. This +replaces the earlier disk-only server response proposal: the new OS extracts +only disk_crypt_key and, when needed, env_crypt_key for migration, discarding +other historical material. It retains its latest bundle for app startup. This +accepted tradeoff restricts recipients, not cryptographic uses of returned keys. + +The guest checks explicit epoch responses against the requested number. An old +KMS ignores the selector and serves epoch 0, reporting 0; that is +indistinguishable from a not-yet-rotated KMS using these fields alone. +Existing root-public-key pins and removal of old KMS endpoints remain essential; +unpinned clients gain no new downgrade protection. Do not rely on cached/disabled +KMS self-authorization for immediate revocation. Test JSON compatibility separately. + +Authenticate the KMS connection against current configured trust. Historical +ca_cert in the response is historical data, not a replacement transport trust +anchor: do not install it or compare it as though it were the current server pin. + +## 5. OS slot migration and LUKS header metadata + +Store the epochs in one LUKS2 JSON token bound to the keyslot holding their key: + +```json +{"type":"dstack-kms","keyslots":["0"],"root_epoch":2,"app_epoch":0} +``` + +The validator rejects nonzero subsystem, unexpected labels, and any token but +this one. It accepts keyslot 0, keyslot 1, or both (only mid-migration), each +with the same pinned parameters, and requires both header copies to agree. +Disks without the token are epoch 0. Requires cryptsetup 2.5 or later +(`--token-replace`, `--new-key-slot`); Debian trixie ships 2.7. + +```text +copy the header to tmpfs -> validate the copy + initialization label set -> reformat (the disk holds no data yet) + token_or_0 > current -> refuse + current key unlocks a keyslot of the copy -> finish + otherwise, token_or_0 < current -> refuse unless + unsafe_allow_disk_migration + -> old keys of epoch token_or_0 + -> check they unlock the recorded slot (token slot, else slot 0) + -> luksKillSlot any other slot + -> luksAddKey (old key authorizes the new key in the free slot) + -> recopy and validate -> finish + finish: token import (current epochs, surviving slot) -> luksKillSlot others + -> recopy, validate, and check the result -> open with the copy +``` + +Each step is one LUKS2 metadata commit, which cryptsetup keeps crash-consistent +across both header copies. Whatever step a crash interrupts, the next boot +finds either the old key alone or a keyslot the current key already unlocks, +so trying the current key first resumes the migration. If another rotation +happens before that boot, the current key unlocks neither of the two keyslots +an interrupted migration leaves; the token still names the slot of the recorded +epochs, so the other slot is dropped, but only once the recorded epochs' key is +confirmed to unlock that slot, and the migration restarts from it. A crash between +`luksFormat` and the token import leaves the initialization label set, which is +cleared only after the filesystem exists, so such a disk is reformatted. Never +format on unlock failure. Invalid or unsupported metadata requires recovery. +The disk is opened only with the last validated in-memory copy. + +The guest refuses such a disk unless the app compose sets +`requirements.unsafe_allow_disk_migration`, which is strongly discouraged. +Re-keying keeps the volume key. The old root and any copy of the old LUKS +header reveal it, and every host, storage backend or snapshot that saw the disk +before the rotation has such a copy, since the header is plaintext. Whoever +holds both can read and modify a migrated disk at any time, before or after the +migration, and no later check can tell. Disabling the flag afterwards does not +help: the disk is then at the current epochs and never migrates again. Use it +only when the old root is known not to have leaked, or when losing the data is +worse than exposing it to whoever holds that root; otherwise start from a fresh +disk and restore data at the application layer. A resumed migration whose +current key already unlocks a keyslot needs no flag. Refusing historical keys to +the new image in the old policy row also blocks migration, but for every app and +together with env migration and historical `GetKey`. + +No extra reboot is required. Historical material is confined to the migration +step, not persisted or passed to applications. +Old OS implementations with the existing validator reject a token-bearing disk; +this is an additional defense, not a substitute for the OS allowlist. Because of +that, an epoch-0 disk is never tagged: before any rotation the new OS leaves the +header untouched, so rolling back to an older OS image still works. Disks +formatted at a later epoch are tagged immediately. + +Tested in a Debian trixie container (cryptsetup 2.7.5, 32 MiB file images, +LUKS2/PBKDF2, no dm mapping): full migrations, resumption after each step, +disagreeing header copies, failed `luksAddKey` or denied old epochs leaving the +old epochs in place, failed token import, and disks recording newer epochs. +Old key-area wiping remains a release blocker. + +## 6. Environment migration, application keys, and TLS + +First decrypt env using latest. On authentication failure, try historical keys +from current down to 0, at most once each per boot; no platform metadata is +required. Skip an epoch whose key the KMS refuses, or that does not decrypt, until +one does: each historical key is still authorized by the KMS, and stopping at a +refusal would strand env encrypted under an older epoch whose image is approved +there but not in a newer row. The search costs at most current+1 RA-TLS requests, +only until the env has been migrated. Ciphertext no key decrypts fails closed; +env epoch is independent of the disk token. Empty env requires no migration. + +Decrypt/re-encrypt only inside the CVM, using current env public key, existing +format, and fresh randomness. The guest does not read the replacement back: +sealing and opening are deterministic code, so integration tests guarantee that +a re-sealed env opens on the next boot, after the VMM has replaced the old one. +The guest pushes the result to the VMM with `HostApi.UpdateSealedEnv` on +every boot, before any application code runs, sending an empty env when nothing +changed. The host API is reached over the VM's own vsock, so the VMM knows which +VM sent it. The VMM records the env each boot starts with and accepts one update +per boot, only if the stored env is still the boot env, so an owner's concurrent +update is never overwritten. The update closes the window, and the guest starts +init scripts and containers only once the VMM has answered, failing the boot +otherwise; application-stage progress reports close it as well. Application +containers and scripts therefore cannot replace the env. Rocket's per-method limit bounds the request (1 MiB by default). A +missed update is retried on the next boot. Plaintext and private keys never +leave the CVM. + +`GetAppEnvEncryptPubKey` keeps its interface. It always derives and signs with +the current epoch's roots and never serves historical epochs: env public keys +encrypt new data, so serving an older epoch would encrypt new secrets to a leaked +key. The signer public key identifies the epoch; no response field is added. +SDKs/frontends refresh cached env public keys before uploads; old-key uploads +are still migrated at boot, but put new secrets under an exposed key. Prompt owners to replace exposed +external credentials: reencryption alone does not revoke passwords/tokens. + +Guest API v1 `GetKey` takes an optional `root_epoch` (unset = current) and reports the epoch it +derived from; the SDKs expose it as an optional argument. The default is the +current epoch so new keys never come from an exposed root by accident. GetKey +outputs therefore change after a rotation: owners migrate app-encrypted records, +signing trust, wallets, and permissions by reading old keys with an explicit +`root_epoch` before releasing business services. The guest agent fetches an +older epoch's app root from the KMS the first time GetKey names it and keeps it +in memory; old roots are not stored in the keys file. The frozen v0 surface +always uses the current epoch. A per-app epoch, if added later, follows the same convention. SignCert +retains existing checks and signs under current roots; GetMeta is not a trust +anchor. Change CVM/gateway certificate trust in both directions. Public ACME +certificates remain separate. Orchestration gates all business activity, including +outbound workers, until readiness. + +## 7. Full-history KMS onboarding + +Onboarding imports the source's whole keyring, 0..S, and checks it against the +recipient's `authorizeKms` result: the current epoch's chain hash, and the latest +registered epoch L (`latestRootEpoch`, `latestRootEpochHash`). It never selects a +subset. A source holding epochs beyond L is refused ("source KMS holds +unregistered root epochs"). When S = L, the chain hash of L must match; chain +hashes are cumulative, so this binds the whole pending tail, not only the current +prefix. A source holding exactly the current epoch still joins; one stopping +between the current epoch and L is refused, since its tail cannot be checked. With +`rotate`, it then generates epoch S+1. + +| Mode | Source requirement | Result | +| --- | --- | --- | +| Ordinary join | Holds the current epoch and nothing unregistered; a registered tail pending activation must match the latest chain hash | Keyring 0..S | +| Rotation join (`rotate=true`) | Holds exactly up to the current epoch, with no epoch registered beyond it | Keyring 0..S plus fresh epoch S+1 and attestation evidence | + +Every handover requires the recipient's KMS attestation: the source checks the +attested RA-TLS client certificate on both `Admin.GetKmsKey` and the public +`KMS.GetKmsKey`. Admin authorization (`source_token`) is required for joins +and rotations alike, because the public `KMS.GetKmsKey` is off by default +(`core.onboard.public_key_handover = false`). Enable it on a source only for +receivers that cannot use the admin listener, such as 0.5.x KMS nodes, and +reject incompatible legacy receivers without reducing the payload. The source's certificate must carry its +OS image hash. +Deployments that never registered epochs can still join at epoch 0. + +For rotation, generate fresh roots and attest them with the bootstrap encoding +used for every epoch: report data is +`keccak256("dstack-kms-genereted-keys-v1:{ca_pubkey_hex};{k256_pubkey_hex};")` +zero-padded to 64 bytes. The "genereted" spelling is part of the released format. +The evidence only has to prove the key pair was generated in an approved TEE. +It binds neither the epoch number, which comes from the on-chain registration +order, nor the preceding chain hash, which joins already check against the +registry; a mismatch in either is an availability problem that `servable_epoch` +catches at once, not a key leak. Before registering N, the owner verifies the +quote with dstack-verifier, checks the approved code and measurements, and +recomputes the report data from the published keys; the cluster keeps +serving N-1. After the other nodes onboard and hold N, the owner activates N and +every KMS restarts onto it. An old-root signature is not authorization. +Competing generators cannot both be registered as N; a losing node's keyring no +longer reproduces the chain hash, so it never serves and must onboard again. It +also cannot hand its N over: joining from it fails the latest-epoch check while N +is pending, so the wrong tail does not reach later joiners. + +Every authorization request (app checks and the KMS self check that gates all +RPCs) carries the epoch the KMS serves, so a backend refuses a stale or forked +KMS. On a denial the KMS reads the current epoch from the info endpoint and +restarts if it moved. A KMS predating root epochs sends none; backends treat it +as epoch 0 and, once a later epoch is current, deny both its self check and its +app checks, so old KMS software stops serving. The contract's legacy +`isKmsAllowed` and `isAppAllowed` refuse as well, so this cutoff does not depend +on the backend. Upgrade every KMS before +activating a new epoch. In-flight operations are not cancelled. + +Backups retain full history; closing migration does not delete roots. Replacement +KMS boot cannot depend on its own unavailable service or stopped gateway ingress. +Protect root storage and independent admin access. + +## 8. Cutover runbook + +1. Inventory app/key dependencies, env ciphertext, pins, and historical snapshots. + Prepare trusted OS images, application recovery, and provider-pin adjustments. +2. Stop business writes, CVMs, gateways, and compromised KMS paths. Repair/replace + KMS execution and rotate independently exposed admin credentials. +3. Rotation-onboard one node, register its new epoch, then ordinary-onboard peers. + Authorize new KMS images before removing old OS images; do not rotate again + during the cutover. +4. Boot new OS with business services held by orchestration. Start apps from + fresh data disks; `requirements.unsafe_allow_disk_migration` keeps an old + disk but leaves it exposed to the old root (section 5). Migrate slots and + complete platform env replacement; confirm app readiness. Ingress closure alone does + not stop workers, cron jobs, queues, or outbound database/wallet writes. +5. Start gateways with fresh data directories/KV namespaces and clean WireGuard + peers. Rebuild required non-admission configuration from trusted sources; + never restore old registration databases or admit old sync nodes. +6. Re-register CVMs with new certificates and release approved business + services/ingress. Keep failed instances isolated for operator follow-up. +7. Notify env public-key verifiers (vmm-cli signer whitelists, frontends, SDK + callers) to replace the old k256 signer with the new one, preferably by reading + it from DstackKms. For vmm-cli, run `kms remove `, then + `kms add `. A stale whitelist entry does not break migration, but + lets anyone holding the old root and able to intercept client-to-KMS traffic + forge env public keys; the `root_epoch` in a response is set by its signer + and protects nothing. + +## 9. Invariants and acceptance + +[TLA+ models](formal/key-rotation/README.md) check the registry, disk +migration and env update steps against crashes and interleavings. + +Authenticate actual secret-bearing connections; old-CA signatures alone do not +replace evidence checks. Do not downgrade on failure or expose secrets in logs, +command lines, swap, app key files, or host-shared storage. Released secrets +cannot be recalled. Historical key possession, +current unlock success, and production readiness are three different facts. + +Test legacy compatibility, OS-allowlist cutoff, selector boundaries and epoch-0 compatibility, non-adjacent epochs, +both onboarding modes, full-history atomic persistence, pending registration +restart, competing roots, live stale-node rejection, and epoch mismatch, slot/token crash recovery, +new-key reboot success, old-key unlock failure against the working header, and +absence of residual old paths and recovery from missing/stale epoch tokens. Confirm the volume key intentionally stays the +same. Test env corruption, independent env epochs, concurrent platform updates, +response-source authentication, bounded epoch search, stale-key uploads, +replacement/reboot recovery, application readiness, +and clean gateway reauthentication/sync. +Reports must state OS/TEE, kernel/cryptsetup, filesystem/layout, builds, topology, +policy, and failure injections. The preliminary test above is limited evidence, not release validation. diff --git a/docs/onboarding.md b/docs/onboarding.md index 28b216ff2c..c46db76f59 100644 --- a/docs/onboarding.md +++ b/docs/onboarding.md @@ -14,8 +14,8 @@ curl http://127.0.0.1:8080/ AMD SEV-SNP hosts use the same `dstackup` and `dstack` commands after you provide a guest image that contains the image digest (`digest.txt`); see -[AMD SEV-SNP Support](./amd-sev-snp.md) for the experimental platform's image, -attestation, and KMS requirements. +[AMD SEV-SNP Support](./amd-sev-snp.md) for the platform's image, attestation, +and KMS requirements. The default onboarding flow uses a published image. To build or customize the guest OS first, follow [Build the dstack guest OS](./building-guest-os.md), then @@ -33,7 +33,7 @@ For multi-node production, Gateway TLS, custom domains, or on-chain governance, - Source and build cache under `/var/cache/dstack`. - Runtime sockets and process state under `/run/dstack`. - A localhost-only VMM dashboard on port `9080`. -- A local `dstack-auth` webhook and `dstack-vmm` systemd unit. +- A local `dstack-auth` webhook (development, testing and evaluation only) and `dstack-vmm` systemd unit. - A single KMS CVM unless you pass `--no-kms`. - A direct host port mapping for your app. @@ -312,3 +312,26 @@ dstack logs ``` The KMS VM ID is printed by `dstackup install` when it creates or reuses the KMS CVM. + +### Upgrading the local KMS to root epochs + +Upgrade the bundled `dstack-auth` together with the KMS. Before normal key release, +set `kmsContractAddr` in the host's `auth-allowlist.json` to the KMS's attested app ID +and register the verified bootstrap CA/k256 public keys in `rootEpochs` (epoch zero). +Use the bootstrap evidence to verify these keys; do not trust an unauthenticated +metadata response. Set `currentRootEpoch` to the active registered epoch (initially +zero). See [root registration and rotation](deployment.md#rotating-kms-root-keys). +The local installer does not register these keys automatically; an older installed +KMS can continue using the legacy boot routes while this migration is prepared. + +The Rust backend implements `/authorizeKms` and `/authorizeApp` with the same +registered-root requirement as the other backends. Missing registration denies key +release, and invalid epoch configuration returns HTTP 503. Legacy `/bootAuth/*` +routes remain available for bootstrap. Local compose/device allowlists apply to +all permitted historical roots; they are not the on-chain per-epoch matrices. + +Application entries also accept `currentAppEpoch` (default zero). Keep this value +monotonic, restart the application after advancing it, and retain permissions for +historical keys needed during migration. `/app/:appId` exposes the current app +epoch; legacy app boot authorization is denied once it is nonzero. The Rust +backend uses the same normalized app ID lookup for policy and epoch selection. diff --git a/docs/onchain-governance.md b/docs/onchain-governance.md index 777675399b..d9ff879a36 100644 --- a/docs/onchain-governance.md +++ b/docs/onchain-governance.md @@ -16,14 +16,12 @@ On-chain governance adds: - Production dstack deployment with KMS and Gateway as CVMs (see [Deployment Guide](./deployment.md)) - Ethereum wallet with funds on Sepolia testnet (or your target network) - [Foundry](https://book.getfoundry.sh/getting-started/installation) installed -- Node.js and npm installed (for the bootAuth server) ## Deploy DstackKms Contract ```bash cd dstack/kms/auth-eth -npm install # Install Node.js dependencies -forge install # Install Foundry dependencies +forge install # Install Foundry dependencies (git submodules) # Deploy contracts (deploys both DstackApp implementation and DstackKms proxy) PRIVATE_KEY= forge script script/Deploy.s.sol:DeployScript \ @@ -51,11 +49,13 @@ export RPC_URL="https://eth-sepolia.g.alchemy.com/v2/" ## Configure KMS for On-Chain Auth -The KMS CVM includes an auth-api service that connects to your DstackKms contract. Configure it via environment variables in the KMS CVM: +The KMS CVM includes an auth-api service, [auth-eth](../dstack/kms/auth-eth/), that connects to your DstackKms contract. Configure it via environment variables in the KMS CVM: ```bash KMS_CONTRACT_ADDR= ETH_RPC_URL= +ETH_CHAIN_ID= # optional, rejects decisions from another chain +ETH_BLOCK_TAG=finalized # latest, safe or finalized (default) ``` The auth-api validates boot requests against the smart contract. See [Deployment Guide](./deployment.md#2-deploy-kms-as-cvm) for complete setup instructions. @@ -63,7 +63,7 @@ The auth-api validates boot requests against the smart contract. See [Deployment ## Whitelist OS Image ```bash -OS_IMAGE_HASH=0x \ +OS_IMAGE_HASH=0x ROOT_EPOCH=0 \ forge script script/Manage.s.sol:AddOsImage --broadcast --rpc-url $RPC_URL ``` @@ -109,7 +109,7 @@ sha256sum /path/to/gateway-compose.json | awk '{print "0x"$1}' Then add it: ```bash -APP_CONTRACT_ADDR= COMPOSE_HASH= \ +APP_CONTRACT_ADDR= COMPOSE_HASH= APP_EPOCH=0 \ forge script script/Manage.s.sol:AddComposeHash --broadcast --rpc-url $RPC_URL ``` @@ -139,7 +139,7 @@ sha256sum /path/to/your-app-compose.json | awk '{print "0x"$1}' Then add it: ```bash -APP_CONTRACT_ADDR= COMPOSE_HASH= \ +APP_CONTRACT_ADDR= COMPOSE_HASH= APP_EPOCH=0 \ forge script script/Manage.s.sol:AddComposeHash --broadcast --rpc-url $RPC_URL ``` @@ -155,9 +155,11 @@ The central governance contract that manages OS image whitelisting, app registra | Function | Description | |----------|-------------| -| `addOsImageHash(bytes32)` | Whitelist an OS image hash | -| `removeOsImageHash(bytes32)` | Remove an OS image from whitelist | +| `addOsImageHashAtEpochs(uint256,uint256,bytes32)` | Whitelist an OS image hash in a range of root epochs | +| `removeOsImageHashAtEpochs(uint256,uint256,bytes32)` | Remove an OS image from a range of root epochs; `0` through the latest revokes it | | `setGatewayAppId(string)` | Set the trusted Gateway app ID(s) | +| `setAllowAnyTeeVariant(bool)` / `setAllowedTeeVariants(string[])` | Allow KMS instances and apps on any TEE platform, or only the listed ones, at every root epoch | +| `setSevSnpTcbRequirements(string)` | Publish the minimum TCB each CPU must meet for an SEV-SNP TCB to report `UpToDate`, as a JSON list (see [AMD SEV-SNP](./amd-sev-snp.md)). While empty, a KMS judges a CPU only against its own list, and refuses one neither lists | | `registerApp(address)` | Register an app contract | | `deployAndRegisterApp(...)` | Deploy and register app in one transaction | | `isAppAllowed(AppBootInfo)` | Check if an app is allowed to boot | @@ -165,18 +167,41 @@ The central governance contract that manages OS image whitelisting, app registra ### DstackApp (Per-App Contract) -Each app has its own contract controlling which compose hashes and devices are allowed. +Each app has its own contract controlling which compose hashes and devices are allowed, +per app epoch. Every setter names the app epoch rows it writes: one epoch, or a range up +to the next epoch. Removing a value from rows `0` through the current epoch revokes it. | Function | Description | |----------|-------------| -| `addComposeHash(bytes32)` | Whitelist a compose hash | -| `removeComposeHash(bytes32)` | Remove a compose hash from whitelist | -| `addDevice(bytes32)` | Whitelist a device ID | -| `removeDevice(bytes32)` | Remove a device from whitelist | -| `setAllowAnyDevice(bool)` | Allow any device to run this app | -| `isAppAllowed(AppBootInfo)` | Check if app can boot with given config | +| `addComposeHashAtEpoch(uint256,bytes32)` / `addComposeHashAtEpochs(uint256,uint256,bytes32)` | Whitelist a compose hash in one app epoch or a range | +| `removeComposeHashAtEpoch(uint256,bytes32)` / `removeComposeHashAtEpochs(uint256,uint256,bytes32)` | Remove a compose hash from one app epoch or a range | +| `addDeviceAtEpoch(uint256,bytes32)` / `addDeviceAtEpochs(uint256,uint256,bytes32)` | Whitelist a device ID | +| `removeDeviceAtEpoch(uint256,bytes32)` / `removeDeviceAtEpochs(uint256,uint256,bytes32)` | Remove a device | +| `setAllowAnyDevice(bool)` | Allow any device to run this app, at every app epoch | +| `setAllowAnyTeeVariant(bool)` / `setAllowedTeeVariants(string[])` | Allow any TEE platform, or only the listed ones (e.g. `dstack-tdx`), at every app epoch. Set the list before restricting: a restricted empty list refuses every platform | +| `currentAppEpoch()` | The app epoch new keys are derived for | +| `isAppAllowed(AppBootInfo)` | Check if app can boot with given config (app epoch 0 only) | | `disableUpgrades()` | Permanently disable contract upgrades | +#### Apps deployed before app epochs + +App contracts deployed from dstack 0.6.x or earlier, and not upgraded since, have only +app epoch 0 and the epoch-less setters `addComposeHash(bytes32)`, +`removeComposeHash(bytes32)`, `addDevice(bytes32)`, `removeDevice(bytes32)` and +`setAllowAnyDevice(bool)`. They keep working with an upgraded `DstackKms` and KMS, +which authorize them for app epoch 0. Tell the two kinds apart by ERC-165 interface ID: + +```bash +cast call "supportsInterface(bytes4)(bool)" 0x8c0524c4 --rpc-url $RPC_URL # IAppEpochManagement: epoch setters +cast call "supportsInterface(bytes4)(bool)" 0x8fd37527 --rpc-url $RPC_URL # IAppAuthBasicManagement: epoch-less setters +``` + +The `Manage.s.sol` app scripts check this themselves: on an older app they call the +epoch-less setter and accept only `APP_EPOCH=0` or no epoch; on a current app they +require `APP_EPOCH`, or `FROM_APP_EPOCH` and `TO_APP_EPOCH`. `SetAllowAnyDevice` takes +no epoch on either kind. Upgrading an older app to the current `DstackApp` keeps its +compose hashes and devices as app epoch 0, and its `allowAnyDevice` for every epoch. + ### AppBootInfo Structure Both `isAppAllowed` and `isKmsAllowed` take an `AppBootInfo` struct: diff --git a/docs/rc-testing-runbook.md b/docs/rc-testing-runbook.md index 971a451ed9..afa9c6aa95 100644 --- a/docs/rc-testing-runbook.md +++ b/docs/rc-testing-runbook.md @@ -153,8 +153,11 @@ KMS first, then gateway, then the app. Each needs the previous one's identity. gramine-sealing-key-provider on the host, default `127.0.0.1:3443`). The simplest authorization that releases keys without a chain is `[core.auth_api] type = "dev"` with `gateway_app_id = "any"` — no extra - containers, unlike the on-chain compose which needs a Helios light client. - Keep `[core.image] verify = true`. + containers, unlike the on-chain compose, which runs auth-eth next to the KMS + and needs an Ethereum RPC endpoint. The KMS refuses to start without a + key handover path, dev auth included: give it `[listeners.admin]` with TLS + (`key`, `certs`) and an `auth_token_hash`, or set + `core.onboard.public_key_handover = true`. 3. **Gateway as a CVM** with `--kms`. Internal ports are RPC 8000, admin 8001, WireGuard 51820/udp, proxy 443. diff --git a/docs/sealed-env.md b/docs/sealed-env.md new file mode 100644 index 0000000000..6258d38a70 --- /dev/null +++ b/docs/sealed-env.md @@ -0,0 +1,141 @@ +# Sealed environment variables + +SealedEnv protects environment variables with HPKE and identifies the KMS root +and application key epochs needed to decrypt them. Plaintext remains inside the client and CVM; +the VMM stores and forwards ciphertext. + +## Wire format + +The `.sealed-env` file contains UTF-8 JSON: + +```json +{"version":1,"root_epoch":3,"app_epoch":0,"enc":"","ciphertext":""} +``` + +Version 1 fixes RFC 9180 Base mode with DHKEM(X25519, HKDF-SHA256), +HKDF-SHA256, and AES-256-GCM. `enc` is a 32-byte encapsulated key; `ciphertext` +includes the 16-byte authentication tag. Binary fields use standard padded +Base64. HPKE `info` is UTF-8 `dstack-sealed-env-v1:R:A`, where `R` and `A` are the canonical +decimal uint32 root and app epochs, with no leading zeros. AAD is empty. Unknown envelope +versions are rejected; extra JSON fields may be ignored. This provides +confidentiality, not authentication of the person uploading the environment. + +Plaintext uses the existing JSON representation: + +```json +{"env":[{"key":"MESSAGE","value":"Hello"}]} +``` + +The guest still enforces the application's environment-name allowlist. + +## Keys and signatures + +`GetSealedEnvPubKey` is available on KMS and proxied by VMM. Its request contains +`app_id` (20 bytes) only and always selects the current active epochs. Historical +private keys for decryption and migration are obtained through `GetAppKey`, not +through either environment public-key endpoint. The response contains +`public_key`, `root_epoch`, `app_epoch`, `timestamp`, and `signature`. + +For each app, the KMS derives the 32-byte receiver private key directly from +that epoch's P-256 CA private scalar using HKDF-SHA256: + +- salt: ASCII `dstack-sealed-env-v1`; +- IKM: the 32-byte P-256 private scalar; +- info: the raw 20-byte app ID. + +`GetAppKey` returns it as `sealed_env_key` alongside the legacy key. The legacy +key derivation remains unchanged at app epoch zero. `GetAppEnvEncryptPubKey` +rejects nonzero app epochs; use `GetSealedEnvPubKey` after app rotation. + +The public-key response signs Keccak256 of this unambiguous byte sequence: + +```text +"dstack-sealed-env-pubkey-v1:" || app_id[20] || root_epoch[4, big-endian] + || app_epoch[4, big-endian] || public_key[32] || timestamp[8, big-endian] +``` + +The signing key is the selected epoch's secp256k1 root. The signature is +`r[32] || s[32] || recovery_id[1]`. Clients must compare the recovered signer +against an independently trusted epoch root key or pin. Recovering a signer +alone is not a trust decision. Clients should reject stale responses (default +maximum age 300 seconds, future clock tolerance 60 seconds). + +## Image compatibility + +New image `metadata.json` files declare `"sealed_env": true`; `ListImages` exposes +this flag. Missing metadata means legacy encryption only. The UI and CLI use the target +image for both creation and environment updates, including image changes. +Old or unknown images use legacy encryption even with a capable KMS. Capable images require the SealedEnv RPC: CLI and UI fail on any lookup error, +including "service not found". Such errors are not signed and must not select a +weaker encryption protocol. Upgrade the KMS before submitting secrets for a +SealedEnv-capable image. + +The VMM also enforces the flag for API callers and `dstack-vmm run`, including +existing SealedEnv files in a reused one-shot workdir. Creation, updates and image changes +through resize reject an effective SealedEnv file when the target image lacks the +capability, before writing files or changing resources. An update may replace it +with nonempty legacy `encrypted_env` while switching to an older image. Empty env +fields preserve the existing format. Guest `UpdateSealedEnv` uploads also require +a capable running image. + +SealedEnv has one format, version 1, with both epoch fields always present. The +receiver-key KDF appends `"app-epoch-v1:" || app_epoch[4, big-endian]` to its info +for nonzero app epochs; at zero its info is just the app ID. Signature and HPKE +contexts always include both epochs, including zero. Changing either epoch +invalidates the signature or ciphertext. See [application epochs](app-key-epochs.md) +for owner operations. + +The browser UI receives the key through the same-origin VMM API and does not +independently verify the response signer or freshness. Its trust boundary includes +the VMM and the configured KMS connection; it does not provide the independently +pinned signer verification described above. Use the CLI with a trusted signer +allowlist, or an SDK verification helper with an independently trusted signer, +when that verification is required. + +## File precedence and migration + +A new guest chooses `.sealed-env` whenever that file exists. An empty, invalid, +or unreadable sealed file is an error; it must not fall back to a legacy file. +If no sealed file exists, the guest accepts `.encrypted-env` for compatibility. +The copy limits are 384 KiB for sealed JSON and 256 KiB for legacy ciphertext. + +At boot, sealed ciphertext explicitly selects its historical root/app epoch pair. The +guest obtains that epoch's app key over the already trusted KMS connection, +decrypts, and seals to the current epoch. Legacy ciphertext uses the legacy +key path at app epoch zero, trying earlier root epochs when necessary. It is +converted to SealedEnv only when decrypted with a historical epoch. Ciphertext +already decryptable with the current keys is left unchanged, even in the legacy +format; an older KMS need not provide a SealedEnv key in that case. +A future epoch or failed authentication stops environment provisioning. + +The guest sends `UpdateSealedEnv` through the host channel before application +code runs. The VMM binds the update to the VM's CID and a snapshot of both env +files, including presence. It accepts at most one update in the boot window; +an empty update closes the window without replacing files. Owner updates and +guest replacement share the VM launch lock so an owner change cannot be lost +between the snapshot comparison and write. + +The window is guaranteed closed before application code runs: the VMM closes it +as soon as it identifies the VM and then always answers, logging why an env was +not stored, and the guest starts init scripts and containers only after an +answer, failing the boot if none comes after a few retries. A VMM that predates +`UpdateSealedEnv` has no window; the guest recognizes its unknown-method answer. + +VM creation and update accept either `sealed_env` or legacy `encrypted_env`. +Supplying both nonempty fields is rejected. Writing one format removes the other: +an external legacy update after a guest sealed update therefore becomes the +sole environment for the next boot. Omitting both preserves existing files on +update. A replacement is safely written before the other file is removed; +filesystem errors are reported rather than ignored. + +Old OS images understand only `.encrypted-env`. After conversion removes that +file, reverting to an old OS requires the owner to upload legacy ciphertext +again. Rotation does not revoke credentials exposed before migration, and +cannot erase old host snapshots. + +## Scope of verification + +Local tests exercise HPKE implementations with synthetic keys, signature +contexts, file precedence and update races. They do not establish production +TEE isolation or real-chain availability. The shared fixture under +`sdk/fixtures/sealed-env/` is public test data, never deployment key material. diff --git a/docs/security/cvm-boundaries.md b/docs/security/cvm-boundaries.md index 8c4380c230..10dd920367 100644 --- a/docs/security/cvm-boundaries.md +++ b/docs/security/cvm-boundaries.md @@ -33,19 +33,21 @@ This is the main configuration file for the application in JSON format: | kms_enabled | 0.3.1 | boolean | Enable/disable KMS | | gateway_enabled | 0.3.1 | boolean | Enable/disable gateway | | local_key_provider_enabled | 0.3.1 | boolean | Use a local key provider | -| key_provider_id | 0.5.1 | string | Optional pin for the key provider identity (hex-encoded bytes). For `kms` this is the KMS CA public key; for `local` the sealing-provider MR. For `tpm` and `none` it must be an empty string — the TPM app-root public key is instance-specific and is not used as a provider id or measured as one. When empty, any provider is accepted; its identity is still recorded in the `key-provider` launch event. | +| key_provider_id | 0.5.1 | string | Optional pin for the key provider identity (hex-encoded bytes). For `kms` this is the KMS CA public key; for `local` the sealing-provider MR. For `tpm`, `sev-snp`, `tdx-seal` and `none` it must be an empty string — the TPM app-root public key is instance-specific and is not used as a provider id or measured as one. When empty, any provider is accepted; its identity is still recorded in the `key-provider` launch event. | | public_logs | 0.3.3 | boolean | Whether logs are publicly visible | | public_sysinfo | 0.3.3 | boolean | Whether system info is public. Covers the guest dashboard and `/metrics`, including the `dstack_gpu_*` series (since 0.6.0), which expose each GPU's UUID and PCI bus address alongside utilization, memory, temperature and power. | | public_tcbinfo | 0.5.1 | boolean | Whether TCB info is public | -| allowed_envs | 0.4.2 | array of string | List of allowed environment variable names | +| allowed_envs | 0.4.2 | array of string | List of allowed environment variable names. An entry may be `NAME: spec` to also constrain the value, see [Environment value specs](#environment-value-specs). | | no_instance_id | 0.4.2 | boolean | Disable instance ID generation | | secure_time | 0.5.0 | boolean | Whether secure time is enabled | | pre_launch_script | 0.4.0 | string | Prelaunch bash script that runs before `docker compose up`. It runs *after* dockerd, so containers restored by a Docker restart policy can already be running when it executes. Do not build security gates on it — see [security-best-practices.md](./security-best-practices.md#security-semantics-must-not-depend-on-pre_launch_script-running-first). | | init_script | 0.5.5 (string), 0.6.0 (string[]) | string or string[] | Up to 5 Bash scripts executed in order prior to dockerd startup, so they always complete before any container starts, on every boot; a string is treated as a one-element array. Multiple scripts require string `manifest_version: "3"` so older guests fail closed. MrConfigV3 binds the hashes only for manifest v3. | | storage_fs | 0.5.5 | string | Filesystem type for the data disk of the CVM. Supported values: "zfs", "ext4". default to "zfs". **ZFS:** Checksums every block, so a modified block fails the read. **ext4:** Lower overhead and faster I/O for database workloads; checksums metadata but not file data, so a modified block is not detected. | | storage_discard | 0.6.0 | boolean | Return unused data-disk blocks to the host. Defaults to `true` so encrypted sparse images track live data instead of historical writes. Set to `false` if revealing filesystem allocation and deletion patterns to the host is unacceptable. | +| requirements.ephemeral_data_disk | 0.6.3 | boolean | Start every boot with an empty data disk. The guest formats the data disk before any app code runs, so app code sees nothing an earlier boot wrote. With storage encryption on (the default), each format generates a fresh LUKS volume key, so earlier ciphertext, including a disk image the host rolled back, can no longer be decrypted. With encryption off, old blocks may remain readable on the raw device. Images and container layers live on the data disk, so every boot pulls them again. Defaults to `false`. Requires string `manifest_version: "3"`. | +| requirements.unsafe_allow_disk_migration | 0.6.7 | boolean | **Strongly discouraged.** Let the guest re-key a data disk left at older KMS key epochs after a key rotation instead of refusing to boot on it. Re-keying keeps the volume key, which the old root and any copy of the old LUKS header (held by every host or snapshot that saw the disk) reveal, so whoever holds them can read and modify the disk for good, including after the migration; disabling the flag later does not help. Use a fresh data disk instead. Defaults to `false`. Requires string `manifest_version: "3"`. | | swap_size | 0.5.5 | string/integer | The linux swap size. default to 0. Can be in byte or human-readable format (e.g., "1G", "256M"). | -| key_provider | 0.5.6 | string | Key provider type. Supported values: "none", "kms", "local", "tpm". GCP vTPM and AWS EC2 NitroTPM are part of their platform trust models. The Dstack platform can use VMM-managed swtpm for seal/unseal and restart persistence, but it offers no protection against the host and is intentionally not accepted by remote verifiers. | +| key_provider | 0.5.6 | string | Key provider type. Supported values: "none", "kms", "local", "tpm", "sev-snp", "tdx-seal". `sev-snp` and `tdx-seal` derive keys from the CPU's hardware sealing key on the current host. GCP vTPM and AWS EC2 NitroTPM are part of their platform trust models. The Dstack platform can use VMM-managed swtpm for seal/unseal and restart persistence, but it offers no protection against the host and is intentionally not accepted by remote verifiers. | The five-script limit bounds runtime-event-log and MrConfigV3 growth while allowing several independently approved infrastructure initialization stages. @@ -59,8 +61,8 @@ This file contains metadata about the application instance: | Field | Description | |-------|-------------| | app_id | The application ID. This is the deploy-time `app_id` from this file; when it is unset it defaults to the SHA256 digest of the app-compose.json (truncated to the first 20 bytes). The deploy-time value is honored in all key-provider modes. | -| instance_id | The instance ID, determined by the SHA256 digest of the instance_id_seed || app_id (truncated to the first 20 bytes). Empty if no_instance_id is true in app-compose.json | -| instance_id_seed | The random seed that determines the instance ID | +| instance_id | The instance ID: the SHA256 digest of instance_id_seed \|\| app_id, followed on GCP and AWS by a per-instance platform binding, truncated to the first 20 bytes. Empty if no_instance_id is true in app-compose.json. The host supplies the seed, so the instance ID is unique only together with the app ID: identify an instance by the (app_id, instance_id) pair | +| instance_id_seed | The 20-byte random seed that determines the instance ID. Generated by the CVM when empty. A seed of another length is used as given, with a warning, so an existing CVM keeps its instance ID | The hash of this file is not extended as a single measurement. Instead, the `app_id` and `instance_id` are extended as separate dstack launch events named `app-id` and `instance-id`. On TDX-family platforms those events go into RTMR3. On AWS NitroTPM they go into SHA384 PCR14. @@ -125,11 +127,46 @@ dstack uses encrypted environment variables to allow app developers to securely - CVM derives the shared secret using the ephemeral public key via X25519 key exchange - CVM decrypts the ciphertext using AESGCM with the derived shared secret - CVM parses the JSON and only stores variables listed in allowed_envs from app-compose.json - - CVM performs basic regex validation on values - - Final result is stored as /dstack/.host-shared/.decrypted-env.json and passed to app-compose.service through `dstack-util exec-with-env` + - CVM validates variable names and checks each value against the specs given in allowed_envs + - Final result is stored as /dstack/.host-shared/.decrypted-env.json and passed to app-compose.service through `dstack-util exec-with-env`, which rejects variables outside allowed_envs and checks the values against the specs again This file is not measured to RTMRs, and the envelope is not bound to an instance or compose hash: the KMS derives `env_crypt_key` from the app ID alone, so the host can withhold the file or replay any earlier ciphertext for the same app. It is highly recommended to add application-specific integrity checks, such as a version or expiry inside the plaintext, at the application layer. See [security-best-practices.md](./security-best-practices.md) for more details. +#### Environment value specs + +Since 0.6.7, an `allowed_envs` entry may be `NAME: spec`, such as `PORT: int(1..=65535)`; the space after the colon is optional, and `NAME` must be `[A-Za-z_][A-Za-z0-9_]*`, at most 255 bytes, with nothing between it and the colon. The CVM refuses to boot when the encrypted environment gives `NAME` a value that does not match the spec. Before the application starts, after every `init_script` has run, a variable that is still not set counts as empty, so `NAME` is required unless its spec accepts the empty string, as one ending in `?` does. This last check is made by `app-compose.service`; a program that reads `.decrypted-env` on its own does not get it. A spec is one of: + +| Spec | Accepts | +|------|---------| +| `int` | any integer within `i128` | +| `int(1..=65535)` | integers from 1 to 65535 | +| `int(0\|1024..<65536)` | 0, or integers from 1024 up to but excluding 65536 | +| `float` | any decimal number, compared exactly | +| `float(0<..=1)` | decimals above 0 and up to 1 | +| `/mainnet\|testnet/` | values the regex matches in full | +| `int(1..=65535)?` | the empty string, or integers from 1 to 65535 | + +A range is `start..=end` or `start..` or `X-Admin-Token`. -- Gateway: set `[core.admin] admin_token` (or `htpasswd_file`) and keep `insecure_no_auth = false`. Clients send `Authorization: Bearer ` or `X-Admin-Token`. -- KMS: enable `[core.admin]` with an `auth_token` (or `htpasswd_file`); the admin RPCs are served on a dedicated listener and clients send `Authorization: Bearer ` or `X-Admin-Token`. Enabled with no credential denies all admin RPCs (fail-closed). +- Gateway: set `[listeners.admin] auth_token` (or `htpasswd_file`) and keep `insecure_no_auth = false`. Clients send `Authorization: Bearer ` or `X-Admin-Token`. +- KMS: enable `[listeners.admin]` with an `auth_token` (or `htpasswd_file`); the admin RPCs are served on that dedicated listener and clients send `Authorization: Bearer ` or `X-Admin-Token`. Enabled with no credential denies all admin RPCs (fail-closed). All three share the same HTTP authenticator: bcrypt-only htpasswd (via `htpasswd -B`), constant-time token comparison, and fail-closed behavior. @@ -129,7 +131,7 @@ The VMM RPC is a management interface for trusted operators and front-end servic ## Keep private material owner-only -Secret-bearing files should be owner-only (`0600`) wherever possible, including app keys, decrypted env files, KMS root keys, gateway WireGuard/TLS keys, and ACME credentials. Preserve restrictive permissions when copying volumes, backing up `/etc/kms/certs`, or moving gateway and certbot state between hosts. Public issue [#606](https://github.com/Dstack-TEE/dstack/issues/606) tracks the remaining low-cost hardening work in dstack-managed file writes. +Secret-bearing files should be owner-only (`0600`) wherever possible, including app keys, decrypted env files, KMS root keys, gateway WireGuard/TLS keys, and ACME credentials. Preserve restrictive permissions when copying volumes, backing up the KMS `keyring_dir`, or moving gateway and certbot state between hosts. Public issue [#606](https://github.com/Dstack-TEE/dstack/issues/606) tracks the remaining low-cost hardening work in dstack-managed file writes. ## docker logs is public available by default @@ -146,7 +148,7 @@ Example app-compose.json: ## Don't expose unexpected ports -In dstack CVM, dstack-guest-agent listens on port 8090, allowing public access to basic CVM information. +In dstack CVM, dstack-guest-agent listens on port 8090. It is not anonymous by default; see [guest-api-auth.md](../guest-api-auth.md) for what the host can grant anonymously. In docker-compose.yaml, all declared ports will be exposed to the public internet. Do not expose unnecessary ports. diff --git a/docs/security/security-model.md b/docs/security/security-model.md index 1791e970d4..51999f7bfa 100644 --- a/docs/security/security-model.md +++ b/docs/security/security-model.md @@ -8,7 +8,7 @@ This document helps you evaluate whether dstack's security model fits your needs dstack removes the need to trust most infrastructure operators. On TEE platforms such as Intel TDX and AMD SEV-SNP, the cloud or host operator cannot read your protected memory, modify your measured code, or access your secrets without detection. On AWS EC2 NitroTPM attested instances, AWS Nitro is part of the trusted platform, and the untrusted party is the workload AWS account administrator/operator. Network attackers cannot intercept your traffic because TLS terminates inside the attested environment with keys controlled by that environment (Zero Trust HTTPS). Docker registries cannot serve malicious images because the guest verifies SHA256 digests before pulling. -The primary trust input is **attested platform hardware**. Intel TDX is the production TEE path. AMD SEV-SNP is available where the selected dstack OS image and host support it, but it is new and experimental. AWS EC2 NitroTPM attested instances use a different trust root: the AWS Nitro system and AWS NitroTPM attestation PKI. In that mode, the threat model protects against the workload AWS account administrator and EC2 operator actions, but AWS remains trusted. For GPU workloads, you also trust **NVIDIA GPU hardware**, NVIDIA's attestation PKI/RIMs, and its revocation service (or NRAS when a deployment selects remote verification). These are hardware-level trust assumptions. +The primary trust input is **attested platform hardware**. On bare metal, dstack supports Intel TDX and AMD SEV-SNP; SEV-SNP instances in public clouds are not supported yet. AWS EC2 NitroTPM attested instances use a different trust root: the AWS Nitro system and AWS NitroTPM attestation PKI. In that mode, the threat model protects against the workload AWS account administrator and EC2 operator actions, but AWS remains trusted. For GPU workloads, you also trust **NVIDIA GPU hardware**, NVIDIA's attestation PKI/RIMs, and its revocation service (or NRAS when a deployment selects remote verification). These are hardware-level trust assumptions. Everything else is verifiable. @@ -63,10 +63,12 @@ An application may additionally set `requirements.gpu_policy` to an object with - `attest_gpu` (boolean, default `true`): require local NVIDIA GPU attestation before enabling an attached GPU. Setting this to `false` skips attestation and is an explicit reduction in protection. - `rego` (optional string): a Rego v0 script evaluated with the nvattest output's `claims` array as `input`. It must define the boolean entrypoint `data.policy.nv_match` in `package policy`. -- `allow_devtools` (boolean, default `false`): permit NVIDIA DevTools mode. Production applications should leave this disabled because DevTools removes the expected GPU memory-confidentiality guarantee. +- `allow_devtools` (boolean, default `false`): skip dstack's NVML DevTools check. It cannot make a DevTools GPU boot with `attest_gpu` on: DevTools changes the GPU's signed measurements, so NVIDIA's appraisal fails. DevTools lifts the GPU's profiling and debugging restrictions and must not be used in production. - `allow_debug` (boolean, default `false`): permit an attestation claim whose `dbgstat` is `enabled`. - `allow_insecure_boot` (boolean, default `false`): permit an attestation claim whose GPU `secboot` value is false. +nvattest sets `dbgstat` to `disabled` and `secboot` to `true` exactly when the measurements match, and dstack always requires `measres == "success"`, so `allow_debug` and `allow_insecure_boot` currently have no effect. + The optional Rego v0 policy can enforce deployment-specific claims. A minimal `app-compose.json` containing one looks like this; replace the placeholder with the policy source: ```json @@ -112,9 +114,9 @@ The policy digest is remotely verifiable on each supported platform, but through - **TDX:** `gpu-policy-hash` contains the raw 32-byte digest and is measured into RTMR3. Replay the event log and compare the result with the quote's RTMR3, then compare the event payload with the expected digest. When an MrConfigV3 document includes `gpu_policy_hash`, TDX `MR_CONFIG_ID` additionally binds that field. - **AWS NitroTPM:** the same `gpu-policy-hash` event is extended into non-resettable SHA384 PCR14. Replay the PCR14 event chain against the signed NitroTPM Attestation Document, then compare the payload with the expected digest. -- **AMD SEV-SNP:** there is no quote-bound runtime event register in the current stack. Instead, GPU launches put the digest in optional `MrConfigV3.gpu_policy_hash`, and the signed SNP report's `HOST_DATA` binds the exact MrConfigV3 document. Verify the SNP report and `HOST_DATA` binding, then compare the field with the expected digest. If the optional field is absent, this check is not asserted. +- **AMD SEV-SNP:** there is no quote-bound runtime event register in the current stack. The signed SNP report's `HOST_DATA` binds the exact MrConfigV3 document, whose `compose_hash` covers the app-compose file and so the policy in it; the guest stops boot if that file does not match. GPU launches also put the digest in `MrConfigV3.gpu_policy_hash`. Verify the SNP report and `HOST_DATA` binding, then compare the policy, or the field when present, with the expected one. -For every NVML-enumerated GPU, dstack calls `Device::is_cc_enabled()` and `Device::is_cc_dev_mode_enabled()` and requires the NVML device count to match the expected GPU count. CC must always be ON; DevTools must be OFF unless the measured policy explicitly permits it. The typed claim checks always require `measres == "success"`; by default they also require `dbgstat == "disabled"` and `secboot == true`, with the latter two checks controlled by their explicit opt-ins. Only after the default appraisal, typed claim checks, optional Rego policy, and per-device NVML checks succeed does dstack call `Device::set_confidential_compute_state(true)` to set the GPU ready state. The dstack CPU/guest boot chain is verified independently through measured boot; a GPU claim named `secboot` refers to the GPU appraisal, not UEFI Secure Boot in the CVM. +For every NVML-enumerated GPU, dstack calls `Device::is_cc_enabled()` and `Device::is_cc_dev_mode_enabled()` and requires the NVML device count to match the expected GPU count. CC must always be ON; DevTools must be OFF unless the measured policy explicitly permits it. These NVML checks only give an early, specific error: the guest driver reads both states from GPU registers over MMIO, which the host can emulate. The signed evidence is what excludes DevTools. Its firmware and driver measurements differ from NVIDIA's reference values, so `measres` is not `success`. The typed claim checks always require `measres == "success"`; by default they also require `dbgstat == "disabled"` and `secboot == true`, with the latter two checks controlled by their explicit opt-ins. Only after the default appraisal, typed claim checks, optional Rego policy, and per-device NVML checks succeed does dstack call `Device::set_confidential_compute_state(true)` to set the GPU ready state. The dstack CPU/guest boot chain is verified independently through measured boot; a GPU claim named `secboot` refers to the GPU appraisal, not UEFI Secure Boot in the CVM. ### Dual Attestation @@ -151,7 +153,8 @@ The GPU gate itself runs before the app keys are requested, and a failed gate st ``` `devtools` is the aggregate NVML state and is true if any device has DevTools -mode enabled. `dbgstat` and `secboot` summarize the NVIDIA-signed claims: +mode enabled. It is host-reported; the signed `measres` check is what excludes +DevTools. `dbgstat` and `secboot` summarize the NVIDIA-signed claims: `dbgstat` is `enabled` if any device reports enabled, and `secboot` is true only if every device reports secure boot. The complete per-device claims remain in the boot-time evidence committed by `evidence_sha256`. @@ -172,7 +175,9 @@ The events make the following **boot-time** statement: immediately before key pr This is **not a lifetime or physical co-location guarantee**. After `system-ready`, an application with sufficient guest privileges can unload the NVIDIA driver, and a malicious host may attempt PCI hot-remove/replacement or proxy GPU traffic. The boot event remains a true historical statement but does not prove that the same device is still attached. dstack also cannot rule out a live relay/cuckoo attack to a genuine remote GPU: current Hopper/Blackwell deployments do not provide a CPU-TEE-verifiable TEE-I/O/TDISP device binding. Applications that mutate the driver or PCI topology are outside this guarantee; higher-assurance deployments must prevent that behavior and re-attest before using a newly initialized GPU; the guest-agent `/v1/AttestGpu` API does that re-check against a caller-chosen nonce, returning bundles tagged `nvidia-nvattest-collect-evidence-json-v1` rather than the boot-time format. Being an NVIDIA report, its result is subject to the same relay caveat as any attestation-time GPU sample: it establishes that a genuine CC-enabled GPU is reachable and responsive now, not that the device is bound to this TD, so it must not be forwarded to a remote relying party as proof of GPU possession. -AMD SEV-SNP has no runtime measurement register in the current dstack stack. The local boot gate can still fail closed, but a `gpu-attestation` event carried beside an SNP report is not remotely bound to that report and must not be accepted as dual-attestation evidence. SNP needs a measured vTPM/PCR channel before it can provide the same remote binding. +AMD SEV-SNP gets the same boot-time statement from the gate itself. The launch `MEASUREMENT` covers the dstack OS that runs the gate, and `HOST_DATA` binds the `compose_hash` that fixes the policy. Because the gate runs before key provisioning and before the application starts, and stops boot on any failure, a verified SNP report from the running application proves that the gate passed under that policy. Even on TDX, `gpu-attestation` records the guest's own appraisal of the GPU rather than a GPU-signed report, so both platforms rest on the same measured gate. + +What SNP lacks is the per-boot record. It has no runtime measurement register in the current dstack stack, so a `gpu-attestation` event or boot-time evidence carried beside an SNP report is not bound to it and must not be accepted as evidence. The default policy also accepts a launch with no GPU, so an SNP verifier that requires GPU protection must check that the measured policy keeps `attest_gpu` on and that its Rego rule requires the expected GPU count. A measured vTPM/PCR channel would let SNP carry the per-boot record as TDX does. ### AI Workload Protection @@ -276,8 +281,9 @@ Use this checklist to verify a workload running in a dstack CVM. - [ ] Exactly one `gpu-policy-hash` event follows `compose-hash`, and its payload matches `SHA-256(JCS(requirements.gpu_policy))` (default `{}` when omitted) - [ ] When MrConfigV3 includes `gpu_policy_hash`, it matches the same expected GPU policy digest - [ ] Exactly one `gpu-attestation` event appears before `system-ready` -- [ ] CC is ON and the event's DevTools field complies with the measured policy -- [ ] The platform binds the event log to a quoted RTMR/PCR (do not accept it from current SEV-SNP evidence) +- [ ] The event reports CC ON (DevTools is excluded by the signed appraisal, not by the event's `devtools` field) +- [ ] The platform binds the event log to a quoted RTMR/PCR (TDX, NitroTPM) +- [ ] On SEV-SNP, where the event checks above do not apply: the policy bound by `compose_hash` keeps `attest_gpu` on and its Rego rule requires the expected GPU count **Key management verification:** - [ ] key-provider matches expected KMS identity @@ -425,11 +431,12 @@ The KMS Rocket TLS listener permits connections without a client certificate bec App key release and KMS key handover require verified caller attestation from the RA-TLS client certificate. Certificate signing verifies the CSR signature and the attestation embedded in the CSR before signing. -The unauthenticated or non-client-certificate surface includes bootstrap and temp-CA bootstrap material retrieval, env-encryption public-key retrieval, metadata, health, and metrics behavior documented for operators. `GetTempCaCert` returns temp CA private material and remains in use by guests and by KMS-to-KMS onboarding, which mint their client certificates from that CA; operators must treat it as bootstrap-sensitive rather than harmless public metadata. +The unauthenticated or non-client-certificate surface includes bootstrap, env-encryption public-key retrieval, metadata, health, and metrics behavior documented for operators. Clients create self-issued certificates locally. The temporary-CA RPC and its public key material remain available for legacy clients. Guest key retrieval verifies the actual response connection's attestation and checks that the returned CA signed its RPC certificate. Provider pins and launch measurement continue to bind the selected KMS root identity; attestation alone does not authorize an arbitrary CVM as the expected KMS. KMS-to-KMS root-key handover is served by `Admin.GetKmsKey` on the authenticated admin listener, which additionally requires a verified RA-TLS client certificate. -The legacy public `KMS.GetKmsKey` is controlled by `core.onboard.public_key_handover`. +The legacy public `KMS.GetKmsKey` is off by default and is served only when +`core.onboard.public_key_handover = true` is set explicitly. ## Limitations diff --git a/docs/tdx-seal-key-provider.md b/docs/tdx-seal-key-provider.md new file mode 100644 index 0000000000..2b0d283752 --- /dev/null +++ b/docs/tdx-seal-key-provider.md @@ -0,0 +1,94 @@ +# TDX Hardware Key Provider + +The `tdx-seal` key provider derives a CVM's app keys and disk key from the TDX +module's hardware sealing key (`TDG.MR.KEY.GET`). No KMS, SGX enclave, or other +service is involved. The same CVM on the same host gets the same keys after every +restart, as long as the host's TDX module is not updated (see +[TDX module updates](#tdx-module-updates)). Use it for CVMs that must recover +their encrypted state on their own, such as a KMS CVM. Application CVMs normally +keep using `key_provider: kms`. + +## Requirements + +- A TDX module that reports `TDX_FEATURES0.HW_SEALING` (bit 12). The CPU + microcode matters too: module 2.0.18 reports it on a Xeon 6776P with microcode + `0x1000444`, but not on a Xeon 6767P with microcode `0x10003c2`. A guest on a + platform without sealing stops at boot with `the TDX module or CPU does not + support hardware sealing`. +- A dstack OS image that ships this provider, and a VMM that recognizes it. +- Encrypted storage, which is the default. + +No host configuration is needed. The guest kernel sets +`TDCS.TD_CTLS.ENABLE_HW_KEYS` itself, so neither KVM nor QEMU has to set the +`TD_PARAMS.CONFIG_FLAGS.SEALING` flag. + +## Enable the provider + +Set this field in the app-compose document: + +```json +{"key_provider": "tdx-seal"} +``` + +`dstack deploy --key-provider tdx-seal` and `vmm-cli.py compose --key-provider +tdx-seal` set the same field. The VMM rejects the provider on non-TDX hosts and +for simulated or `no_tee` CVMs. + +## What the key is bound to + +| Input | Changes when | +| --- | --- | +| Platform hardware secret | The CVM moves to another host | +| MRTD | The OVMF firmware changes | +| RTMR0 | vCPU count, memory size, attached devices, or ACPI tables change | +| RTMR1 | The kernel changes, or the memory size changes | +| RTMR2 | The kernel command line or initramfs changes | +| RTMR3 at `boot-mr-done` | The app id, compose hash, init scripts, GPU policy, or instance id changes | +| MROWNER | The host sets a different MROWNER | +| ATTRIBUTES and XFAM | TD attributes (for example DEBUG) or XSAVE features change | +| CPUSVN and TEE_TCB_SVN | Fixed at first boot, see [Recovery](#recovery) | + +The guest refuses to derive the key in a debug, profiled, or migratable TD. +Containers given +`/dev/tdx_guest` can call `TDG.MR.KEY.GET` too, but RTMR3 has moved past +`boot-mr-done` by then, so they cannot derive the provider's key again. + +TDX module 2.0.18 accepts the MRCONFIGID and MROWNERCONFIG policy bits but +ignores them during derivation, so the provider does not select them. RTMR3 +binds the app identity instead. + +## Recovery + +When it formats a new disk, the guest seals it to the running CPUSVN and +TEE_TCB_SVN, and stores them in `.instance_info` (`tdx_sealing`) through the +host API. Later boots derive the key for the stored SVNs, so a microcode update +that raises CPUSVN keeps the key. The stored values are host-supplied, but they +only select a key: values that differ from the first boot derive a key that does +not unlock the disk. Keep `.instance_info`, the encrypted disk, and the launch +configuration together. If the parameters are missing for an existing disk, or +their version is unknown, startup stops. + +This pinning is a trade-off. The TCB the disk was first sealed to can derive the +key for the disk's lifetime, even after a later update fixes a vulnerability in +it. Like any local sealing, it gives no rollback protection either: the host can +restore an older copy of the disk together with its `.instance_info`. + +When a measured input in the table changes, the CVM derives a different key and +the disk does not unlock. The data stays intact: restoring the original +configuration on the same host restores the key. Hardware replacement, OS +upgrades, compose changes, and VM resizing therefore need a migration path +outside this provider, such as the KMS onboarding and replication flow. + +## TDX module updates + +Treat every TDX module update on a host that runs `tdx-seal` CVMs as a key-loss +event, and migrate state such as KMS roots off those CVMs first. Intel only +specifies that sealing keys are bound to the platform; it does not promise that +they survive a module update, and the stored SVNs cannot recover a key the new +module derives differently. Two known cases: + +- Module 2.0.20 (and 1.5.36) mixes the key policy into the derivation, while + 2.0.18 (and 1.5.34) does not. The SVNs stay the same, but every key changes. +- Module 2.0.18 refuses a request for a lower module major SVN + (`TEE_TCB_SVN[1]`), although it accepts a lower CPUSVN and a lower minor SVN + (`TEE_TCB_SVN[0]`). An update that raises the major SVN loses the key. diff --git a/docs/tutorials/contract-deployment.md b/docs/tutorials/contract-deployment.md index b5e4298713..cc940dd9af 100644 --- a/docs/tutorials/contract-deployment.md +++ b/docs/tutorials/contract-deployment.md @@ -12,7 +12,7 @@ tags: - kms - ethereum - sepolia - - hardhat + - foundry - deployment difficulty: "intermediate" estimatedTime: "15 minutes" @@ -58,31 +58,20 @@ git checkout next cd dstack/kms/auth-eth ``` -### Step 2: Install Node.js and Dependencies +### Step 2: Install Foundry and Dependencies -Install nvm (Node Version Manager), then use it to install the correct Node.js version: +The contracts are built and deployed with [Foundry](https://book.getfoundry.sh/getting-started/installation). Install it if `forge --version` fails: ```bash -# Install nvm -curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash - -# Load nvm into current shell -export NVM_DIR="$HOME/.nvm" -[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" - -# Install and use Node.js 18 (LTS) -nvm install 18 -nvm use 18 - -# Verify versions -node --version # Should show v18.x.x -npm --version # Should show 9.x.x or 10.x.x +curl -L https://foundry.paradigm.xyz | bash +foundryup ``` -Then install the project dependencies: +Then fetch the contract dependencies (git submodules): ```bash -npm install +git submodule update --init --recursive lib/forge-std \ + lib/openzeppelin-contracts-upgradeable lib/openzeppelin-foundry-upgrades ``` ### Step 3: Load Credentials @@ -117,36 +106,26 @@ You need at least 0.01 ETH (shown in wei: `10000000000000000`). If insufficient, ### Step 5: Compile Contracts ```bash -npx hardhat compile -``` - -Expected output (compiler version and file count may vary): - -``` -Downloading compiler 0.8.22 -Generating typings for: 19 artifacts in dir: typechain-types for target: ethers-v6 -Successfully generated 72 typings! -Compiled 19 Solidity files successfully (evm target: paris). +forge build ``` -This generates the contract artifacts (ABI and bytecode) needed for deployment. +This generates the contract artifacts (ABI and bytecode) under `out/`. ### Step 6: Deploy Contracts ```bash -npx hardhat kms:deploy --with-app-impl --network custom +forge script script/Deploy.s.sol:DeployScript --broadcast --rpc-url $RPC_URL ``` Expected output: ``` Deploying with account: 0xYourAddress -Account balance: 0.123456789 ETH -Step 1: Deploying DstackApp implementation... +Account balance: 123456789000000000 DstackApp implementation deployed to: 0x... -Step 2: Deploying DstackKms... -DstackKms Proxy deployed to: 0x... -Complete KMS setup deployed successfully! +DstackKms implementation deployed to: 0x... +DstackKms proxy deployed to: 0x... +Deployment complete! ``` ### Step 7: Save Contract Addresses @@ -252,5 +231,5 @@ With contracts deployed, you're ready to build and configure the KMS: ## Additional Resources - [Sepolia Etherscan](https://sepolia.etherscan.io/) -- [Hardhat Deployment Guide](https://hardhat.org/hardhat-runner/docs/guides/deploying) +- [Foundry scripting guide](https://book.getfoundry.sh/guides/scripting-with-solidity) - [dstack GitHub Repository](https://github.com/Dstack-TEE/dstack) diff --git a/docs/tutorials/gateway-build-configuration.md b/docs/tutorials/gateway-build-configuration.md index 53afb1e271..10dfc20c95 100644 --- a/docs/tutorials/gateway-build-configuration.md +++ b/docs/tutorials/gateway-build-configuration.md @@ -278,7 +278,7 @@ echo "OS image hash: 0x$OS_IMAGE_HASH" ``` ```bash -cast send "$KMS_CONTRACT_ADDR" "addOsImageHash(bytes32)" "0x$OS_IMAGE_HASH" --rpc-url "$ETH_RPC_URL" --private-key "$PRIVATE_KEY" +cast send "$KMS_CONTRACT_ADDR" "addOsImageHashAtEpochs(uint256,uint256,bytes32)" 0 0 "0x$OS_IMAGE_HASH" --rpc-url "$ETH_RPC_URL" --private-key "$PRIVATE_KEY" ``` Verify it was added: @@ -510,7 +510,9 @@ export GATEWAY_APP_ID=$(cat ~/.dstack/secrets/gateway-app-id) Add the compose hash to the gateway app's allowed list: ```bash -cast send "$GATEWAY_APP_ID" "addComposeHash(bytes32)" "0x$COMPOSE_HASH" --rpc-url "$ETH_RPC_URL" --private-key "$PRIVATE_KEY" +# App contracts deployed before app epochs (0.6.x or earlier) take "addComposeHash(bytes32)" "0x$COMPOSE_HASH"; +# see onchain-governance.md#apps-deployed-before-app-epochs. +cast send "$GATEWAY_APP_ID" "addComposeHashAtEpoch(uint256,bytes32)" 0 "0x$COMPOSE_HASH" --rpc-url "$ETH_RPC_URL" --private-key "$PRIVATE_KEY" ``` Verify the hash was added: diff --git a/docs/tutorials/hello-world-app.md b/docs/tutorials/hello-world-app.md index 51d1ce656d..31fa493ab5 100644 --- a/docs/tutorials/hello-world-app.md +++ b/docs/tutorials/hello-world-app.md @@ -236,9 +236,11 @@ COMPOSE_HASH="" HELLO_APP_ID=$(cat ~/.dstack/secrets/hello-world-app-id) +# App contracts deployed before app epochs (0.6.x or earlier) take "addComposeHash(bytes32)" "0x$COMPOSE_HASH"; +# see onchain-governance.md#apps-deployed-before-app-epochs. cast send "$HELLO_APP_ID" \ - "addComposeHash(bytes32)" \ - "0x$COMPOSE_HASH" \ + "addComposeHashAtEpoch(uint256,bytes32)" \ + 0 "0x$COMPOSE_HASH" \ --rpc-url "$ETH_RPC_URL" \ --private-key "$PRIVATE_KEY" ``` diff --git a/docs/tutorials/kms-build-configuration.md b/docs/tutorials/kms-build-configuration.md index f8264e3a20..f9432a1fd5 100644 --- a/docs/tutorials/kms-build-configuration.md +++ b/docs/tutorials/kms-build-configuration.md @@ -41,7 +41,7 @@ The dstack KMS provides: | Component | Purpose | |-----------|---------| | **dstack-kms** | Main KMS binary - generates and stores cryptographic keys | -| **auth-eth** | Node.js service - verifies app permissions via smart contract | +| **auth-eth** | Bun webhook service - verifies app permissions via smart contract | | **kms.toml** | Configuration file for KMS settings | | **auth-eth.env** | Environment file with Ethereum RPC credentials | | **Docker image** | Containerized KMS for deployment in a CVM | @@ -165,24 +165,20 @@ cat > /etc/kms/kms.toml << 'EOF' # dstack KMS Configuration # See: https://github.com/Dstack-TEE/dstack -[default] -workers = 8 -max_blocking = 64 -ident = "DStack KMS" -temp_dir = "/tmp" -keep_alive = 10 +# Settings shared by all listeners +[listeners.default] log_level = "info" -# RPC Server Configuration -[rpc] +# TLS certificate for the listeners (not the plain-HTTP onboard page) +[listeners.default.tls] +key = "/var/lib/kms/certs/rpc.key" +certs = "/var/lib/kms/certs/rpc.crt" + +# KMS RPCs for CVMs +[listeners.guest] address = "0.0.0.0" port = 9100 -# TLS Certificate Configuration for RPC -[rpc.tls] -key = "/etc/kms/certs/rpc.key" -certs = "/etc/kms/certs/rpc.crt" - # No mutual-TLS section: client certificates are verified by the attestation they # carry, not by an issuer CA, so there is nothing to pin. Connections without a # certificate are still accepted, because bootstrap and public endpoints must be @@ -191,7 +187,8 @@ certs = "/etc/kms/certs/rpc.crt" # Core KMS Configuration [core] -cert_dir = "/etc/kms/certs" +cert_dir = "/var/lib/kms/certs" +keyring_dir = "/var/lib/kms/keyring" subject_postfix = ".dstack" # Intel PCCS URL for TDX quote verification pccs_url = "https://pccs.phala.network/sgx/certification/v4" @@ -204,12 +201,24 @@ type = "webhook" [core.auth_api.webhook] url = "http://127.0.0.1:9200" +# Admin listener, which serves the key handover to other KMS nodes; a serving +# KMS requires it. ADMIN_TOKEN_HASH is the token's SHA-256, filled in by the +# KMS CVM deployment tutorial. +[listeners.admin] +enabled = true +address = "0.0.0.0" +port = 9101 +auth_token_hash = "ADMIN_TOKEN_HASH" + +# Onboarding page, served over plain HTTP before the KMS has keys +[listeners.onboard] +address = "0.0.0.0" +port = 9100 + # Onboarding Configuration [core.onboard] enabled = true auto_bootstrap_domain = "" -address = "0.0.0.0" -port = 9100 EOF ``` @@ -217,64 +226,30 @@ EOF | Section | Key | Description | |---------|-----|-------------| -| `[default]` | `workers` | Number of worker threads (default: 8) | -| `[default]` | `log_level` | Logging level: debug, info, warn, error | -| `[rpc]` | `address` | RPC server bind address | -| `[rpc]` | `port` | RPC server port (9100) | +| `[listeners.default]` | `log_level` | Logging level: debug, info, warn, error | +| `[listeners.default.tls]` | `key`, `certs` | TLS certificate for the guest and admin listeners | +| `[listeners.guest]` | `address`, `port` | KMS RPC bind address and port (9100) | +| `[listeners.admin]` | `address`, `port`, `auth_token_hash` | Admin listener (9101), which serves the key handover; the SHA-256 of the admin token. A serving KMS requires it with TLS | +| `[listeners.onboard]` | `address`, `port` | Plain-HTTP onboarding page (9100, before the KMS has keys) | | `[core]` | `cert_dir` | Directory for certificates | +| `[core]` | `keyring_dir` | Directory for the root keys of every epoch (must be persistent) | | `[core]` | `pccs_url` | PCCS endpoint for quote verification | -| `[core.auth_api]` | `url` | Auth-eth webhook service URL | +| `[core.auth_api]` | `url` | auth-eth webhook service URL | | `[core.onboard]` | `enabled` | Enable bootstrap/onboard mode | -## Step 5: Build Auth-ETH Service - -The KMS requires the auth-eth service to query the Ethereum contract for authorization. - -### Install Node.js - -The auth-eth service requires Node.js. Install Node.js 20.x from NodeSource: - -```bash -curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - -sudo apt-get install -y nodejs -``` - -Verify the installation: - -```bash -node --version -npm --version -``` - -You should see Node.js v20.x and npm v10.x (or later). +## Step 5: Prepare the auth-eth Service -### Navigate to auth-eth directory +The KMS requires the [auth-eth](https://github.com/Dstack-TEE/dstack/tree/next/dstack/kms/auth-eth) webhook service to query the Ethereum contract for authorization. -```bash -cd ~/dstack/dstack/kms/auth-eth -``` - -### Install dependencies - -```bash -npm install -``` - -### Build TypeScript - -```bash -npx tsc --project tsconfig.json -``` - -### Verify build +auth-eth runs directly from its TypeScript source with [Bun](https://bun.sh), so there is no build step. The Docker image in Step 7 installs Bun and the locked dependencies. Check that the source is present: ```bash -ls -la dist/src/ +ls ~/dstack/dstack/kms/auth-eth/index.ts ~/dstack/dstack/kms/auth-eth/package.json ~/dstack/dstack/kms/auth-eth/bun.lock ``` -You should see `main.js` and other compiled files. +The same directory also holds the Foundry project for the contracts; the server needs only these three files. -## Step 6: Create Auth-ETH Configuration +## Step 6: Create auth-eth Configuration Create environment configuration for the auth-eth service. @@ -299,15 +274,17 @@ If you've lost the address, find it on [Sepolia Etherscan](https://sepolia.ether ```bash cat > /etc/kms/auth-eth.env << EOF -# Auth-ETH Service Configuration +# auth-eth Service Configuration -# Server settings -HOST=127.0.0.1 +# Server port (must match the kms.toml webhook URL) PORT=9200 # Ethereum RPC endpoint (Sepolia testnet) ETH_RPC_URL=https://ethereum-sepolia-rpc.publicnode.com +# Reject decisions if the RPC serves a different chain (Sepolia) +ETH_CHAIN_ID=11155111 + # KMS Authorization Contract Address KMS_CONTRACT_ADDR=$KMS_CONTRACT_ADDRESS EOF @@ -368,6 +345,8 @@ The Dockerfile bakes all configuration into the image for reliable CVM deploymen ```bash cat > Dockerfile << 'EOF' # KMS Docker Image for CVM Deployment +FROM oven/bun:1.4.4 AS bun + FROM ubuntu:24.04 # Install runtime dependencies @@ -375,13 +354,11 @@ RUN apt-get update && \ apt-get install -y ca-certificates curl && \ rm -rf /var/lib/apt/lists/* -# Install Node.js 20.x for auth-eth -RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && \ - apt-get install -y nodejs && \ - rm -rf /var/lib/apt/lists/* +# Install Bun for auth-eth +COPY --from=bun /usr/local/bin/bun /usr/local/bin/bun # Create directories -RUN mkdir -p /etc/kms/certs /etc/kms/images /var/run/kms /var/log/kms +RUN mkdir -p /etc/kms/images /var/lib/kms/certs /var/lib/kms/keyring /var/run/kms /var/log/kms # Copy KMS binary COPY dstack-kms /usr/local/bin/dstack-kms @@ -389,12 +366,13 @@ RUN chmod 755 /usr/local/bin/dstack-kms # Copy configuration files (baked into image) COPY kms.toml /etc/kms/kms.toml -COPY auth-eth.env /etc/kms/auth-eth.env COPY sgx_default_qcnl.conf /etc/sgx_default_qcnl.conf -# Copy auth-eth service and install dependencies +# Copy auth-eth and install its locked dependencies. Bun loads .env from +# the working directory; variables set in docker-compose take precedence. COPY auth-eth /opt/auth-eth -RUN cd /opt/auth-eth && npm install --production +COPY auth-eth.env /opt/auth-eth/.env +RUN cd /opt/auth-eth && bun install --frozen-lockfile --production --ignore-scripts # Copy startup script COPY start-kms.sh /usr/local/bin/start-kms.sh @@ -417,8 +395,7 @@ set -e # Start auth-eth in background cd /opt/auth-eth -node dist/src/main.js & -AUTH_ETH_PID=$! +bun index.ts & # Wait for auth-eth to be ready sleep 2 @@ -436,24 +413,20 @@ The KMS config for CVM deployment enables TDX attestation: cat > kms.toml << 'EOF' # dstack KMS Configuration (CVM Deployment) -[default] -workers = 8 -max_blocking = 64 -ident = "DStack KMS" -temp_dir = "/tmp" -keep_alive = 10 +# Settings shared by all listeners +[listeners.default] log_level = "info" -# RPC Server Configuration -[rpc] +# TLS certificate for the listeners (not the plain-HTTP onboard page) +[listeners.default.tls] +key = "/var/lib/kms/certs/rpc.key" +certs = "/var/lib/kms/certs/rpc.crt" + +# KMS RPCs for CVMs +[listeners.guest] address = "0.0.0.0" port = 9100 -# TLS Certificate Configuration for RPC -[rpc.tls] -key = "/etc/kms/certs/rpc.key" -certs = "/etc/kms/certs/rpc.crt" - # No mutual-TLS section: client certificates are verified by the attestation they # carry, not by an issuer CA, so there is nothing to pin. Connections without a # certificate are still accepted, because bootstrap and public endpoints must be @@ -462,14 +435,14 @@ certs = "/etc/kms/certs/rpc.crt" # Core KMS Configuration [core] -cert_dir = "/etc/kms/certs" +cert_dir = "/var/lib/kms/certs" +keyring_dir = "/var/lib/kms/keyring" subject_postfix = ".dstack" pccs_url = "https://pccs.phala.network/sgx/certification/v4" # OS Image Verification # KMS downloads OS images to compute expected TDX measurements [core.image] -verify = true cache_dir = "/etc/kms/images" download_url = "https://download.dstack.org/os-images/mr_{OS_IMAGE_HASH}.tar.gz" download_timeout = "2m" @@ -481,18 +454,20 @@ type = "webhook" [core.auth_api.webhook] url = "http://127.0.0.1:9200" +# Onboarding page, served over plain HTTP before the KMS has keys +[listeners.onboard] +address = "0.0.0.0" +port = 9100 + # Onboarding Configuration [core.onboard] enabled = true -# Empty domain = manual bootstrap mode (ensures bootstrap-info.json is written) +# Empty domain = manual bootstrap mode auto_bootstrap_domain = "" -# Enable TDX quotes - works because KMS runs in CVM -address = "0.0.0.0" -port = 9100 EOF ``` -> **Why empty `auto_bootstrap_domain`?** With an empty domain, KMS starts in "onboard mode" — a plain HTTP server that waits for you to trigger bootstrap via an RPC call. This ensures `bootstrap-info.json` is written to disk, which is required for on-chain KMS registration. You'll provide the domain during the bootstrap step in [KMS CVM Deployment](/tutorial/kms-cvm-deployment). +> **Why empty `auto_bootstrap_domain`?** With an empty domain, KMS starts in "onboard mode" — a plain HTTP server that waits for you to trigger bootstrap via an RPC call. Its response carries the attestation and public keys required for on-chain KMS registration. You'll provide the domain during the bootstrap step in [KMS CVM Deployment](/tutorial/kms-cvm-deployment). ### Copy build artifacts and configuration @@ -500,8 +475,9 @@ EOF # Copy KMS binary cp ~/dstack/dstack/target/release/dstack-kms . -# Copy auth-eth service -cp -r ~/dstack/dstack/kms/auth-eth auth-eth +# Copy the auth-eth webhook server (not the Foundry project next to it) +mkdir -p auth-eth +cp ~/dstack/dstack/kms/auth-eth/{index.ts,package.json,bun.lock} auth-eth/ # Copy auth-eth environment config cp /etc/kms/auth-eth.env . @@ -569,16 +545,15 @@ services: volumes: # Mount config file from local directory - ./kms.toml:/etc/kms/kms.toml:ro - - ./auth-eth.env:/etc/kms/auth-eth.env:ro - # Named volume for persistent certificates - - kms-certs:/etc/kms/certs + # Named volume for persistent state: certificates and root keys + - kms-data:/var/lib/kms environment: - RUST_LOG=info restart: unless-stopped volumes: - kms-certs: - # Certificates persist across container restarts + kms-data: + # Certificates and root keys persist across container restarts EOF ``` @@ -591,11 +566,11 @@ ls -la ~/kms-deployment/ You should have: - `Dockerfile` - Container build definition - `dstack-kms` - KMS binary -- `auth-eth/` - Auth-eth service directory +- `auth-eth/` - auth-eth webhook server (`index.ts`, `package.json`, `bun.lock`) - `start-kms.sh` - Startup script - `docker-compose.yml` - Deployment manifest - `kms.toml` - KMS configuration -- `auth-eth.env` - Auth-eth environment +- `auth-eth.env` - auth-eth environment - `sgx_default_qcnl.conf` - QCNL configuration for CVM PCCS access ## Step 9: Verify Configuration @@ -648,7 +623,7 @@ curl -s -X POST "$ETH_RPC_URL" \ ``` ┌─────────────┐ ┌─────────────┐ ┌──────────────┐ -│ TEE App │────►│ KMS │────►│ Auth-ETH │ +│ TEE App │────►│ KMS │────►│ auth-eth │ └─────────────┘ └─────────────┘ └──────────────┘ │ │ │ │ │ ▼ @@ -666,8 +641,8 @@ curl -s -X POST "$ETH_RPC_URL" \ ### Data Flow 1. **TEE App** requests key from **KMS** -2. **KMS** calls **Auth-ETH** webhook to verify authorization -3. **Auth-ETH** queries **Ethereum** smart contract +2. **KMS** calls **auth-eth** webhook to verify authorization +3. **auth-eth** queries **Ethereum** smart contract 4. If authorized, **KMS** returns key to app 5. **VMM** orchestrates the overall TEE environment @@ -677,7 +652,7 @@ For detailed solutions, see the [KMS Deployment Troubleshooting Guide](/tutorial - [Build fails with missing dependencies](/tutorial/troubleshooting-kms-deployment#build-fails-with-missing-dependencies) - [Configuration file not found](/tutorial/troubleshooting-kms-deployment#configuration-file-not-found) -- [Auth-eth npm install fails](/tutorial/troubleshooting-kms-deployment#auth-eth-npm-install-fails) +- [auth-eth install fails](/tutorial/troubleshooting-kms-deployment#auth-eth-install-fails) - [Invalid TOML syntax](/tutorial/troubleshooting-kms-deployment#invalid-toml-syntax) - [RPC connection failed](/tutorial/troubleshooting-kms-deployment#rpc-connection-failed) - [Contract address not set](/tutorial/troubleshooting-kms-deployment#contract-address-not-set) diff --git a/docs/tutorials/kms-cvm-deployment.md b/docs/tutorials/kms-cvm-deployment.md index 2c3cb278b2..9ad991b9a9 100644 --- a/docs/tutorials/kms-cvm-deployment.md +++ b/docs/tutorials/kms-cvm-deployment.md @@ -65,18 +65,22 @@ When you deploy KMS as a CVM, the following happens: ### Generated Artifacts -Inside the CVM at `/etc/kms/certs/`: +Inside the CVM, in the `kms-data` volume at `/var/lib/kms/`. The root keyring under `keyring/` (`keyring_dir`): + +| File | Purpose | +|------|---------| +| `epochs//root-ca.crt` | Root Certificate Authority of epoch `n` (self-signed) | +| `epochs//root-ca.key` | Root CA signing key of epoch `n` (P256 ECDSA) | +| `epochs//root-k256.key` | Ethereum signing key of epoch `n` (secp256k1) | +| `epochs//root-attestation` | Attestation produced when the epoch `n` keys were generated; absent if there is none | +| `root-epoch` | Newest root epoch held | + +And the RPC certificates under `certs/` (`cert_dir`): | File | Purpose | |------|---------| -| `root-ca.crt` | Root Certificate Authority (self-signed) | -| `root-ca.key` | Root CA signing key (P256 ECDSA) | | `rpc.crt` | TLS certificate for RPC server | | `rpc.key` | RPC server private key | -| `tmp-ca.crt` | Temp CA, served by the legacy `GetTempCaCert` bootstrap RPC | -| `tmp-ca.key` | Temp CA private key, served alongside it | -| `root-k256.key` | Ethereum signing key (secp256k1) | -| `bootstrap-info.json` | Public keys and TDX attestation quote | --- @@ -137,9 +141,10 @@ services: image: registry.yourdomain.com/dstack-kms:fixed ports: - "9100:9100" + - "9101:9101" volumes: - /var/run/dstack.sock:/var/run/dstack.sock - - kms-certs:/etc/kms/certs + - kms-data:/var/lib/kms environment: - RUST_LOG=info - KMS_DOMAIN=kms.yourdomain.com @@ -152,18 +157,30 @@ services: restart: unless-stopped volumes: - kms-certs: + kms-data: configs: kms_config: content: | - [rpc] + [listeners.default.tls] + key = "/var/lib/kms/certs/rpc.key" + certs = "/var/lib/kms/certs/rpc.crt" + + [listeners.guest] address = "0.0.0.0" port = 9100 - [rpc.tls] - key = "/etc/kms/certs/rpc.key" - certs = "/etc/kms/certs/rpc.crt" + # Admin listener: serves the key handover to other KMS nodes, so a + # KMS requires it. Only the token's SHA-256 goes into the compose. + [listeners.admin] + enabled = true + address = "0.0.0.0" + port = 9101 + auth_token_hash = "ADMIN_TOKEN_HASH" + + [listeners.onboard] + address = "0.0.0.0" + port = 9100 # No mutual-TLS section: client certificates are verified by the attestation # they carry, not by an issuer CA. Connections without a certificate are still @@ -172,11 +189,11 @@ configs: # certificate signing verifies CSR signature and attestation. [core] - cert_dir = "/etc/kms/certs" + cert_dir = "/var/lib/kms/certs" + keyring_dir = "/var/lib/kms/keyring" pccs_url = "https://pccs.phala.network/sgx/certification/v4" [core.image] - verify = true cache_dir = "/etc/kms/images" download_url = "https://download.dstack.org/os-images/mr_{OS_IMAGE_HASH}.tar.gz" download_timeout = "2m" @@ -190,8 +207,6 @@ configs: [core.onboard] enabled = true auto_bootstrap_domain = "" - address = "0.0.0.0" - port = 9100 EOF ``` @@ -206,6 +221,10 @@ sed -i 's|kms.yourdomain.com|kms.your-actual-domain.com|g' docker-compose.yaml # KMS contract address (from contract deployment tutorial) sed -i "s|YOUR_CONTRACT_ADDRESS|$(cat ~/.dstack/secrets/kms-contract-address)|g" docker-compose.yaml + +# KMS admin token: keep the token, put only its SHA-256 in the compose +(umask 077 && openssl rand -hex 32 > ~/.dstack/secrets/kms-admin-token) +sed -i "s|ADMIN_TOKEN_HASH|$(tr -d '\n' < ~/.dstack/secrets/kms-admin-token | sha256sum | cut -d' ' -f1)|g" docker-compose.yaml ``` This docker-compose uses a Docker `configs` section to inject a complete `kms.toml` into the container at `/etc/kms/kms.toml`, overriding the config baked into the image. This approach lets you change KMS configuration without rebuilding the Docker image. @@ -214,13 +233,15 @@ This docker-compose uses a Docker `configs` section to inject a complete `kms.to | Section | Purpose | |---------|---------| -| `[rpc]` | RPC server address and port (9100) | -| `[rpc.tls]` | TLS certificate paths for HTTPS | +| `[listeners.default.tls]` | TLS certificate paths for HTTPS, shared by the listeners | +| `[listeners.guest]` | KMS RPC address and port (9100) | +| `[listeners.admin]` | Admin listener on port 9101 with TLS; other KMS nodes onboard through it with the admin token. Without it (or `core.onboard.public_key_handover = true`) the KMS does not start | +| `[listeners.onboard]` | Plain-HTTP onboarding page on port 9100, before the KMS has keys | | `[core.image]` | OS image verification — downloads images from `download.dstack.org` to compute expected TDX measurements | | `[core.auth_api]` | Authentication via auth-eth webhook on localhost:9200 | | `[core.onboard]` | Bootstrap settings — `auto_bootstrap_domain` is empty so KMS enters onboard mode for manual bootstrap | -> **Why manual bootstrap?** With `auto_bootstrap_domain` left empty, KMS starts in "onboard mode" — a plain HTTP server on port 9100 that waits for you to trigger bootstrap via an RPC call. This ensures `bootstrap-info.json` (containing the TDX attestation quote and public keys) is written to disk. You'll need this file later to register the KMS on-chain. +> **Why manual bootstrap?** With `auto_bootstrap_domain` left empty, KMS starts in "onboard mode" — a plain HTTP server on port 9100 that waits for you to trigger bootstrap via an RPC call. The response carries the TDX attestation quote and public keys you'll need later to register the KMS on-chain. **Environment variables explained:** @@ -319,8 +340,8 @@ Onboarding > > **Critical prerequisite:** before bootstrap can succeed, the KMS must already be authorized by your auth backend. > -> - For `auth-simple`, add the KMS `mrAggregated` to `kms.mrAggregated` -> - For `auth-eth`, add the KMS `mrAggregated` on-chain with `addKmsAggregatedMr(...)` +> - For `dstack-auth`, add the KMS `mrAggregated` to `kms.mrAggregated` +> - For `auth-eth`, add the KMS `mrAggregated` on-chain with `script/Manage.s.sol:AddKmsAggregatedMr` > > You can fetch the value before bootstrap with: > @@ -342,7 +363,7 @@ Onboarding ### Step 6: Bootstrap KMS -With KMS in onboard mode, trigger key generation by calling the Bootstrap RPC endpoint. This generates root keys, a TDX attestation quote, and writes `bootstrap-info.json`: +With KMS in onboard mode, trigger key generation by calling the Bootstrap RPC endpoint. This generates root keys and a TDX attestation quote over them: ```bash # Inspect the KMS measurement before bootstrap @@ -481,11 +502,11 @@ The TDX quote can be verified by: │ │ │ │ Docker Container │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ┌─────────┐ ┌──────────────┐ │ │ │ │ -│ │ │ │ │ KMS │◄──│ auth-eth │ │ │ │ │ +│ │ │ │ │ KMS │◄──│ auth-eth │ │ │ │ │ │ │ │ │ └────┬────┘ └──────┬───────┘ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ▼ ▼ │ │ │ │ -│ │ │ │ /etc/kms/certs Ethereum RPC │ │ │ │ +│ │ │ │ /var/lib/kms Ethereum RPC │ │ │ │ │ │ │ └──────────────────────────────────┘ │ │ │ │ │ │ │ │ │ │ │ │ guest-agent (/var/run/dstack.sock) │ │ │ @@ -530,9 +551,9 @@ For detailed solutions, see the [KMS Deployment Troubleshooting Guide](/tutorial ### Understanding Storage -CVM certificates are stored in a Docker named volume (`kms-certs`). This provides: +CVM certificates and root keys are stored in the Docker named volume `kms-data`, while `/etc/kms` holds only configuration. This provides: -- **Container restart persistence** - Certificates survive container restarts +- **Container restart persistence** - Certificates and root keys survive container restarts - **CVM restart consideration** - Depending on VMM configuration, volumes may or may not persist ### Backup Recommendations diff --git a/docs/tutorials/troubleshooting-gateway-deployment.md b/docs/tutorials/troubleshooting-gateway-deployment.md index 650b30ba88..f458ae0b4a 100644 --- a/docs/tutorials/troubleshooting-gateway-deployment.md +++ b/docs/tutorials/troubleshooting-gateway-deployment.md @@ -35,7 +35,9 @@ If `deployAndRegisterApp` reverts, check: "appImplementation()(address)" \ --rpc-url "$ETH_RPC_URL" ``` - Should return a non-zero address. + Should return a non-zero address, of a `DstackApp` that has `deployProxy`. + A `DstackApp` from v0.6.5 or earlier has none, and `deployAndRegisterApp` + reverts without a reason until the owner sets a current one. 2. **Insufficient funds:** Your wallet needs Sepolia ETH for gas ```bash @@ -67,7 +69,7 @@ export DSTACK_VMM_AUTH_PASSWORD=$(cat ~/.dstack/secrets/vmm-auth-token) **Symptom:** `curl -sk https://localhost:9100/prpc/KMS.GetMeta | jq '.gateway_app_id'` returns the wrong app ID, an empty string, or KMS is unreachable. -**Cause:** The KMS auth-eth service queries the blockchain directly (via `eth_call`) — it does not cache state. If KMS was deployed with a different `ETH_RPC_URL` or the KMS CVM is having connectivity issues, it may fail to read on-chain changes. Alternatively, you may need to redeploy KMS after port binding changes from the KMS tutorial. +**Cause:** The KMS auth-eth service queries the blockchain directly (via `eth_call`) — it does not cache state. If KMS was deployed with a different `ETH_RPC_URL` or the KMS CVM is having connectivity issues, it may fail to read on-chain changes. By default it reads the `finalized` block, so a transaction takes effect only once finalized; set `ETH_BLOCK_TAG=latest` on development chains. Alternatively, you may need to redeploy KMS after port binding changes from the KMS tutorial. **Solution:** Redeploy the KMS CVM: @@ -141,8 +143,8 @@ echo "OS image hash: 0x$OS_IMAGE_HASH" # Whitelist it on the KMS contract export KMS_CONTRACT_ADDR=$(cat ~/.dstack/secrets/kms-contract-address) cast send "$KMS_CONTRACT_ADDR" \ - "addOsImageHash(bytes32)" \ - "0x$OS_IMAGE_HASH" \ + "addOsImageHashAtEpochs(uint256,uint256,bytes32)" \ + 0 0 "0x$OS_IMAGE_HASH" \ --rpc-url "https://ethereum-sepolia-rpc.publicnode.com" \ --private-key "$(cat ~/.dstack/secrets/sepolia-private-key)" ``` @@ -196,9 +198,11 @@ cast call "$(cat ~/.dstack/secrets/gateway-app-id)" \ --rpc-url "https://ethereum-sepolia-rpc.publicnode.com" # If false, add it +# App contracts deployed before app epochs (0.6.x or earlier) take "addComposeHash(bytes32)" "0x$COMPOSE_HASH"; +# see onchain-governance.md#apps-deployed-before-app-epochs. cast send "$(cat ~/.dstack/secrets/gateway-app-id)" \ - "addComposeHash(bytes32)" \ - "0x$COMPOSE_HASH" \ + "addComposeHashAtEpoch(uint256,bytes32)" \ + 0 "0x$COMPOSE_HASH" \ --rpc-url "https://ethereum-sepolia-rpc.publicnode.com" \ --private-key "$(cat ~/.dstack/secrets/sepolia-private-key)" ``` diff --git a/docs/tutorials/troubleshooting-kms-deployment.md b/docs/tutorials/troubleshooting-kms-deployment.md index 7282db94d1..24e9cde555 100644 --- a/docs/tutorials/troubleshooting-kms-deployment.md +++ b/docs/tutorials/troubleshooting-kms-deployment.md @@ -27,13 +27,15 @@ This appendix consolidates troubleshooting content from the KMS Deployment tutor ### Artifact not found ``` -Error HH700: Artifact for contract "DstackApp" not found. +Error: could not find artifact ``` -Contracts must be compiled before deployment. Run: +Contracts must be compiled, with their dependencies checked out, before deployment. In `dstack/kms/auth-eth`, run: ```bash -npx hardhat compile +git submodule update --init --recursive lib/forge-std \ + lib/openzeppelin-contracts-upgradeable lib/openzeppelin-foundry-upgrades +forge build ``` ### Insufficient funds @@ -104,19 +106,18 @@ Verify the file exists and has correct permissions: ls -la /etc/kms/kms.toml ``` -### Auth-eth npm install fails +### auth-eth install fails ``` -Error: EACCES permission denied +error: lockfile had changes, but lockfile is frozen ``` -Fix npm permissions: +The copied `auth-eth/` directory does not match its `bun.lock`. Copy it again from a clean checkout of the dstack repository and rebuild the Docker image: ```bash -mkdir -p ~/.npm-global -npm config set prefix '~/.npm-global' -export PATH=~/.npm-global/bin:$PATH -npm install +rm -rf ~/kms-deployment/auth-eth +mkdir -p ~/kms-deployment/auth-eth +cp ~/dstack/dstack/kms/auth-eth/{index.ts,package.json,bun.lock} ~/kms-deployment/auth-eth/ ``` ### Invalid TOML syntax @@ -303,12 +304,12 @@ sudo systemctl restart qgsd ### GetMeta Returns "Connection refused" on Port 9200 -**Symptom:** KMS responds to `GetTempCaCert` but GetMeta returns: +**Symptom:** The KMS health endpoint responds but GetMeta returns: ```json {"error": "error sending request for url (http://127.0.0.1:9200/): ...Connection refused (os error 111)"} ``` -**Root Cause:** auth-eth defaults to port 8000, but kms.toml expects the webhook at port 9200. +**Root Cause:** auth-eth listens on `PORT` (3000 when run from source, 8000 in its release image), but kms.toml expects the webhook at port 9200. **Solution:** Ensure your docker-compose.yaml includes `PORT=9200` in the environment section: @@ -334,7 +335,7 @@ Then regenerate the app-compose.json and redeploy: {"error": "error decoding response body: missing field `status` at line 1 column ..."} ``` -**Root Cause:** auth-eth is running and reachable (port 9200 is correct), but it cannot connect to Ethereum RPC. Without `ETH_RPC_URL` and `KMS_CONTRACT_ADDR`, auth-eth defaults to `http://localhost:8545` (nothing there) and returns a Fastify error instead of the expected `{status: 'ok', ...}` response. +**Root Cause:** auth-eth is reachable (port 9200 is correct), but it cannot read the contract. Without `KMS_CONTRACT_ADDR`, auth-eth defaults to the zero address and returns `{status: 'error', ...}` instead of the expected `{status: 'ok', ...}` response. If `ETH_RPC_URL` is missing or the RPC is unreachable at startup, auth-eth exits instead, and GetMeta reports "Connection refused". **Solution:** Ensure your docker-compose.yaml includes both Ethereum configuration variables: diff --git a/docs/tutorials/vmm-configuration.md b/docs/tutorials/vmm-configuration.md index b3dede9e22..b4a0becede 100644 --- a/docs/tutorials/vmm-configuration.md +++ b/docs/tutorials/vmm-configuration.md @@ -113,7 +113,7 @@ cid_start = 1000 cid_pool_size = 1000 max_allocable_vcpu = 124 # Adjust: total cores - 4 max_allocable_memory_in_mb = 990616 # Adjust: total MB - 16384 -qmp_socket = false +qmp_socket = true use_mrconfigid = true qemu_pci_hole64_size = 0 qemu_hotplug_off = true diff --git a/docs/upgrading-to-0.6.md b/docs/upgrading-to-0.6.md index 942a4a7e2d..ce5c0aeaed 100644 --- a/docs/upgrading-to-0.6.md +++ b/docs/upgrading-to-0.6.md @@ -217,6 +217,10 @@ Both sides must authorize each other first: the new KMS allows the old `os_image_hash`. After onboarding, compare the KMS CA public keys; the CA certificate itself is reissued. The source must be 0.5.8 or later. +KMS releases after 0.6 can join only from a 0.6+ source: a 0.5.x certificate +carries no OS image hash, and they refuse such a source. Upgrade a 0.5.x +cluster to 0.6.x first, then onboard later releases from it. + Keep the old KMS running until every client has moved. While a 0.5.x KMS still verifies 0.6.0 guests, it can only measure guests with exactly 2 GiB or at least 2816 MiB of memory, and it must be able to download the 0.6.0 image. @@ -228,14 +232,27 @@ Configuration changes: - Key release on AMD SEV-SNP, AWS NitroTPM, and AWS Nitro Enclaves stays off until you set `sev_snp_key_release`, `aws_nitro_tpm_key_release`, or `nitro_enclave_key_release`. -- Keep `core.onboard.public_key_handover = true` while any KMS still onboards - through the public port, and turn it off afterwards. +- `core.onboard.public_key_handover` now defaults to `false`, which removes + `KMS.GetKmsKey` from the public port. While a 0.5.x KMS still onboards from + this cluster, it can only use that public entry, so set the option to `true` + on the source node, and remove it once every node is upgraded. +- A KMS without a key handover path does not start. Configure the admin + listener with `[core.admin.tls]` (`key` and `certs`) and an admin token, or + set `core.onboard.public_key_handover = true`. The built-in default enables + the admin listener with TLS, so it needs `core.admin.auth_token`, + `DSTACK_KMS_ADMIN_TOKEN` or `core.admin.auth_token_hash` to start. In a KMS + app compose, which is public, use `auth_token_hash` with a high-entropy random + token (`openssl rand -hex 32`), since its hash can be brute-forced offline. - Auto-bootstrap refuses to overwrite existing root keys. -If you use `auth-simple`, three defaults now deny boots that 0.5.x allowed: an -empty `devices` list denies every device unless `allowAnyDevice` is true, -`allowedTcbStatuses` defaults to `["UpToDate"]`, and any advisory ID on a -quote denies unless listed in `allowedAdvisoryIds`. +If you use `auth-simple`, replace it with `dstack-auth`, which reads the same +config file; see +[Migrating from auth-simple](./dstack-auth-operations.md#migrating-from-auth-simple). +Compared with 0.5.x auth-simple, an empty `devices` list now denies every device +unless `allowAnyDevice` is true. To also deny a non-`UpToDate` TCB or any +advisory ID, as auth-simple did by default, set +`"allowedTcbStatuses": ["UpToDate"]` and `"allowedAdvisoryIds": []`; without +them dstack-auth checks neither. ### Gateway diff --git a/docs/usage.md b/docs/usage.md index 85702f2c98..46e962acf2 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -17,7 +17,7 @@ Open the dstack-vmm webpage [http://localhost:9080](http://localhost:9080) (chan After the container is deployed, it should take some time to start the CVM and the containers. Time would vary depending on your workload. - **[Logs]**: Click this button to view the CVM logs and monitor container startup progress -- **[Dashboard]**: Once the container is running, click this button to view container information and logs. (Note: This button is only visible when dstack-gateway is enabled. If disabled, you'll need to add a port mapping to port 8090 to access the CVM dashboard) +- **[Dashboard]**: Once the container is running, click this button to view container information and logs. (Note: This button is only visible when dstack-gateway is enabled. If disabled, you'll need to add a port mapping to port 8090 and allow the dashboard scopes in `[cvm.guest_agent_api]`; see [Guest Agent API access control](./guest-api-auth.md))
Guest Agent Dashboard diff --git a/docs/verity-volumes.md b/docs/verity-volumes.md index 6c7dac2950..431f014001 100644 --- a/docs/verity-volumes.md +++ b/docs/verity-volumes.md @@ -9,11 +9,16 @@ hash measured in `app-compose.json`. A built volume is a raw GPT image: ```text -p1: DSTACK_VOLUME metadata envelope -p2: filesystem data -p3: dm-verity superblock and hash tree +p1 dstack-volume: DSTACK_VOLUME metadata envelope +p2 dstack-volume-data: filesystem data +p3 dstack-verity: dm-verity superblock and hash tree ``` +The guest opens the partitions by number; the labels only keep a volume apart +from the app data disk, whose partition is `dstack-data`. Older volumes label +p2 `dstack-data` too; the guest skips any disk with a `dstack-volume` +partition when it looks for the data disk. + The envelope identifies a candidate disk. It is not trusted. The guest passes the root from the measured app compose to `veritysetup`, so a forged envelope or partition table cannot substitute different contents. diff --git a/docs/vmm-cli-user-guide.md b/docs/vmm-cli-user-guide.md index c2953d42f4..7a5ac8e3cf 100644 --- a/docs/vmm-cli-user-guide.md +++ b/docs/vmm-cli-user-guide.md @@ -231,12 +231,14 @@ First, create an application composition file that describes your application: - `--name`: Friendly name for your application - `--docker-compose`: Path to your Docker Compose file - `--prelaunch-script`: Optional script to run before starting containers. It runs after dockerd, so containers restored by a Docker restart policy may already be running; do not put security gates here (see [security best practices](./security/security-best-practices.md#security-semantics-must-not-depend-on-pre_launch_script-running-first)) +- `--init-script`: Optional Bash script to run before dockerd starts. Repeat it for up to 5 scripts, which run in order; several scripts set `manifest_version` to `"3"`, which guests before 0.6.0 reject. For a one-line script, Bash process substitution saves a file: `--init-script <(echo 'sysctl -w net.core.somaxconn=4096')` - `--kms`: Enable Key Management Service for secrets - `--gateway`: Enable dstack-gateway for external access - `--local-key-provider`: Use local key provider - `--public-logs`: Make logs publicly accessible - `--public-sysinfo`: Make system info publicly accessible - `--env-file`: File with environment variables to encrypt +- `--env-spec`: Allow an environment variable, as `NAME`, or also constrain its value, as `NAME: SPEC`, e.g. `--env-spec 'PORT: int(1..=65535)'`; repeat for more variables. See [environment value specs](./security/cvm-boundaries.md#environment-value-specs). Variables of `--env-file` that no `--env-spec` names are allowed without a spec - `--no-instance-id`: Disable unique instance identification - `--no-storage-discard`: Keep deleted data-disk blocks instead of returning them to the host. Required by `deploy --disk-prealloc falloc|full`, and it also keeps filesystem allocation and deletion patterns from the host. The cost is that the image only ever grows: space freed inside the guest is never given back @@ -293,6 +295,32 @@ Deploy your application with the compose file: - `--kms-url`: KMS server URL - `--gateway-url`: Gateway server URL - `--stopped`: Create VM in stopped state (requires dstack-vmm >= 0.5.4) +- `--launch-ticket-file`: File holding the launch ticket the guest presents to the KMS (see below) + +#### Launch Tickets + +When the app's `DstackApp` contract requires a launch ticket, the KMS releases +keys only to a CVM presenting a ticket whose hash the contract allows. Create a +fresh ticket per deployment, allow its hash on chain, and deploy with it: + +```bash +./vmm-cli.py launch-ticket new ./prod.ticket # writes the ticket (mode 0600), prints its hash +# addLaunchTicket(, "prod") on the DstackApp contract, then: +./vmm-cli.py deploy ... --launch-ticket-file ./prod.ticket +``` + +`launch-ticket hash FILE` prints the hash of an existing ticket, for +`addLaunchTicket` or, for a KMS onboarding ticket, `addKmsLaunchTicket`. A KMS +takes its ticket in the `Onboard` request rather than from +`--launch-ticket-file`, so deploy a KMS CVM without it. `update +--launch-ticket-file FILE` replaces the ticket of a VM and `update +--no-launch-ticket` removes it. The VMM keeps the ticket and writes it to the +guest's sys-config at every boot; it returns only its hash, which `info` shows. +The host holds the ticket, so remove that hash from the contract once the host +stops serving the app. Tickets need dstack-vmm, the KMS and the auth backend at +0.6.5 or later, and a guest OS at 0.6.5 or later, or 0.5.15 or later on 0.5.x. +See +[launch tickets](../dstack/kms/README.md#launch-tickets). #### Port Mapping @@ -524,21 +552,15 @@ Manage trusted KMS public keys for enhanced security: ./vmm-cli.py kms remove 0x1234567890abcdef... ``` -The whitelist is stored in `~/.dstack-vmm/kms-whitelist.json`. - -### Updating Running VMs +The whitelist is stored in `~/.dstack-vmm/kms-whitelist.json`; set `DSTACK_VMM_KMS_WHITELIST_PATH` to use a different file. -#### Update Environment Variables +After a KMS root rotation, first remove the old signer with `kms remove`, then +add the new one with `kms add`. The whitelist is a flat set and the CLI cannot +tell which epoch is current, so a signer left in it stays trusted: anyone +holding the rotated, possibly leaked, root can sign env public keys that the +CLI accepts, whatever root epoch the response claims. -```bash -./vmm-cli.py update-env --env-file ./new-secrets.env -``` - -#### Update Application Compose - -```bash -./vmm-cli.py update-app-compose ./new-app-compose.json -``` +### Updating Running VMs #### Update User Configuration @@ -568,9 +590,7 @@ Use the all-in-one `update` command to update multiple VM aspects in a single op # Update application configuration ./vmm-cli.py update \ - --compose ./new-docker-compose.yml \ - --prelaunch-script ./setup.sh \ - --swap 4G \ + --compose ./new-app-compose.json \ --env-file ./new-secrets.env \ --user-config ./new-config.json @@ -591,9 +611,7 @@ Use the all-in-one `update` command to update multiple VM aspects in a single op --vcpu 8 \ --memory 16G \ --disk 200G \ - --compose ./new-docker-compose.yml \ - --prelaunch-script ./init.sh \ - --swap 8G \ + --compose ./new-app-compose.json \ --env-file ./new-secrets.env \ --port tcp:8080:80 \ --ppcie @@ -601,7 +619,7 @@ Use the all-in-one `update` command to update multiple VM aspects in a single op **Available Options:** - **Resource changes** (requires VM to be stopped): `--vcpu`, `--memory`, `--disk`, `--image` -- **Application updates**: `--compose` (docker-compose file), `--prelaunch-script`, `--swap`, `--env-file`, `--user-config` +- **Application updates**: `--compose` (an app-compose.json made by `compose`, sent unchanged), `--env-file`, `--user-config`. To change the Docker Compose file, scripts or swap, run `compose` again and pass its output. `--env-file` refuses variables missing from the compose's `allowed_envs` and an `APP_LAUNCH_TOKEN` that does not match its `launch_token_hash`; pass a compose made with the same `--env-file` - **Networking** (mutually exclusive): - `--port ` (can be used multiple times) - `--no-ports` (remove all port mappings) @@ -611,7 +629,7 @@ Use the all-in-one `update` command to update multiple VM aspects in a single op - `--ppcie` (attach all available GPUs) - `--no-gpus` (detach all GPUs) - _No GPU flag: GPU configuration remains unchanged_ -- **KMS**: `--kms-url` (for environment encryption) +- **KMS**: `--kms-url` replaces the VM's KMS URLs and also encrypts `--env-file`; `--kms-encrypt-url` only encrypts `--env-file` and leaves the KMS URLs as they are **Notes:** - Resource changes (vCPU, memory, disk, image) require the VM to be stopped diff --git a/dstack/Cargo.lock b/dstack/Cargo.lock index a5cb819e1e..b968d2505a 100644 --- a/dstack/Cargo.lock +++ b/dstack/Cargo.lock @@ -23,20 +23,18 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" dependencies = [ - "crypto-common", + "crypto-common 0.1.7", "generic-array", ] [[package]] -name = "aes" -version = "0.7.5" +name = "aead" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e8b47f52ea9bae42228d07ec09eb676433d7c4ed1ebdf0f1d1c29ed446f1ab8" +checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99" dependencies = [ - "cfg-if", - "cipher 0.3.0", - "cpufeatures 0.2.17", - "opaque-debug", + "crypto-common 0.2.2", + "inout 0.2.2", ] [[package]] @@ -50,20 +48,45 @@ dependencies = [ "cpufeatures 0.2.17", ] +[[package]] +name = "aes" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35f0f96ce78e38c3dc6d8948aa8163d06385be74000f3c7a95bf1eef35d3ea32" +dependencies = [ + "cipher 0.5.2", + "cpubits", + "cpufeatures 0.3.0", +] + [[package]] name = "aes-gcm" version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" dependencies = [ - "aead", + "aead 0.5.2", "aes 0.8.4", "cipher 0.4.4", - "ctr", - "ghash", + "ctr 0.9.2", + "ghash 0.5.1", "subtle", ] +[[package]] +name = "aes-gcm" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f2b8006a0c83f52b62ba44a97b58bf76fe2f70a329e588f67f89691d93d498f" +dependencies = [ + "aead 0.6.1", + "aes 0.9.3", + "cipher 0.5.2", + "ctr 0.10.1", + "ctutils", + "ghash 0.6.0", +] + [[package]] name = "ahash" version = "0.8.12" @@ -138,7 +161,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -149,7 +172,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -185,12 +208,6 @@ version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" -[[package]] -name = "arrayvec" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b" - [[package]] name = "arrayvec" version = "0.7.6" @@ -337,9 +354,9 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "aws-lc-rs" -version = "1.17.0" +version = "1.18.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ec2f1fc3ec205783a5da9a7e6c1509cc69dedf09a1949e412c1e18469326d00" +checksum = "faac5829c2b74c28f830747e7818ccfb684261b5f48a1118b1e2a13d36dfab13" dependencies = [ "aws-lc-sys", "untrusted 0.7.1", @@ -348,14 +365,15 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.41.0" +version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a2f9779ce85b93ab6170dd940ad0169b5766ff848247aff13bb788b832fe3f4" +checksum = "f1622d8446a2d4b2ce0c7eefc73dd43a99779028d5ee5c2dd8073a658ba8a2bc" dependencies = [ "cc", "cmake", "dunce", "fs_extra", + "pkg-config", ] [[package]] @@ -430,6 +448,12 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" +[[package]] +name = "base16ct" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" + [[package]] name = "base64" version = "0.13.1" @@ -442,6 +466,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "base64ct" version = "1.8.3" @@ -470,6 +500,19 @@ dependencies = [ "zeroize", ] +[[package]] +name = "bigdecimal" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fa3f3d8cbf4dffcfe4991de61d012bef509a409ecbe9dd41049bfe32b4d4653" +dependencies = [ + "autocfg", + "libm", + "num-bigint", + "num-integer", + "num-traits", +] + [[package]] name = "binascii" version = "0.1.4" @@ -591,17 +634,6 @@ dependencies = [ "digest 0.10.7", ] -[[package]] -name = "blake2b_simd" -version = "0.5.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afa748e348ad3be8263be728124b24a24f268266f6f5d58af9d75f6a40b5c587" -dependencies = [ - "arrayref", - "arrayvec 0.5.2", - "constant_time_eq 0.1.5", -] - [[package]] name = "blake3" version = "1.8.5" @@ -609,29 +641,29 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0aa83c34e62843d924f905e0f5c866eb1dd6545fc4d719e803d9ba6030371fce" dependencies = [ "arrayref", - "arrayvec 0.7.6", + "arrayvec", "cc", "cfg-if", - "constant_time_eq 0.4.2", + "constant_time_eq", "cpufeatures 0.3.0", ] [[package]] name = "block-buffer" -version = "0.9.0" +version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" dependencies = [ "generic-array", ] [[package]] name = "block-buffer" -version = "0.10.4" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" dependencies = [ - "generic-array", + "hybrid-array", ] [[package]] @@ -801,7 +833,7 @@ checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" [[package]] name = "cached-cell" -version = "0.6.0" +version = "0.6.6" dependencies = [ "tokio", ] @@ -820,7 +852,7 @@ dependencies = [ [[package]] name = "cc-eventlog" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "digest 0.10.7", @@ -840,7 +872,7 @@ dependencies = [ [[package]] name = "cert-client" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "dstack-guest-agent-rpc", @@ -848,6 +880,8 @@ dependencies = [ "dstack-types", "hex", "http-client", + "mock-attestation", + "prpc", "ra-rpc", "ra-tls", "rocket", @@ -860,7 +894,7 @@ dependencies = [ [[package]] name = "certbot" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "bon", @@ -888,7 +922,7 @@ dependencies = [ [[package]] name = "certbot-cli" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "certbot", @@ -979,22 +1013,24 @@ dependencies = [ [[package]] name = "cipher" -version = "0.3.0" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ee52072ec15386f770805afd189a01c8841be8696bed250fa2f13c4c0d6dfb7" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ - "generic-array", + "crypto-common 0.1.7", + "inout 0.1.4", + "zeroize", ] [[package]] name = "cipher" -version = "0.4.4" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" dependencies = [ - "crypto-common", - "inout", - "zeroize", + "block-buffer 0.12.1", + "crypto-common 0.2.2", + "inout 0.2.2", ] [[package]] @@ -1072,6 +1108,12 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "codicon" version = "3.0.0" @@ -1111,6 +1153,12 @@ version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + [[package]] name = "const_format" version = "0.2.36" @@ -1132,12 +1180,6 @@ dependencies = [ "unicode-xid", ] -[[package]] -name = "constant_time_eq" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc" - [[package]] name = "constant_time_eq" version = "0.4.2" @@ -1208,6 +1250,12 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -1280,31 +1328,6 @@ version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" -[[package]] -name = "crossterm" -version = "0.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c36c10130df424b2f3552fcc2ddcd9b28a27b1e54b358b45874f88d1ca6888c" -dependencies = [ - "bitflags 1.3.2", - "crossterm_winapi", - "lazy_static", - "libc", - "mio 0.7.14", - "parking_lot 0.11.2", - "signal-hook 0.1.17", - "winapi", -] - -[[package]] -name = "crossterm_winapi" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0da8964ace4d3e4a044fd027919b2237000b24315a37c916f61809f1ff2140b9" -dependencies = [ - "winapi", -] - [[package]] name = "crunchy" version = "0.2.4" @@ -1323,6 +1346,21 @@ dependencies = [ "zeroize", ] +[[package]] +name = "crypto-bigint" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c035cb64cba03dad2fb921f3e218785e8cf9a41790da5eb3a1400f62fa2be11" +dependencies = [ + "cpubits", + "ctutils", + "hybrid-array", + "num-traits", + "rand_core 0.10.1", + "subtle", + "zeroize", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -1335,18 +1373,18 @@ dependencies = [ ] [[package]] -name = "crypto-mac" -version = "0.11.0" +name = "crypto-common" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25fab6889090c8133f3deb8f73ba3c65a7f456f66436fc012a1b1e272b1e103e" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" dependencies = [ - "generic-array", - "subtle", + "hybrid-array", + "rand_core 0.10.1", ] [[package]] name = "ct_monitor" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "clap", @@ -1373,6 +1411,25 @@ dependencies = [ "cipher 0.4.4", ] +[[package]] +name = "ctr" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baaca1c4b237092596f64d571e9db6ce4109c4ef9742e27590f1709594461f21" +dependencies = [ + "cipher 0.5.2", +] + +[[package]] +name = "ctutils" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe3e9d21d39e6f39ff46e03d5b621424f88ee23d8a1672c6bfc9ccc7f2da4f6a" +dependencies = [ + "cmov", + "subtle", +] + [[package]] name = "curve25519-dalek" version = "4.1.3" @@ -1383,7 +1440,22 @@ dependencies = [ "cpufeatures 0.2.17", "curve25519-dalek-derive", "digest 0.10.7", - "fiat-crypto", + "fiat-crypto 0.2.9", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "curve25519-dalek-derive", + "fiat-crypto 0.3.0", "rustc_version", "subtle", "zeroize", @@ -1480,7 +1552,7 @@ dependencies = [ "hashbrown 0.14.5", "lock_api", "once_cell", - "parking_lot_core 0.9.12", + "parking_lot_core", ] [[package]] @@ -1491,26 +1563,26 @@ checksum = "a4ae5f15dda3c708c0ade84bfee31ccab44a3da4f88015ed22f63732abe300c8" [[package]] name = "dcap-qvl" -version = "0.5.3" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b3d93e370c7f1bc394106d8f1dc7b58d7d23e765c95b084fe3657efe02ba166" +checksum = "b992c9511adf7135ae7c63c023c9303a3615c0f38d7b39514dcc262f91c6adda" dependencies = [ "anyhow", "asn1_der", - "base64 0.22.1", + "base64 0.23.1", "borsh", "byteorder", "chrono", - "const-oid", + "const-oid 0.10.2", "dcap-qvl-webpki", - "der", + "der 0.8.3", "derive_more 2.1.1", "futures", "hex", "log", - "p256", + "p256 0.14.0", "parity-scale-codec", - "pem", + "pem 4.0.0", "reqwest", "ring", "rustls-pki-types", @@ -1518,29 +1590,27 @@ dependencies = [ "serde", "serde-human-bytes", "serde_json", - "sha2 0.10.9", - "signature", + "sha2 0.11.1", + "signature 3.0.0", "tracing", "urlencoding", - "wasm-bindgen-futures", - "x509-cert", + "x509-cert 0.3.0", ] [[package]] name = "dcap-qvl-webpki" -version = "0.103.4+dcap.1" +version = "0.103.15+dcap.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0af040afe66c4f26ca05f308482d98bd75a35a80a227d877c2e28c9947a9fa6" +checksum = "0e8f2341b6a0f80654c55d0753d420aa306c97b5234c3a47f7e4ccfb6a695b2e" dependencies = [ - "ecdsa", + "ecdsa 0.17.0", "ed25519-dalek", - "p256", - "p384", + "p256 0.14.0", + "p384 0.14.0", "ring", - "rsa", "rustls-pki-types", "sha2 0.10.9", - "signature", + "signature 2.2.0", "untrusted 0.9.0", ] @@ -1567,13 +1637,25 @@ version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ - "const-oid", - "der_derive", + "const-oid 0.9.6", + "der_derive 0.7.3", "flagset", "pem-rfc7468", "zeroize", ] +[[package]] +name = "der" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" +dependencies = [ + "const-oid 0.10.2", + "der_derive 0.8.0", + "flagset", + "zeroize", +] + [[package]] name = "der-parser" version = "9.0.0" @@ -1613,6 +1695,17 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "der_derive" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59600e2c2d636fde9b65e99cc6445ac770c63d3628195ff39932b8d6d7409903" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "deranged" version = "0.5.8" @@ -1703,23 +1796,26 @@ dependencies = [ [[package]] name = "digest" -version = "0.9.0" +version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "generic-array", + "block-buffer 0.10.4", + "const-oid 0.9.6", + "crypto-common 0.1.7", + "subtle", ] [[package]] name = "digest" -version = "0.10.7" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ - "block-buffer 0.10.4", - "const-oid", - "crypto-common", - "subtle", + "block-buffer 0.12.1", + "const-oid 0.10.2", + "crypto-common 0.2.2", + "ctutils", ] [[package]] @@ -1761,7 +1857,7 @@ dependencies = [ "libc", "option-ext", "redox_users 0.5.2", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -1820,19 +1916,22 @@ dependencies = [ [[package]] name = "dstack-api-auth" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "base64 0.22.1", "bcrypt", + "ed25519-dalek", "rocket", + "serde", + "serde_json", "sha2 0.10.9", "subtle", ] [[package]] name = "dstack-attest" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "aws-nitro-enclaves-nsm-api", @@ -1853,7 +1952,7 @@ dependencies = [ "nsm-qvl", "or-panic", "parity-scale-codec", - "pem", + "pem 3.0.6", "rand 0.8.6", "rcgen 0.13.2", "rmp-serde", @@ -1881,25 +1980,28 @@ dependencies = [ [[package]] name = "dstack-auth" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "clap", + "dstack-types", + "hex", "rocket", "serde", "serde_json", + "tempfile", ] [[package]] name = "dstack-build-info" -version = "0.6.0" +version = "0.6.6" dependencies = [ "git-version", ] [[package]] name = "dstack-cli" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "clap", @@ -1916,7 +2018,7 @@ dependencies = [ [[package]] name = "dstack-cli-core" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "dstack-types", @@ -1930,7 +2032,7 @@ dependencies = [ [[package]] name = "dstack-gateway" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "arc-swap", @@ -1976,6 +2078,7 @@ dependencies = [ "rmp-serde", "rmpv", "rocket", + "rocket-proxy-listener", "rustls", "safe-write", "serde", @@ -1993,26 +2096,31 @@ dependencies = [ "tracing-subscriber", "uuid", "wavekv 1.0.0", - "wavekv 2.1.0", + "wavekv 2.2.0", "x509-parser 0.16.0", ] [[package]] name = "dstack-gateway-rpc" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", + "base64 0.22.1", + "hkdf 0.12.4", + "hmac 0.12.1", "parity-scale-codec", "prost 0.13.5", "prpc", "prpc-build", "serde", "serde_json", + "sha2 0.10.9", + "x25519-dalek 2.0.1", ] [[package]] name = "dstack-guest-agent" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "base64 0.22.1", @@ -2024,6 +2132,7 @@ dependencies = [ "clap", "cmd_lib", "default-net", + "dstack-api-auth", "dstack-attest", "dstack-build-info", "dstack-guest-agent-rpc", @@ -2068,7 +2177,7 @@ dependencies = [ [[package]] name = "dstack-guest-agent-rpc" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "hex", @@ -2084,7 +2193,7 @@ dependencies = [ [[package]] name = "dstack-guest-agent-simulator" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "cc-eventlog", @@ -2104,9 +2213,31 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "dstack-key-recovery" +version = "0.6.6" +dependencies = [ + "anyhow", + "axum", + "cert-client", + "clap", + "dstack-attest", + "dstack-kms-rpc", + "dstack-types", + "ed25519-dalek", + "fs-err", + "hex", + "k256", + "ra-tls", + "semver", + "serde", + "serde_json", + "tokio", +] + [[package]] name = "dstack-kms" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "cc-eventlog", @@ -2120,12 +2251,15 @@ dependencies = [ "dstack-types", "dstack-verifier", "fs-err", + "futures", "hex", "hex_fmt", "http-client", "k256", "load_config", + "mock-attestation", "moka", + "p256 0.13.2", "parity-scale-codec", "ra-rpc", "ra-tls", @@ -2133,6 +2267,7 @@ dependencies = [ "reqwest", "ring", "rocket", + "rocket-proxy-listener", "safe-write", "serde", "serde-duration", @@ -2144,14 +2279,14 @@ dependencies = [ "tokio", "tracing", "tracing-subscriber", - "x25519-dalek", + "x25519-dalek 2.0.1", "x509-parser 0.16.0", "yasna 0.5.2", ] [[package]] name = "dstack-kms-rpc" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "fs-err", @@ -2165,11 +2300,13 @@ dependencies = [ [[package]] name = "dstack-mr" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "binrw", "bon", + "cc-eventlog", + "dcap-qvl", "dstack-types", "flate2", "fs-err", @@ -2205,7 +2342,7 @@ dependencies = [ [[package]] name = "dstack-netd-rpc" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "prost 0.13.5", @@ -2217,7 +2354,7 @@ dependencies = [ [[package]] name = "dstack-nvidia-attest-proxy" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "base64 0.22.1", @@ -2245,7 +2382,7 @@ dependencies = [ [[package]] name = "dstack-tee-simulator" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "aws-nitro-enclaves-nsm-api", @@ -2263,7 +2400,7 @@ dependencies = [ "mock-attestation", "nix 0.29.0", "nsm-qvl", - "pem", + "pem 3.0.6", "reqwest", "safe-write", "sd-notify", @@ -2282,7 +2419,7 @@ dependencies = [ [[package]] name = "dstack-types" -version = "0.6.0" +version = "0.6.6" dependencies = [ "ciborium", "hex", @@ -2300,9 +2437,9 @@ dependencies = [ [[package]] name = "dstack-util" -version = "0.6.0" +version = "0.6.6" dependencies = [ - "aes-gcm", + "aes-gcm 0.10.3", "anyhow", "base64 0.22.1", "binrw", @@ -2311,8 +2448,9 @@ dependencies = [ "cert-client", "clap", "cmd_lib", - "curve25519-dalek", + "curve25519-dalek 4.1.3", "dcap-qvl", + "dstack-api-auth", "dstack-attest", "dstack-gateway-rpc", "dstack-kms-rpc", @@ -2325,10 +2463,10 @@ dependencies = [ "hex", "hex_fmt", "host-api", + "hpke", "k256", "libc", "lspci", - "luks2", "nvattest", "nvml-wrapper", "parity-scale-codec", @@ -2344,6 +2482,8 @@ dependencies = [ "serde", "serde-human-bytes", "serde_json", + "serde_with", + "sev-snp-attest", "sha2 0.10.9", "sha3", "sodiumbox", @@ -2357,17 +2497,18 @@ dependencies = [ "tracing", "tracing-subscriber", "url", - "x25519-dalek", + "value-spec", + "x25519-dalek 2.0.1", "x509-parser 0.16.0", "yaml-rust2", + "zeroize", ] [[package]] name = "dstack-verifier" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", - "cc-eventlog", "clap", "dcap-qvl", "dstack-attest", @@ -2387,6 +2528,7 @@ dependencies = [ "serde", "serde-human-bytes", "serde_json", + "sev-snp-qvl", "sha2 0.10.9", "tar", "tempfile", @@ -2398,14 +2540,29 @@ dependencies = [ "x509-parser 0.16.0", ] +[[package]] +name = "dstack-verifier-wasm" +version = "0.6.6" +dependencies = [ + "anyhow", + "cc-eventlog", + "dcap-qvl", + "dstack-mr", + "dstack-types", + "hex", + "serde", + "serde_json", +] + [[package]] name = "dstack-vmm" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "base64 0.22.1", "bon", "clap", + "dcap-qvl", "dirs 6.0.0", "dstack-api-auth", "dstack-build-info", @@ -2436,6 +2593,7 @@ dependencies = [ "or-panic", "path-absolutize", "ra-rpc", + "ra-tls", "rand 0.8.6", "rocket", "rocket-vsock-listener", @@ -2447,15 +2605,18 @@ dependencies = [ "sha2 0.10.9", "shared_child", "size-parser", + "sodiumbox", "strip-ansi-escapes", "supervisor-client", "tailf", + "tdx-attest", "tempfile", "tokio", "tracing", "tracing-subscriber", "url", "uuid", + "value-spec", "vfio-ioctls", "wait-timeout", "which 7.0.3", @@ -2463,7 +2624,7 @@ dependencies = [ [[package]] name = "dstack-vmm-rpc" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "parity-scale-codec", @@ -2476,7 +2637,7 @@ dependencies = [ [[package]] name = "dstack-volume" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "binrw", @@ -2497,7 +2658,7 @@ dependencies = [ [[package]] name = "dstackup" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "clap", @@ -2530,12 +2691,26 @@ version = "0.16.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" dependencies = [ - "der", + "der 0.7.10", "digest 0.10.7", - "elliptic-curve", - "rfc6979", - "signature", - "spki", + "elliptic-curve 0.13.8", + "rfc6979 0.4.0", + "signature 2.2.0", + "spki 0.7.3", +] + +[[package]] +name = "ecdsa" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0681a4fc24c767085329728d8dfba959af91228aa4610cca4f8ce317ba46ae0" +dependencies = [ + "der 0.8.3", + "digest 0.11.3", + "elliptic-curve 0.14.3", + "rfc6979 0.6.0", + "signature 3.0.0", + "zeroize", ] [[package]] @@ -2545,7 +2720,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" dependencies = [ "pkcs8", - "signature", + "signature 2.2.0", ] [[package]] @@ -2554,7 +2729,7 @@ version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" dependencies = [ - "curve25519-dalek", + "curve25519-dalek 4.1.3", "ed25519", "rand_core 0.6.4", "serde", @@ -2575,17 +2750,36 @@ version = "0.13.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" dependencies = [ - "base16ct", - "crypto-bigint", + "base16ct 0.2.0", + "crypto-bigint 0.5.5", "digest 0.10.7", - "ff", + "ff 0.13.1", "generic-array", - "group", - "hkdf", + "group 0.13.0", + "hkdf 0.12.4", "pem-rfc7468", "pkcs8", "rand_core 0.6.4", - "sec1", + "sec1 0.7.3", + "subtle", + "zeroize", +] + +[[package]] +name = "elliptic-curve" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900f37e7e18d74a2347389af6cd69e3a30d5cc9e697f40004865679aa75e9c7c" +dependencies = [ + "base16ct 1.0.0", + "crypto-bigint 0.7.10", + "crypto-common 0.2.2", + "digest 0.11.3", + "ff 0.14.0", + "group 0.14.0", + "hybrid-array", + "rand_core 0.10.1", + "sec1 0.8.1", "subtle", "zeroize", ] @@ -2680,7 +2874,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -2768,12 +2962,28 @@ dependencies = [ "subtle", ] +[[package]] +name = "ff" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1f686ab92a9fb0eaf188f6c6c87b89490baa6fdb0db4544ba4dc47f7942489f" +dependencies = [ + "rand_core 0.10.1", + "subtle", +] + [[package]] name = "fiat-crypto" version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" +[[package]] +name = "fiat-crypto" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24" + [[package]] name = "figment" version = "0.10.19" @@ -3107,7 +3317,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" dependencies = [ "opaque-debug", - "polyval", + "polyval 0.6.2", +] + +[[package]] +name = "ghash" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2eecf2d5dc9b66b732b97707a0210906b1d30523eb773193ab777c0c84b3e8d5" +dependencies = [ + "polyval 0.7.3", ] [[package]] @@ -3166,14 +3385,25 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" dependencies = [ - "ff", + "ff 0.13.1", "rand_core 0.6.4", "subtle", ] +[[package]] +name = "group" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fd1a1c7a5206c5b7a3f5a0d7ccd3ff85d0c8f5133d62a02680255b0004af5f4" +dependencies = [ + "ff 0.14.0", + "rand_core 0.10.1", + "subtle", +] + [[package]] name = "guest-api" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "http-client", @@ -3186,9 +3416,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.14" +version = "0.4.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "171fefbc92fe4a4de27e0698d6a5b392d6a0e333506bc49133760b3bcf948733" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" dependencies = [ "atomic-waker", "bytes", @@ -3385,7 +3615,7 @@ dependencies = [ "moka", "ndk-context", "once_cell", - "parking_lot 0.12.5", + "parking_lot", "rand 0.10.1", "resolv-conf", "smallvec", @@ -3405,13 +3635,12 @@ dependencies = [ ] [[package]] -name = "hmac" -version = "0.11.0" +name = "hkdf" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a2a2320eb7ec0ebe8da8f744d7812d9fc4cb4d09344ac01898dbcb6a20ae69b" +checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" dependencies = [ - "crypto-mac", - "digest 0.9.0", + "hmac 0.13.0", ] [[package]] @@ -3423,6 +3652,15 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "home" version = "0.5.12" @@ -3434,7 +3672,7 @@ dependencies = [ [[package]] name = "host-api" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "http-client", @@ -3445,6 +3683,25 @@ dependencies = [ "serde_json", ] +[[package]] +name = "hpke" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f512e325a1a71bf3273fb9b7fc9e5d96dac136fb4a95d0e6637001b12ea3e09" +dependencies = [ + "aead 0.6.1", + "aes-gcm 0.11.1", + "curve25519-dalek 5.0.0", + "getrandom 0.4.2", + "hkdf 0.13.0", + "hybrid-array", + "rand_core 0.10.1", + "sha2 0.11.1", + "subtle", + "x25519-dalek 3.0.0", + "zeroize", +] + [[package]] name = "http" version = "1.4.1" @@ -3480,7 +3737,7 @@ dependencies = [ [[package]] name = "http-client" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "http-body-util", @@ -3525,6 +3782,17 @@ version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "subtle", + "typenum", + "zeroize", +] + [[package]] name = "hyper" version = "1.10.1" @@ -3596,7 +3864,7 @@ dependencies = [ "libc", "percent-encoding", "pin-project-lite", - "socket2 0.5.10", + "socket2 0.6.4", "tokio", "tower-service", "tracing", @@ -3825,6 +4093,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "inout" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7" +dependencies = [ + "hybrid-array", +] + [[package]] name = "insta" version = "1.47.2" @@ -3837,15 +4114,6 @@ dependencies = [ "tempfile", ] -[[package]] -name = "instant" -version = "0.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" -dependencies = [ - "cfg-if", -] - [[package]] name = "instant-acme" version = "0.8.5" @@ -3889,7 +4157,7 @@ checksum = "d8972d5be69940353d5347a1344cb375d9b457d6809b428b05bb1ca2fb9ce007" [[package]] name = "iohash" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "blake2", @@ -3930,7 +4198,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -4106,11 +4374,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6e3919bbaa2945715f0bb6d3934a173d1e9a59ac23767fbaaef277265a7411b" dependencies = [ "cfg-if", - "ecdsa", - "elliptic-curve", + "ecdsa 0.16.9", + "elliptic-curve 0.13.8", "once_cell", "sha2 0.10.9", - "signature", + "signature 2.2.0", ] [[package]] @@ -4124,7 +4392,7 @@ dependencies = [ [[package]] name = "key-provider-client" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "dstack-types", @@ -4210,9 +4478,9 @@ checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" [[package]] name = "libc" -version = "0.2.186" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "libloading" @@ -4270,8 +4538,9 @@ checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" [[package]] name = "load_config" -version = "0.6.0" +version = "0.6.6" dependencies = [ + "anyhow", "figment", "rocket", "tempfile", @@ -4280,7 +4549,7 @@ dependencies = [ [[package]] name = "local-key-provider" -version = "0.6.0" +version = "0.6.6" dependencies = [ "blake2", "dcap-qvl", @@ -4294,7 +4563,7 @@ dependencies = [ "tokio", "tracing", "tracing-subscriber", - "x25519-dalek", + "x25519-dalek 2.0.1", "xsalsa20poly1305", ] @@ -4342,35 +4611,13 @@ checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" [[package]] name = "lspci" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "insta", "tempfile", ] -[[package]] -name = "luks2" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2044d8bd5489b199890c3dbf38d4c8f50f3a5a38833986808b14e2367fe267fa" -dependencies = [ - "aes 0.7.5", - "base64 0.13.1", - "bincode 1.3.3", - "crossterm", - "hmac 0.11.0", - "pbkdf2", - "rust-argon2", - "secrecy", - "serde", - "serde-big-array 0.3.3", - "serde_json", - "sha2 0.9.9", - "thiserror 1.0.69", - "xts-mode", -] - [[package]] name = "matchers" version = "0.2.0" @@ -4476,19 +4723,6 @@ dependencies = [ "simd-adler32", ] -[[package]] -name = "mio" -version = "0.7.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8067b404fe97c70829f082dec8bcf4f71225d7eaea1d8645349cb76fa06205cc" -dependencies = [ - "libc", - "log", - "miow", - "ntapi 0.3.7", - "winapi", -] - [[package]] name = "mio" version = "1.2.1" @@ -4501,18 +4735,9 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "miow" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9f1c5b025cda876f66ef43a113f91ebc9f4ccef34843000e0adf6ebbab84e21" -dependencies = [ - "winapi", -] - [[package]] name = "mock-attestation" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "axum", @@ -4524,8 +4749,8 @@ dependencies = [ "fs-err", "hex", "nsm-qvl", - "p256", - "p384", + "p256 0.13.2", + "p384 0.13.1", "parity-scale-codec", "rand 0.8.6", "rcgen 0.13.2", @@ -4557,7 +4782,7 @@ dependencies = [ "equivalent", "event-listener", "futures-util", - "parking_lot 0.12.5", + "parking_lot", "portable-atomic", "smallvec", "tagptr", @@ -4723,7 +4948,7 @@ dependencies = [ "kqueue", "libc", "log", - "mio 1.2.1", + "mio", "notify-types", "walkdir", "windows-sys 0.60.2", @@ -4740,7 +4965,7 @@ dependencies = [ [[package]] name = "nsm-attest" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "aws-nitro-enclaves-nsm-api", @@ -4752,15 +4977,15 @@ dependencies = [ [[package]] name = "nsm-qvl" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "ciborium", "dcap-qvl-webpki", "hex", "nsm-attest", - "p384", - "pem", + "p384 0.13.1", + "pem 3.0.6", "pki-fetch", "rustls-pki-types", "serde", @@ -4771,15 +4996,6 @@ dependencies = [ "x509-parser 0.16.0", ] -[[package]] -name = "ntapi" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c28774a7fd2fbb4f0babd8237ce554b73af68021b5f695a3cebd6c59bac0980f" -dependencies = [ - "winapi", -] - [[package]] name = "ntapi" version = "0.4.3" @@ -4795,7 +5011,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -4934,7 +5150,7 @@ dependencies = [ [[package]] name = "nvattest" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "serde", @@ -5073,7 +5289,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.48.0", + "windows-sys 0.61.2", ] [[package]] @@ -5088,24 +5304,51 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" dependencies = [ - "ecdsa", - "elliptic-curve", - "primeorder", + "ecdsa 0.16.9", + "elliptic-curve 0.13.8", + "primeorder 0.13.6", "sha2 0.10.9", ] +[[package]] +name = "p256" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2c9239b2dbc807adbbe147e8cf72ea7450c3a0aabe62cb8e75ff4ec22e1f72a" +dependencies = [ + "ecdsa 0.17.0", + "elliptic-curve 0.14.3", + "primefield", + "primeorder 0.14.0", + "sha2 0.11.1", +] + [[package]] name = "p384" version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" dependencies = [ - "ecdsa", - "elliptic-curve", - "primeorder", + "ecdsa 0.16.9", + "elliptic-curve 0.13.8", + "primeorder 0.13.6", "sha2 0.10.9", ] +[[package]] +name = "p384" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d17b851e6b3e378ab4ecb07fa2ed23f4d15f075735f8fec9fa1e7bdce5f8301f" +dependencies = [ + "ecdsa 0.17.0", + "elliptic-curve 0.14.3", + "fiat-crypto 0.3.0", + "primefield", + "primeorder 0.14.0", + "sha2 0.11.1", +] + [[package]] name = "page_size" version = "0.6.0" @@ -5144,7 +5387,7 @@ version = "3.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "799781ae679d79a948e13d4824a40970bfa500058d245760dd857301059810fa" dependencies = [ - "arrayvec 0.7.6", + "arrayvec", "bitvec", "byte-slice-cast", "const_format", @@ -5172,17 +5415,6 @@ version = "2.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" -[[package]] -name = "parking_lot" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99" -dependencies = [ - "instant", - "lock_api", - "parking_lot_core 0.8.6", -] - [[package]] name = "parking_lot" version = "0.12.5" @@ -5190,21 +5422,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" dependencies = [ "lock_api", - "parking_lot_core 0.9.12", -] - -[[package]] -name = "parking_lot_core" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60a2cfe6f0ad2bfc16aefa463b497d5c7a5ecd44a23efa72aa342d90177356dc" -dependencies = [ - "cfg-if", - "instant", - "libc", - "redox_syscall 0.2.16", - "smallvec", - "winapi", + "parking_lot_core", ] [[package]] @@ -5215,7 +5433,7 @@ checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" dependencies = [ "cfg-if", "libc", - "redox_syscall 0.5.18", + "redox_syscall", "smallvec", "windows-link 0.2.1", ] @@ -5244,15 +5462,6 @@ dependencies = [ "once_cell", ] -[[package]] -name = "pbkdf2" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d95f5254224e617595d2cc3cc73ff0a5eaf2637519e25f03388154e9378b6ffa" -dependencies = [ - "crypto-mac", -] - [[package]] name = "pear" version = "0.2.9" @@ -5286,6 +5495,16 @@ dependencies = [ "serde_core", ] +[[package]] +name = "pem" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120" +dependencies = [ + "base64 0.23.1", + "serde_core", +] + [[package]] name = "pem-rfc7468" version = "0.7.0" @@ -5401,9 +5620,9 @@ version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" dependencies = [ - "der", + "der 0.7.10", "pkcs8", - "spki", + "spki 0.7.3", ] [[package]] @@ -5412,16 +5631,22 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" dependencies = [ - "der", - "spki", + "der 0.7.10", + "spki 0.7.3", ] +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + [[package]] name = "pki-fetch" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", - "pem", + "pem 3.0.6", "reqwest", "tokio", "tracing", @@ -5436,7 +5661,7 @@ checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" dependencies = [ "cpufeatures 0.2.17", "opaque-debug", - "universal-hash", + "universal-hash 0.5.1", ] [[package]] @@ -5448,7 +5673,18 @@ dependencies = [ "cfg-if", "cpufeatures 0.2.17", "opaque-debug", - "universal-hash", + "universal-hash 0.5.1", +] + +[[package]] +name = "polyval" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0fa31d631f2b2cb2a544d0aa321ce847a94764d701ca2becc411138b93d49cd" +dependencies = [ + "cpubits", + "cpufeatures 0.3.0", + "universal-hash 0.6.1", ] [[package]] @@ -5502,13 +5738,38 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "primefield" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c555a6e4eb7d4e158fcb028c835c3b8642206ddc279b5c6b202ef9a8bdb592f4" +dependencies = [ + "crypto-bigint 0.7.10", + "crypto-common 0.2.2", + "ff 0.14.0", + "rand_core 0.10.1", + "subtle", + "zeroize", +] + [[package]] name = "primeorder" version = "0.13.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" dependencies = [ - "elliptic-curve", + "elliptic-curve 0.13.8", +] + +[[package]] +name = "primeorder" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c9f42978c78a00e3d68f69fc03e57a234debae69da4020a4fb588fcdcd07b06" +dependencies = [ + "elliptic-curve 0.14.3", + "primefield", + "wnaf", ] [[package]] @@ -5777,7 +6038,7 @@ dependencies = [ "quinn-udp", "rustc-hash", "rustls", - "socket2 0.5.10", + "socket2 0.6.4", "thiserror 2.0.18", "tokio", "tracing", @@ -5816,7 +6077,7 @@ dependencies = [ "cfg_aliases", "libc", "once_cell", - "socket2 0.5.10", + "socket2 0.6.4", "tracing", "windows-sys 0.60.2", ] @@ -5844,7 +6105,7 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "ra-rpc" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "bon", @@ -5860,13 +6121,14 @@ dependencies = [ "serde", "serde_json", "tokio", + "tokio-rustls", "tracing", "x509-parser 0.16.0", ] [[package]] name = "ra-tls" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "bon", @@ -5875,17 +6137,17 @@ dependencies = [ "dstack-attest", "dstack-types", "ed25519-dalek", - "elliptic-curve", + "elliptic-curve 0.13.8", "errify", "ez-hash", "flate2", "fs-err", "hex", "hex_fmt", - "hkdf", + "hkdf 0.12.4", "k256", "or-panic", - "p256", + "p256 0.13.2", "parity-scale-codec", "rand 0.8.6", "rcgen 0.13.2", @@ -6004,7 +6266,7 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75e669e5202259b5314d1ea5397316ad400819437857b90861765f24c4cf80a2" dependencies = [ - "pem", + "pem 3.0.6", "ring", "rustls-pki-types", "time", @@ -6019,22 +6281,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "091e7a8e7d86e6feb87a27ce8e2cba29d49eff9507afeebefab7eeb2ca667fb4" dependencies = [ "aws-lc-rs", - "pem", + "pem 3.0.6", "rustls-pki-types", "time", "x509-parser 0.18.1", "yasna 0.6.0", ] -[[package]] -name = "redox_syscall" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" -dependencies = [ - "bitflags 1.3.2", -] - [[package]] name = "redox_syscall" version = "0.5.18" @@ -6104,7 +6357,7 @@ dependencies = [ "hashbrown 0.16.1", "itoa", "micromap", - "parking_lot 0.12.5", + "parking_lot", "percent-encoding", "serde_json", ] @@ -6157,7 +6410,7 @@ dependencies = [ "msvc_spectre_libs", "num-bigint", "num-traits", - "parking_lot 0.12.5", + "parking_lot", "rand 0.10.1", "regex", "semver", @@ -6236,6 +6489,16 @@ dependencies = [ "subtle", ] +[[package]] +name = "rfc6979" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4a459cddafb3fe76b31fd8f1108007566c40301feb64dc7b54656eb7388172b" +dependencies = [ + "crypto-bigint 0.7.10", + "hmac 0.13.0", +] + [[package]] name = "ring" version = "0.17.14" @@ -6340,7 +6603,7 @@ dependencies = [ "memchr", "multer", "num_cpus", - "parking_lot 0.12.5", + "parking_lot", "pin-project-lite", "rand 0.9.4", "ref-cast", @@ -6369,9 +6632,22 @@ dependencies = [ "yansi", ] +[[package]] +name = "rocket-proxy-listener" +version = "0.6.6" +dependencies = [ + "anyhow", + "pin-project", + "proxy-protocol", + "rocket", + "serde", + "tokio", + "tracing", +] + [[package]] name = "rocket-vsock-listener" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "derive_more 2.1.1", @@ -6425,7 +6701,7 @@ version = "0.9.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" dependencies = [ - "const-oid", + "const-oid 0.9.6", "digest 0.10.7", "num-bigint-dig", "num-integer", @@ -6433,25 +6709,12 @@ dependencies = [ "pkcs1", "pkcs8", "rand_core 0.6.4", - "sha2 0.10.9", - "signature", - "spki", + "signature 2.2.0", + "spki 0.7.3", "subtle", "zeroize", ] -[[package]] -name = "rust-argon2" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b18820d944b33caa75a71378964ac46f58517c92b6ae5f762636247c09e78fb" -dependencies = [ - "base64 0.13.1", - "blake2b_simd", - "constant_time_eq 0.1.5", - "crossbeam-utils", -] - [[package]] name = "rustc-hash" version = "2.1.2" @@ -6499,14 +6762,14 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] name = "rustls" -version = "0.23.40" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef86cd5876211988985292b91c96a8f2d298df24e75989a43a3c73f2d4d8168b" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "aws-lc-rs", "log", @@ -6567,7 +6830,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -6578,9 +6841,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" [[package]] name = "rustls-webpki" -version = "0.103.13" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "aws-lc-rs", "ring", @@ -6835,10 +7098,10 @@ version = "0.11.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e9fcb6c2e176e86ec703e22560d99d65a5ee9056ae45a08e13e84ebf796296f" dependencies = [ - "aead", + "aead 0.5.2", "arrayref", - "arrayvec 0.7.6", - "curve25519-dalek", + "arrayvec", + "curve25519-dalek 4.1.3", "getrandom_or_panic", "merlin", "rand_core 0.6.4", @@ -6875,8 +7138,8 @@ version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" dependencies = [ - "base16ct", - "der", + "base16ct 0.2.0", + "der 0.7.10", "generic-array", "pkcs8", "subtle", @@ -6884,11 +7147,16 @@ dependencies = [ ] [[package]] -name = "secrecy" -version = "0.8.0" +name = "sec1" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bd1c54ea06cfd2f6b63219704de0b9b4f72dcc2b8fdef820be6cd799780e91e" +checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d" dependencies = [ + "base16ct 1.0.0", + "ctutils", + "der 0.8.3", + "hybrid-array", + "subtle", "zeroize", ] @@ -6931,15 +7199,6 @@ dependencies = [ "serde_derive", ] -[[package]] -name = "serde-big-array" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd31f59f6fe2b0c055371bb2f16d7f0aa7d8881676c04a55b1596d1a17cd10a4" -dependencies = [ - "serde", -] - [[package]] name = "serde-big-array" version = "0.5.1" @@ -6951,7 +7210,7 @@ dependencies = [ [[package]] name = "serde-duration" -version = "0.6.0" +version = "0.6.6" dependencies = [ "serde", "serde_json", @@ -7160,40 +7419,44 @@ dependencies = [ "iocuddle", "lazy_static", "libc", - "p384", + "p384 0.13.1", "rsa", "serde", - "serde-big-array 0.5.1", + "serde-big-array", "serde_bytes", "sha2 0.10.9", "static_assertions", "uuid", - "x509-cert", + "x509-cert 0.2.5", ] [[package]] name = "sev-snp-attest" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "fs-err", "hex", + "libc", "sev", "tracing", + "zeroize", ] [[package]] name = "sev-snp-qvl" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "hex", "moka", - "pem", + "pem 3.0.6", + "rcgen 0.13.2", "reqwest", "rustls-pki-types", "rustls-webpki", "sev", + "time", "tokio", "x509-parser 0.16.0", ] @@ -7211,26 +7474,24 @@ dependencies = [ [[package]] name = "sha2" -version = "0.9.9" +version = "0.10.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ - "block-buffer 0.9.0", "cfg-if", "cpufeatures 0.2.17", - "digest 0.9.0", - "opaque-debug", + "digest 0.10.7", ] [[package]] name = "sha2" -version = "0.10.9" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" dependencies = [ "cfg-if", - "cpufeatures 0.2.17", - "digest 0.10.7", + "cpufeatures 0.3.0", + "digest 0.11.3", ] [[package]] @@ -7277,18 +7538,7 @@ checksum = "47106eded3c154e70176fc83df9737335c94ce22f821c32d17ed1db1f83badb1" dependencies = [ "libc", "os_pipe", - "signal-hook 0.3.18", -] - -[[package]] -name = "signal-hook" -version = "0.1.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e31d442c16f047a671b5a71e2161d6e68814012b7f5379d269ebd915fac2729" -dependencies = [ - "libc", - "mio 0.7.14", - "signal-hook-registry", + "signal-hook", ] [[package]] @@ -7321,6 +7571,16 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "signature" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" +dependencies = [ + "digest 0.11.3", + "rand_core 0.10.1", +] + [[package]] name = "simd-adler32" version = "0.3.9" @@ -7363,7 +7623,7 @@ checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649" [[package]] name = "size-parser" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "serde", @@ -7421,7 +7681,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -7432,7 +7692,7 @@ dependencies = [ "or-panic", "rand_core 0.6.4", "salsa20", - "x25519-dalek", + "x25519-dalek 2.0.1", "xsalsa20poly1305", ] @@ -7455,7 +7715,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" dependencies = [ "base64ct", - "der", + "der 0.7.10", +] + +[[package]] +name = "spki" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9" +dependencies = [ + "base64ct", + "der 0.8.3", ] [[package]] @@ -7532,7 +7802,7 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "supervisor" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "bon", @@ -7555,7 +7825,7 @@ dependencies = [ [[package]] name = "supervisor-client" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "clap", @@ -7625,7 +7895,7 @@ checksum = "3c3ffa3e4ff2b324a57f7aeb3c349656c7b127c3c189520251a648102a92496e" dependencies = [ "libc", "memchr", - "ntapi 0.4.3", + "ntapi", "objc2-core-foundation", "objc2-io-kit", "windows 0.61.3", @@ -7708,13 +7978,14 @@ dependencies = [ [[package]] name = "tdx-attest" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "cc-eventlog", "dcap-qvl", "fs-err", "hex", + "hkdf 0.12.4", "insta", "libc", "parity-scale-codec", @@ -7726,6 +7997,7 @@ dependencies = [ "thiserror 2.0.18", "tokio", "vsock", + "zeroize", ] [[package]] @@ -7738,7 +8010,7 @@ dependencies = [ "getrandom 0.4.2", "once_cell", "rustix 1.1.4", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -7906,8 +8178,8 @@ checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe" dependencies = [ "bytes", "libc", - "mio 1.2.1", - "parking_lot 0.12.5", + "mio", + "parking_lot", "pin-project-lite", "signal-hook-registry", "socket2 0.6.4", @@ -8092,7 +8364,7 @@ checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" [[package]] name = "tpm-attest" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "dstack-types", @@ -8111,7 +8383,7 @@ dependencies = [ [[package]] name = "tpm-qvl" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "base64 0.22.1", @@ -8119,8 +8391,8 @@ dependencies = [ "dstack-types", "hex", "nom", - "p256", - "pem", + "p256 0.13.2", + "pem 3.0.6", "pki-fetch", "rsa", "rustls-pki-types", @@ -8134,7 +8406,7 @@ dependencies = [ [[package]] name = "tpm-types" -version = "0.6.0" +version = "0.6.6" dependencies = [ "cc-eventlog", "dstack-types", @@ -8145,7 +8417,7 @@ dependencies = [ [[package]] name = "tpm2" -version = "0.6.0" +version = "0.6.6" dependencies = [ "anyhow", "hex", @@ -8207,7 +8479,7 @@ dependencies = [ "matchers", "nu-ansi-term", "once_cell", - "parking_lot 0.12.5", + "parking_lot", "regex-automata", "sharded-slab", "smallvec", @@ -8294,10 +8566,20 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" dependencies = [ - "crypto-common", + "crypto-common 0.1.7", "subtle", ] +[[package]] +name = "universal-hash" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96" +dependencies = [ + "crypto-common 0.2.2", + "ctutils", +] + [[package]] name = "unsafe-libyaml" version = "0.2.11" @@ -8381,6 +8663,16 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" +[[package]] +name = "value-spec" +version = "0.6.6" +dependencies = [ + "bigdecimal", + "regex", + "thiserror 2.0.18", + "winnow 1.0.3", +] + [[package]] name = "version_check" version = "0.9.5" @@ -8630,9 +8922,9 @@ dependencies = [ [[package]] name = "wavekv" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99f5f24dfab68f43806c0a15c3b87d9cde250dfc876cae3ec34642427becf336" +checksum = "7abcc88e4e31da65469d4bfa568c7bae38cc6473532cdcdd9cf1e217ef7af844" dependencies = [ "anyhow", "bincode 2.0.1", @@ -8673,9 +8965,9 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.8" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d46a5a140e6f7afeccd8eae97eff335163939eac8b929834875168b29b3d267" +checksum = "58ec80e73fd8baf57bf0d9615554c75348bda990d6d5bbeab964dd068319fecb" dependencies = [ "rustls-pki-types", ] @@ -8732,7 +9024,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.48.0", + "windows-sys 0.61.2", ] [[package]] @@ -9236,6 +9528,18 @@ dependencies = [ "wasmparser", ] +[[package]] +name = "wnaf" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "795ca18b3fdb5e62bf982199278341ddcf7ebf7d32e25e212ad05d496e95f6fa" +dependencies = [ + "ff 0.14.0", + "group 0.14.0", + "hybrid-array", + "primefield", +] + [[package]] name = "wrapcenum-derive" version = "0.4.1" @@ -9269,24 +9573,46 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277" dependencies = [ - "curve25519-dalek", + "curve25519-dalek 4.1.3", "rand_core 0.6.4", "serde", "zeroize", ] +[[package]] +name = "x25519-dalek" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e8131a03190127fb2263afc72b322ecadae46b6ff8c6f399ff5d02f5559af6" +dependencies = [ + "curve25519-dalek 5.0.0", + "rand_core 0.10.1", + "zeroize", +] + [[package]] name = "x509-cert" version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94" dependencies = [ - "const-oid", - "der", - "spki", + "const-oid 0.9.6", + "der 0.7.10", + "spki 0.7.3", "tls_codec", ] +[[package]] +name = "x509-cert" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "105ef4642d9cb137ef83d623d0e4bf08b8adf69e9918ca904a174adb6d3d038b" +dependencies = [ + "const-oid 0.10.2", + "der 0.8.3", + "spki 0.8.1", +] + [[package]] name = "x509-parser" version = "0.16.0" @@ -9339,23 +9665,13 @@ version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "02a6dad357567f81cd78ee75f7c61f1b30bb2fe4390be8fb7c69e2ac8dffb6c7" dependencies = [ - "aead", + "aead 0.5.2", "poly1305", "salsa20", "subtle", "zeroize", ] -[[package]] -name = "xts-mode" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75a099a2f21d48275314733f85bc43b6c6213b66394233aaea573fc7a520dcd9" -dependencies = [ - "byteorder", - "cipher 0.3.0", -] - [[package]] name = "yaml-rust2" version = "0.10.4" diff --git a/dstack/Cargo.toml b/dstack/Cargo.toml index 7d7cbaf711..9e38113ae7 100644 --- a/dstack/Cargo.toml +++ b/dstack/Cargo.toml @@ -5,7 +5,7 @@ # SPDX-License-Identifier: Apache-2.0 [workspace.package] -version = "0.6.0" +version = "0.6.6" authors = ["Kevin Wang ", "Leechael "] edition = "2021" license = "MIT" @@ -46,6 +46,7 @@ members = [ "supervisor", "supervisor/client", "rocket-vsock-listener", + "rocket-proxy-listener", "http-client", "host-api", "guest-api", @@ -64,6 +65,7 @@ members = [ "nvidia-attest-proxy", "verifier", "size-parser", + "value-spec", "crates/dstack-cli-core", "crates/dstack-cli", "crates/dstack-volume", @@ -74,6 +76,8 @@ members = [ "crates/mock-attestation", "crates/qemu-acpi", "crates/pki-fetch", + "crates/dstack-verifier-wasm", + "tools/key-recovery", ] # Vendored third-party crates are path dependencies but deliberately not members: # `--all-features` applies to members, and ktls declares its `ring` and @@ -112,6 +116,7 @@ sev-snp-qvl = { path = "sev-snp-qvl" } nsm-qvl = { path = "nsm-qvl" } certbot = { path = "certbot" } rocket-vsock-listener = { path = "rocket-vsock-listener" } +rocket-proxy-listener = { path = "rocket-proxy-listener" } host-api = { path = "host-api", default-features = false } guest-api = { path = "guest-api", default-features = false } http-client = { path = "http-client", default-features = false } @@ -126,8 +131,9 @@ serde-duration = { path = "serde-duration" } dstack-mr = { path = "dstack-mr" } dstack-verifier = { path = "verifier", default-features = false } size-parser = { path = "size-parser" } +value-spec = { path = "value-spec" } nvattest = { path = "nvattest" } -wavekv = "2.1" +wavekv = "2.2" vfio-ioctls = { git = "https://github.com/kvinwang/vfio.git", rev = "1b560c2", default-features = false } # Core dependencies @@ -143,7 +149,7 @@ fs-err = "3.1.0" fuser = "0.16.0" path-absolutize = "3.1.1" futures = "0.3.31" -libc = "0.2.171" +libc = "0.2.189" log = "0.4.26" moka = { version = "0.12.15", default-features = false, features = ["sync"] } notify = "8.0.0" @@ -170,6 +176,7 @@ base64 = "0.22.1" bcrypt = "0.17.1" hex = { version = "0.4.3", default-features = false } hex_fmt = "0.3.0" +hpke = { version = "0.15.1", default-features = false, features = ["alloc", "getrandom", "x25519", "aes"] } hex-literal = "1.0.0" prost = "0.13.5" prost-types = "0.13.5" @@ -236,22 +243,24 @@ url = "2.5" # Cryptography/Security aes-gcm = "0.10.3" curve25519-dalek = "4.1.3" -dcap-qvl = "0.5.3" -dcap-qvl-webpki = "0.103.4" +dcap-qvl = "0.7.0" +dcap-qvl-webpki = "0.103.15" elliptic-curve = { version = "0.13.8", features = ["pkcs8"] } getrandom = "0.3.1" hkdf = "0.12.4" +hmac = "0.12.1" p256 = "0.13.2" p384 = "0.13" rsa = "0.9" ring = "0.17.14" rustls = "0.23.23" rustls-pki-types = "1.13.1" -rustls-webpki = "0.103.10" +rustls-webpki = "0.103.16" schnorrkel = "0.11.4" sha2 = { version = "0.10.8", default-features = false } sha3 = "0.10.8" subtle = "2" +zeroize = "1.8" blake2 = "0.10.6" tokio-rustls = { version = "0.26.2", features = ["ring"] } x25519-dalek = { version = "2.0.1", features = ["static_secrets"] } @@ -294,6 +303,8 @@ humantime = "2.2.0" parcelona = "0.4.3" pin-project = "1.1.10" regex = "1.11.1" +winnow = "1.0.3" +bigdecimal = "0.4.11" rinja = "0.3.5" shared_child = "1.0.1" strip-ansi-escapes = "0.2.1" @@ -306,7 +317,6 @@ smallvec = "1.14.0" cmd_lib = "1.9.5" yaml-rust2 = "0.10.4" -luks2 = "0.5.0" scopeguard = "1.2.0" tar = "0.4" proxy-protocol = "0.5.0" diff --git a/dstack/build/shared/pin-packages.sh b/dstack/build/shared/pin-packages.sh index dbc036ad04..840c7b1af8 100755 --- a/dstack/build/shared/pin-packages.sh +++ b/dstack/build/shared/pin-packages.sh @@ -15,7 +15,7 @@ set -e PKG_LIST=$1 -SNAPSHOT_DATE=${SNAPSHOT_DATE:-20260317T000000Z} +SNAPSHOT_DATE=${SNAPSHOT_DATE:-20261021T000000Z} if [ -z "$PKG_LIST" ]; then echo "Usage: $0 " >&2 diff --git a/dstack/cc-eventlog/src/runtime_events.rs b/dstack/cc-eventlog/src/runtime_events.rs index 404d6450e8..f09ae7b9d6 100644 --- a/dstack/cc-eventlog/src/runtime_events.rs +++ b/dstack/cc-eventlog/src/runtime_events.rs @@ -2,7 +2,7 @@ // // SPDX-License-Identifier: Apache-2.0 -use anyhow::{Context, Result}; +use anyhow::{bail, Context, Result}; use dstack_types::EventLogVersion; use fs_err as fs; use or_panic::ResultOrPanic; @@ -140,6 +140,20 @@ impl RuntimeEvent { } } + /// Reject an event whose digest preimage does not determine its fields. + /// + /// The V1 preimage `event_type_le || ":" || name || ":" || payload` splits + /// back into a single `(name, payload)` pair only if the name has no ':'. + pub fn validate(&self) -> Result<()> { + if self.version.is_v1() && self.event.contains(':') { + bail!( + "V1 runtime event name {:?} must not contain ':'", + self.event + ); + } + Ok(()) + } + /// The event type used when extending RTMR. Always `DSTACK_RUNTIME_EVENT_TYPE`. /// Version is distinguished via `EventLogVersion`, not the event type. pub fn cc_event_type(&self) -> u32 { @@ -225,6 +239,22 @@ mod tests { ); } + #[test] + fn v1_name_with_colon_is_rejected() { + let v1 = |name: &str, payload: &[u8]| { + RuntimeEvent::new(name.to_string(), payload.to_vec(), EventLogVersion::V1) + }; + let forged = v1("app-id:x", b"y"); + assert_eq!( + forged.digest::(), + v1("app-id", b"x:y").digest::() + ); + assert!(forged.validate().is_err()); + assert!(v1("app-id", b"x:y").validate().is_ok()); + let v2 = RuntimeEvent::new("a:b".to_string(), vec![], EventLogVersion::V2); + assert!(v2.validate().is_ok()); + } + #[test] fn v1_event_type() { let event = RuntimeEvent::new("test".to_string(), vec![], EventLogVersion::V1); diff --git a/dstack/cert-client/Cargo.toml b/dstack/cert-client/Cargo.toml index 092824e28f..558389531b 100644 --- a/dstack/cert-client/Cargo.toml +++ b/dstack/cert-client/Cargo.toml @@ -20,10 +20,13 @@ tdx-attest.workspace = true dstack-guest-agent-rpc.workspace = true http-client = { workspace = true, features = ["prpc"] } tokio.workspace = true +x509-parser = { workspace = true, features = ["verify"] } [dev-dependencies] +prpc.workspace = true +ra-rpc = { workspace = true, features = ["rocket", "client"] } +mock-attestation = { path = "../crates/mock-attestation" } hex.workspace = true rocket.workspace = true tempfile.workspace = true -x509-parser.workspace = true tokio = { workspace = true, features = ["macros", "rt", "rt-multi-thread", "sync"] } diff --git a/dstack/cert-client/src/lib.rs b/dstack/cert-client/src/lib.rs index da48efa05f..d41a5e76ab 100644 --- a/dstack/cert-client/src/lib.rs +++ b/dstack/cert-client/src/lib.rs @@ -2,15 +2,15 @@ // // SPDX-License-Identifier: Apache-2.0 -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use anyhow::{bail, Context, Result}; -use dstack_kms_rpc::{kms_client::KmsClient, SignCertRequest}; -use dstack_types::{AppKeys, KeyProvider}; -use ra_rpc::client::{CertInfo, RaClient, RaClientConfig}; +use dstack_kms_rpc::{kms_client::KmsClient, AppKeyResponse, GetAppKeyRequest, SignCertRequest}; +use dstack_types::{AppKeys, KeyProvider, SysConfig}; +use ra_rpc::client::{CertInfo, PinnedIssuer, RaClient, RaClientConfig}; use ra_tls::{ attestation::{AppInfo, AttestationVerifier, VersionedAttestation}, - cert::{generate_ra_cert, CaCert, CertSigningRequestV2}, + cert::{generate_self_signed_ra_cert, CaCert, CertPair, CertSigningRequestV2}, }; pub enum CertRequestClient { @@ -20,6 +20,7 @@ pub enum CertRequestClient { Kms { client: KmsClient, vm_config: String, + launch_ticket: String, }, } @@ -49,6 +50,100 @@ pub fn validate_kms_rpc_cert(cert: Option) -> Result<()> { Ok(()) } +/// Fetch keys directly over the attested connection, without a metadata/CA preflight. +/// A supplied CA always pins the connection, independently of the epoch selector. +/// Callers retain the startup KMS CA for the CVM lifetime, including later key +/// requests. Without a supplied CA, bind the response CA to this connection and +/// establish its identity through the provider pin or launch-measurement policy. +/// A supplied CA, else a non-empty `key_provider_id`, pins the TLS handshake so +/// the request is never sent to a server without a `kms:rpc` certificate. +pub async fn request_app_keys( + url: String, + request: GetAppKeyRequest, + client_cert: CertPair, + attestation_verifier: Arc, + trusted_ca: Option, + key_provider_id: &[u8], +) -> Result { + let pinned_issuer = match trusted_ca.as_deref() { + Some(ca) => Some(kms_rpc_pin(ca_pubkey(ca)?)), + None if !key_provider_id.is_empty() => Some(kms_rpc_pin(key_provider_id.to_vec())), + None => None, + }; + let server_cert = Arc::new(Mutex::new(None)); + let captured = server_cert.clone(); + let client = RaClientConfig::builder() + .remote_uri(url) + .tls_client_cert(client_cert.cert_pem) + .tls_client_key(client_cert.key_pem) + .tls_skip_ca_verification(trusted_ca.is_none()) + .maybe_tls_pinned_issuer(pinned_issuer) + .tls_built_in_root_certs(false) + .maybe_tls_ca_cert(trusted_ca.clone()) + .attestation_verifier(attestation_verifier) + .cert_validator(Box::new(move |info| { + let info = info.context("missing KMS server certificate")?; + if info.attestation.is_none() { + bail!("KMS server certificate has no verified attestation"); + } + let cert_der = info.cert_der.clone(); + validate_kms_rpc_cert(Some(info))?; + *captured + .lock() + .map_err(|_| anyhow::anyhow!("KMS certificate lock poisoned"))? = Some(cert_der); + Ok(()) + })) + .build() + .into_client()?; + let requested_root_epoch = request.root_epoch; + let requested_app_epoch = request.app_epoch; + let response = KmsClient::new(client).get_app_key(request).await?; + if requested_root_epoch.is_some_and(|epoch| epoch != response.root_epoch) { + bail!("KMS returned a different root epoch than requested"); + } + if requested_app_epoch.is_some_and(|epoch| epoch != response.app_epoch) { + bail!("KMS returned a different app epoch than requested"); + } + let cert = server_cert + .lock() + .map_err(|_| anyhow::anyhow!("KMS certificate lock poisoned"))?; + validate_kms_root( + cert.as_deref().context("missing KMS server certificate")?, + trusted_ca.as_deref().unwrap_or(&response.ca_cert), + )?; + Ok(response) +} + +fn validate_kms_root(server_cert: &[u8], root_ca: &str) -> Result<()> { + let (_, pem) = + x509_parser::pem::parse_x509_pem(root_ca.as_bytes()).context("invalid KMS root CA")?; + let root = pem.parse_x509().context("invalid KMS root CA")?; + let (_, leaf) = + x509_parser::parse_x509_certificate(server_cert).context("invalid KMS RPC certificate")?; + if !root.is_ca() || !root.validity().is_valid() || !leaf.validity().is_valid() { + bail!("invalid or expired KMS certificate"); + } + if leaf.issuer() != root.subject() { + bail!("KMS RPC certificate issuer does not match the root CA"); + } + leaf.verify_signature(Some(root.public_key())) + .context("KMS root CA did not sign the attested RPC certificate") +} + +fn kms_rpc_pin(pubkey: Vec) -> PinnedIssuer { + PinnedIssuer { + pubkey, + usage: KMS_RPC_CERT_USAGE.into(), + } +} + +fn ca_pubkey(ca: &str) -> Result> { + let (_, pem) = + x509_parser::pem::parse_x509_pem(ca.as_bytes()).context("invalid KMS root CA")?; + let root = pem.parse_x509().context("invalid KMS root CA")?; + Ok(root.public_key().raw.to_vec()) +} + fn kms_client( url: String, ca_cert: String, @@ -56,11 +151,13 @@ fn kms_client( client_key_pem: String, attestation_verifier: Arc, ) -> Result> { + let pinned_issuer = kms_rpc_pin(ca_pubkey(&ca_cert)?); let ra_client = RaClientConfig::builder() .remote_uri(url) .tls_client_cert(client_cert_pem) .tls_client_key(client_key_pem) .tls_ca_cert(ca_cert) + .tls_pinned_issuer(pinned_issuer) .tls_built_in_root_certs(false) .attestation_verifier(attestation_verifier) // Root pin plus `kms:rpc` already identify the KMS; re-verifying its @@ -87,13 +184,18 @@ impl CertRequestClient { .context("Failed to sign certificate")?; Ok(vec![cert.pem(), ca.pem_cert.clone()]) } - CertRequestClient::Kms { client, vm_config } => { + CertRequestClient::Kms { + client, + vm_config, + launch_ticket, + } => { let response = client .sign_cert(SignCertRequest { api_version: 2, csr: csr.to_vec(), signature: signature.to_vec(), vm_config: vm_config.clone(), + launch_ticket: launch_ticket.clone(), }) .await?; Ok(response.certificate_chain) @@ -101,6 +203,38 @@ impl CertRequestClient { } } + /// Fetch app keys from the startup KMS, using its current epochs for omitted selectors. + pub async fn get_app_key( + &self, + root_epoch: Option, + app_epoch: Option, + ) -> Result { + let CertRequestClient::Kms { + client, + vm_config, + launch_ticket, + } = self + else { + bail!("only KMS-provided keys have older root epochs"); + }; + let response = client + .get_app_key(GetAppKeyRequest { + api_version: 1, + vm_config: vm_config.clone(), + root_epoch, + app_epoch, + launch_ticket: launch_ticket.clone(), + }) + .await?; + if root_epoch.is_some_and(|epoch| epoch != response.root_epoch) { + bail!("KMS returned a different root epoch than requested"); + } + if app_epoch.is_some_and(|epoch| epoch != response.app_epoch) { + bail!("KMS returned a different app epoch than requested"); + } + Ok(response) + } + pub async fn get_root_ca(&self) -> Result { match self { CertRequestClient::Local { ca } => Ok(ca.pem_cert.clone()), @@ -111,24 +245,23 @@ impl CertRequestClient { pub async fn create( keys: &AppKeys, attestation_verifier: Arc, - vm_config: String, + sys_config: &SysConfig, ) -> Result { match &keys.key_provider { KeyProvider::None { key } | KeyProvider::Local { key, .. } + | KeyProvider::SevSnp { key } + | KeyProvider::TdxSeal { key } | KeyProvider::Tpm { key, .. } => { let ca = CaCert::new(keys.ca_cert.clone(), key.clone()) .context("Failed to create CA")?; Ok(CertRequestClient::Local { ca: Box::new(ca) }) } - KeyProvider::Kms { - url, - tmp_ca_key, - tmp_ca_cert, - .. - } => { - let client_cert = generate_ra_cert(tmp_ca_cert.clone(), tmp_ca_key.clone()) - .context("Failed to generate RA cert")?; + KeyProvider::Kms { url, .. } => { + // Self-issued: the KMS authenticates the quote inside this certificate, + // not whoever signed it. + let client_cert = + generate_self_signed_ra_cert(None).context("Failed to generate RA cert")?; let client = kms_client( url.clone(), keys.ca_cert.clone(), @@ -136,7 +269,11 @@ impl CertRequestClient { client_cert.key_pem, attestation_verifier, )?; - Ok(CertRequestClient::Kms { client, vm_config }) + Ok(CertRequestClient::Kms { + client, + vm_config: sys_config.vm_config.clone(), + launch_ticket: sys_config.launch_ticket.clone().unwrap_or_default(), + }) } } } @@ -377,6 +514,362 @@ mod tests { ) } + #[test] + fn generated_epoch_selectors_preserve_omission_and_explicit_zero() { + use prpc::Message; + + let default = GetAppKeyRequest::default(); + assert_eq!((default.root_epoch, default.app_epoch), (None, None)); + for json in ["{}", r#"{"api_version":1,"vm_config":""}"#] { + let request: GetAppKeyRequest = serde_json::from_str(json).unwrap(); + assert_eq!((request.root_epoch, request.app_epoch), (None, None)); + } + for root_epoch in [None, Some(0), Some(7)] { + for app_epoch in [None, Some(0), Some(9)] { + let request = GetAppKeyRequest { + root_epoch, + app_epoch, + ..Default::default() + }; + let json = serde_json::to_vec(&request).unwrap(); + let from_json: GetAppKeyRequest = serde_json::from_slice(&json).unwrap(); + let from_proto = + GetAppKeyRequest::decode(request.encode_to_vec().as_slice()).unwrap(); + for decoded in [from_json, from_proto] { + assert_eq!( + (decoded.root_epoch, decoded.app_epoch), + (root_epoch, app_epoch) + ); + } + } + } + let explicit: GetAppKeyRequest = + serde_json::from_str(r#"{"root_epoch":0,"app_epoch":0}"#).unwrap(); + assert_eq!( + (explicit.root_epoch, explicit.app_epoch), + (Some(0), Some(0)) + ); + } + + #[rocket::post("/GetAppKey", data = "")] + fn direct_app_keys( + request: String, + _cert: rocket::mtls::Certificate<'_>, + state: &rocket::State<(Arc>, Arc>>)>, + ) -> rocket::response::content::RawJson { + state + .1 + .lock() + .unwrap() + .push(serde_json::from_str(&request).unwrap()); + rocket::response::content::RawJson(state.0.lock().unwrap().clone()) + } + + #[tokio::test(flavor = "multi_thread")] + async fn direct_key_fetch_verifies_the_response_connection_without_preflight() { + use ra_tls::attestation::{ + AttestationVerifierConfig, DstackNitroQuote, QuoteContentType, RootCaPaths, + }; + use rocket::tls::Resolver as _; + let dir = tempfile::tempdir().unwrap(); + let attester = mock_attestation::nsm::NsmGenerator::new().unwrap(); + let attestation_root = dir.path().join("attestation-root.pem"); + std::fs::write(&attestation_root, attester.root_ca_pem()).unwrap(); + let verifier = Arc::new( + AttestationVerifier::load(&AttestationVerifierConfig { + insecure_allow_external_trust_anchors: true, + root_ca: RootCaPaths { + aws_nitro_enclave: Some(attestation_root), + ..Default::default() + }, + ..Default::default() + }) + .unwrap(), + ); + let root = kms_root(); + let rpc_key = p256_key(); + let report_data = QuoteContentType::RaTlsCert.to_report_data(&rpc_key.public_key_der()); + let pcrs = [0, 1, 2, 4] + .into_iter() + .map(|i| (i, vec![i as u8; 48])) + .collect(); + let evidence = attester.attest_with_pcrs(&report_data, pcrs).unwrap(); + let attestation = Attestation { + quote: AttestationQuote::DstackNitroEnclave(DstackNitroQuote { + nsm_quote: evidence, + }), + runtime_events: Vec::new(), + report_data, + config: String::new(), + report: (), + } + .into_versioned(); + let rpc_cert = root + .sign( + CertRequest::builder() + .subject("localhost") + .alt_names(&["127.0.0.1".into()]) + .key(&rpc_key) + .special_usage("kms:rpc") + .usage_server_auth(true) + .attestation(&attestation) + .build(), + ) + .unwrap(); + let cert_path = dir.path().join("rpc.crt"); + let key_path = dir.path().join("rpc.key"); + std::fs::write(&cert_path, rpc_cert.pem()).unwrap(); + std::fs::write(&key_path, rpc_key.serialize_pem()).unwrap(); + let response = AppKeyResponse { + ca_cert: root.pem_cert.clone(), + root_epoch: 1, + ..Default::default() + }; + let figment = rocket::Config::figment() + .merge(("port", 0)) + .merge(("address", "127.0.0.1")) + .merge(("log_level", "off")) + .merge(("shutdown.ctrlc", false)) + .merge(("tls.certs", cert_path)) + .merge(("tls.key", key_path)); + let (tx, rx) = tokio::sync::oneshot::channel(); + let tx = Mutex::new(Some(tx)); + let response_body = Arc::new(Mutex::new(serde_json::to_string(&response).unwrap())); + let requests = Arc::new(Mutex::new(Vec::::new())); + let server = rocket::custom(figment) + .attach(ra_rpc::ratls_client_verifier::RaTlsClientAuth::fairing()) + .manage((response_body.clone(), requests.clone())) + .mount("/", rocket::routes![direct_app_keys]) + .attach(rocket::fairing::AdHoc::on_liftoff("port", move |rocket| { + if let Some(tx) = tx.lock().unwrap().take() { + let _ = tx.send(rocket.endpoints().find_map(|e| e.port()).unwrap()); + } + Box::pin(async {}) + })) + .ignite() + .await + .unwrap(); + let shutdown = server.shutdown(); + let task = tokio::spawn(server.launch()); + let url = format!("https://127.0.0.1:{}", rx.await.unwrap()); + let client_cert = || { + let key = p256_key(); + let report_data = QuoteContentType::RaTlsCert.to_report_data(&key.public_key_der()); + let pcrs = [0, 1, 2, 4] + .into_iter() + .map(|i| (i, vec![i as u8; 48])) + .collect(); + let evidence = attester.attest_with_pcrs(&report_data, pcrs).unwrap(); + let attestation = Attestation { + quote: AttestationQuote::DstackNitroEnclave(DstackNitroQuote { + nsm_quote: evidence, + }), + runtime_events: Vec::new(), + report_data, + config: String::new(), + report: (), + } + .into_versioned(); + let cert = CertRequest::builder() + .subject("guest") + .key(&key) + .attestation(&attestation) + .usage_client_auth(true) + .build() + .self_signed() + .unwrap(); + CertPair { + cert_pem: cert.pem(), + key_pem: key.serialize_pem(), + } + }; + let request = || GetAppKeyRequest { + api_version: 1, + ..Default::default() + }; + let result = request_app_keys( + url.clone(), + request(), + client_cert(), + verifier.clone(), + None, + &[], + ) + .await + .unwrap(); + assert_eq!(result.ca_cert, response.ca_cert); + assert_eq!(result.root_epoch, 1); + let received = requests.lock().unwrap().last().unwrap().clone(); + assert_eq!((received.root_epoch, received.app_epoch), (None, None)); + + // A provider pin is enforced in TLS, before the RPC handler runs. + for (pin, ok) in [ + (root.key.public_key_der(), true), + (kms_root().key.public_key_der(), false), + ] { + let before = requests.lock().unwrap().len(); + let result = request_app_keys( + url.clone(), + request(), + client_cert(), + verifier.clone(), + None, + &pin, + ) + .await; + assert_eq!(result.is_ok(), ok); + assert_eq!(requests.lock().unwrap().len(), before + ok as usize); + } + + let other_ca = kms_root().pem_cert; + for requested_root_epoch in [None, Some(0), Some(1)] { + let request = || GetAppKeyRequest { + api_version: 1, + root_epoch: requested_root_epoch, + ..Default::default() + }; + let selected = AppKeyResponse { + root_epoch: requested_root_epoch.unwrap_or(1), + ..response.clone() + }; + *response_body.lock().unwrap() = serde_json::to_string(&selected).unwrap(); + // Omission and explicit epoch selectors have the same trust semantics. + assert!(request_app_keys( + url.clone(), + request(), + client_cert(), + verifier.clone(), + None, + &[], + ) + .await + .is_ok()); + // An unrelated pin must fail in TLS, before the RPC handler runs. + assert!(request_app_keys( + url.clone(), + request(), + client_cert(), + verifier.clone(), + Some(other_ca.clone()), + &[], + ) + .await + .is_err()); + + let different_epoch_ca = AppKeyResponse { + ca_cert: other_ca.clone(), + ..selected + }; + *response_body.lock().unwrap() = serde_json::to_string(&different_epoch_ca).unwrap(); + // A key response cannot replace the startup CA pin, even for default requests. + let result = request_app_keys( + url.clone(), + request(), + client_cert(), + verifier.clone(), + Some(root.pem_cert.clone()), + &[], + ) + .await + .unwrap(); + assert_eq!(result.ca_cert, other_ca); + // First-contact validation still requires the response CA to sign the RPC cert. + assert!(request_app_keys( + url.clone(), + request(), + client_cert(), + verifier.clone(), + None, + &[], + ) + .await + .is_err()); + } + assert_eq!(requests.lock().unwrap().len(), 11); + + let cert = client_cert(); + let client = CertRequestClient::Kms { + client: kms_client( + url.clone(), + root.pem_cert.clone(), + cert.cert_pem, + cert.key_pem, + verifier.clone(), + ) + .unwrap(), + vm_config: "selector-test".into(), + launch_ticket: String::new(), + }; + for root_epoch in [None, Some(0), Some(1)] { + for app_epoch in [None, Some(0), Some(2)] { + let selected = AppKeyResponse { + root_epoch: root_epoch.unwrap_or(3), + app_epoch: app_epoch.unwrap_or(4), + ..response.clone() + }; + *response_body.lock().unwrap() = serde_json::to_string(&selected).unwrap(); + let result = client.get_app_key(root_epoch, app_epoch).await.unwrap(); + assert_eq!( + (result.root_epoch, result.app_epoch), + (selected.root_epoch, selected.app_epoch) + ); + let received = requests.lock().unwrap().last().unwrap().clone(); + assert_eq!( + (received.root_epoch, received.app_epoch), + (root_epoch, app_epoch) + ); + assert_eq!(received.api_version, 1); + assert_eq!(received.vm_config, "selector-test"); + + for (wrong_root, wrong_app, message) in [ + (selected.root_epoch + 1, selected.app_epoch, "root epoch"), + (selected.root_epoch, selected.app_epoch + 1, "app epoch"), + ] { + let mismatched = AppKeyResponse { + root_epoch: wrong_root, + app_epoch: wrong_app, + ..selected.clone() + }; + *response_body.lock().unwrap() = serde_json::to_string(&mismatched).unwrap(); + let result = client.get_app_key(root_epoch, app_epoch).await; + if (message == "root epoch" && root_epoch.is_some()) + || (message == "app epoch" && app_epoch.is_some()) + { + assert!(result.unwrap_err().to_string().contains(message)); + } else { + assert!(result.is_ok()); + } + } + } + } + *response_body.lock().unwrap() = serde_json::to_string(&response).unwrap(); + let production = Arc::new(AttestationVerifier::new_prod(None).unwrap()); + assert!( + request_app_keys(url, request(), client_cert(), production, None, &[]) + .await + .is_err() + ); + shutdown.notify(); + task.await.unwrap().unwrap(); + assert_eq!(requests.lock().unwrap().len(), 39); + } + + #[test] + fn the_returned_root_must_sign_the_actual_rpc_certificate() { + let root = kms_root(); + let (leaf, _) = kms_rpc_cert(&root, "kms.example"); + let (_, leaf) = x509_parser::pem::parse_x509_pem(leaf.as_bytes()).unwrap(); + validate_kms_root(&leaf.contents, &root.pem_cert).unwrap(); + let unrelated = kms_root(); + assert!(validate_kms_root(&leaf.contents, &unrelated.pem_cert).is_err()); + assert!(validate_kms_root(&leaf.contents, "not a certificate").is_err()); + assert!(validate_kms_root(b"not a certificate", &root.pem_cert).is_err()); + + let (app_leaf, _) = app_cert(&root, &[0xa1; 20], "kms.example"); + let (_, app_leaf) = x509_parser::pem::parse_x509_pem(app_leaf.as_bytes()).unwrap(); + assert!(validate_kms_root(&app_leaf.contents, &root.pem_cert).is_err()); + } + #[rocket::post("/GetMeta")] fn get_meta() -> &'static str { r#"{"ca_cert":"served ca cert"}"# @@ -442,7 +935,7 @@ mod tests { .await .expect_err("an app's certificate must not authenticate the KMS"); assert!( - format!("{err:#}").contains("invalid server cert usage: app:custom"), + format!("{err:#}").contains("server certificate does not match the pinned issuer"), "unexpected error: {err:#}" ); } diff --git a/dstack/crates/api-auth/Cargo.toml b/dstack/crates/api-auth/Cargo.toml index c3df2919d0..47967d4f94 100644 --- a/dstack/crates/api-auth/Cargo.toml +++ b/dstack/crates/api-auth/Cargo.toml @@ -13,6 +13,9 @@ license.workspace = true anyhow.workspace = true base64.workspace = true bcrypt.workspace = true +ed25519-dalek.workspace = true rocket.workspace = true +serde.workspace = true +serde_json = { workspace = true, features = ["std"] } sha2.workspace = true subtle.workspace = true diff --git a/dstack/crates/api-auth/src/jwt.rs b/dstack/crates/api-auth/src/jwt.rs new file mode 100644 index 0000000000..b80cdcdede --- /dev/null +++ b/dstack/crates/api-auth/src/jwt.rs @@ -0,0 +1,426 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// +// SPDX-License-Identifier: Apache-2.0 + +//! Ed25519 JWT tokens for the guest agent's external API. +//! +//! Deliberately a small subset: one algorithm, a fixed claim set, and no +//! key-discovery header. Everything a general-purpose JWT library would let a +//! caller negotiate is something an attacker would like to negotiate too -- +//! `none`, an HMAC verified with a public key as the secret, or a `jku`/`x5u`/ +//! `jwk` header naming a key the verifier never configured. Here those are not +//! rejected by policy but impossible to express. + +use std::collections::BTreeSet; + +use anyhow::{bail, Context, Result}; +use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; +use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; +use serde::{Deserialize, Serialize}; + +/// Tolerance for clock skew in either direction. +pub const CLOCK_LEEWAY_SECS: u64 = 30; + +/// The base64url header every token carries. +/// +/// A constant, not a serialized struct: a header this module writes is a +/// header it can also verify exactly. +const HEADER: &str = "eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9"; + +/// The scope names the guest agent understands. +/// +/// A vocabulary rather than free-form strings, so a typo in `anonymous_scopes` +/// is a startup error instead of a permission that silently never matches. +pub mod scope { + /// `Worker.Version` on either pRPC surface. + pub const VERSION: &str = "guest:version"; + /// `Worker.Health` on the v1 surface. + pub const HEALTH: &str = "guest:health"; + /// `Worker.Info` on either pRPC surface. + pub const INFO: &str = "guest:info"; + /// `Worker.GetAttestationForAppKey` on the frozen surface. + pub const ATTEST_APP_KEY: &str = "guest:attest-app-key"; + /// The HTML dashboard itself. + pub const DASHBOARD: &str = "guest:dashboard"; + /// The container table on the dashboard. + pub const CONTAINERS: &str = "guest:containers"; + /// `/logs/`. + pub const LOGS: &str = "guest:logs"; + /// `/metrics`, and the sysinfo block on the dashboard. + pub const METRICS: &str = "guest:metrics"; + + /// Every name above, in the order a dashboard shows them. + pub const ALL: &[&str] = &[ + VERSION, + HEALTH, + INFO, + ATTEST_APP_KEY, + DASHBOARD, + CONTAINERS, + LOGS, + METRICS, + ]; + + pub fn is_known(name: &str) -> bool { + ALL.contains(&name) + } +} + +/// A set of granted scopes. +/// +/// Space-separated on the wire, because that is what RFC 8693 and every +/// OAuth-adjacent tool produces, and a collection here because the only +/// operation is membership. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ScopeSet(BTreeSet); + +impl ScopeSet { + /// Parse the space-separated `scope` claim. + pub fn parse(scope: &str) -> Self { + Self(scope.split_whitespace().map(str::to_owned).collect()) + } + + pub fn from_names(names: impl IntoIterator>) -> Self { + Self(names.into_iter().map(Into::into).collect()) + } + + pub fn contains(&self, scope: &str) -> bool { + self.0.contains(scope) + } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// Everything in both sets. Used to add the anonymous baseline to a + /// caller's own grants. + pub fn union(&self, other: &Self) -> Self { + Self(self.0.union(&other.0).cloned().collect()) + } +} + +/// The claims this module issues and accepts. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Claims { + /// Who minted the token. + pub iss: String, + /// Which application the token is for, hex-encoded. + pub aud: String, + pub iat: u64, + pub exp: u64, + /// Space-separated [`scope`] names. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub scope: String, +} + +impl Claims { + pub fn scopes(&self) -> ScopeSet { + ScopeSet::parse(&self.scope) + } +} + +/// The domain the internal issuer key is derived under. +/// +/// Part of the wire contract between the agent (which derives the public half +/// to verify with) and the application (which derives the private half to +/// sign with). Changing it invalidates every token in flight, and a host and +/// guest on either side of the change would stop trusting each other, so it +/// never changes. +pub const INTERNAL_ISSUER_DOMAIN: &str = "dstack:guest-api:issuer:v1"; + +/// The `iss` an internally minted token carries. +/// +/// Bound to the app id so a token minted for one application cannot be +/// replayed against another: `aud` alone would already stop that, but naming +/// the application in the issuer too keeps the two checks independent. +pub fn internal_issuer(app_id_hex: &str) -> String { + format!("dstack:guest-api:{app_id_hex}") +} + +/// A token whose shape and claims have been read, with the signature still +/// unchecked. +/// +/// Split out from verification so a caller can refuse a malformed token before +/// it does anything expensive. The guest agent needs exactly that: checking a +/// token it was handed must not cost a boot attestation. +#[derive(Clone, Debug)] +pub struct Decoded { + signing_input: String, + signature: Vec, + pub claims: Claims, +} + +/// Read a token's header and claims without verifying it. +/// +/// Everything here is cheap and local. The result says nothing about whether +/// the token was signed by anyone; [`Verifier::verify_decoded`] answers that. +pub fn decode(token: &str) -> Result { + let mut parts = token.split('.'); + let (Some(header), Some(encoded_payload), Some(encoded_signature), None) = + (parts.next(), parts.next(), parts.next(), parts.next()) + else { + bail!("token is not a JWT"); + }; + if header != HEADER { + // Covers `alg: none`, HMAC, and any header carrying key material. + bail!("unsupported JWT header"); + } + let payload = URL_SAFE_NO_PAD + .decode(encoded_payload) + .context("payload is not base64url")?; + let claims = serde_json::from_slice(&payload).context("malformed claims")?; + let signature = URL_SAFE_NO_PAD + .decode(encoded_signature) + .context("signature is not base64url")?; + Ok(Decoded { + signing_input: format!("{header}.{encoded_payload}"), + signature, + claims, + }) +} + +/// Mint a token. `signing_key` is the raw 32-byte Ed25519 seed. +pub fn sign(signing_key: &[u8; 32], claims: &Claims) -> Result { + let payload = serde_json::to_vec(claims).context("failed to serialize claims")?; + let signing_input = format!("{HEADER}.{}", URL_SAFE_NO_PAD.encode(payload)); + let signature = SigningKey::from_bytes(signing_key).sign(signing_input.as_bytes()); + Ok(format!( + "{signing_input}.{}", + URL_SAFE_NO_PAD.encode(signature.to_bytes()) + )) +} + +/// The public keys one issuer may sign with. +/// +/// A list so a key can be rotated without a flag day: publish the new key +/// alongside the old, wait out the tokens signed by the old one, drop it. +#[derive(Clone, Debug)] +pub struct IssuerKeys { + /// The exact `iss` this issuer's tokens must carry. + pub name: String, + pub keys: Vec, +} + +/// Verifies tokens and reports what they grant. +#[derive(Clone)] +pub struct Verifier { + internal: VerifyingKey, + external: Vec, +} + +impl Verifier { + pub fn new(internal: VerifyingKey, external: Vec) -> Self { + Self { internal, external } + } + + /// Verify `token` for the application whose id is `app_id_hex`. + /// + /// `now` is seconds since the UNIX epoch, passed in rather than read here + /// so the expiry rules can be tested. + pub fn verify(&self, token: &str, app_id_hex: &str, now: u64) -> Result { + self.verify_decoded(&decode(token)?, app_id_hex, now) + } + + /// Check the signature and claims of a token [`decode`] already read. + /// + /// Separate from [`Verifier::verify`] so a caller can pay for [`decode`] + /// alone -- it needs no key material and no app id -- and refuse the token + /// before doing anything that costs. + /// + /// The signature is checked before the claims: a claim error from an + /// unsigned token is a guess about a caller's intent, not a fact. + pub fn verify_decoded(&self, token: &Decoded, app_id_hex: &str, now: u64) -> Result { + let Decoded { + signing_input, + signature, + claims, + } = token; + let signature = + Signature::from_slice(signature).context("signature has the wrong length")?; + + let keys = self.keys_for(&claims.iss, app_id_hex); + if keys.is_empty() { + bail!("unknown token issuer"); + } + if !keys.iter().any(|key| { + key.verify_strict(signing_input.as_bytes(), &signature) + .is_ok() + }) { + bail!("token signature does not verify"); + } + + if claims.aud != app_id_hex { + bail!("token was issued for a different application"); + } + if claims.exp < now.saturating_sub(CLOCK_LEEWAY_SECS) { + bail!("token has expired"); + } + if claims.iat > now + CLOCK_LEEWAY_SECS { + bail!("token was issued in the future"); + } + Ok(claims.scopes()) + } + + fn keys_for(&self, iss: &str, app_id_hex: &str) -> Vec<&VerifyingKey> { + if iss == internal_issuer(app_id_hex) { + return vec![&self.internal]; + } + self.external + .iter() + .find(|issuer| issuer.name == iss) + .map(|issuer| issuer.keys.iter().collect()) + .unwrap_or_default() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const APP_ID: &str = "00112233445566778899aabbccddeeff00112233"; + + fn signing_key(seed: u8) -> [u8; 32] { + [seed; 32] + } + + fn mint(seed: u8, iss: &str, aud: &str, iat: u64, exp: u64, scope: &str) -> String { + sign( + &signing_key(seed), + &Claims { + iss: iss.to_owned(), + aud: aud.to_owned(), + iat, + exp, + scope: scope.to_owned(), + }, + ) + .unwrap() + } + + fn verifier(seed: u8) -> Verifier { + Verifier::new( + SigningKey::from_bytes(&signing_key(seed)).verifying_key(), + vec![], + ) + } + + #[test] + fn round_trips_scopes() { + let token = mint( + 1, + &internal_issuer(APP_ID), + APP_ID, + 1000, + 1300, + "guest:info guest:logs", + ); + let scopes = verifier(1).verify(&token, APP_ID, 1100).unwrap(); + assert!(scopes.contains(scope::INFO)); + assert!(scopes.contains(scope::LOGS)); + assert!(!scopes.contains(scope::METRICS)); + } + + #[test] + fn rejects_a_token_for_another_application() { + let token = mint( + 1, + &internal_issuer(APP_ID), + APP_ID, + 1000, + 1300, + "guest:info", + ); + let other = "ffeeddccbbaa99887766554433221100ffeeddcc"; + assert!(verifier(1).verify(&token, other, 1100).is_err()); + } + + #[test] + fn rejects_alg_none_and_foreign_signatures() { + for token in [ + "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJpc3MiOiJ4In0.".to_owned(), + mint( + 2, + &internal_issuer(APP_ID), + APP_ID, + 1000, + 1300, + "guest:info", + ), + ] { + assert!(verifier(1).verify(&token, APP_ID, 1100).is_err()); + } + } + + #[test] + fn rejects_expired_and_future_tokens() { + let expired = mint( + 1, + &internal_issuer(APP_ID), + APP_ID, + 1000, + 1100, + "guest:info", + ); + assert!(verifier(1).verify(&expired, APP_ID, 1200).is_err()); + + let future = mint( + 1, + &internal_issuer(APP_ID), + APP_ID, + 5000, + 5300, + "guest:info", + ); + assert!(verifier(1).verify(&future, APP_ID, 1000).is_err()); + } + + #[test] + fn decoding_refuses_a_shape_no_token_could_have() { + for token in [ + "not-a-token", + "a.b.c.d", + "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJpc3MiOiJ4In0.", + "eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.!!!.c2ln", + ] { + assert!(decode(token).is_err(), "{token}"); + } + // A well-formed token decodes without any key: that is what lets the + // caller refuse it before doing work. + let token = mint( + 1, + &internal_issuer(APP_ID), + APP_ID, + 1000, + 1300, + "guest:info", + ); + assert_eq!(decode(&token).unwrap().claims.aud, APP_ID); + } + + #[test] + fn accepts_an_external_issuer_by_name() { + let verifier = Verifier::new( + SigningKey::from_bytes(&signing_key(1)).verifying_key(), + vec![IssuerKeys { + name: "ops".into(), + keys: vec![SigningKey::from_bytes(&signing_key(9)).verifying_key()], + }], + ); + let token = mint(9, "ops", APP_ID, 1000, 1300, "guest:containers"); + assert!(verifier + .verify(&token, APP_ID, 1100) + .unwrap() + .contains(scope::CONTAINERS)); + + // The same key under the internal issuer name is not an internal token. + let impostor = mint( + 9, + &internal_issuer(APP_ID), + APP_ID, + 1000, + 1300, + "guest:info", + ); + assert!(verifier.verify(&impostor, APP_ID, 1100).is_err()); + } +} diff --git a/dstack/crates/api-auth/src/lib.rs b/dstack/crates/api-auth/src/lib.rs index c52f7bcb39..f53deab2b7 100644 --- a/dstack/crates/api-auth/src/lib.rs +++ b/dstack/crates/api-auth/src/lib.rs @@ -5,8 +5,10 @@ //! Shared HTTP API authentication for dstack services. //! //! Supports bearer/shared-secret tokens, HTTP Basic credentials backed by an -//! Apache htpasswd file, and an optional GET-only query token for compatibility -//! with browser dashboard links. +//! Apache htpasswd file, an optional GET-only query token for compatibility +//! with browser dashboard links, and Ed25519 JWT scope grants (see [`jwt`]). + +pub mod jwt; use std::{collections::HashMap, path::Path, sync::Arc}; @@ -21,7 +23,9 @@ use rocket::{ use sha2::{Digest, Sha256}; use subtle::{Choice, ConstantTimeEq}; -const UNAUTH_URI: &str = "/__dstack_api_auth_unauthorized"; +/// Where a denied request is rewritten to, so every refusal is answered by one +/// responder regardless of which route it was headed for. +pub const UNAUTHORIZED_PATH: &str = "/__dstack_api_auth_unauthorized"; #[derive(Debug)] struct Htpasswd { @@ -252,11 +256,11 @@ impl Fairing for HttpAuthFairing { async fn on_request(&self, req: &mut Request<'_>, _: &mut Data<'_>) { req.local_cache(|| RequestRealm(self.config.realm.clone())); - if req.uri().path() == UNAUTH_URI { + if req.uri().path() == UNAUTHORIZED_PATH { return; } if !self.authorized(req) { - if let Ok(uri) = Origin::parse_owned(UNAUTH_URI.to_owned()) { + if let Ok(uri) = Origin::parse_owned(UNAUTHORIZED_PATH.to_owned()) { req.set_uri(uri); } } else if self.config.allow_get_query_token { @@ -267,17 +271,32 @@ impl Fairing for HttpAuthFairing { } } -struct Unauthorized; +/// What a 401 asks the caller for. +/// +/// A Basic challenge tells a bearer-token client to do something it cannot do, +/// so a fairing denying on a token denies with `Bearer` instead. +#[derive(Clone, Copy, Default, PartialEq, Eq)] +pub enum Challenge { + #[default] + Basic, + Bearer, +} + +/// The responder every denied request lands on. +pub struct Unauthorized; impl<'r> Responder<'r, 'static> for Unauthorized { fn respond_to(self, req: &'r Request<'_>) -> rocket::response::Result<'static> { - let realm = &req.local_cache(|| RequestRealm("dstack API".into())).0; + let value = match req.local_cache(Challenge::default) { + Challenge::Basic => { + let realm = &req.local_cache(|| RequestRealm("dstack API".into())).0; + format!("Basic realm=\"{realm}\"") + } + Challenge::Bearer => "Bearer".to_owned(), + }; Response::build() .status(Status::Unauthorized) - .header(Header::new( - "WWW-Authenticate", - format!("Basic realm=\"{realm}\""), - )) + .header(Header::new("WWW-Authenticate", value)) .ok() } } diff --git a/dstack/crates/dstack-auth/Cargo.toml b/dstack/crates/dstack-auth/Cargo.toml index d9fb1879b6..518c712c2b 100644 --- a/dstack/crates/dstack-auth/Cargo.toml +++ b/dstack/crates/dstack-auth/Cargo.toml @@ -14,7 +14,12 @@ path = "src/main.rs" [dependencies] anyhow.workspace = true +dstack-types.workspace = true +hex.workspace = true clap.workspace = true rocket = { workspace = true, features = ["json"] } serde.workspace = true serde_json.workspace = true + +[dev-dependencies] +tempfile.workspace = true diff --git a/dstack/crates/dstack-auth/src/main.rs b/dstack/crates/dstack-auth/src/main.rs index 2a752e4b04..ab54b7694d 100644 --- a/dstack/crates/dstack-auth/src/main.rs +++ b/dstack/crates/dstack-auth/src/main.rs @@ -2,26 +2,35 @@ // // SPDX-License-Identifier: Apache-2.0 -//! `dstack-auth` — the single-operator KMS auth webhook (Rust reimplementation -//! of `auth-simple`). +//! `dstack-auth` — the file-based KMS auth webhook. +//! +//! Intended for development, testing and evaluation only; not for production. //! //! Runs on the host as `dstack-auth.service`; the KMS-in-CVM reaches it at //! `http://10.0.2.2:` under user-mode networking and POSTs `BootInfo` to -//! `/bootAuth/app` (compose-hash allowlist) and `/bootAuth/kms` (mrAggregated -//! allowlist). The allowlist JSON is re-read on every request, so `dstack run` -//! can add an app without a restart. Fails closed: a missing/invalid allowlist -//! denies everything. +//! `/authorizeApp` (compose-hash allowlist) and `/authorizeKms` (mrAggregated +//! allowlist). Legacy `/bootAuth/*` routes remain available for bootstrap. The +//! allowlist JSON is re-read on every request, so `dstack run` can add an app +//! without a restart. Fails closed: a missing/invalid allowlist denies +//! everything. +//! +//! The allowlist format is the one the removed `auth-simple` server used, so +//! its config files load unchanged. One default differs: the TCB status and +//! advisory IDs are checked only when the allowlist sets `allowedTcbStatuses` +//! / `allowedAdvisoryIds` (auth-simple defaulted to `["UpToDate"]` and `[]`). +//! Real TDX hosts routinely report a non-`UpToDate` TCB (microcode / TDX +//! module behind), and in the single-node model the operator already controls +//! and trusts their own host, so a hard TCB gate would be friction without a +//! corresponding trust gain there. Deployments that serve other parties should +//! set both fields. //! -//! Deliberate single-node deviation from `auth-simple`: it does NOT enforce -//! `tcbStatus == UpToDate`. Real TDX hosts routinely report a non-`UpToDate` -//! TCB (microcode / TDX-module behind), and in the single-node model the -//! operator already controls and trusts their own host, so a hard TCB gate -//! would be friction without a corresponding trust gain here. Re-add the check -//! (capture `tcbStatus`, deny unless `UpToDate`) if this grows into a -//! multi-tenant / hosted deployment. - -use anyhow::Result; +//! KMS boots are not checked against `osImages`: `kms.mrAggregated` already +//! pins the OS image measurements. + +use anyhow::{bail, Context, Result}; use clap::Parser; +use dstack_types::authorization::AuthorizationOperation as Operation; +use rocket::http::Status; use rocket::serde::json::Json; use rocket::{get, post, routes, State}; use serde::{Deserialize, Serialize}; @@ -33,7 +42,7 @@ use std::path::PathBuf; #[command( name = "dstack-auth", version, - about = "single-operator KMS auth webhook" + about = "single-operator KMS auth webhook (development, testing and evaluation only)" )] struct Cli { /// path to the allowlist JSON (re-read on every request). @@ -58,6 +67,19 @@ struct BootInfo { app_id: String, compose_hash: String, device_id: String, + /// verifier-derived TCB status, e.g. `UpToDate`; checked only when the + /// allowlist sets `allowedTcbStatuses`. + tcb_status: String, + /// security advisories reported for the platform; checked only when the + /// allowlist sets `allowedAdvisoryIds`. + advisory_ids: Vec, + /// the root epoch the asking KMS serves and its chain hash; absent from a + /// KMS that predates root epochs, and from KMS checks made while onboarding. + root_epoch: Option, + root_epoch_hash: Option, + /// hash of the launch ticket the attested subject presented; empty when it + /// presented none, and from the legacy routes. + launch_ticket_hash: String, } #[derive(Serialize)] @@ -68,13 +90,117 @@ struct BootResponse { reason: String, } +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct AuthorizationRequest { + operation: Operation, + #[serde(flatten)] + boot_info: BootInfo, + requested_root_epoch: Option, + requested_app_epoch: Option, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct AuthorizationResult { + authorized: bool, + rejection_reason: String, + gateway_app_id: String, + current_root_epoch: usize, + current_root_epoch_hash: String, + current_app_epoch: u32, + latest_root_epoch: usize, + latest_root_epoch_hash: String, +} + +/// a KMS root epoch and its chain hash, which commits to the root public keys +/// of epochs 0..=number. +struct EpochInfo { + number: usize, + hash: String, +} + #[derive(Deserialize, Default)] #[serde(rename_all = "camelCase", default)] struct Allowlist { os_images: Vec, + /// when set, deny unless the reported `tcbStatus` is listed; an empty list + /// denies everything. Absent: the TCB status is not checked. + allowed_tcb_statuses: Option>, + /// when set, deny any reported advisory ID that is not listed; an empty + /// list denies any advisory. Absent: advisories are not checked. + allowed_advisory_ids: Option>, + /// the minimum TCB of each CPU the KMS judges an SEV-SNP TCB against; for + /// a CPU without one it falls back to its own list. + sev_snp_tcb_requirements: Vec, + kms_contract_addr: String, gateway_app_id: String, + /// informational, reported by `GET /`. + chain_id: u64, + /// informational, reported by `GET /`. + app_implementation: String, kms: KmsRules, apps: HashMap, + /// root public keys of each KMS root epoch, indexed by epoch; append only. + root_epochs: Vec, + /// the root epoch KMS instances serve; raise it once every node holds it. + current_root_epoch: usize, +} + +#[derive(Deserialize, Default, Clone)] +#[serde(rename_all = "camelCase", default)] +struct RootEpoch { + ca_pubkey: String, + k256_pubkey: String, +} + +impl Allowlist { + fn app(&self, app_id: &str) -> Option<&AppRules> { + let app_id = norm(app_id); + self.apps + .iter() + .find(|(id, _)| norm(id) == app_id) + .map(|(_, app)| app) + } + + /// `None` only when no epoch is configured; invalid configuration is an error. + fn current_root_epoch(&self) -> Result> { + Ok(self.root_epoch_info()?.map(|(current, _)| current)) + } + + /// the current and the latest configured root epochs; configured epochs + /// beyond the current one are pending activation. + fn root_epoch_info(&self) -> Result> { + if self.root_epochs.is_empty() && self.current_root_epoch == 0 { + return Ok(None); + } + u32::try_from(self.root_epochs.len()).context("root epoch exceeds uint32")?; + if self.current_root_epoch >= self.root_epochs.len() { + bail!("currentRootEpoch is not a configured root epoch"); + } + let keys = self + .root_epochs + .iter() + .map(|e| { + Ok(( + hex::decode(norm(&e.ca_pubkey)).context("invalid root epoch CA public key")?, + hex::decode(norm(&e.k256_pubkey)) + .context("invalid root epoch k256 public key")?, + )) + }) + .collect::>>()?; + let hashes = dstack_types::root_epoch::chain_hashes( + keys.iter().map(|(ca, k256)| (&ca[..], &k256[..])), + ); + let info = |number: usize| EpochInfo { + number, + hash: format!("0x{}", hex::encode(hashes[number])), + }; + Ok(Some(( + info(self.current_root_epoch), + info(self.root_epochs.len() - 1), + ))) + } } #[derive(Deserialize, Default)] @@ -83,14 +209,22 @@ struct KmsRules { mr_aggregated: Vec, devices: Vec, allow_any_device: bool, + /// when set, a KMS importing the root keys must present one of these + /// launch ticket hashes; an empty list denies every import. Absent: the + /// import needs no ticket. + launch_tickets: Option>, } #[derive(Deserialize, Default)] #[serde(rename_all = "camelCase", default)] struct AppRules { + current_app_epoch: u32, compose_hashes: Vec, devices: Vec, allow_any_device: bool, + /// when set, the app must present one of these launch ticket hashes; an + /// empty list denies everything. Absent: no ticket is needed. + launch_tickets: Option>, } /// normalize a hex string for comparison: trim, drop a `0x`/`0X` prefix, @@ -111,10 +245,16 @@ fn contains(list: &[String], value: &str) -> bool { list.iter().any(|x| norm(x) == v) } -/// matches auth-simple: an empty `devices` list means "any device" even when -/// `allowAnyDevice` is false (it only enforces a non-empty list). +/// No allowlist admits any ticket; an empty one admits none. +fn launch_ticket_ok(tickets: &Option>, ticket_hash: &str) -> bool { + tickets + .as_ref() + .is_none_or(|tickets| !ticket_hash.is_empty() && contains(tickets, ticket_hash)) +} + +/// An empty `devices` list allows no device; any device needs `allowAnyDevice`. fn device_ok(allow_any: bool, devices: &[String], device_id: &str) -> bool { - allow_any || devices.is_empty() || contains(devices, device_id) + allow_any || contains(devices, device_id) } fn deny(al: &Allowlist, reason: &str) -> BootResponse { @@ -125,25 +265,74 @@ fn deny(al: &Allowlist, reason: &str) -> BootResponse { } } -fn allow(al: &Allowlist) -> BootResponse { - BootResponse { - is_allowed: true, - gateway_app_id: al.gateway_app_id.clone(), - reason: "ok".to_string(), +/// allow, provided the asking KMS serves the current root epoch with the +/// registered keys up to it. A KMS that predates root epochs reports none and +/// holds only epoch 0, so it is served only until another epoch is activated. +fn allow(info: &BootInfo, al: &Allowlist) -> BootResponse { + let current = match al.current_root_epoch() { + Ok(current) => current, + Err(error) => return deny(al, &format!("invalid root epoch configuration: {error}")), + }; + let current_epoch = current.as_ref().map_or(0, |c| c.number); + let denial = match (info.root_epoch, ¤t) { + (None, _) if current_epoch == 0 => None, + (None, _) => Some(format!( + "root epoch {current_epoch} is current, but the KMS reports none" + )), + (Some(0), None) => None, + (Some(epoch), None) => Some(format!("root epoch {epoch} is not registered")), + (Some(epoch), Some(_)) if epoch != current_epoch => Some(format!( + "the KMS serves root epoch {epoch}, but {current_epoch} is current" + )), + (Some(_), Some(c)) if info.root_epoch_hash.as_deref().map(norm) != Some(norm(&c.hash)) => { + Some(format!( + "the KMS root keys up to epoch {current_epoch} are not the registered ones" + )) + } + _ => None, + }; + match denial { + Some(reason) => deny(al, &reason), + None => BootResponse { + is_allowed: true, + gateway_app_id: al.gateway_app_id.clone(), + reason: "ok".to_string(), + }, } } -fn check_app(info: &BootInfo, al: &Allowlist) -> BootResponse { - if !al.os_images.is_empty() && !contains(&al.os_images, &info.os_image_hash) { +/// the opt-in platform checks shared by app and KMS policy. +fn tcb_denial(info: &BootInfo, al: &Allowlist) -> Option<&'static str> { + if let Some(allowed) = &al.allowed_tcb_statuses { + if !allowed.contains(&info.tcb_status) { + return Some("tcb status not allowed"); + } + } + if let Some(allowed) = &al.allowed_advisory_ids { + if info.advisory_ids.iter().any(|id| !allowed.contains(id)) { + return Some("advisory id not allowed"); + } + } + None +} + +fn app_policy(info: &BootInfo, al: &Allowlist) -> BootResponse { + if al + .app(&info.app_id) + .is_some_and(|app| !launch_ticket_ok(&app.launch_tickets, &info.launch_ticket_hash)) + { + return deny(al, "invalid launch ticket"); + } + if let Some(reason) = tcb_denial(info, al) { + return deny(al, reason); + } + if al.os_images.is_empty() { + return deny(al, "os image allowlist is empty"); + } + if !contains(&al.os_images, &info.os_image_hash) { return deny(al, "os image not allowed"); } - let app_id = norm(&info.app_id); - let Some(app) = al - .apps - .iter() - .find(|(k, _)| norm(k) == app_id) - .map(|(_, v)| v) - else { + let Some(app) = al.app(&info.app_id) else { return deny(al, "app not registered"); }; if !contains(&app.compose_hashes, &info.compose_hash) { @@ -152,17 +341,197 @@ fn check_app(info: &BootInfo, al: &Allowlist) -> BootResponse { if !device_ok(app.allow_any_device, &app.devices, &info.device_id) { return deny(al, "device not allowed"); } - allow(al) + BootResponse { + is_allowed: true, + gateway_app_id: al.gateway_app_id.clone(), + reason: String::new(), + } } -fn check_kms(info: &BootInfo, al: &Allowlist) -> BootResponse { +fn kms_policy(info: &BootInfo, al: &Allowlist) -> BootResponse { + if let Some(reason) = tcb_denial(info, al) { + return deny(al, reason); + } if !contains(&al.kms.mr_aggregated, &info.mr_aggregated) { return deny(al, "kms mrAggregated not allowed"); } if !device_ok(al.kms.allow_any_device, &al.kms.devices, &info.device_id) { return deny(al, "device not allowed"); } - allow(al) + BootResponse { + is_allowed: true, + gateway_app_id: al.gateway_app_id.clone(), + reason: String::new(), + } +} + +fn check_app(info: &BootInfo, al: &Allowlist) -> BootResponse { + if al + .app(&info.app_id) + .is_some_and(|app| app.current_app_epoch != 0) + { + return deny(al, "app epoch requires epoch-aware authorization"); + } + let result = app_policy(info, al); + if result.is_allowed { + allow(info, al) + } else { + result + } +} + +fn check_kms(info: &BootInfo, al: &Allowlist) -> BootResponse { + // legacy callers present no ticket and cannot say which operation they authorize + if al.kms.launch_tickets.is_some() { + return deny(al, "invalid launch ticket"); + } + let result = kms_policy(info, al); + if result.is_allowed { + allow(info, al) + } else { + result + } +} + +fn authorize( + request: &AuthorizationRequest, + is_kms: bool, + al: &Allowlist, +) -> Result { + let epochs = al.root_epoch_info()?; + let current = epochs.as_ref().map(|(current, _)| current); + let latest = epochs.as_ref().map(|(_, latest)| latest); + let zero_hash = || format!("0x{}", "00".repeat(32)); + let mut result = AuthorizationResult { + authorized: false, + rejection_reason: String::new(), + gateway_app_id: al.gateway_app_id.clone(), + current_root_epoch: current.map_or(0, |epoch| epoch.number), + current_root_epoch_hash: current.map_or_else(zero_hash, |epoch| epoch.hash.clone()), + latest_root_epoch: latest.map_or(0, |epoch| epoch.number), + latest_root_epoch_hash: latest.map_or_else(zero_hash, |epoch| epoch.hash.clone()), + current_app_epoch: if is_kms { + 0 + } else { + al.app(&request.boot_info.app_id) + .map_or(0, |app| app.current_app_epoch) + }, + }; + let info = &request.boot_info; + // key handover may carry a registered but not yet active epoch, so the + // keyring can be distributed before activation; key-issuing operations + // stay on active epochs. + let handover = matches!( + request.operation, + Operation::KmsExportKeys | Operation::KmsImportKeys + ); + result.rejection_reason = if request.operation.is_kms() != is_kms { + "invalid authorization operation".into() + } else if request.operation == Operation::KmsImportKeys + && !launch_ticket_ok(&al.kms.launch_tickets, &info.launch_ticket_hash) + { + // only the import hands a joining KMS the root keys + "invalid launch ticket".into() + } else if current.is_none() && request.operation != Operation::KmsBootstrap { + "root epoch not registered".into() + } else if request + .requested_root_epoch + .is_some_and(|epoch| epoch as usize > result.latest_root_epoch) + { + "requested root epoch is not registered".into() + } else if !handover + && request + .requested_root_epoch + .is_some_and(|epoch| epoch as usize > result.current_root_epoch) + { + "requested root epoch is not active".into() + } else if request + .requested_app_epoch + .is_some_and(|epoch| epoch > result.current_app_epoch) + { + "requested app epoch is not active".into() + } else if request.operation != Operation::KmsBootstrap && norm(&al.kms_contract_addr).is_empty() + { + "kmsContractAddr is not configured".into() + } else if request.operation != Operation::KmsBootstrap + && (norm(&info.app_id) == norm(&al.kms_contract_addr)) != is_kms + { + "caller does not match authorization scope".into() + } else { + let policy = if is_kms { + kms_policy(info, al) + } else { + app_policy(info, al) + }; + result.authorized = policy.is_allowed; + policy.reason + }; + Ok(result) +} + +fn unavailable(error: anyhow::Error) -> Status { + rocket::warn!("invalid authorization configuration: {error}"); + Status::ServiceUnavailable +} + +/// authorize and log the decision with the identities an operator needs to +/// extend the allowlist (device ID, measurements, TCB status). +fn authorize_logged( + request: &AuthorizationRequest, + is_kms: bool, + config: &PathBuf, +) -> Result, Status> { + let result = authorize(request, is_kms, &load(config)).map_err(unavailable)?; + let info = &request.boot_info; + rocket::info!( + "authorize {:?} app={} compose={} mr={} os={} device={} tcb={} advisories={:?} -> authorized={} ({})", + request.operation, + norm(&info.app_id), + norm(&info.compose_hash), + norm(&info.mr_aggregated), + norm(&info.os_image_hash), + norm(&info.device_id), + info.tcb_status, + info.advisory_ids, + result.authorized, + result.rejection_reason + ); + Ok(Json(result)) +} + +#[post("/authorizeApp", data = "")] +fn authorize_app( + request: Json, + cli: &State, +) -> Result, Status> { + authorize_logged(&request, false, &cli.config) +} + +#[post("/authorizeKms", data = "")] +fn authorize_kms( + request: Json, + cli: &State, +) -> Result, Status> { + authorize_logged(&request, true, &cli.config) +} + +#[get("/app/")] +fn app_epoch(app_id: &str, cli: &State) -> Result, Status> { + let id = norm(app_id); + if hex::decode(&id).map_or(true, |bytes| bytes.len() != 20) { + return Err(Status::BadRequest); + } + // An unknown app is not epoch zero: its epoch cannot be vouched for. + let app = load(&cli.config); + let app = app.app(&id).ok_or(Status::NotFound)?; + Ok(Json(json!({ "currentAppEpoch": app.current_app_epoch }))) +} + +/// the KMS parses the list itself, as it does one read from `DstackKms`. +#[get("/sevSnpTcbRequirements")] +fn sev_snp_tcb_requirements(cli: &State) -> Json { + let requirements = json!(load(&cli.config).sev_snp_tcb_requirements).to_string(); + Json(json!({ "requirements": requirements })) } /// load the allowlist, failing closed (deny-all) if it's missing or invalid. @@ -181,11 +550,16 @@ fn load(path: &PathBuf) -> Allowlist { #[post("/bootAuth/app", data = "")] fn boot_app(info: Json, cli: &State) -> Json { + let mut info = info.into_inner(); + info.launch_ticket_hash.clear(); let r = check_app(&info, &load(&cli.config)); rocket::info!( - "bootAuth/app app={} compose={} -> allowed={} ({})", + "bootAuth/app app={} compose={} os={} device={} tcb={} -> allowed={} ({})", norm(&info.app_id), norm(&info.compose_hash), + norm(&info.os_image_hash), + norm(&info.device_id), + info.tcb_status, r.is_allowed, r.reason ); @@ -196,36 +570,68 @@ fn boot_app(info: Json, cli: &State) -> Json { fn boot_kms(info: Json, cli: &State) -> Json { let r = check_kms(&info, &load(&cli.config)); rocket::info!( - "bootAuth/kms mr={} -> allowed={} ({})", + "bootAuth/kms mr={} device={} tcb={} -> allowed={} ({})", norm(&info.mr_aggregated), + norm(&info.device_id), + info.tcb_status, r.is_allowed, r.reason ); Json(r) } -/// info endpoint the KMS GETs to populate its metadata. Single-node: no chain. +/// info endpoint the KMS GETs to populate its metadata. #[get("/")] -fn info() -> Json { - Json(json!({ +fn info(cli: &State) -> Result, Status> { + info_json(&load(&cli.config)).map(Json).map_err(|error| { + rocket::warn!("invalid root epoch configuration: {error}"); + Status::ServiceUnavailable + }) +} + +fn info_json(al: &Allowlist) -> Result { + let mut info = json!({ "status": "ok", - "kmsContractAddr": "", + "kmsContractAddr": al.kms_contract_addr, "ethRpcUrl": "", - "gatewayAppId": "", - "chainId": 0, - "appImplementation": "" - })) + "gatewayAppId": al.gateway_app_id, + "chainId": al.chain_id, + // `appAuthImplementation` is the older name of `appImplementation`. + "appAuthImplementation": al.app_implementation, + "appImplementation": al.app_implementation, + }); + if let Some(epoch) = al.current_root_epoch()? { + // the root CA key of the current epoch signs every serving KMS's RPC + // certificate + info["rootCaPubkey"] = + format!("0x{}", norm(&al.root_epochs[epoch.number].ca_pubkey)).into(); + info["rootEpoch"] = epoch.number.into(); + info["rootEpochHash"] = epoch.hash.into(); + } + Ok(info) } -#[rocket::main] -async fn main() -> Result<()> { - let cli = Cli::parse(); +fn server(cli: Cli) -> rocket::Rocket { let figment = rocket::Config::figment() .merge(("address", cli.address.clone())) .merge(("port", cli.port)); - rocket::custom(figment) - .manage(cli) - .mount("/", routes![info, boot_app, boot_kms]) + rocket::custom(figment).manage(cli).mount( + "/", + routes![ + info, + boot_app, + boot_kms, + authorize_app, + authorize_kms, + app_epoch, + sev_snp_tcb_requirements + ], + ) +} + +#[rocket::main] +async fn main() -> Result<()> { + server(Cli::parse()) .launch() .await .map_err(|e| anyhow::anyhow!("auth webhook failed: {e}"))?; @@ -236,6 +642,447 @@ async fn main() -> Result<()> { mod tests { use super::*; + #[rocket::async_test] + async fn authorization_routes_use_registered_roots_and_separate_caller_scopes() { + use rocket::{http::ContentType, local::asynchronous::Client}; + + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("allowlist.json"); + let mut policy = json!({ + "kmsContractAddr": "0x1111111111111111111111111111111111111111", + "rootEpochs": [{"caPubkey": "aa", "k256Pubkey": "bb"}], + "osImages": ["aa"], + "kms": {"mrAggregated": ["bb"], "allowAnyDevice": true}, + "apps": {"0x2222222222222222222222222222222222222222": {"composeHashes": ["cc"], "allowAnyDevice": true}} + }); + std::fs::write(&path, policy.to_string()).unwrap(); + let client = Client::tracked(server(Cli { + config: path.clone(), + address: "127.0.0.1".into(), + port: 0, + })) + .await + .unwrap(); + let kms = json!({"operation": "kms_serve", "appId": "11".repeat(20), "mrAggregated": "bb"}); + let app = json!({"operation": "app_get_key", "appId": "22".repeat(20), "composeHash": "cc", "osImageHash": "aa"}); + let with_operation = |body: &serde_json::Value, operation: &str| { + let mut body = body.clone(); + body["operation"] = operation.into(); + body + }; + for (route, body, allowed) in [ + ("/authorizeKms", kms.clone(), true), + ("/authorizeApp", app.clone(), true), + ("/authorizeKms", app.clone(), false), + ("/authorizeApp", kms.clone(), false), + // The caller matches the route, but the operation belongs to the other scope. + ("/authorizeKms", with_operation(&kms, "app_get_key"), false), + ("/authorizeApp", with_operation(&app, "kms_serve"), false), + ] { + let response = client + .post(route) + .header(ContentType::JSON) + .body(body.to_string()) + .dispatch() + .await; + assert_eq!(response.status(), Status::Ok); + let response: serde_json::Value = response.into_json().await.unwrap(); + assert_eq!(response["authorized"], allowed); + assert_eq!(response["currentRootEpoch"], 0); + assert_eq!(response["currentAppEpoch"], 0); + assert_eq!(response["latestRootEpoch"], 0); + assert_eq!( + response["latestRootEpochHash"], + response["currentRootEpochHash"] + ); + assert_ne!( + response["currentRootEpochHash"], + format!("0x{}", "00".repeat(32)) + ); + } + for operation in [serde_json::Value::Null, json!("unknown")] { + let mut body = app.clone(); + body["operation"] = operation; + let response = client + .post("/authorizeApp") + .header(ContentType::JSON) + .body(body.to_string()) + .dispatch() + .await; + assert!(matches!( + response.status(), + Status::BadRequest | Status::UnprocessableEntity + )); + } + for field in ["requestedRootEpoch", "requestedAppEpoch"] { + let mut body = app.clone(); + body[field] = 1.into(); + let response: serde_json::Value = client + .post("/authorizeApp") + .header(ContentType::JSON) + .body(body.to_string()) + .dispatch() + .await + .into_json() + .await + .unwrap(); + assert_eq!(response["authorized"], false); + } + policy["rootEpochs"] = json!([]); + std::fs::write(&path, policy.to_string()).unwrap(); + let response: serde_json::Value = client + .post("/authorizeKms") + .header(ContentType::JSON) + .body(kms.to_string()) + .dispatch() + .await + .into_json() + .await + .unwrap(); + assert_eq!(response["authorized"], false); + assert_eq!( + response["currentRootEpochHash"], + format!("0x{}", "00".repeat(32)) + ); + assert_eq!(response["latestRootEpoch"], 0); + assert_eq!( + response["latestRootEpochHash"], + format!("0x{}", "00".repeat(32)) + ); + policy["currentRootEpoch"] = 1.into(); + std::fs::write(&path, policy.to_string()).unwrap(); + assert_eq!( + client + .post("/authorizeApp") + .header(ContentType::JSON) + .body(app.to_string()) + .dispatch() + .await + .status(), + Status::ServiceUnavailable + ); + } + + #[rocket::async_test] + async fn app_epochs_share_normalized_policy_and_reject_legacy_boot() { + use rocket::{http::ContentType, local::asynchronous::Client}; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("allowlist.json"); + let client = Client::tracked(server(Cli { + config: path.clone(), + address: "127.0.0.1".into(), + port: 0, + })) + .await + .unwrap(); + let id = "ab".repeat(20); + for configured_id in [ + id.clone(), + format!("0X{}", id.to_uppercase()), + format!("0x{id}"), + ] { + let policy = json!({ + "kmsContractAddr": "11".repeat(20), + "rootEpochs": [{"caPubkey": "aa", "k256Pubkey": "bb"}, {"caPubkey": "cc", "k256Pubkey": "dd"}], + "currentRootEpoch": 1, + "osImages": ["aa"], + "apps": {configured_id: {"currentAppEpoch": 2, "composeHashes": ["ee"], "allowAnyDevice": true}} + }); + std::fs::write(&path, policy.to_string()).unwrap(); + let response: serde_json::Value = client + .get(format!("/app/0x{id}")) + .dispatch() + .await + .into_json() + .await + .unwrap(); + assert_eq!(response["currentAppEpoch"], 2); + for selectors in [ + json!({}), + json!({"requestedRootEpoch": 0, "requestedAppEpoch": 0}), + json!({"requestedRootEpoch": 1, "requestedAppEpoch": 2}), + json!({"requestedAppEpoch": 3}), + json!({"requestedRootEpoch": 2}), + ] { + let allowed = + selectors["requestedAppEpoch"] != 3 && selectors["requestedRootEpoch"] != 2; + let mut request = selectors; + request["operation"] = "app_get_key".into(); + request["appId"] = id.clone().into(); + request["composeHash"] = "ee".into(); + request["osImageHash"] = "aa".into(); + let response: serde_json::Value = client + .post("/authorizeApp") + .header(ContentType::JSON) + .body(request.to_string()) + .dispatch() + .await + .into_json() + .await + .unwrap(); + assert_eq!(response["authorized"], allowed); + assert_eq!(response["currentAppEpoch"], 2); + assert_eq!(response["currentRootEpoch"], 1); + } + let body = json!({"appId": id, "composeHash": "ee"}); + let response: serde_json::Value = client + .post("/bootAuth/app") + .header(ContentType::JSON) + .body(body.to_string()) + .dispatch() + .await + .into_json() + .await + .unwrap(); + assert_eq!(response["isAllowed"], false); + } + assert_eq!( + client.get("/app/not-hex").dispatch().await.status(), + Status::BadRequest + ); + assert_eq!( + client + .get(format!("/app/0x{}", "cd".repeat(20))) + .dispatch() + .await + .status(), + Status::NotFound + ); + std::fs::remove_file(&path).unwrap(); + assert_eq!( + client.get(format!("/app/0x{id}")).dispatch().await.status(), + Status::NotFound + ); + } + + async fn post_json( + client: &rocket::local::asynchronous::Client, + route: &str, + body: &serde_json::Value, + ) -> serde_json::Value { + let response = client + .post(route.to_string()) + .header(rocket::http::ContentType::JSON) + .body(body.to_string()) + .dispatch() + .await; + assert_eq!(response.status(), Status::Ok, "{route}"); + response.into_json().await.unwrap() + } + + #[rocket::async_test] + async fn sev_snp_tcb_requirements_are_served_as_the_json_the_kms_parses() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("allowlist.json"); + let client = client_for(&path).await; + let entry = + json!({"cpuid": "00a00f11", "bootloader": 1, "tee": 0, "snp": 0, "microcode": 0}); + for (policy, served) in [ + (json!({"sevSnpTcbRequirements": [entry]}), json!([entry])), + (json!({}), json!([])), + ] { + std::fs::write(&path, policy.to_string()).unwrap(); + let response = client.get("/sevSnpTcbRequirements").dispatch().await; + let response: serde_json::Value = response.into_json().await.unwrap(); + let requirements = response["requirements"].as_str().unwrap(); + assert_eq!( + serde_json::from_str::(requirements).unwrap(), + served + ); + } + } + + async fn client_for(path: &std::path::Path) -> rocket::local::asynchronous::Client { + rocket::local::asynchronous::Client::tracked(server(Cli { + config: path.to_path_buf(), + address: "127.0.0.1".into(), + port: 0, + })) + .await + .unwrap() + } + + #[rocket::async_test] + async fn tcb_status_and_advisories_are_checked_only_when_configured() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("allowlist.json"); + let client = client_for(&path).await; + let base = json!({ + "kmsContractAddr": "11".repeat(20), + "rootEpochs": [{"caPubkey": "aa", "k256Pubkey": "bb"}], + "osImages": ["aa"], + "kms": {"mrAggregated": ["bb"], "allowAnyDevice": true}, + "apps": {"22".repeat(20): {"composeHashes": ["cc"], "allowAnyDevice": true}} + }); + let kms = json!({"operation": "kms_serve", "appId": "11".repeat(20), "mrAggregated": "bb", "osImageHash": "aa"}); + let app = json!({"operation": "app_get_key", "appId": "22".repeat(20), "composeHash": "cc", "osImageHash": "aa"}); + let legacy = json!({"appId": "22".repeat(20), "composeHash": "cc", "osImageHash": "aa"}); + let platform = + |tcb: &str, advisories: &[&str]| json!({"tcbStatus": tcb, "advisoryIds": advisories}); + let cases = [ + // Absent fields: neither the TCB status nor advisories are checked. + (json!({}), platform("OutOfDate", &["INTEL-SA-00001"]), true), + (json!({}), platform("", &[]), true), + ( + json!({"allowedTcbStatuses": ["UpToDate"]}), + platform("UpToDate", &[]), + true, + ), + ( + json!({"allowedTcbStatuses": ["UpToDate"]}), + platform("OutOfDate", &[]), + false, + ), + ( + json!({"allowedTcbStatuses": ["UpToDate"]}), + platform("", &[]), + false, + ), + ( + json!({"allowedTcbStatuses": ["UpToDate", "SWHardeningNeeded"]}), + platform("SWHardeningNeeded", &[]), + true, + ), + ( + json!({"allowedTcbStatuses": []}), + platform("UpToDate", &[]), + false, + ), + ( + json!({"allowedAdvisoryIds": []}), + platform("OutOfDate", &[]), + true, + ), + ( + json!({"allowedAdvisoryIds": []}), + platform("UpToDate", &["INTEL-SA-00001"]), + false, + ), + ( + json!({"allowedAdvisoryIds": ["INTEL-SA-00001"]}), + platform("UpToDate", &["INTEL-SA-00001"]), + true, + ), + ( + json!({"allowedAdvisoryIds": ["INTEL-SA-00001"]}), + platform("UpToDate", &["INTEL-SA-00001", "INTEL-SA-00002"]), + false, + ), + ]; + for (policy_fields, platform, allowed) in cases { + let mut policy = base.clone(); + policy + .as_object_mut() + .unwrap() + .extend(policy_fields.as_object().unwrap().clone()); + std::fs::write(&path, policy.to_string()).unwrap(); + let with_platform = |body: &serde_json::Value| { + let mut body = body.clone(); + body.as_object_mut() + .unwrap() + .extend(platform.as_object().unwrap().clone()); + body + }; + let context = format!("{policy_fields} {platform}"); + let response = post_json(&client, "/authorizeKms", &with_platform(&kms)).await; + assert_eq!(response["authorized"], allowed, "kms {context}"); + let response = post_json(&client, "/authorizeApp", &with_platform(&app)).await; + assert_eq!(response["authorized"], allowed, "app {context}"); + let response = post_json(&client, "/bootAuth/app", &with_platform(&legacy)).await; + assert_eq!(response["isAllowed"], allowed, "bootAuth/app {context}"); + if !allowed { + let reason = response["reason"].as_str().unwrap(); + assert!( + reason.starts_with("tcb status") || reason.starts_with("advisory"), + "{reason}" + ); + } + } + } + + /// A config written for the removed auth-simple server, with every field it + /// read, keeps loading and authorizing. + #[rocket::async_test] + async fn an_auth_simple_config_file_still_authorizes() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("auth-config.json"); + let app_id = "0x7a3b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5B"; + let gateway_id = "0x75537828f2ce51be7289709686A69CbFDbB714F1"; + let kms_id = "0x1111111111111111111111111111111111111111"; + let config = json!({ + "gatewayAppId": gateway_id, + "kmsContractAddr": kms_id, + "chainId": 2035, + "appImplementation": "0x3333333333333333333333333333333333333333", + "osImages": ["0x0B327BCD"], + "allowedTcbStatuses": ["UpToDate"], + "allowedAdvisoryIds": [], + "kms": {"mrAggregated": ["0xAbCd"], "devices": ["0xD1"], "allowAnyDevice": false}, + "apps": { + app_id: {"currentAppEpoch": 0, "composeHashes": ["0x700A"], "devices": ["0xD2"], "allowAnyDevice": false}, + gateway_id: {"composeHashes": ["0x0123"], "allowAnyDevice": true} + }, + "rootEpochs": [{"caPubkey": "0xaa", "k256Pubkey": "0xbb"}], + "currentRootEpoch": 0 + }); + std::fs::write(&path, config.to_string()).unwrap(); + let client = client_for(&path).await; + + let info: serde_json::Value = client.get("/").dispatch().await.into_json().await.unwrap(); + assert_eq!(info["gatewayAppId"], gateway_id); + assert_eq!(info["kmsContractAddr"], kms_id); + assert_eq!(info["chainId"], 2035); + assert_eq!( + info["appImplementation"], + "0x3333333333333333333333333333333333333333" + ); + assert_eq!(info["appAuthImplementation"], info["appImplementation"]); + assert_eq!(info["rootEpoch"], 0); + + // Hex values match regardless of `0x` prefix and case, as in auth-simple. + let app = json!({ + "operation": "app_get_key", "appId": app_id.to_lowercase(), "composeHash": "700a", + "osImageHash": "0b327bcd", "deviceId": "d2", "tcbStatus": "UpToDate", "advisoryIds": [] + }); + let response = post_json(&client, "/authorizeApp", &app).await; + assert_eq!(response["authorized"], true, "{response}"); + assert_eq!(response["gatewayAppId"], gateway_id); + let mut other_device = app.clone(); + other_device["deviceId"] = "d1".into(); + let response = post_json(&client, "/authorizeApp", &other_device).await; + assert_eq!(response["authorized"], false); + assert_eq!(response["rejectionReason"], "device not allowed"); + + let kms = json!({ + "operation": "kms_serve", "appId": kms_id, "mrAggregated": "abcd", + "deviceId": "0xD1", "tcbStatus": "UpToDate", "advisoryIds": [] + }); + let response = post_json(&client, "/authorizeKms", &kms).await; + assert_eq!(response["authorized"], true, "{response}"); + let mut legacy = kms.clone(); + legacy.as_object_mut().unwrap().remove("operation"); + legacy["rootEpoch"] = 0.into(); + legacy["rootEpochHash"] = response["currentRootEpochHash"].clone(); + let response = post_json(&client, "/bootAuth/kms", &legacy).await; + assert_eq!(response["isAllowed"], true, "{response}"); + legacy["tcbStatus"] = "OutOfDate".into(); + let response = post_json(&client, "/bootAuth/kms", &legacy).await; + assert_eq!(response["isAllowed"], false); + assert_eq!(response["reason"], "tcb status not allowed"); + + let epoch: serde_json::Value = client + .get(format!( + "/app/{}", + app_id.to_uppercase().replacen("0X", "0x", 1) + )) + .dispatch() + .await + .into_json() + .await + .unwrap(); + assert_eq!(epoch["currentAppEpoch"], 0); + } + fn allowlist() -> Allowlist { serde_json::from_str( r#"{ @@ -271,6 +1118,58 @@ mod tests { assert!(!check_app(&boot("0xApp1", "0xHASH", "0xnope"), &al).is_allowed); } + #[test] + fn empty_lists_allow_nothing() { + let device = |devices: &[&str], allow_any| -> Allowlist { + let devices: Vec<_> = devices.iter().map(|d| d.to_string()).collect(); + serde_json::from_value(json!({ + "osImages": ["0xIMG"], + "kms": {"mrAggregated": ["0xMR"], "devices": devices, "allowAnyDevice": allow_any}, + "apps": {"0xApp1": {"composeHashes": ["0xHASH"], "devices": devices, "allowAnyDevice": allow_any}} + })) + .unwrap() + }; + let mut app = boot("0xApp1", "0xHASH", "0xIMG"); + app.device_id = "0xDEV".into(); + let kms = BootInfo { + mr_aggregated: "0xMR".into(), + device_id: "0xDEV".into(), + ..Default::default() + }; + for al in [device(&[], false), device(&["0xOTHER"], false)] { + assert_eq!(check_app(&app, &al).reason, "device not allowed"); + assert_eq!(check_kms(&kms, &al).reason, "device not allowed"); + } + for al in [device(&["0xdev"], false), device(&[], true)] { + assert!(check_app(&app, &al).is_allowed); + assert!(check_kms(&kms, &al).is_allowed); + } + let mut al = allowlist(); + al.os_images.clear(); + assert_eq!(check_app(&app, &al).reason, "os image allowlist is empty"); + } + + /// The shape `dstack-cli-core` generates (`auth_allowlist_json` plus an app + /// entry added by `register_app_in_allowlist`) keeps working. + #[test] + fn the_generated_default_allowlist_still_allows() { + let al: Allowlist = serde_json::from_value(json!({ + "osImages": ["0xIMG"], + "kms": {"mrAggregated": ["0xMR"], "devices": [], "allowAnyDevice": true}, + "apps": {"app1": {"composeHashes": ["hash"], "devices": [], "allowAnyDevice": true}} + })) + .unwrap(); + let mut app = boot("0xAPP1", "0xHASH", "img"); + app.device_id = "0xANY".into(); + assert!(check_app(&app, &al).is_allowed); + let kms = BootInfo { + mr_aggregated: "0xmr".into(), + device_id: "0xANY".into(), + ..Default::default() + }; + assert!(check_kms(&kms, &al).is_allowed); + } + #[test] fn kms_allowlist_and_empty_default() { let al = allowlist(); @@ -283,6 +1182,234 @@ mod tests { assert!(!check_kms(&info, &Allowlist::default()).is_allowed); } + #[test] + fn authorization_reports_the_latest_configured_root_epoch() { + let al: Allowlist = serde_json::from_value(json!({ + "rootEpochs": [ + {"caPubkey": "aa", "k256Pubkey": "bb"}, + {"caPubkey": "cc", "k256Pubkey": "dd"}, + {"caPubkey": "ee", "k256Pubkey": "ff"} + ], + "currentRootEpoch": 1 + })) + .unwrap(); + let request: AuthorizationRequest = + serde_json::from_value(json!({"operation": "kms_serve", "appId": "11".repeat(20)})) + .unwrap(); + let result = authorize(&request, true, &al).unwrap(); + let hashes = dstack_types::root_epoch::chain_hashes([ + (&[0xaa][..], &[0xbb][..]), + (&[0xcc], &[0xdd]), + (&[0xee], &[0xff]), + ]); + assert_eq!(result.current_root_epoch, 1); + assert_eq!( + result.current_root_epoch_hash, + format!("0x{}", hex::encode(hashes[1])) + ); + assert_eq!(result.latest_root_epoch, 2); + assert_eq!( + result.latest_root_epoch_hash, + format!("0x{}", hex::encode(hashes[2])) + ); + } + + #[test] + fn a_pending_root_epoch_is_authorized_for_kms_key_handover() { + // epoch 1 is registered (latest) but not current: pending + let al: Allowlist = serde_json::from_value(json!({ + "kmsContractAddr": "0x1111111111111111111111111111111111111111", + "kms": {"mrAggregated": ["bb"], "allowAnyDevice": true}, + "rootEpochs": [ + {"caPubkey": "aa", "k256Pubkey": "bb"}, + {"caPubkey": "cc", "k256Pubkey": "dd"} + ], + "currentRootEpoch": 0 + })) + .unwrap(); + let ask = |operation: &str, requested: u32| { + let request: AuthorizationRequest = serde_json::from_value(json!({ + "operation": operation, + "appId": "11".repeat(20), + "mrAggregated": "bb", + "requestedRootEpoch": requested, + })) + .unwrap(); + authorize(&request, true, &al).unwrap() + }; + + let current = ask("kms_export_keys", 0); + assert!(current.authorized, "{}", current.rejection_reason); + assert_eq!(current.current_root_epoch, 0); + assert_eq!(current.latest_root_epoch, 1); + + for operation in ["kms_import_keys", "kms_export_keys"] { + let pending = ask(operation, 1); + assert!( + pending.authorized, + "{operation} at the pending epoch 1: {}", + pending.rejection_reason + ); + assert!(!ask(operation, 2).authorized); + } + + let serve = ask("kms_serve", 1); + assert!(!serve.authorized); + assert_eq!(serve.rejection_reason, "requested root epoch is not active"); + } + + #[test] + fn launch_tickets_are_required_only_when_configured() { + let mut al: Allowlist = serde_json::from_value(json!({ + "kmsContractAddr": "0x1111111111111111111111111111111111111111", + "rootEpochs": [{"caPubkey": "aa", "k256Pubkey": "bb"}, {"caPubkey": "cc", "k256Pubkey": "dd"}], + "osImages": ["aa"], + "kms": {"mrAggregated": ["bb"], "allowAnyDevice": true, "launchTickets": ["0xEE"]}, + "apps": {"0x2222222222222222222222222222222222222222": { + "composeHashes": ["cc"], "allowAnyDevice": true, "launchTickets": ["0xFF"] + }} + })) + .unwrap(); + let ask = |al: &Allowlist, is_kms: bool, operation: &str, ticket: Option<&str>| { + let mut request = if is_kms { + json!({"operation": operation, "appId": "11".repeat(20), "mrAggregated": "bb"}) + } else { + json!({"operation": operation, "appId": "22".repeat(20), "composeHash": "cc", "osImageHash": "aa"}) + }; + if let Some(ticket) = ticket { + request["launchTicketHash"] = ticket.into(); + } + let request: AuthorizationRequest = serde_json::from_value(request).unwrap(); + authorize(&request, is_kms, al).unwrap() + }; + for operation in ["app_get_key", "app_get_cert"] { + assert!(ask(&al, false, operation, Some("ff")).authorized); + assert_eq!( + ask(&al, false, operation, Some("ee")).rejection_reason, + "invalid launch ticket" + ); + assert!(!ask(&al, false, operation, None).authorized); + } + assert!(ask(&al, true, "kms_import_keys", Some("0xee")).authorized); + assert_eq!( + ask(&al, true, "kms_import_keys", None).rejection_reason, + "invalid launch ticket" + ); + // Only the import hands out the root keys. + assert!(ask(&al, true, "kms_serve", None).authorized); + // Legacy callers cannot present a ticket. + let legacy = boot("0x2222222222222222222222222222222222222222", "cc", "aa"); + assert!(!check_app(&legacy, &al).is_allowed); + assert!( + !check_kms( + &BootInfo { + mr_aggregated: "bb".into(), + ..Default::default() + }, + &al + ) + .is_allowed + ); + + // An empty allowlist admits no ticket; none configured admits any. + al.kms.launch_tickets = Some(vec![]); + assert!(!ask(&al, true, "kms_import_keys", Some("ee")).authorized); + al.kms.launch_tickets = None; + assert!(ask(&al, true, "kms_import_keys", None).authorized); + + assert_eq!(info_json(&al).unwrap()["rootCaPubkey"], "0xaa"); + al.current_root_epoch = 1; + assert_eq!(info_json(&al).unwrap()["rootCaPubkey"], "0xcc"); + assert!(info_json(&Allowlist::default()) + .unwrap() + .get("rootCaPubkey") + .is_none()); + } + + #[test] + fn allows_only_a_kms_serving_the_current_root_epoch() { + // Shared with the DstackKms contract tests. + let h0 = "0x10ab6b6c8e7601901b0f1767985bf40d35bf3129e0866fe12dcc7c8f04a298f2"; + let h1 = "0x50152a82023f2219a31723b476c13bc5f608ab4147946dabdec15d4f3d648ed4"; + let mut al: Allowlist = serde_json::from_str( + r#"{"kms":{"mrAggregated":["0xMR"],"allowAnyDevice":true}, + "rootEpochs":[{"caPubkey":"0x3059301306072a8648ce3d020106082a8648ce3d03010703420004a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0","k256Pubkey":"0x02b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0"}, + {"caPubkey":"0x3059301306072a8648ce3d020106082a8648ce3d03010703420004a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1","k256Pubkey":"0x02b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1"}]}"#, + ) + .unwrap(); + let info = |epoch: Option, hash: &str| BootInfo { + mr_aggregated: "0xMR".into(), + root_epoch: epoch, + root_epoch_hash: Some(hash.into()), + ..Default::default() + }; + assert_eq!(info_json(&al).unwrap()["rootEpochHash"], h0); + assert!(check_kms(&info(Some(0), h0), &al).is_allowed); + // A KMS predating root epochs is served only while epoch 0 is current. + assert!(check_kms(&info(None, ""), &al).is_allowed); + + al.current_root_epoch = 1; + assert_eq!(info_json(&al).unwrap()["rootEpoch"], 1); + assert_eq!(info_json(&al).unwrap()["rootEpochHash"], h1); + assert!(check_kms(&info(Some(1), &h1.to_uppercase()), &al).is_allowed); + assert!(!check_kms(&info(Some(0), h0), &al).is_allowed); + assert!(!check_kms(&info(Some(1), h0), &al).is_allowed); + assert!(!check_kms(&info(None, ""), &al).is_allowed); + + al.current_root_epoch = 2; + assert!(al.current_root_epoch().is_err()); + assert!(info_json(&al).is_err()); + assert!(!check_kms(&info(Some(1), h1), &al).is_allowed); + } + + #[test] + fn a_kms_predating_root_epochs_is_cut_off_once_one_is_current() { + let mut al = allowlist(); + let info = boot("0xapp1", "0xhash", "0ximg"); + assert!(check_app(&info, &al).is_allowed); + al.root_epochs = vec![ + RootEpoch { + ca_pubkey: "0xa0".into(), + k256_pubkey: "0xb0".into(), + }, + RootEpoch { + ca_pubkey: "0xa1".into(), + k256_pubkey: "0xb1".into(), + }, + ]; + assert!(check_app(&info, &al).is_allowed); + al.current_root_epoch = 1; + assert!(!check_app(&info, &al).is_allowed); + } + + #[test] + fn invalid_root_epochs_deny_legacy_and_epoch_aware_kms() { + let invalid_configs = [ + json!({"currentRootEpoch": 1}), + json!({"currentRootEpoch": 1, "rootEpochs": [{"caPubkey": "a0", "k256Pubkey": "b0"}]}), + json!({"rootEpochs": [{"caPubkey": "invalid", "k256Pubkey": "b0"}]}), + json!({"rootEpochs": [{"caPubkey": "a0", "k256Pubkey": "invalid"}]}), + ]; + for config in invalid_configs { + let epochs: Allowlist = serde_json::from_value(config).unwrap(); + let al = Allowlist { + root_epochs: epochs.root_epochs, + current_root_epoch: epochs.current_root_epoch, + ..allowlist() + }; + assert!(info_json(&al).is_err()); + for epoch in [None, Some(0), Some(1)] { + let info = BootInfo { + mr_aggregated: "0xMR".into(), + root_epoch: epoch, + ..boot("0xapp1", "0xhash", "0ximg") + }; + assert!(!check_app(&info, &al).is_allowed); + assert!(!check_kms(&info, &al).is_allowed); + } + } + } + // wire-contract snapshot: BootInfo as the KMS serializes it (camelCase). // Keep these field names in sync with the kms BootInfo. `#[serde(default)]` // means extra fields are ignored AND a renamed field deserializes to "" — @@ -301,7 +1428,7 @@ mod tests { "deviceId": "0xDEV", "keyProviderInfo": "kp", "tcbStatus": "UpToDate", - "advisoryIds": [] + "advisoryIds": ["INTEL-SA-00001"] }"#; let info: BootInfo = serde_json::from_str(wire).expect("kms BootInfo must deserialize"); assert_eq!(norm(&info.mr_aggregated), "aabb"); @@ -309,6 +1436,8 @@ mod tests { assert_eq!(norm(&info.app_id), "app1"); assert_eq!(norm(&info.compose_hash), "hash"); assert_eq!(norm(&info.device_id), "dev"); + assert_eq!(info.tcb_status, "UpToDate"); + assert_eq!(info.advisory_ids, ["INTEL-SA-00001"]); // a check using this payload should pass against a matching allowlist. let info2: BootInfo = serde_json::from_str(wire).unwrap(); let al: Allowlist = serde_json::from_str( diff --git a/dstack/crates/dstack-cli-core/src/compose.rs b/dstack/crates/dstack-cli-core/src/compose.rs index 4db4f53a6b..34d4871b9d 100644 --- a/dstack/crates/dstack-cli-core/src/compose.rs +++ b/dstack/crates/dstack-cli-core/src/compose.rs @@ -5,6 +5,7 @@ //! build the app-compose manifest — the JSON document the VMM hashes (to derive //! the app id) and deploys. The raw docker-compose YAML is embedded as a string. +use dstack_types::KeyProviderKind; use serde_json::json; /// build a minimal app-compose manifest from a docker-compose YAML body @@ -34,7 +35,11 @@ pub fn build_app_compose_with_runtime( build_app_compose_with_runtime_and_volumes( name, docker_compose_yaml, - kms_enabled, + if kms_enabled { + KeyProviderKind::Kms + } else { + KeyProviderKind::None + }, runner, snapshotter, &[], @@ -45,7 +50,7 @@ pub fn build_app_compose_with_runtime( pub fn build_app_compose_with_runtime_and_volumes( name: &str, docker_compose_yaml: &str, - kms_enabled: bool, + key_provider: KeyProviderKind, runner: &str, snapshotter: Option<&str>, verity_volumes: &[dstack_types::VerityVolume], @@ -55,7 +60,7 @@ pub fn build_app_compose_with_runtime_and_volumes( "name": name, "runner": runner, "docker_compose_file": docker_compose_yaml, - "kms_enabled": kms_enabled, + "kms_enabled": key_provider.is_kms(), "gateway_enabled": false, "local_key_provider_enabled": false, "public_logs": true, @@ -74,7 +79,48 @@ pub fn build_app_compose_with_runtime_and_volumes( if !verity_volumes.is_empty() { manifest["verity_volumes"] = json!(verity_volumes); } + // Preserve legacy KMS/None manifest bytes, which determine app identity. + if !matches!(key_provider, KeyProviderKind::Kms | KeyProviderKind::None) { + manifest["key_provider"] = json!(key_provider); + } // pretty-print via Value's Display (`{:#}`) — infallible, and byte-identical // to serde_json::to_string_pretty (avoids an expect on an unfailable Result). format!("{manifest:#}") } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn typed_provider_matches_previous_cli_manifest_encoding() { + let volumes = [dstack_types::VerityVolume { + source: "test.img".into(), + verity_root: [1; 32], + target: "/test".into(), + }]; + for volumes in [&[][..], &volumes[..]] { + let build = |provider| { + build_app_compose_with_runtime_and_volumes( + "test", + "", + provider, + "nerdctl-compose", + Some("soci"), + volumes, + ) + }; + for provider in [ + KeyProviderKind::SevSnp, + KeyProviderKind::Local, + KeyProviderKind::Tpm, + ] { + // The old CLI serialized a legacy manifest, then inserted the provider. + let mut legacy: serde_json::Value = + serde_json::from_str(&build(KeyProviderKind::None)).unwrap(); + legacy["key_provider"] = json!(provider); + assert_eq!(build(provider), format!("{legacy:#}")); + } + } + } +} diff --git a/dstack/crates/dstack-cli-core/src/config.rs b/dstack/crates/dstack-cli-core/src/config.rs index cb0855ce30..d2f832bce6 100644 --- a/dstack/crates/dstack-cli-core/src/config.rs +++ b/dstack/crates/dstack-cli-core/src/config.rs @@ -98,10 +98,11 @@ pub struct HostConfig { pub os_image_hash: String, /// OS image download URL template (must contain `{OS_IMAGE_HASH}`). pub image_download_url: String, - /// whether the KMS verifies the OS image hash on app key requests. - pub verify_os_image: bool, /// confidential-computing platform (selects SNP-specific KMS settings). pub platform: Platform, + /// hex SHA-256 of the KMS admin token; the KMS refuses to start without + /// an admin credential. + pub kms_admin_token_hash: String, } impl Default for HostConfig { @@ -111,8 +112,8 @@ impl Default for HostConfig { kms_bootstrap_domain: "10.0.2.2".to_string(), os_image_hash: String::new(), image_download_url: DEFAULT_IMAGE_DOWNLOAD_URL.to_string(), - verify_os_image: true, platform: Platform::Tdx, + kms_admin_token_hash: String::new(), } } } @@ -138,7 +139,6 @@ cert_dir = "/kms/certs" enforce_self_authorization = false {sev_snp} [core.image] -verify = {verify} cache_dir = "/kms/images" download_url = "{download_url}" download_timeout = "2m" @@ -152,6 +152,17 @@ type = "webhook" [core.auth_api.webhook] url = "{webhook_url}" +# the key handover path a serving KMS requires; the token stays on the host. +[core.admin] +enabled = true +address = "127.0.0.1" +port = 8001 +auth_token_hash = "{admin_token_hash}" + +[core.admin.tls] +key = "/kms/certs/rpc.key" +certs = "/kms/certs/rpc.crt" + [core.onboard] enabled = true auto_bootstrap_domain = "{bootstrap_domain}" @@ -165,10 +176,10 @@ port = 8000 Platform::AmdSevSnp => "sev_snp_key_release = true\namd_kds_base_url = \"\"\n", Platform::Tdx => "", }, - verify = cfg.verify_os_image, download_url = cfg.image_download_url, webhook_url = cfg.auth_webhook_url, bootstrap_domain = cfg.kms_bootstrap_domain, + admin_token_hash = cfg.kms_admin_token_hash, ) } @@ -199,10 +210,8 @@ pub fn auth_allowlist_json(cfg: &HostConfig) -> String { /// compose hash. pub const DEFAULT_KMS_IMAGE: &str = "dstacktee/dstack-kms:0.5.11@sha256:84b793feed825a5b5e70d04386e931e0e110461492793f17ab2128e39808d989"; -/// build the KMS-in-CVM app-compose manifest. An init script writes the -/// rendered `kms.toml` into the guest and the KMS container mounts it. On TDX -/// the CVM uses the SGX local key provider to seal the KMS root key; AMD -/// SEV-SNP has no such provider, so it's disabled there. +/// Build the KMS app-compose manifest with an embedded `kms.toml` init script. +/// Select SGX local provisioning on TDX and native SNP provisioning on AMD. pub fn kms_app_compose(kms_toml: &str, kms_image: &str, platform: Platform) -> String { let docker_compose = format!( r#"services: @@ -223,7 +232,7 @@ volumes: let init_script = format!( "mkdir -p /dstack/kms-config\ncat > /dstack/kms-config/kms.toml <<'KMSTOML'\n{kms_toml}\nKMSTOML\ntrue\n" ); - let manifest = json!({ + let mut manifest = json!({ "manifest_version": 2, "name": "dstack-kms", "runner": "docker-compose", @@ -239,6 +248,9 @@ volumes: "secure_time": false, "allowed_envs": [] }); + if platform == Platform::AmdSevSnp { + manifest["key_provider"] = json!("sev-snp"); + } // infallible pretty-print via Value's Display; see compose::build_app_compose. format!("{manifest:#}") } @@ -340,7 +352,7 @@ cid_start = {cid_start} cid_pool_size = {cid_pool_size} max_allocable_vcpu = 20 max_allocable_memory_in_mb = 100_000 -qmp_socket = false +qmp_socket = true user = "" use_mrconfigid = {use_mrconfigid} qemu_pci_hole64_size = 0 @@ -348,6 +360,12 @@ qemu_hotplug_off = true host_share_mode = "{host_share_mode}" qgs_port = 4050 +# What an unconfigured 8090 serves: the dashboard, and the identity, version +# and health it publishes. Containers, logs, metrics and app-key attestation +# need a token. See docs/guest-api-auth.md. +[cvm.guest_agent_api] +anonymous_scopes = ["guest:dashboard", "guest:version", "guest:health", "guest:info"] + [cvm.product] sys_vendor = "dstack" product_name = "dstack" @@ -402,7 +420,7 @@ address = "vsock:2" port = {host_api_port} [key_provider] -enabled = true +enabled = {use_sgx_key_provider} address = "{kp_addr}" port = {kp_port} "#, @@ -431,6 +449,7 @@ port = {kp_port} host_api_port = r.host_api_port, kp_addr = r.key_provider_addr, kp_port = r.key_provider_port, + use_sgx_key_provider = r.platform == Platform::Tdx, auth_enabled = r.auth_enabled, auth_tokens = if r.auth_token.is_empty() { String::new() @@ -477,10 +496,20 @@ mod tests { let cfg = HostConfig { auth_webhook_url: "http://10.0.2.2:8001".into(), kms_bootstrap_domain: "10.0.2.2".into(), + kms_admin_token_hash: "ab".repeat(32), ..Default::default() }; let toml = kms_toml(&cfg); assert!(toml.contains("enforce_self_authorization = false")); + let v: toml::Value = toml::from_str(&toml).unwrap(); + let admin = &v["core"]["admin"]; + assert_eq!(admin["enabled"].as_bool(), Some(true)); + assert_eq!( + admin["auth_token_hash"].as_str(), + Some("ab".repeat(32).as_str()) + ); + assert_eq!(admin["tls"]["key"].as_str(), Some("/kms/certs/rpc.key")); + assert_eq!(admin["tls"]["certs"].as_str(), Some("/kms/certs/rpc.crt")); assert!(toml.contains(r#"auto_bootstrap_domain = "10.0.2.2""#)); assert!(toml.contains(r#"type = "webhook""#)); assert!(toml.contains(r#"url = "http://10.0.2.2:8001""#)); @@ -498,11 +527,12 @@ mod tests { assert!(tdx_vmm.contains(r#"platform = "tdx""#)); assert!(tdx_vmm.contains(r#"host_share_mode = "9p""#)); assert!(tdx_vmm.contains("use_mrconfigid = false")); + assert!(tdx_vmm.contains("[key_provider]\nenabled = true")); toml::from_str::(&tdx_vmm).expect("tdx vmm.toml valid"); assert!(kms_app_compose("x", "img", Platform::Tdx) .contains(r#""local_key_provider_enabled": true"#)); - // SNP: key-release gate set, vhd share, mrconfigid on, no local provider. + // SNP: key-release gate set, vhd share, mrconfigid on, native sealing. let snp = kms_toml(&HostConfig { platform: Platform::AmdSevSnp, ..Default::default() @@ -516,9 +546,14 @@ mod tests { assert!(snp_vmm.contains(r#"platform = "amd-sev-snp""#)); assert!(snp_vmm.contains(r#"host_share_mode = "vhd""#)); assert!(snp_vmm.contains("use_mrconfigid = true")); + assert!(snp_vmm.contains("[key_provider]\nenabled = false")); toml::from_str::(&snp_vmm).expect("snp vmm.toml valid"); assert!(kms_app_compose("x", "img", Platform::AmdSevSnp) .contains(r#""local_key_provider_enabled": false"#)); + let snp_compose: serde_json::Value = + serde_json::from_str(&kms_app_compose("x", "img", Platform::AmdSevSnp)).unwrap(); + assert_eq!(snp_compose["key_provider"], "sev-snp"); + assert_eq!(snp_compose["kms_enabled"], false); } #[test] diff --git a/dstack/crates/dstack-cli/src/main.rs b/dstack/crates/dstack-cli/src/main.rs index 8a70141e93..41d3cd41f3 100644 --- a/dstack/crates/dstack-cli/src/main.rs +++ b/dstack/crates/dstack-cli/src/main.rs @@ -15,8 +15,14 @@ use clap::{Parser, Subcommand, ValueEnum}; use dstack_cli_core::layout::InstallLayout; use dstack_cli_core::vmm::{Vmm, DEFAULT_HOST}; use dstack_cli_core::{compose, ports, rpc}; +use dstack_types::KeyProviderKind; use fs_err as fs; +fn parse_key_provider(value: &str) -> std::result::Result { + serde_json::from_value(serde_json::Value::String(value.to_string())) + .map_err(|_| "expected kms, local, sev-snp, tdx-seal, tpm, or none".to_string()) +} + #[derive(Parser)] #[command( name = "dstack", @@ -115,6 +121,9 @@ enum Command { /// deploy in non-KMS mode (ephemeral keys; no KMS required). #[arg(long)] no_kms: bool, + /// key provider: kms (default), local (SGX), sev-snp, tdx-seal, tpm, or none. + #[arg(long, value_parser = parse_key_provider, conflicts_with = "no_kms")] + key_provider: Option, /// register the app's compose hash in this auth-allowlist.json. Defaults /// to the local allowlist from `dstackup install`. #[arg(long, value_name = "PATH")] @@ -236,11 +245,17 @@ async fn main() -> Result<()> { ports, volumes, no_kms, + key_provider, allowlist, dry_run, runner, snapshotter, } => { + let key_provider = key_provider.unwrap_or(if no_kms { + KeyProviderKind::None + } else { + KeyProviderKind::Kms + }); let compose = resolve_compose_arg(compose, compose_file)?; let image = if use_local_defaults { image.or_else(|| defaults.as_ref().and_then(|d| d.image.clone())) @@ -249,7 +264,8 @@ async fn main() -> Result<()> { }; let allowlist = if use_local_defaults { allowlist.or_else(|| { - (!no_kms) + key_provider + .is_kms() .then(|| defaults.as_ref().and_then(LocalDefaults::allowlist_path)) .flatten() }) @@ -267,7 +283,7 @@ async fn main() -> Result<()> { disk, &ports, &volumes, - no_kms, + key_provider, allowlist.as_deref(), dry_run, json, @@ -446,7 +462,7 @@ async fn cmd_deploy( disk: u32, port_specs: &[String], volume_specs: &[String], - no_kms: bool, + key_provider: KeyProviderKind, allowlist: Option<&str>, dry_run: bool, json: bool, @@ -474,7 +490,7 @@ async fn cmd_deploy( let app_compose = compose::build_app_compose_with_runtime_and_volumes( name, &yaml, - !no_kms, + key_provider, runner.as_str(), snapshotter.map(Snapshotter::as_str), &parsed_volumes, @@ -534,7 +550,7 @@ async fn cmd_deploy( " (the KMS issues keys only if this is the allowlist its auth webhook serves)" ); } - } else if !no_kms && !json { + } else if key_provider.is_kms() && !json { println!("note: no --allowlist given; a KMS-mode app needs its compose hash registered to get keys"); } @@ -763,6 +779,44 @@ mod tests { } } + #[test] + fn sev_snp_provider_is_explicit_and_conflicts_with_no_kms_alias() { + let cli = Cli::try_parse_from([ + "dstack", + "deploy", + "compose.yaml", + "--key-provider", + "sev-snp", + ]) + .unwrap(); + assert!(matches!( + cli.command, + Command::Deploy { + key_provider: Some(KeyProviderKind::SevSnp), + .. + } + )); + assert!(Cli::try_parse_from([ + "dstack", + "deploy", + "compose.yaml", + "--key-provider", + "sev-snp", + "--no-kms" + ]) + .is_err()); + for invalid in ["snp", "sev_snp", "unknown"] { + assert!(Cli::try_parse_from([ + "dstack", + "deploy", + "compose.yaml", + "--key-provider", + invalid + ]) + .is_err()); + } + } + #[test] fn parses_verity_fs_image_flag() { let cli = Cli::parse_from(["dstack", "verity", "--fs-image", "rootfs.ext4"]); diff --git a/dstack/crates/dstack-verifier-wasm/Cargo.toml b/dstack/crates/dstack-verifier-wasm/Cargo.toml new file mode 100644 index 0000000000..3407c55999 --- /dev/null +++ b/dstack/crates/dstack-verifier-wasm/Cargo.toml @@ -0,0 +1,29 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "dstack-verifier-wasm" +version.workspace = true +authors.workspace = true +edition.workspace = true +license.workspace = true +homepage.workspace = true +repository.workspace = true +publish = false +description = "WASM ABI for dstack TDX lite OS verification" + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +anyhow.workspace = true +cc-eventlog.workspace = true +dstack-mr.workspace = true +dstack-types.workspace = true +hex = { workspace = true, features = ["std"] } +serde = { workspace = true, features = ["derive"] } +serde_json.workspace = true + +[dev-dependencies] +dcap-qvl.workspace = true diff --git a/dstack/crates/dstack-verifier-wasm/src/lib.rs b/dstack/crates/dstack-verifier-wasm/src/lib.rs new file mode 100644 index 0000000000..609a31f173 --- /dev/null +++ b/dstack/crates/dstack-verifier-wasm/src/lib.rs @@ -0,0 +1,189 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// +// SPDX-License-Identifier: Apache-2.0 + +//! WASM ABI for [`dstack_mr::tdx::verify_tdx_lite_os`]. +//! +//! Zero imports, no wasm-bindgen. JSON in/out: +//! input `{mrtd, rtmr0, rtmr1, rtmr2, event_log, vm_config}`, +//! output `{ok, os_image_hash, reason}`. `os_image_hash` is set only when `ok`. + +#![cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + +use anyhow::{bail, Context, Result}; +use cc_eventlog::TdxEvent; +use dstack_mr::{tdx::verify_tdx_lite_os, TdxMeasurements}; +use dstack_types::VmConfig; +use serde::{Deserialize, Serialize}; + +#[derive(Deserialize)] +struct Input { + mrtd: String, + rtmr0: String, + rtmr1: String, + rtmr2: String, + event_log: String, + vm_config: String, +} + +#[derive(Serialize, Default)] +struct Output { + ok: bool, + os_image_hash: Option, + reason: Option, +} + +fn parse_mr(name: &str, value: &str) -> Result> { + let value = value + .strip_prefix("0x") + .or_else(|| value.strip_prefix("0X")) + .unwrap_or(value); + let bytes = hex::decode(value).with_context(|| format!("{name} is not valid hex"))?; + if bytes.len() != 48 { + bail!("{name} has length {}, expected 48 bytes", bytes.len()); + } + Ok(bytes) +} + +fn verify_input(input: Input) -> Result { + let vm: VmConfig = + serde_json::from_str(&input.vm_config).context("vm_config is not valid JSON")?; + let mrs = TdxMeasurements { + mrtd: parse_mr("mrtd", &input.mrtd)?, + rtmr0: parse_mr("rtmr0", &input.rtmr0)?, + rtmr1: parse_mr("rtmr1", &input.rtmr1)?, + rtmr2: parse_mr("rtmr2", &input.rtmr2)?, + }; + let events: Vec = + serde_json::from_str(&input.event_log).context("event_log is not valid JSON")?; + verify_tdx_lite_os(&mrs, &events, &vm)?; + Ok(Output { + ok: true, + os_image_hash: Some(hex::encode(&vm.os_image_hash)), + reason: None, + }) +} + +fn run(bytes: &[u8]) -> Output { + match serde_json::from_slice::(bytes) + .context("input is not valid JSON") + .and_then(verify_input) + { + Ok(out) => out, + Err(err) => Output { + ok: false, + os_image_hash: None, + reason: Some(format!("{err:#}")), + }, + } +} + +#[cfg(target_arch = "wasm32")] +mod abi { + use super::run; + + #[no_mangle] + pub extern "C" fn alloc(len: usize) -> *mut u8 { + let mut v = Vec::::with_capacity(len); + let ptr = v.as_mut_ptr(); + core::mem::forget(v); + ptr + } + + /// # Safety + /// `ptr`/`len` must come from [`alloc`] or a result of [`verify_tdx_lite`]. + #[no_mangle] + pub unsafe extern "C" fn dealloc(ptr: *mut u8, len: usize) { + drop(Vec::from_raw_parts(ptr, 0, len)); + } + + /// # Safety + /// `ptr`/`len` must describe a buffer obtained from [`alloc`] and filled by + /// the caller. + #[no_mangle] + pub unsafe extern "C" fn verify_tdx_lite(ptr: *const u8, len: usize) -> u64 { + let input = core::slice::from_raw_parts(ptr, len); + let out = serde_json::to_vec(&run(input)).unwrap_or_else(|_| b"{\"ok\":false}".to_vec()); + let mut out = out.into_boxed_slice(); + let (ptr, len) = (out.as_mut_ptr() as u64, out.len() as u64); + core::mem::forget(out); + (ptr << 32) | len + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[derive(Deserialize)] + struct GetQuoteFixture { + quote: String, + event_log: String, + vm_config: String, + } + + /// Builds the ABI input from the captured GetQuote fixture, letting each + /// test edit it before serialization. + fn fixture_payload(edit: impl FnOnce(&mut serde_json::Value)) -> Vec { + let fixture: GetQuoteFixture = serde_json::from_str(include_str!( + "../../../verifier/fixtures/tdx-lite-getquote.json" + )) + .expect("fixture parses"); + let quote = hex::decode(&fixture.quote).expect("quote is hex"); + let quote = dcap_qvl::quote::Quote::parse("e).expect("fixture quote parses"); + let report = quote.report.as_td10().expect("TDX 1.0 report"); + let mut payload = serde_json::json!({ + "mrtd": hex::encode(report.mr_td), + "rtmr0": hex::encode(report.rt_mr0), + "rtmr1": hex::encode(report.rt_mr1), + "rtmr2": hex::encode(report.rt_mr2), + "event_log": fixture.event_log, + "vm_config": fixture.vm_config, + }); + edit(&mut payload); + serde_json::to_vec(&payload).expect("payload serializes") + } + + #[test] + fn fixture_is_accepted() { + let out = run(&fixture_payload(|_| {})); + assert!(out.ok, "{:?}", out.reason); + assert!(out.os_image_hash.is_some()); + assert!(out.reason.is_none()); + } + + #[test] + fn stuffed_os_image_hash_is_not_returned_on_failure() { + let out = run(&fixture_payload(|payload| { + let mut vm: serde_json::Value = + serde_json::from_str(payload["vm_config"].as_str().expect("vm_config string")) + .expect("vm_config parses"); + vm["os_image_hash"] = "ab".repeat(32).into(); + payload["vm_config"] = vm.to_string().into(); + })); + assert!(!out.ok); + assert_eq!(out.os_image_hash, None); + } + + #[test] + fn mixed_case_hex_is_accepted() { + let out = run(&fixture_payload(|payload| { + let mrtd = payload["mrtd"] + .as_str() + .expect("mrtd string") + .to_uppercase(); + payload["mrtd"] = mrtd.into(); + })); + assert!(out.ok, "{:?}", out.reason); + } + + #[test] + fn garbage_input_is_rejected_without_panic() { + let out = run( + br#"{"mrtd":"","rtmr0":"","rtmr1":"","rtmr2":"","event_log":"[]","vm_config":"{}"}"#, + ); + assert!(!out.ok); + assert!(out.reason.is_some()); + assert_eq!(out.os_image_hash, None); + } +} diff --git a/dstack/crates/dstack-volume/src/volume.rs b/dstack/crates/dstack-volume/src/volume.rs index 604e86ac13..ba9ee6ac18 100644 --- a/dstack/crates/dstack-volume/src/volume.rs +++ b/dstack/crates/dstack-volume/src/volume.rs @@ -332,7 +332,7 @@ fn write_gpt(mut out: fs::File, layout: &GptLayout, root_hash: &str) -> Result t, - None => generate_vmm_token()?, + None => generate_token()?, }; write_token_file(&token_path, &vmm_token)?; + // the KMS admin token, which the KMS config holds only as a hash. + let kms_admin_token_path = layout.config_dir.join("kms-admin-token"); + let kms_admin_token = match read_token_file(&kms_admin_token_path) { + Some(t) => t, + None => generate_token()?, + }; + write_token_file(&kms_admin_token_path, &kms_admin_token)?; // 8. resolve the key provider - run our own unless told to use an existing // one (TDX only; SNP has no SGX local provider). @@ -173,19 +181,17 @@ pub(crate) async fn cmd_install(mut o: InstallOpts, release_api_base_url: &str) ..Default::default() }); // the KMS-in-CVM reaches the host auth webhook at 10.0.2.2:. - // The KMS's own image download-verify stays off for the single-node flow - // (it would need a published image source), but we PIN the app OS image in - // the webhook allowlist (resolved in preflight, fail-closed): digest.txt - // holds the measured image hash the KMS reports for an app (with - // platform measurement material such as measurement.snp.cbor committed by - // sha256sum.txt), so an app cannot boot under a different, unmeasured image - // and still receive keys. + // We also PIN the app OS image in the webhook allowlist (resolved in + // preflight, fail-closed): digest.txt holds the measured image hash the + // KMS reports for an app (with platform measurement material such as + // measurement.snp.cbor committed by sha256sum.txt), so an app cannot boot + // under a different, unmeasured image and still receive keys. // bootAuth/kms ignores osImages, so the KMS bootstrap itself is unaffected. let host_cfg = HostConfig { auth_webhook_url: format!("http://10.0.2.2:{}", o.auth_port), os_image_hash: os_image_hash.unwrap_or_default(), - verify_os_image: false, platform, + kms_admin_token_hash: hex::encode(Sha256::digest(kms_admin_token.as_bytes())), ..Default::default() }; let kms = config::kms_toml(&host_cfg); @@ -845,11 +851,10 @@ fn resolve_key_provider( println!(" [ok] using existing key provider at {addr}:{port}"); return Ok((addr, port, None)); } - // AMD SEV-SNP has no SGX local key provider; the rendered [key_provider] - // block is unused (the KMS-in-CVM runs with local_key_provider_enabled = - // false), so don't require or start one. + // AMD SEV-SNP derives its sealing seed inside the KMS CVM. The SGX + // service's [key_provider] block is unused, so don't start that service. if platform == Platform::AmdSevSnp { - println!(" [ok] no local key provider (sev-snp)"); + println!(" [ok] native guest key provider (sev-snp)"); return Ok(("127.0.0.1".to_string(), o.key_provider_port, None)); } // TDX: run our in-tree provider under Gramine from the installed assets unless @@ -1219,8 +1224,8 @@ async fn wait_ready(client_url: &str, token: Option<&str>, timeout: Duration) -> } } -/// mint a 256-bit management-API token, hex-encoded, from the OS RNG. -fn generate_vmm_token() -> Result { +/// mint a 256-bit API token, hex-encoded, from the OS RNG. +fn generate_token() -> Result { let mut buf = [0u8; 32]; let mut f = fs::File::open("/dev/urandom").context("opening /dev/urandom")?; std::io::Read::read_exact(&mut f, &mut buf).context("reading /dev/urandom")?; diff --git a/dstack/crates/mock-attestation/src/server.rs b/dstack/crates/mock-attestation/src/server.rs index fb733ab87e..41a495c9a3 100644 --- a/dstack/crates/mock-attestation/src/server.rs +++ b/dstack/crates/mock-attestation/src/server.rs @@ -67,6 +67,7 @@ pub fn router(state: Arc) -> Router { .route("/tdx/certification/v4/tcb", get(tcb_info)) .route("/tdx/certification/v4/qe/identity", get(qe_identity)) .route("/vcek/v1/Milan/cert_chain", get(sev_ca_chain)) + .route("/vcek/v1/Milan/crl", get(sev_crl)) .route("/vcek/v1/Milan/{chip_id}", get(sev_vcek)) .route("/tpm/aia/root.pem", get(tpm_root)) .route("/tpm/aia/intermediate.der", get(tpm_intermediate)) @@ -138,6 +139,10 @@ async fn sev_ca_chain(State(state): State>) -> impl Int binary(state.sev_snp.ca_chain_pem(), None) } +async fn sev_crl(State(state): State>) -> impl IntoResponse { + binary(state.sev_snp.crl_der(), None) +} + async fn sev_vcek(State(state): State>) -> impl IntoResponse { binary(state.sev_snp.vcek_der(), None) } @@ -276,13 +281,17 @@ mod tests { let sev_evidence = state.sev_snp.attest([0x43; 64]).unwrap(); let kds = sev_snp_qvl::AmdKdsClient::with_base_url(format!("{base}/vcek/v1")).unwrap(); - sev_snp_qvl::QuoteVerifier::new_with_root( + let sev_verifier = sev_snp_qvl::QuoteVerifier::new_with_root( sev_snp_qvl::AmdSnpProduct::Milan, state.sev_snp.root_ca_pem().into_bytes(), - ) - .fetch_and_verify(&kds, &sev_evidence.report, &[], &[0x43; 64]) - .await - .unwrap(); + ); + // Fetched and supplied certificates are both checked against the CRL. + for cert_chain in [&[][..], &sev_evidence.cert_chain] { + sev_verifier + .fetch_and_verify(&kds, &sev_evidence.report, cert_chain, &[0x43; 64]) + .await + .unwrap(); + } task.abort(); } diff --git a/dstack/crates/mock-attestation/src/sev_snp.rs b/dstack/crates/mock-attestation/src/sev_snp.rs index 720078198f..edcbc659d2 100644 --- a/dstack/crates/mock-attestation/src/sev_snp.rs +++ b/dstack/crates/mock-attestation/src/sev_snp.rs @@ -6,19 +6,23 @@ use anyhow::Result; use p384::ecdsa::{signature::DigestSigner, Signature as P384Signature, SigningKey}; use p384::pkcs8::DecodePrivateKey; use rcgen::{ - BasicConstraints, Certificate, CertificateParams, CertifiedKey, DnType, IsCa, KeyPair, - KeyUsagePurpose, + BasicConstraints, Certificate, CertificateParams, CertificateRevocationListParams, + CertifiedKey, CustomExtension, DnType, IsCa, KeyIdMethod, KeyPair, KeyUsagePurpose, + SerialNumber, }; use sev::firmware::guest::AttestationReport; use sha2::{Digest, Sha384}; use time::{Duration, OffsetDateTime}; +const CHIP_ID: [u8; 64] = [0x33; 64]; + pub struct SevSnpGenerator { root: Certificate, root_key: KeyPair, ask: Certificate, vcek: Certificate, vcek_key: KeyPair, + crl: Vec, } #[derive(serde::Serialize, serde::Deserialize)] @@ -49,13 +53,40 @@ impl SevSnpGenerator { let vcek_key = crate::p384_key(&seed, "sev-vcek")?; let mut params = base_params("Mock AMD VCEK")?; params.key_usages.push(KeyUsagePurpose::DigitalSignature); + // hwID, then blSPL/teeSPL/snpSPL/ucodeSPL matching the report's zero reported_tcb. + let hw_id = [&[0x04, 0x40][..], &CHIP_ID].concat(); + params + .custom_extensions + .push(CustomExtension::from_oid_content( + &[1, 3, 6, 1, 4, 1, 3704, 1, 4], + hw_id, + )); + params.custom_extensions.extend([1, 2, 3, 8].map(|spl| { + CustomExtension::from_oid_content( + &[1, 3, 6, 1, 4, 1, 3704, 1, 3, spl], + vec![0x02, 0x01, 0x00], + ) + })); let vcek = params.signed_by(&vcek_key, &ask, &ask_key)?; + let now = OffsetDateTime::now_utc(); + let crl = CertificateRevocationListParams { + this_update: now - Duration::days(1), + next_update: now + Duration::days(30), + crl_number: SerialNumber::from(1), + issuing_distribution_point: None, + revoked_certs: Vec::new(), + key_identifier_method: KeyIdMethod::Sha256, + } + .signed_by(&root, &root_key)? + .der() + .to_vec(); Ok(Self { root, root_key, ask, vcek, vcek_key, + crl, }) } @@ -71,6 +102,10 @@ impl SevSnpGenerator { format!("{}{}", self.ask.pem(), self.root.pem()).into_bytes() } + pub fn crl_der(&self) -> Vec { + self.crl.clone() + } + pub fn vcek_der(&self) -> Vec { self.vcek.der().to_vec() } @@ -100,16 +135,21 @@ impl SevSnpGenerator { encoded[0x50..0x90].copy_from_slice(&report_data); encoded[0x90..0xc0].copy_from_slice(&measurement); encoded[0xc0..0xe0].copy_from_slice(&host_data); - encoded[0x1a0..0x1e0].fill(0x33); - let signing_key = SigningKey::from_pkcs8_pem(&self.vcek_key.serialize_pem())?; - let signature: P384Signature = - signing_key.sign_digest(Sha384::new_with_prefix(&encoded[..0x2a0])); - write_amd_signature(&mut encoded[0x2a0..], &signature); + encoded[0x1a0..0x1e0].copy_from_slice(&CHIP_ID); + self.sign(&mut encoded)?; Ok(SevSnpEvidence { report: encoded, cert_chain: vec![self.ask.pem().into_bytes(), self.vcek.pem().into_bytes()], }) } + + fn sign(&self, report: &mut [u8]) -> Result<()> { + let signing_key = SigningKey::from_pkcs8_pem(&self.vcek_key.serialize_pem())?; + let signature: P384Signature = + signing_key.sign_digest(Sha384::new_with_prefix(&report[..0x2a0])); + write_amd_signature(&mut report[0x2a0..], &signature); + Ok(()) + } } fn make_ca( @@ -187,5 +227,16 @@ mod tests { assert!(verifier .verify(&evidence.report, &evidence.cert_chain, &[0x24; 64]) .is_err()); + + // A validly signed report must still match the VCEK's chip and TCB. + for (offset, expected_err) in [(0x1a0, "hwID"), (0x180, "blSPL")] { + let mut forged = evidence.report.clone(); + forged[offset] ^= 1; + generator.sign(&mut forged).unwrap(); + let err = verifier + .verify(&forged, &evidence.cert_chain, &report_data) + .unwrap_err(); + assert!(format!("{err:#}").contains(expected_err), "{err:#}"); + } } } diff --git a/dstack/crates/qemu-acpi/examples/dump.rs b/dstack/crates/qemu-acpi/examples/dump.rs index 312ab4feca..eb531c3a6d 100644 --- a/dstack/crates/qemu-acpi/examples/dump.rs +++ b/dstack/crates/qemu-acpi/examples/dump.rs @@ -29,11 +29,15 @@ fn main() -> Result<(), Box> { let memory_size = optional(&mut args, 2u64 << 30)?; let volumes = optional(&mut args, 0)?; let pic = optional::(&mut args, 0)? == 1; - // Comma-separated PXB bus of each NUMA node; empty keeps the legacy layout. + // Comma-separated PXB bus of each NUMA node, `-` for none; empty keeps the + // legacy layout. let numa_nodes = optional::(&mut args, String::new())? .split(',') .filter(|bus| !bus.is_empty()) - .map(|bus| bus.parse().map(|bus| NumaNode { pxb_bus: Some(bus) })) + .map(|bus| match bus { + "-" => Ok(NumaNode { pxb_bus: None }), + bus => bus.parse().map(|bus| NumaNode { pxb_bus: Some(bus) }), + }) .collect::>()?; // Devices appended after the root ports: `e` endpoint, `r` root port. let extra_root_devices = optional::(&mut args, String::new())? diff --git a/dstack/crates/qemu-acpi/fixtures/README.md b/dstack/crates/qemu-acpi/fixtures/README.md index e6fb7aa49a..2b2d11942e 100644 --- a/dstack/crates/qemu-acpi/fixtures/README.md +++ b/dstack/crates/qemu-acpi/fixtures/README.md @@ -55,6 +55,10 @@ for each compatibility family cover the Cartesian product of: whose PXBs sit on buses 5, 6 and 8 (12 vCPUs, 6 GiB, two NICs), together with their loader and RSDP blobs. +`qemu-11.1-q35-hotplug-off-numa2-plain-*.bin` capture two guest NUMA nodes +without PXBs (8 vCPUs, 2 GiB, one NIC, two GPU root ports and one extra +endpoint on the root bus). + `qemu-11.1-q35-one-nic.bin` is an untrimmed byte-for-byte regression fixture. Fixture names identify the emulated compatibility version, not necessarily the source tree's release number. diff --git a/dstack/crates/qemu-acpi/fixtures/qemu-11.1-q35-hotplug-off-numa2-plain-base.bin b/dstack/crates/qemu-acpi/fixtures/qemu-11.1-q35-hotplug-off-numa2-plain-base.bin new file mode 100644 index 0000000000..9e3f1f418c Binary files /dev/null and b/dstack/crates/qemu-acpi/fixtures/qemu-11.1-q35-hotplug-off-numa2-plain-base.bin differ diff --git a/dstack/crates/qemu-acpi/fixtures/qemu-11.1-q35-hotplug-off-numa2-plain-loader.bin b/dstack/crates/qemu-acpi/fixtures/qemu-11.1-q35-hotplug-off-numa2-plain-loader.bin new file mode 100644 index 0000000000..d7f9c12f6d Binary files /dev/null and b/dstack/crates/qemu-acpi/fixtures/qemu-11.1-q35-hotplug-off-numa2-plain-loader.bin differ diff --git a/dstack/crates/qemu-acpi/fixtures/qemu-11.1-q35-hotplug-off-numa2-plain-rsdp.bin b/dstack/crates/qemu-acpi/fixtures/qemu-11.1-q35-hotplug-off-numa2-plain-rsdp.bin new file mode 100644 index 0000000000..6128229d5f Binary files /dev/null and b/dstack/crates/qemu-acpi/fixtures/qemu-11.1-q35-hotplug-off-numa2-plain-rsdp.bin differ diff --git a/dstack/crates/qemu-acpi/scripts/differential-qemu.sh b/dstack/crates/qemu-acpi/scripts/differential-qemu.sh index 07bce40535..1b34e0c349 100755 --- a/dstack/crates/qemu-acpi/scripts/differential-qemu.sh +++ b/dstack/crates/qemu-acpi/scripts/differential-qemu.sh @@ -24,17 +24,19 @@ rust_dump="$workspace/target/debug/examples/dump" run_case() { local version=$1 topology=$2 - # pxb_buses: one guest NUMA node per bus, GPUs split evenly across them. - local hugepages=0 gpus=0 pxb_buses=() + # pxb_buses: one guest NUMA node per bus, GPUs split evenly across them; + # plain_nodes: guest NUMA nodes without expanders, GPUs on the root bus. + local hugepages=0 gpus=0 pxb_buses=() plain_nodes=0 hotplug_off=0 case "$topology" in normal) ;; numa) hugepages=1 ;; numa-pxb) hugepages=1; gpus=8; pxb_buses=(5) ;; numa2-pxb) hugepages=1; gpus=8; pxb_buses=(5 10) ;; numa4-pxb-adjacent) hugepages=1; gpus=4; pxb_buses=(5 6 8 9) ;; + numa2-plain) gpus=4; plain_nodes=2; hotplug_off=1 ;; *) echo "invalid internal topology: $topology" >&2; exit 2 ;; esac - local nodes=${#pxb_buses[@]} + local nodes=$((${#pxb_buses[@]} + plain_nodes)) ((hugepages && nodes == 0)) && nodes=1 local output="$tmp/$version-$topology" @@ -58,26 +60,30 @@ run_case() { -numa "node,nodeid=$node,cpus=$((node * 8 / nodes))-$(((node + 1) * 8 / nodes - 1)),memdev=mem$node" -object "memory-backend-file,id=mem$node,size=$((2048 / nodes))M,mem-path=/dev/hugepages,share=on,prealloc=no" ) - if ((gpus)); then + if ((gpus && !plain_nodes)); then args+=(-device "pxb-pcie,id=pcie.node$node,bus=pcie.0,addr=$((10 + node)),numa_node=$node,bus_nr=${pxb_buses[$node]}") fi done if ((gpus)); then args+=(-object "iommufd,id=iommufd0") for ((index = 0; index < gpus; index++)); do + local bus=pcie.0 + ((plain_nodes)) || bus=pcie.node$((index * nodes / gpus)) args+=( - -device "pcie-root-port,id=pci.$index,bus=pcie.node$((index * nodes / gpus)),chassis=$index" + -device "pcie-root-port,id=pci.$index,bus=$bus,chassis=$index" -device "vfio-pci,host=00:00.0,bus=pci.$index,iommufd=iommufd0" ) done fi + ((hotplug_off)) && args+=(-global ICH9-LPC.acpi-pci-hotplug-with-bridge-support=off) QEMU_ACPI_COMPAT_VER="$version" QEMU_ACPI_DUMP_DIR="$output" \ "$qemu" "${args[@]}" -machine "$machine" local numa="" ((nodes > 1)) && numa=$(IFS=,; echo "${pxb_buses[*]}") + ((plain_nodes)) && numa=$(printf -- '-,%.0s' $(seq "$plain_nodes")) QEMU_ACPI_OUTPUT_DIR="$output/rust" \ - "$rust_dump" 2 8 "$version" "$gpus" 0 "$hugepages" 1 0 0 0 $((2048 << 20)) 0 0 "$numa" + "$rust_dump" 2 8 "$version" "$gpus" 0 "$hugepages" 1 "$hotplug_off" 0 0 $((2048 << 20)) 0 0 "$numa" for blob in tables loader rsdp; do cmp "$output/$blob.bin" "$output/rust/$blob.bin" done @@ -85,7 +91,7 @@ run_case() { } for version in 8.0.0 8.2.0 9.0.0 9.1.0 9.2.0 10.0.0 10.2.0 11.0.0 11.1.0 11.2.0; do - for topology in normal numa numa-pxb numa2-pxb numa4-pxb-adjacent; do + for topology in normal numa numa-pxb numa2-pxb numa4-pxb-adjacent numa2-plain; do run_case "$version" "$topology" done done diff --git a/dstack/crates/qemu-acpi/scripts/differential-random.py b/dstack/crates/qemu-acpi/scripts/differential-random.py index 9f688936bc..405248c2a5 100755 --- a/dstack/crates/qemu-acpi/scripts/differential-random.py +++ b/dstack/crates/qemu-acpi/scripts/differential-random.py @@ -39,7 +39,8 @@ class Case: smm: bool = False pic: bool = False pci_hole64_size: int = 0 - # PXB bus of each guest NUMA node; empty keeps the layout `hugepages` implies. + # PXB bus of each guest NUMA node, None for a node without one; empty + # keeps the layout `hugepages` implies. pxb_buses: tuple = () # Devices a QEMU wrapper appends to the root bus: "e" endpoint, "r" root port. extra: str = "" @@ -51,7 +52,7 @@ def numa_nodes(self): def pxbs(self): """PXB bus of each node that has one, explicit or implied.""" if self.pxb_buses: - return self.pxb_buses + return tuple(bus for bus in self.pxb_buses if bus is not None) return (5,) if self.hugepages and self.gpus else () @@ -106,6 +107,28 @@ def fixed_cases(): pxb_buses=(5, 7), extra="eree", ), + # Guest NUMA nodes without expanders: SRAT and _PXM only. + Case(cpus=2, pxb_buses=(None, None)), + Case(cpus=12, memory_mib=6144, nics=2, pxb_buses=(None,) * 3), + Case( + cpus=192, + memory_mib=8192, + gpus=4, + hotplug_off=True, + pci_hole64_size=1 << 43, + pxb_buses=(None, None), + extra="eeeee", + ), + Case( + version="9.2.0", + cpus=4, + hugepages=True, + gpus=2, + switches=1, + hotplug_off=True, + pxb_buses=(None, None), + extra="er", + ), ] return cases @@ -114,11 +137,14 @@ def random_case(rng): hugepages = rng.choice([False, True]) gpus = rng.randint(0, 8) switches = rng.randint(0, 4) if gpus else 0 - nodes = rng.choice([0, 0, 2, 3, 4]) if hugepages else 0 + nodes = rng.choice([0, 0, 2, 3, 4]) pxb_buses = [] - for _ in range(nodes): - pxb_buses.append(pxb_buses[-1] + rng.randint(1, 6) if pxb_buses else 5) - pxbs = len(pxb_buses) or int(hugepages and gpus > 0) + if hugepages: + for _ in range(nodes): + pxb_buses.append(pxb_buses[-1] + rng.randint(1, 6) if pxb_buses else 5) + else: + pxb_buses = [None] * nodes + pxbs = sum(bus is not None for bus in pxb_buses) or int(hugepages and gpus > 0) pxb = pxbs > 0 available = 26 - pxbs passthrough = switches if pxb else gpus + switches @@ -365,7 +391,7 @@ def run_case(case, image, rust_dump, output): str(case.memory_mib * 1024 * 1024), str(case.volumes), str(int(case.pic)), - ",".join(map(str, case.pxb_buses)), + ",".join("-" if bus is None else str(bus) for bus in case.pxb_buses), case.extra, ], check=True, diff --git a/dstack/crates/qemu-acpi/src/golden_tests.rs b/dstack/crates/qemu-acpi/src/golden_tests.rs index 2fb64fb168..0fe2f6448d 100644 --- a/dstack/crates/qemu-acpi/src/golden_tests.rs +++ b/dstack/crates/qemu-acpi/src/golden_tests.rs @@ -89,6 +89,31 @@ mod tests { Ok(()) } + /// Two nodes without expanders: GPUs and a wrapper's endpoint stay on + /// the root bus, and only the SRAT and the CPUs' `_PXM` carry the nodes. + #[test] + fn numa_nodes_without_pxb_match_qemu_byte_for_byte() -> Result<(), Error> { + let mut c = config(1, 0); + c.cpu_count = 8; + c.numa_nodes = vec![NumaNode { pxb_bus: None }; 2]; + c.num_gpus = 2; + c.extra_root_devices = vec![RootBusDevice::Endpoint]; + c.hotplug_off = true; + let actual = build(&c)?; + let expected = include_bytes!("../fixtures/qemu-11.1-q35-hotplug-off-numa2-plain-base.bin"); + assert_eq!(&actual.tables[..expected.len()], expected); + assert!(actual.tables[expected.len()..].iter().all(|b| *b == 0)); + assert_eq!( + actual.loader, + include_bytes!("../fixtures/qemu-11.1-q35-hotplug-off-numa2-plain-loader.bin") + ); + assert_eq!( + actual.rsdp, + include_bytes!("../fixtures/qemu-11.1-q35-hotplug-off-numa2-plain-rsdp.bin") + ); + Ok(()) + } + #[test] fn numa_layouts_qemu_cannot_build_are_rejected() { let nodes = |buses: &[u8]| { @@ -107,6 +132,7 @@ mod tests { 2, vec![NumaNode { pxb_bus: None }, NumaNode { pxb_bus: Some(5) }], ), + (3, vec![NumaNode { pxb_bus: None }; 2]), ] { c.cpu_count = cpus; c.numa_nodes = buses; diff --git a/dstack/crates/qemu-acpi/src/topology.rs b/dstack/crates/qemu-acpi/src/topology.rs index 8e2a66f639..40f74ca63f 100644 --- a/dstack/crates/qemu-acpi/src/topology.rs +++ b/dstack/crates/qemu-acpi/src/topology.rs @@ -89,8 +89,8 @@ pub enum TopologyError { }, #[error("{0} NUMA nodes exceed QEMU's limit of 128")] TooManyNumaNodes(usize), - #[error("every explicit NUMA node needs a PXB expander")] - NumaNodeWithoutPxb, + #[error("NUMA nodes must either all have a PXB expander or none")] + MixedPxbNumaNodes, #[error("{0} PXB expanders do not fit on the root bus")] TooManyPxbs(usize), #[error("PXB bus numbers must be nonzero and distinct: {0:?}")] @@ -125,8 +125,13 @@ impl MachineConfig { return Err(TopologyError::TooManyNumaNodes(nodes)); } // Node `i`'s expander sits on slot 0x10 + i only if every node has one. - if self.numa_nodes.iter().any(|node| node.pxb_bus.is_none()) { - return Err(TopologyError::NumaNodeWithoutPxb); + let pxbs = self + .numa_nodes + .iter() + .filter(|n| n.pxb_bus.is_some()) + .count(); + if pxbs != 0 && pxbs != nodes { + return Err(TopologyError::MixedPxbNumaNodes); } for (what, count) in [ ("cpu_count", u64::from(self.cpu_count)), diff --git a/dstack/dstack-attest/src/attestation.rs b/dstack/dstack-attest/src/attestation.rs index 1fa97c5e6e..912644ccf4 100644 --- a/dstack/dstack-attest/src/attestation.rs +++ b/dstack/dstack-attest/src/attestation.rs @@ -58,6 +58,78 @@ pub struct AttestationVerifierConfig { /// the vendor hosts in `pki_fetch::DEFAULT_ALLOWED_HOSTS`. #[serde(default)] pub allowed_collateral_hosts: Option>, + /// AMD SEV-SNP has no vendor TCB status, so it is judged against the + /// minimums in this JSON file: the list the KMS reads from its auth API. A + /// report below the one for its CPU is `OutOfDate`; one whose CPU has + /// none, and any report without a file, carries an empty status. + #[serde(default)] + pub sev_snp_tcb_requirements_file: Option, +} + +/// The minimum TCB of one CPU: the highest SVNs AMD's security bulletins +/// require of it. +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct SevSnpTcbRequirement { + /// CPUID Fn0000_0001 EAX as the bulletins print it, in eight hex digits: + /// `00a00f11` is Milan and `00a00f12` Milan-X. + cpuid: String, + bootloader: u8, + tee: u8, + snp: u8, + microcode: u8, + /// Family 1Ah (Turin) only. + #[serde(default)] + fmc: Option, +} + +impl TryFrom<&SevSnpTcbRequirement> for sev_snp_qvl::AmdSnpTcbRequirement { + type Error = anyhow::Error; + + fn try_from(value: &SevSnpTcbRequirement) -> Result { + let eax = u32::from_str_radix(&value.cpuid, 16) + .ok() + .filter(|_| value.cpuid.len() == 8) + .with_context(|| format!("sev_snp_tcb_requirements: invalid cpuid {}", value.cpuid))?; + let cpuid = sev_snp_qvl::AmdSnpCpuid::from_eax(eax); + // Only family 1Ah has an FMC SVN: an entry for it without one would + // pass any FMC, and an entry for another family with one would fail + // every report. + anyhow::ensure!( + (cpuid.family == 0x1a) == value.fmc.is_some(), + "sev_snp_tcb_requirements {}: set fmc for family 1Ah, and only for it", + value.cpuid + ); + Ok(Self { + cpuid, + min_tcb: sev_snp_qvl::AmdSnpTcbVersion { + fmc: value.fmc, + bootloader: value.bootloader, + tee: value.tee, + snp: value.snp, + microcode: value.microcode, + }, + }) + } +} + +/// Parse the JSON list of minimum TCBs, as governance publishes it. +pub fn sev_snp_tcb_requirements_from_json( + json: &str, +) -> Result> { + let mut seen = std::collections::HashSet::new(); + serde_json::from_str::>(json)? + .iter() + .map(|requirement| { + let parsed = sev_snp_qvl::AmdSnpTcbRequirement::try_from(requirement)?; + anyhow::ensure!( + seen.insert(parsed.cpuid), + "sev_snp_tcb_requirements lists cpuid {} twice", + requirement.cpuid + ); + Ok(parsed) + }) + .collect() } pub struct AttestationVerifier { @@ -136,6 +208,16 @@ impl AttestationVerifier { sev_snp = sev_snp.with_root(product, root); } } + let sev_snp_tcb_requirements = config + .sev_snp_tcb_requirements_file + .as_deref() + .map(|path| { + sev_snp_tcb_requirements_from_json(&fs_err::read_to_string(path)?).with_context( + || format!("invalid SEV-SNP TCB requirements in {}", path.display()), + ) + }) + .transpose()? + .unwrap_or_default(); let pccs = config .urls .pccs @@ -154,7 +236,7 @@ impl AttestationVerifier { gcp_tpm, aws_nitro_enclave: nsm(aws_nitro_enclave.as_deref(), "AWS Nitro Enclave")?, aws_nitro_tpm: nsm(aws_nitro_tpm.as_deref(), "AWS NitroTPM")?, - sev_snp, + sev_snp: sev_snp.with_tcb_requirements(sev_snp_tcb_requirements), amd_kds: AmdKdsClient::with_base_url(amd_kds)?, allowed_collateral_hosts: config .allowed_collateral_hosts @@ -390,6 +472,13 @@ fn replay_runtime_events( cc_eventlog::replay_events::(runtime_events, to_event) } +fn validate_runtime_events(runtime_events: &[RuntimeEvent]) -> Result<()> { + runtime_events + .iter() + .try_for_each(RuntimeEvent::validate) + .context("invalid runtime event") +} + fn find_event(runtime_events: &[RuntimeEvent], name: &str) -> Result { for event in runtime_events { if event.event == "system-ready" { @@ -1081,6 +1170,7 @@ impl AttestationV1 { config, ), }; + validate_runtime_events(&runtime_events)?; let report = match &platform { PlatformEvidence::Tdx { quote, .. } => DstackVerifiedReport::DstackTdx( verify_tdx_quote_with_events(verifier, quote, &runtime_events, &report_data) @@ -2349,6 +2439,7 @@ impl Attestation { verifier: &AttestationVerifier, now: Option, ) -> Result { + validate_runtime_events(&self.runtime_events)?; let report = match &self.quote { AttestationQuote::DstackTdx(q) => { let report = self.verify_tdx(verifier, &q.quote).await?; @@ -2582,6 +2673,7 @@ pub fn validate_tcb(report: &TdxVerifiedReport) -> Result<()> { } match &report.report { Report::TD15(report) => validate_td15(report), + Report::TD15Ex(report) => validate_td15(&report.base), Report::TD10(report) => validate_td10(report), Report::SgxEnclave(report) => validate_sgx(report), } @@ -2682,6 +2774,51 @@ mod tests { .expect("production roots and URLs must load"); } + #[test] + fn sev_snp_tcb_requirements_are_read_and_checked_during_load() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("requirements.json"); + let load = |json: Option<&str>| { + if let Some(json) = json { + fs_err::write(&file, json).unwrap(); + } + AttestationVerifier::load(&AttestationVerifierConfig { + sev_snp_tcb_requirements_file: Some(file.clone()), + ..Default::default() + }) + .err() + .map(|err| format!("{err:#}")) + }; + let entry = |cpuid: &str, fmc: &str| { + format!(r#"{{"cpuid":"{cpuid}","bootloader":1,"tee":1,"snp":1,"microcode":1{fmc}}}"#) + }; + let (milan, turin) = (entry("00a00f11", ""), entry("00b00f21", r#","fmc":1"#)); + assert!(load(None).unwrap().contains("requirements.json")); + let milan_x = entry("00A00F12", ""); + assert_eq!(load(Some(&format!("[{milan},{milan_x},{turin}]"))), None); + assert_eq!(load(Some("[]")), None); + + for (json, expected) in [ + (format!("[{}]", entry("00b00f21", "")), "only for it"), + ( + format!("[{}]", entry("00a10f11", r#","fmc":1"#)), + "only for it", + ), + (format!("[{}]", entry("milan", "")), "invalid cpuid"), + (format!("[{}]", entry("0x00a00f11", "")), "invalid cpuid"), + (format!("[{}]", entry("a00f11", "")), "invalid cpuid"), + (format!("[{milan},{milan}]"), "twice"), + ( + format!("[{}]", entry("00a00f11", r#","advisory_id":"AMD-SB-1""#)), + "unknown field", + ), + (String::new(), "invalid SEV-SNP TCB requirements"), + ] { + let error = load(Some(&json)).unwrap_or_default(); + assert!(error.contains(expected), "{error}"); + } + } + #[test] fn opted_in_external_root_is_read_during_load() { let config = AttestationVerifierConfig { diff --git a/dstack/dstack-attest/src/lib.rs b/dstack/dstack-attest/src/lib.rs index 8852838251..3365a35b93 100644 --- a/dstack/dstack-attest/src/lib.rs +++ b/dstack/dstack-attest/src/lib.rs @@ -65,6 +65,7 @@ pub fn default_verifier( .filter_map(|url| Some(url::Url::parse(url).ok()?.host_str()?.to_owned())) .collect(), ), + sev_snp_tcb_requirements_file: None, }) } @@ -193,6 +194,7 @@ pub fn emit_runtime_event(event: &str, payload: &[u8]) -> anyhow::Result<()> { let _lock = runtime_event_lock()?; let version = runtime_event_version()?; let event = RuntimeEvent::new(event.to_string(), payload.to_vec(), version); + event.validate()?; let mode = detect_tee_variant()?; if mode.has_tdx() { diff --git a/dstack/dstack-attest/src/trust_anchors.rs b/dstack/dstack-attest/src/trust_anchors.rs index 6458a511f9..59bac92776 100644 --- a/dstack/dstack-attest/src/trust_anchors.rs +++ b/dstack/dstack-attest/src/trust_anchors.rs @@ -154,6 +154,7 @@ mod tests { urls: Default::default(), root_ca, allowed_collateral_hosts: None, + sev_snp_tcb_requirements_file: None, }) } diff --git a/dstack/dstack-attest/tests/sev_snp_fixture.README.md b/dstack/dstack-attest/tests/sev_snp_fixture.README.md index 5b88fd4b53..3d52ef9465 100644 --- a/dstack/dstack-attest/tests/sev_snp_fixture.README.md +++ b/dstack/dstack-attest/tests/sev_snp_fixture.README.md @@ -45,7 +45,7 @@ chip_id: 38d174589d2dff97a6d40cb9f9d90b9507c027491219083cef3ce73e d18f7289142d941ad61eabecd27d25f268c1095d665f6001358e98a4769c82734a6bb877 measurement 7f51e17f72a04d5422cb2c00998166536019a217376f3aa45a630e59c805a599... host_data: 783f0057820acb99249af56cc3b07b4e8d80f65183167cba9cf437bb680f742f -tcb_status: OutOfDate (this fixture host's firmware TCB; tests verify reporting, auth policy decides acceptability) +tcb_status: empty (no sev_snp_tcb_requirements_file configured; see docs/amd-sev-snp.md) ``` ## Refreshing diff --git a/dstack/dstack-attest/tests/sev_snp_verify.rs b/dstack/dstack-attest/tests/sev_snp_verify.rs index 73455dc746..fc6750fba3 100644 --- a/dstack/dstack-attest/tests/sev_snp_verify.rs +++ b/dstack/dstack-attest/tests/sev_snp_verify.rs @@ -78,7 +78,7 @@ fn verify_sev_snp_attestation_bin() { println!("measurement: {}", hex::encode(verified.measurement)); println!("host_data: {}", hex::encode(verified.host_data)); println!("chip_id: {}", hex::encode(verified.chip_id)); - println!("tcb_status: {}", verified.tcb_info.tcb_status()); + println!("tcb_status: {}", verified.tcb_status); // End-to-end OS image binding, fully offline — exactly what dstack-verifier // does after the hardware report verifies. Recompute the launch measurement @@ -447,3 +447,44 @@ async fn an_empty_snp_report_from_the_verify_body_is_rejected_rather_than_parsed "unexpected error: {err:#}" ); } + +#[test] +fn configured_tcb_requirements_judge_the_real_report() { + use dstack_attest::attestation::sev_snp_tcb_requirements_from_json; + + let reported = verified_fixture_report().tcb_info.reported; + // The fixture's CPU is Milan. + let requirement = |cpuid: &str, microcode: u8| { + serde_json::json!([{ + "cpuid": cpuid, + "bootloader": reported.bootloader, + "tee": reported.tee, + "snp": reported.snp, + "microcode": microcode, + }]) + .to_string() + }; + let verify = |requirements: &str| { + sev_snp_qvl::QuoteVerifier::new_prod() + .with_tcb_requirements(sev_snp_tcb_requirements_from_json(requirements).unwrap()) + .verify( + &fixture_report(), + &[SEV_ASK_PEM.to_vec(), SEV_VCEK_PEM.to_vec()], + &expected_report_data(), + ) + .expect("verify SEV-SNP attestation offline") + .tcb_status + }; + + assert_eq!(verify("[]"), ""); + assert_eq!( + verify(&requirement("00a00f11", reported.microcode)), + "UpToDate" + ); + assert_eq!( + verify(&requirement("00a00f11", reported.microcode + 1)), + "OutOfDate" + ); + // Milan-X's minimum says nothing about Milan. + assert_eq!(verify(&requirement("00a00f12", reported.microcode)), ""); +} diff --git a/dstack/dstack-mr/Cargo.toml b/dstack/dstack-mr/Cargo.toml index 7e3248486d..631e74a143 100644 --- a/dstack/dstack-mr/Cargo.toml +++ b/dstack/dstack-mr/Cargo.toml @@ -35,9 +35,11 @@ bon.workspace = true log.workspace = true scale.workspace = true dstack-types.workspace = true +cc-eventlog.workspace = true qemu-acpi.workspace = true [dev-dependencies] +dcap-qvl.workspace = true reqwest = { workspace = true, features = ["blocking"] } flate2.workspace = true tar.workspace = true diff --git a/dstack/dstack-mr/cli/src/main.rs b/dstack/dstack-mr/cli/src/main.rs index 104d6cf21b..4f67c5182d 100644 --- a/dstack/dstack-mr/cli/src/main.rs +++ b/dstack/dstack-mr/cli/src/main.rs @@ -66,6 +66,11 @@ struct MachineConfig { #[arg(long, value_delimiter = ',')] numa_pxb_buses: Vec, + /// Number of guest NUMA nodes without PXB expanders (every device on the + /// root bus) + #[arg(long, conflicts_with = "numa_pxb_buses")] + numa_nodes: Option, + /// Number of GPUs #[arg(long, default_value = "0")] num_gpus: u32, @@ -132,11 +137,14 @@ fn main() -> Result<()> { // The image declares its OVMF layout. Older metadata.json files // predate the field, so fall back to the only layout that existed. let ovmf_variant = image_info.ovmf_variant.unwrap_or_default(); - let numa_nodes: Vec<_> = config - .numa_pxb_buses - .iter() - .map(|&bus| dstack_types::NumaNodeConfig { pxb_bus: bus }) - .collect(); + let numa_nodes = match config.numa_nodes { + Some(nodes) => vec![dstack_types::NumaNodeConfig { pxb_bus: None }; nodes], + None => config + .numa_pxb_buses + .iter() + .map(|&bus| dstack_types::NumaNodeConfig { pxb_bus: Some(bus) }) + .collect(), + }; let machine = Machine::builder() .cpu_count(config.cpu) diff --git a/dstack/dstack-mr/src/acpi.rs b/dstack/dstack-mr/src/acpi.rs index facbdefc85..15d026ea26 100644 --- a/dstack/dstack-mr/src/acpi.rs +++ b/dstack/dstack-mr/src/acpi.rs @@ -40,7 +40,7 @@ impl Machine<'_> { .numa_nodes .iter() .map(|node| NumaNode { - pxb_bus: Some(node.pxb_bus), + pxb_bus: node.pxb_bus, }) .collect(), num_gpus: self.num_gpus, diff --git a/dstack/dstack-mr/src/sev.rs b/dstack/dstack-mr/src/sev.rs index b413e8b430..1e023b7466 100644 --- a/dstack/dstack-mr/src/sev.rs +++ b/dstack/dstack-mr/src/sev.rs @@ -39,6 +39,18 @@ const VMSA_GPA: u64 = 0x0000_FFFF_FFFF_F000; /// the same bit layout the SEV-SNP ABI's `GUEST_FEATURES` field in /// `SNP_LAUNCH_START` carries). Set on every SNP guest. const SEV_FEATURE_SNP_ACTIVE: u64 = 1 << 0; +/// `SecureTSC`, bit 9: the PSP fixes the guest TSC scale and offset, so the +/// hypervisor can no longer intercept or skew the guest's TSC. +const SEV_FEATURE_SECURE_TSC: u64 = 1 << 9; + +/// `SEV_FEATURES` dstack launches an amd sev-snp guest with. +pub fn launch_guest_features(secure_tsc: bool) -> u64 { + if secure_tsc { + SEV_FEATURE_SNP_ACTIVE | SEV_FEATURE_SECURE_TSC + } else { + SEV_FEATURE_SNP_ACTIVE + } +} /// `SEV_FEATURES` bits a dstack launch may carry. /// @@ -55,16 +67,13 @@ const SEV_FEATURE_SNP_ACTIVE: u64 = 1 << 0; /// SecureTSC (bit 9) or VmsaRegProt (bit 14) likewise removes a guest-side /// protection the operator may believe is on. /// -/// dstack has exactly one launch path, and it sets no feature property: -/// `sev-snp-guest,id=sev0,policy=0x30000,...` in `dstack/vmm/src/app/qemu.rs`, -/// which leaves KVM to start the guest with `SNPActive` alone, and the VMM -/// writes the matching `guest_features: 1` into the measurement document -/// (`dstack/vmm/src/app.rs`). `1` is therefore the only value dstack has ever -/// produced — the captured real-hardware vector in this module's tests carries -/// it too — so it is the only value accepted. Widening this is a one-line -/// change once a launch path actually sets another bit; accepting bits nothing -/// emits would only ever admit a guest dstack did not configure. -const ALLOWED_GUEST_FEATURES: u64 = SEV_FEATURE_SNP_ACTIVE; +/// dstack has exactly one launch path, `sev-snp-guest,id=sev0,policy=0x30000,...` +/// in `dstack/vmm/src/app/qemu.rs`. It starts the guest with `SNPActive`, plus +/// `SecureTSC` when the app compose sets `secure_time`, and the VMM writes the +/// matching `guest_features` into the measurement document +/// (`dstack/vmm/src/app.rs`). Those are the only bits accepted; accepting bits +/// nothing emits would only ever admit a guest dstack did not configure. +const ALLOWED_GUEST_FEATURES: u64 = SEV_FEATURE_SNP_ACTIVE | SEV_FEATURE_SECURE_TSC; #[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)] #[serde(deny_unknown_fields)] @@ -150,7 +159,7 @@ pub fn validate_measurement_input(input: &MeasurementInput) -> Result<()> { if unexpected_features != 0 { bail!( "guest_features {:#x} carries unsupported SEV_FEATURES bits {unexpected_features:#x}; \ - dstack launches amd sev-snp guests with SNPActive only ({ALLOWED_GUEST_FEATURES:#x})", + dstack launches amd sev-snp guests with at most {ALLOWED_GUEST_FEATURES:#x}", input.guest_features ); } @@ -1657,7 +1666,7 @@ mod tests { let cases: [(&str, u64); 4] = [ ("RestrictedInjection", SNP_ACTIVE | (1 << 3)), ("DebugSwap", SNP_ACTIVE | (1 << 5)), - ("SecureTSC", SNP_ACTIVE | (1 << 9)), + ("VmsaRegProt", SNP_ACTIVE | (1 << 14)), ("reserved bit 63", SNP_ACTIVE | (1 << 63)), ]; for (name, features) in cases { @@ -1683,10 +1692,12 @@ mod tests { "unexpected error: {err}" ); - // The one value dstack's launch path produces stays accepted. - let mut input = valid_input(); - input.guest_features = SNP_ACTIVE; - validate_measurement_input(&input).expect("SNPActive-only launch is accepted"); + // The values dstack's launch path produces stay accepted. + for secure_tsc in [false, true] { + let mut input = valid_input(); + input.guest_features = launch_guest_features(secure_tsc); + validate_measurement_input(&input).expect("dstack launch features are accepted"); + } } #[test] diff --git a/dstack/dstack-mr/src/tdx.rs b/dstack/dstack-mr/src/tdx.rs index 7592fa5360..484121307a 100644 --- a/dstack/dstack-mr/src/tdx.rs +++ b/dstack/dstack-mr/src/tdx.rs @@ -20,9 +20,16 @@ use crate::tdvf::{ }; use crate::util::{measure_log, measure_sha384}; use anyhow::{bail, Context, Result}; +use cc_eventlog::{ + tdx::{ + TDX_ACPI_DATA_EVENT_PAYLOAD, TDX_ACPI_DATA_EVENT_TYPE, TDX_ACPI_LOADER_EVENT, + TDX_ACPI_RSDP_EVENT, TDX_ACPI_TABLES_EVENT, + }, + TdxEvent, +}; use dstack_types::{ - OvmfVariant, TdxImageMeasurement, TdxMrtdCandidates, TdxOsImageMeasurement, - TdxOsImageMeasurementDocument, TdxTdvfMeasurement, VmConfig, + OvmfVariant, TdxAttestationVariant, TdxImageMeasurement, TdxMrtdCandidates, + TdxOsImageMeasurement, TdxOsImageMeasurementDocument, TdxTdvfMeasurement, VmConfig, }; use fs_err as fs; use serde::Deserialize; @@ -485,6 +492,166 @@ pub fn tdx_measurements_from_measurement_document( }) } +fn rtmr0_acpi_hashes_from_event_log(event_log: &[TdxEvent]) -> Result { + let rtmr0_events = event_log + .iter() + .filter(|event| event.imr == 0) + .collect::>(); + let acpi_events = rtmr0_events + .iter() + .filter(|event| { + event.event_type == TDX_ACPI_DATA_EVENT_TYPE + && event.event_payload == TDX_ACPI_DATA_EVENT_PAYLOAD + }) + .collect::>(); + if acpi_events.len() != 3 { + bail!( + "TDX lite attestation requires exactly 3 RTMR0 ACPI DATA events; found {} candidates and {} RTMR0 events", + acpi_events.len(), + rtmr0_events.len() + ); + } + + let digest_for = |name: &str| -> Result> { + let matches = acpi_events + .iter() + .copied() + .filter(|event| event.event == name) + .collect::>(); + if matches.len() != 1 { + bail!( + "TDX lite attestation requires exactly one RTMR0 ACPI DATA event named {name}; found {}", + matches.len() + ); + } + let digest = matches[0].digest(); + if digest.len() != 48 { + bail!( + "TDX RTMR0 ACPI DATA event {name} has invalid digest length {}, expected 48", + digest.len() + ); + } + Ok(digest) + }; + + Ok(TdxRtmr0AcpiHashes { + loader: digest_for(TDX_ACPI_LOADER_EVENT)?, + rsdp: digest_for(TDX_ACPI_RSDP_EVENT)?, + tables: digest_for(TDX_ACPI_TABLES_EVENT)?, + }) +} + +/// Compare recomputed ACPI digests against the ones the guest reported. +/// +/// RTMR0 alone would already fail on a mismatch, but only with an opaque +/// "MRs do not match": name the offending table here so an operator can +/// tell a tampered table apart from an unexpected VM shape. +fn assert_tdx_acpi_hashes_match( + expected: &TdxRtmr0AcpiHashes, + reported: &TdxRtmr0AcpiHashes, +) -> Result<()> { + for (name, expected, reported) in [ + (TDX_ACPI_LOADER_EVENT, &expected.loader, &reported.loader), + (TDX_ACPI_RSDP_EVENT, &expected.rsdp, &reported.rsdp), + (TDX_ACPI_TABLES_EVENT, &expected.tables, &reported.tables), + ] { + if expected != reported { + bail!( + "TDX lite {name} digest mismatch: expected {}, reported {}", + hex::encode(expected), + hex::encode(reported) + ); + } + } + Ok(()) +} + +pub fn assert_tdx_mrs_eq( + expected: &crate::TdxMeasurements, + actual: &crate::TdxMeasurements, +) -> Result<()> { + for (name, expected, actual) in [ + ("MRTD", &expected.mrtd, &actual.mrtd), + ("RTMR0", &expected.rtmr0, &actual.rtmr0), + ("RTMR1", &expected.rtmr1, &actual.rtmr1), + ("RTMR2", &expected.rtmr2, &actual.rtmr2), + ] { + if expected != actual { + bail!( + "{name} mismatch: expected={}, actual={}", + hex::encode(expected), + hex::encode(actual) + ); + } + } + Ok(()) +} + +/// Verify a dstack TDX lite CVM's OS against already-verified MRTD/RTMR0-2. +/// +/// Regenerates the three RTMR0 ACPI digests from `vm_config` with qemu-acpi, +/// checks them against the named events in `event_log`, recomputes MRTD and +/// RTMR0-2 from `vm_config.tdx_measurement`, and compares them with +/// `verified_mrs`. Does not judge os_image_hash approval, DCAP quote validity, +/// or RTMR3: those stay the caller's job. +/// +/// This is the single source of truth used by `dstack-verifier` and the wasm +/// package. It takes only primitive, already-verified values so it can build +/// for wasm32 without tokio/reqwest/tempfile. +pub fn verify_tdx_lite_os( + verified_mrs: &crate::TdxMeasurements, + event_log: &[TdxEvent], + vm_config: &VmConfig, +) -> Result<()> { + if vm_config.tdx_attestation_variant != TdxAttestationVariant::Lite { + bail!("vm_config is not a TDX lite attestation"); + } + let document = vm_config + .tdx_measurement + .as_ref() + .context("tdx lite attestation requires vm_config.tdx_measurement")?; + document + .verify(&vm_config.os_image_hash) + .map_err(anyhow::Error::msg) + .context("tdx lite measurement material does not match os_image_hash")?; + let measurement = document + .decode_measurement() + .map_err(anyhow::Error::msg) + .context("failed to decode vm_config.tdx_measurement CBOR")?; + if let Some(config_ovmf_variant) = vm_config.ovmf_variant { + if config_ovmf_variant != measurement.tdvf.ovmf_variant { + bail!( + "tdx measurement ovmf_variant mismatch: vm_config={:?}, document={:?}", + config_ovmf_variant, + measurement.tdvf.ovmf_variant + ); + } + } + + // The guest labels the three RTMR0 ACPI DATA events as acpi-loader, + // acpi-rsdp, and acpi-tables before exposing the event log, so this does + // not guess based on event order. + let reported_acpi_hashes = rtmr0_acpi_hashes_from_event_log(event_log) + .context("TDX lite attestation is missing named RTMR0 ACPI DATA digests")?; + // Recompute the digests from the declared VM shape instead of trusting + // the reported ones, and treat both failure modes as fatal: a mismatch + // means the tables are not the ones this shape produces, and a shape + // the generator cannot model (`swtpm`, a QEMU older than any profile) + // leaves nothing to compare against. Downgrading either case to "pass, + // but unverified" would make the check optional at the host's + // discretion, because `swtpm` and `qemu_version` are host-declared + // fields that no other measurement independently constrains. + let acpi_hashes = expected_rtmr0_acpi_hashes(vm_config, measurement.tdvf.ovmf_variant) + .context("failed to recompute expected TDX lite ACPI table digests")?; + assert_tdx_acpi_hashes_match(&acpi_hashes, &reported_acpi_hashes)?; + // RTMR0 below is rebuilt from the recomputed digests, so the expected + // value depends on nothing the host reported about the tables. + let expected_mrs = + tdx_measurements_from_measurement_document(document, vm_config, &acpi_hashes) + .context("failed to compute TDX expected measurements without image download")?; + assert_tdx_mrs_eq(&expected_mrs, verified_mrs).context("MRs do not match") +} + /// Compute image-critical TDX measurements without RTMR[0]. /// /// RTMR[0] contains QEMU-generated ACPI blobs and other launch-environment @@ -862,4 +1029,190 @@ mod tests { .expect_err("a wrapping range end must be rejected"); assert!(err.contains("overflow"), "unexpected error: {err}"); } + + fn acpi_event(name: &str, digest_byte: u8) -> TdxEvent { + TdxEvent { + imr: 0, + event_type: TDX_ACPI_DATA_EVENT_TYPE, + digest: vec![digest_byte; 48], + event: name.to_string(), + event_payload: TDX_ACPI_DATA_EVENT_PAYLOAD.to_vec(), + version: Default::default(), + preimage: None, + } + } + + #[test] + fn tdx_lite_acpi_hashes_are_selected_by_event_name() { + let event_log = vec![ + acpi_event(TDX_ACPI_RSDP_EVENT, 2), + acpi_event(TDX_ACPI_TABLES_EVENT, 3), + acpi_event(TDX_ACPI_LOADER_EVENT, 1), + ]; + + let hashes = rtmr0_acpi_hashes_from_event_log(&event_log).expect("named ACPI hashes"); + + assert_eq!(hashes.loader, vec![1u8; 48]); + assert_eq!(hashes.rsdp, vec![2u8; 48]); + assert_eq!(hashes.tables, vec![3u8; 48]); + } + + #[test] + fn tdx_lite_acpi_hashes_reject_unlabeled_events() { + let event_log = vec![ + acpi_event("", 1), + acpi_event(TDX_ACPI_RSDP_EVENT, 2), + acpi_event(TDX_ACPI_TABLES_EVENT, 3), + ]; + + assert!(rtmr0_acpi_hashes_from_event_log(&event_log).is_err()); + } + + #[test] + fn tdx_lite_acpi_hash_mismatch_names_the_table() { + let expected = TdxRtmr0AcpiHashes { + loader: vec![1; 48], + rsdp: vec![2; 48], + tables: vec![3; 48], + }; + let mut reported = expected.clone(); + reported.tables = vec![4; 48]; + let err = assert_tdx_acpi_hashes_match(&expected, &reported) + .expect_err("mismatched tables digest is rejected"); + assert!(err.to_string().contains(TDX_ACPI_TABLES_EVENT), "{err:#}"); + assert!(assert_tdx_acpi_hashes_match(&expected, &expected).is_ok()); + } + + #[derive(serde::Deserialize)] + struct GetQuoteFixture { + quote: String, + event_log: String, + vm_config: String, + } + + fn tdx_lite_getquote_fixture() -> GetQuoteFixture { + serde_json::from_str(include_str!( + "../../verifier/fixtures/tdx-lite-getquote.json" + )) + .expect("TDX lite getquote fixture parses") + } + + fn mrs_from_quote_hex(quote_hex: &str) -> crate::TdxMeasurements { + let quote = hex::decode(quote_hex).expect("quote is hex"); + let quote = dcap_qvl::quote::Quote::parse("e).expect("fixture quote parses"); + let report = quote.report.as_td10().expect("TDX 1.0 report"); + crate::TdxMeasurements { + mrtd: report.mr_td.to_vec(), + rtmr0: report.rt_mr0.to_vec(), + rtmr1: report.rt_mr1.to_vec(), + rtmr2: report.rt_mr2.to_vec(), + } + } + + fn parse_fixture( + fixture: &GetQuoteFixture, + ) -> (crate::TdxMeasurements, Vec, VmConfig) { + let events: Vec = + serde_json::from_str(&fixture.event_log).expect("fixture event log parses"); + let vm_config: VmConfig = + serde_json::from_str(&fixture.vm_config).expect("fixture vm_config parses"); + (mrs_from_quote_hex(&fixture.quote), events, vm_config) + } + + #[test] + fn tdx_lite_getquote_fixture_is_accepted() { + let fixture = tdx_lite_getquote_fixture(); + let (mrs, events, vm_config) = parse_fixture(&fixture); + verify_tdx_lite_os(&mrs, &events, &vm_config).expect("captured TDX lite CVM verifies"); + } + + #[test] + fn tdx_lite_rejects_tampered_vm_shape() { + let fixture = tdx_lite_getquote_fixture(); + let (mrs, events, vm_config) = parse_fixture(&fixture); + let mut cases = Vec::new(); + + let mut tampered = vm_config.clone(); + tampered.memory_size = 4 * 1024 * 1024 * 1024; + cases.push(("memory_size", tampered)); + + let mut tampered = vm_config.clone(); + tampered.pci_hole64_size = if vm_config.pci_hole64_size == 0 { + 1 << 50 + } else { + 0 + }; + cases.push(("pci_hole64_size", tampered)); + + let mut tampered = vm_config.clone(); + tampered.hotplug_off = !vm_config.hotplug_off; + cases.push(("hotplug_off", tampered)); + + let mut tampered = vm_config.clone(); + tampered.num_nics = 2; + cases.push(("num_nics", tampered)); + + let mut tampered = vm_config.clone(); + tampered.cpu_count += 1; + cases.push(("cpu_count", tampered)); + + let mut tampered = vm_config.clone(); + tampered.qemu_version = Some("9.2.1".into()); + cases.push(("qemu_version", tampered)); + + for (name, tampered) in cases { + verify_tdx_lite_os(&mrs, &events, &tampered) + .expect_err(&format!("{name} tamper must be rejected")); + } + } + + #[test] + fn tdx_lite_rejects_tampered_acpi_event_and_rtmr2() { + let fixture = tdx_lite_getquote_fixture(); + let (mrs, mut events, vm_config) = parse_fixture(&fixture); + let index = events + .iter() + .position(|event| event.event == TDX_ACPI_TABLES_EVENT) + .expect("acpi-tables event"); + events[index].digest[0] ^= 0x01; + let err = verify_tdx_lite_os(&mrs, &events, &vm_config) + .expect_err("edited acpi-tables digest must be rejected"); + assert!( + format!("{err:#}").contains(TDX_ACPI_TABLES_EVENT), + "unexpected error: {err:#}" + ); + + let (mrs, events, vm_config) = parse_fixture(&fixture); + let mut mrs = mrs; + mrs.rtmr2 = vec![0; 48]; + let err = verify_tdx_lite_os(&mrs, &events, &vm_config) + .expect_err("zeroed RTMR2 must be rejected"); + assert!( + format!("{err:#}").contains("RTMR2"), + "unexpected error: {err:#}" + ); + } + + /// The captured VM ran 2 vCPUs; a VM shape that disagrees with the quote + /// must not reproduce its ACPI digests, which is what makes the recomputed + /// digests worth comparing in the first place. + #[test] + fn tdx_lite_acpi_hashes_depend_on_the_reported_vm_shape() { + let fixture = tdx_lite_getquote_fixture(); + let (_, events, mut vm_config) = parse_fixture(&fixture); + let ovmf_variant = vm_config.ovmf_variant.unwrap_or_default(); + + let reported = + rtmr0_acpi_hashes_from_event_log(&events).expect("fixture carries named ACPI digests"); + let expected = expected_rtmr0_acpi_hashes(&vm_config, ovmf_variant) + .expect("ACPI tables are generated for the fixture VM shape"); + assert_tdx_acpi_hashes_match(&expected, &reported) + .expect("recomputed digests match the captured CVM"); + + vm_config.cpu_count += 1; + let expected = expected_rtmr0_acpi_hashes(&vm_config, ovmf_variant) + .expect("ACPI tables are generated for the altered VM shape"); + assert_tdx_acpi_hashes_match(&expected, &reported) + .expect_err("an extra vCPU must change the ACPI tables"); + } } diff --git a/dstack/dstack-types/src/authorization.rs b/dstack/dstack-types/src/authorization.rs new file mode 100644 index 0000000000..876a4aa9c2 --- /dev/null +++ b/dstack/dstack-types/src/authorization.rs @@ -0,0 +1,71 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// +// SPDX-License-Identifier: Apache-2.0 + +//! Operations performed by the attested subject of an authorization request. + +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AuthorizationOperation { + KmsBootstrap, + KmsServe, + KmsExportKeys, + KmsImportKeys, + AppGetKey, + AppGetCert, +} + +impl AuthorizationOperation { + pub fn is_kms(self) -> bool { + matches!( + self, + Self::KmsBootstrap | Self::KmsServe | Self::KmsExportKeys | Self::KmsImportKeys + ) + } +} + +/// The `launchTicketHash` of `ticket`: `sha256("dstack-launch-ticket/v1:" || ticket)`. +/// +/// Shell equivalent: `printf 'dstack-launch-ticket/v1:%s' "$TICKET" | sha256sum`. +pub fn launch_ticket_hash(ticket: &str) -> [u8; 32] { + crate::sha256(format!("dstack-launch-ticket/v1:{ticket}").as_bytes()) +} + +/// Shortest launch ticket a KMS accepts. Its hash is public, so a short ticket +/// can be recovered offline; length alone cannot prove entropy, so generate +/// tickets randomly. +pub const LAUNCH_TICKET_MIN_LEN: usize = 32; +/// Longest launch ticket a KMS accepts; sys-config must stay small. +pub const LAUNCH_TICKET_MAX_LEN: usize = 1024; + +/// Refuse a ticket the KMS would refuse. Surrounding whitespace is refused +/// rather than trimmed: it changes the hash, so a pasted newline would +/// otherwise fail as an unknown ticket. +pub fn check_launch_ticket(ticket: &str) -> Result<(), String> { + if !(LAUNCH_TICKET_MIN_LEN..=LAUNCH_TICKET_MAX_LEN).contains(&ticket.len()) { + return Err(format!( + "launch ticket must be {LAUNCH_TICKET_MIN_LEN} to {LAUNCH_TICKET_MAX_LEN} bytes, got {}", + ticket.len() + )); + } + if ticket.trim() != ticket { + return Err("launch ticket has surrounding whitespace".into()); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Shared with vmm-cli's tests, which compute the hash the contracts allow. + #[test] + fn launch_ticket_hash_is_domain_separated() { + assert_eq!( + hex::encode(launch_ticket_hash(&"t".repeat(32))), + "8185a84114cfd5c0fb70e2233dee133cfa6467b58537ece8b27137828baabecc" + ); + } +} diff --git a/dstack/dstack-types/src/lib.rs b/dstack/dstack-types/src/lib.rs index a513d6401f..4f9cb36e56 100644 --- a/dstack/dstack-types/src/lib.rs +++ b/dstack/dstack-types/src/lib.rs @@ -14,6 +14,8 @@ use size_parser::human_size; /// infrastructure-provider initialization stages. pub const MAX_INIT_SCRIPTS: usize = 5; +pub mod authorization; + pub mod init_script_hashes { use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde_human_bytes::ByteBuf; @@ -421,16 +423,18 @@ pub struct GpuPolicy { /// array. It must define the boolean rule `data.policy.nv_match`. #[serde(default, skip_serializing_if = "Option::is_none")] pub rego: Option, - /// Permit NVIDIA DevTools mode. This defaults to false because DevTools - /// disables the GPU memory-confidentiality guarantees expected in - /// production. + /// Skip the NVML DevTools check. Defaults to false. A DevTools GPU still + /// fails attestation because DevTools changes its signed measurements. #[serde(default)] pub allow_devtools: bool, /// Permit claims whose GPU attestation debug status is `enabled`. Defaults - /// to false. + /// to false. No effect with current nvattest, which reports `disabled` + /// whenever `measres` is `success`. #[serde(default)] pub allow_debug: bool, /// Permit claims that do not assert GPU secure boot. Defaults to false. + /// No effect with current nvattest, which asserts it whenever `measres` + /// is `success`. #[serde(default)] pub allow_insecure_boot: bool, } @@ -533,6 +537,16 @@ pub struct Requirements { /// on chain. #[serde(default, skip_serializing_if = "Option::is_none")] pub health_status_file: Option, + /// Start every boot with an empty data disk. The guest formats the data + /// disk before any app code runs, discarding what earlier boots left on it. + #[serde(default, skip_serializing_if = "is_false")] + pub ephemeral_data_disk: bool, + /// Let the guest re-key a data disk left at older KMS key epochs instead + /// of refusing to boot on it. Strongly discouraged: re-keying keeps the + /// volume key, which the old root and any copy of the old LUKS header + /// reveal, so whoever holds them can read and modify the disk for good. + #[serde(default, skip_serializing_if = "is_false")] + pub unsafe_allow_disk_migration: bool, } impl Requirements { @@ -543,6 +557,8 @@ impl Requirements { && self.gpu_policy.is_default() && !self.health_check && self.health_status_file.is_none() + && !self.ephemeral_data_disk + && !self.unsafe_allow_disk_migration } } @@ -758,9 +774,64 @@ pub enum KeyProviderKind { Kms, Local, Tpm, + #[serde(rename = "sev-snp")] + SevSnp, + #[serde(rename = "tdx-seal")] + TdxSeal, +} + +/// Instance identity and public recovery metadata shared by the VMM and guest. +#[derive(Debug, Clone, Default, Deserialize, Serialize)] +pub struct InstanceInfo { + #[serde(default, with = "hex_bytes")] + pub instance_id_seed: Vec, + #[serde(default, with = "hex_bytes")] + pub instance_id: Vec, + #[serde(default, with = "hex_bytes")] + pub app_id: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub snp_sealing: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tdx_sealing: Option, +} + +/// Public parameters needed to reproduce the SNP sealing seed after a restart. +/// Version 1 fixes the root, guest fields, VMPL, and guest SVN in the provider. +#[serde_with::serde_as] +#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct SnpSealingParameters { + pub version: u32, + // A string preserves all 64 bits through JSON consumers using IEEE doubles. + #[serde_as(as = "serde_with::DisplayFromStr")] + pub tcb_version: u64, +} + +/// Public parameters needed to reproduce the TDX sealing seed after a restart. +/// Version 1 fixes the key policy, masks and salt in the provider. +#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct TdxSealingParameters { + pub version: u32, + #[serde(with = "hex_bytes")] + pub cpusvn: [u8; 16], + #[serde(with = "hex_bytes")] + pub tee_tcb_svn: [u8; 16], } impl KeyProviderKind { + /// Stable name used in measurements and key-provider events. + pub fn measurement_name(self) -> &'static str { + match self { + Self::None => "none", + Self::Local => "local-sgx", + Self::Kms => "kms", + Self::Tpm => "tpm", + Self::SevSnp => "sev-snp", + Self::TdxSeal => "tdx-seal", + } + } + pub fn is_none(&self) -> bool { matches!(self, KeyProviderKind::None) } @@ -801,6 +872,18 @@ impl AppCompose { self.key_provider().is_kms() } + pub fn ephemeral_data_disk(&self) -> bool { + self.requirements + .as_ref() + .is_some_and(|requirements| requirements.ephemeral_data_disk) + } + + pub fn unsafe_allow_disk_migration(&self) -> bool { + self.requirements + .as_ref() + .is_some_and(|requirements| requirements.unsafe_allow_disk_migration) + } + pub fn key_provider(&self) -> KeyProviderKind { match self.key_provider { Some(p) => p, @@ -1243,10 +1326,51 @@ pub struct SysConfig { /// string. #[serde(default, skip_serializing_if = "Option::is_none")] pub mr_config: Option, + /// Access control for the guest agent's external listener. Absent means + /// nothing anonymous and no external issuers. + /// + /// Host-supplied, and deliberately not measured: it decides who may *ask* + /// the agent, never whether data may leave the TEE. Confidentiality stays + /// with the measured `public_logs`/`public_sysinfo`/`public_tcbinfo` + /// switches in app-compose, which a token here cannot widen. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub guest_agent_api: Option, + /// Launch ticket the guest presents to the KMS, which checks its hash + /// against the app's on-chain allowlist before releasing keys. A secret + /// the host holds: unlike `vm_config`, it is never embedded in an + /// attestation or returned by the guest agent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub launch_ticket: Option, // JSON serialized VmConfig pub vm_config: String, } +#[derive(Deserialize, Serialize, Debug, Clone, Default, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct GuestAgentApiConfig { + /// Scopes granted to a caller that presents no token. + /// + /// Empty by default: an app that wants its dashboard on the internet has + /// to say so, in `vmm.toml` or in the guest's sys-config. What a host is + /// expected to open is spelled out in the sample `vmm.toml` rather than + /// here, so the shipped default stays visible where an operator sets it. + #[serde(default)] + pub anonymous_scopes: Vec, + /// Issuers other than the app's own root key. + #[serde(default)] + pub external_issuers: Vec, +} + +#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct ExternalJwtIssuer { + /// The exact `iss` claim tokens from this issuer must carry. + pub name: String, + /// Hex-encoded Ed25519 public keys. More than one so a key can be rotated + /// without a flag day. + pub public_keys: Vec, +} + #[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)] #[serde(deny_unknown_fields)] pub struct GatewayClusterConfig { @@ -1427,8 +1551,10 @@ fn is_false(value: &bool) -> bool { /// node order. #[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)] pub struct NumaNodeConfig { - /// Bus number of the node's `pxb-pcie` expander (its `bus_nr`). - pub pxb_bus: u8, + /// Bus number of the node's `pxb-pcie` expander (its `bus_nr`). Either + /// every node has one or none does, leaving all devices on the root bus. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pxb_bus: Option, } /// A device a host QEMU wrapper appends to the root PCIe bus. @@ -2350,6 +2476,8 @@ pub struct AppKeys { pub disk_crypt_key: Vec, #[serde(with = "hex_bytes", default)] pub env_crypt_key: Vec, + #[serde(with = "hex_bytes", default)] + pub sealed_env_key: Vec, #[serde(with = "hex_bytes")] pub k256_key: Vec, #[serde(with = "hex_bytes")] @@ -2359,6 +2487,24 @@ pub struct AppKeys { pub key_provider: KeyProvider, } +impl AppKeys { + pub fn app_epoch(&self) -> u32 { + match self.key_provider { + KeyProvider::Kms { app_epoch, .. } => app_epoch, + _ => 0, + } + } + + /// KMS root epoch the keys were derived from; 0 for other key providers, + /// which have a single root. + pub fn root_epoch(&self) -> u32 { + match self.key_provider { + KeyProvider::Kms { root_epoch, .. } => root_epoch, + _ => 0, + } + } +} + /// Maximum length of a framed message exchanged with the local key provider. pub const KEY_PROVIDER_MAX_FRAME_SIZE: usize = 8 * 1024 * 1024; @@ -2377,12 +2523,21 @@ pub enum KeyProvider { #[serde(with = "hex_bytes")] pubkey: Vec, }, + SevSnp { + key: String, + }, + TdxSeal { + key: String, + }, Kms { url: String, #[serde(with = "hex_bytes")] pubkey: Vec, - tmp_ca_key: String, - tmp_ca_cert: String, + /// KMS root key epoch the keys were derived from. + #[serde(default)] + root_epoch: u32, + #[serde(default)] + app_epoch: u32, }, } @@ -2392,6 +2547,8 @@ impl KeyProvider { KeyProvider::None { .. } => KeyProviderKind::None, KeyProvider::Local { .. } => KeyProviderKind::Local, KeyProvider::Tpm { .. } => KeyProviderKind::Tpm, + KeyProvider::SevSnp { .. } => KeyProviderKind::SevSnp, + KeyProvider::TdxSeal { .. } => KeyProviderKind::TdxSeal, KeyProvider::Kms { .. } => KeyProviderKind::Kms, } } @@ -2404,11 +2561,14 @@ impl KeyProvider { /// (from a TPM-sealed seed) and must not be treated as a stable provider id /// or measured as one. Mode is already carried by [`Self::kind`]. /// - None: empty + /// - SNP, TDX seal: empty; the fixed hardware policy is identified by the + /// provider kind pub fn id(&self) -> &[u8] { match self { KeyProvider::None { .. } => &[], KeyProvider::Local { mr, .. } => mr, KeyProvider::Tpm { .. } => &[], + KeyProvider::SevSnp { .. } | KeyProvider::TdxSeal { .. } => &[], KeyProvider::Kms { pubkey, .. } => pubkey, } } @@ -2430,6 +2590,113 @@ impl KeyProviderInfo { mod key_provider_tests { use super::*; + #[test] + fn sev_snp_provider_has_no_instance_dependent_id() { + let provider: KeyProvider = + serde_json::from_str(r#"{"SevSnp":{"key":"test-only"}}"#).unwrap(); + assert_eq!(provider.kind(), KeyProviderKind::SevSnp); + assert!(provider.id().is_empty()); + assert_eq!( + serde_json::to_string(&provider.kind()).unwrap(), + r#""sev-snp""# + ); + assert_eq!(provider.kind().measurement_name(), "sev-snp"); + for obsolete_name in ["snp", "sev_snp"] { + assert!( + serde_json::from_value::(serde_json::json!(obsolete_name)) + .is_err() + ); + } + let compose: AppCompose = serde_json::from_value(serde_json::json!({ + "name": "snp-test", "runner": "docker-compose", "manifest_version": "3", "docker_compose_file": "", "key_provider": "sev-snp" + })) + .unwrap(); + assert_eq!(compose.key_provider(), KeyProviderKind::SevSnp); + assert!(!compose.kms_enabled()); + } + + #[test] + fn legacy_instance_metadata_encoding_is_unchanged() { + let raw = r#"{"instance_id_seed":"0102","instance_id":"03","app_id":"04"}"#; + let info: InstanceInfo = serde_json::from_str(raw).unwrap(); + assert_eq!(info.instance_id_seed, [1, 2]); + assert!(info.snp_sealing.is_none()); + assert_eq!(serde_json::to_string(&info).unwrap(), raw); + let empty: InstanceInfo = serde_json::from_str("{}").unwrap(); + assert!(empty.app_id.is_empty()); + } + + #[test] + fn snp_metadata_preserves_full_tcb_precision() { + let metadata = SnpSealingParameters { + version: 1, + tcb_version: u64::MAX - 1, + }; + let encoded = serde_json::to_value(metadata).unwrap(); + assert_eq!(encoded["tcb_version"], (u64::MAX - 1).to_string()); + assert_eq!( + serde_json::from_value::(encoded).unwrap(), + metadata + ); + assert!( + serde_json::from_str::(r#"{"version":1,"tcb_version":1}"#) + .is_err() + ); + assert!(serde_json::from_str::( + r#"{"version":1,"tcb_version":"1","root_key_select":0}"# + ) + .is_err()); + } + + #[test] + fn tdx_seal_provider_and_metadata_encoding() { + let compose: AppCompose = serde_json::from_value(serde_json::json!({ + "name": "tdx-seal-test", "runner": "docker-compose", "manifest_version": "3", "docker_compose_file": "", "key_provider": "tdx-seal" + })) + .unwrap(); + assert_eq!(compose.key_provider(), KeyProviderKind::TdxSeal); + assert_eq!(compose.key_provider().measurement_name(), "tdx-seal"); + let raw = format!( + r#"{{"instance_id_seed":"","instance_id":"","app_id":"","tdx_sealing":{{"version":1,"cpusvn":"{}","tee_tcb_svn":"{}"}}}}"#, + "08".repeat(16), + "09".repeat(16) + ); + let info: InstanceInfo = serde_json::from_str(&raw).unwrap(); + assert_eq!( + info.tdx_sealing, + Some(TdxSealingParameters { + version: 1, + cpusvn: [8; 16], + tee_tcb_svn: [9; 16], + }) + ); + assert_eq!(serde_json::to_string(&info).unwrap(), raw); + assert!(serde_json::from_str::( + r#"{"version":1,"cpusvn":"00","tee_tcb_svn":"00"}"# + ) + .is_err()); + } + + #[test] + fn legacy_kms_provider_drops_temp_ca_material_when_reserialized() { + let provider: KeyProvider = serde_json::from_value(serde_json::json!({ + "Kms": { + "url": "https://kms.example/prpc", + "pubkey": "abcd", + "tmp_ca_key": "obsolete test key", + "tmp_ca_cert": "obsolete test certificate" + } + })) + .unwrap(); + assert_eq!(provider.id(), &[0xab, 0xcd]); + assert_eq!( + serde_json::to_value(provider).unwrap(), + serde_json::json!({ + "Kms": { "url": "https://kms.example/prpc", "pubkey": "abcd", "root_epoch": 0, "app_epoch": 0 } + }) + ); + } + #[test] fn tpm_key_provider_id_is_empty() { let tpm = KeyProvider::Tpm { @@ -2442,10 +2709,10 @@ mod key_provider_tests { assert_eq!(tpm.kind(), KeyProviderKind::Tpm); let kms = KeyProvider::Kms { + app_epoch: 0, url: "https://kms.example".into(), pubkey: vec![0xab; 32], - tmp_ca_key: String::new(), - tmp_ca_cert: String::new(), + root_epoch: 0, }; assert_eq!(kms.id(), &[0xab; 32]); } @@ -2477,6 +2744,7 @@ pub struct ImageInfo { } pub mod mr_config; +pub mod root_epoch; pub mod sha256sum; pub mod shared_filenames; pub mod version; @@ -2656,6 +2924,26 @@ mod vm_config_device_count_tests { ); } + #[test] + fn numa_nodes_keep_their_legacy_serialization() { + let mut json = legacy_json(); + json["numa_nodes"] = serde_json::json!([{ "pxb_bus": 5 }, { "pxb_bus": 10 }]); + let cfg: VmConfig = serde_json::from_value(json.clone()).unwrap(); + assert_eq!(cfg.numa_nodes[1].pxb_bus, Some(10)); + assert_eq!( + serde_json::to_value(&cfg).unwrap()["numa_nodes"], + json["numa_nodes"] + ); + + json["numa_nodes"] = serde_json::json!([{}, {}]); + let cfg: VmConfig = serde_json::from_value(json.clone()).unwrap(); + assert_eq!(cfg.numa_nodes[0].pxb_bus, None); + assert_eq!( + serde_json::to_value(&cfg).unwrap()["numa_nodes"], + json["numa_nodes"] + ); + } + #[test] fn swtpm_is_serialized_only_when_enabled() { let mut cfg: VmConfig = serde_json::from_value(legacy_json()).unwrap(); diff --git a/dstack/dstack-types/src/mr_config.rs b/dstack/dstack-types/src/mr_config.rs index d11c3a5aa0..d1cb4f347d 100644 --- a/dstack/dstack-types/src/mr_config.rs +++ b/dstack/dstack-types/src/mr_config.rs @@ -32,6 +32,8 @@ fn key_provider_kind_byte(key_provider: KeyProviderKind) -> u8 { KeyProviderKind::Local => 1, KeyProviderKind::Kms => 2, KeyProviderKind::Tpm => 3, + KeyProviderKind::SevSnp => 4, + KeyProviderKind::TdxSeal => 5, } } @@ -194,12 +196,7 @@ impl MrConfigV3 { } pub fn key_provider_name(&self) -> &'static str { - match self.key_provider { - KeyProviderKind::None => "none", - KeyProviderKind::Local => "local-sgx", - KeyProviderKind::Kms => "kms", - KeyProviderKind::Tpm => "tpm", - } + self.key_provider.measurement_name() } } @@ -207,6 +204,39 @@ impl MrConfigV3 { mod tests { use super::*; + #[test] + fn sev_snp_provider_is_distinct_without_changing_legacy_codes() { + let providers = [ + KeyProviderKind::None, + KeyProviderKind::Local, + KeyProviderKind::Kms, + KeyProviderKind::Tpm, + KeyProviderKind::SevSnp, + KeyProviderKind::TdxSeal, + ]; + for (code, provider) in providers.into_iter().enumerate() { + assert_eq!(key_provider_kind_byte(provider), code as u8); + } + let snp = MrConfigV3::new( + vec![1; 20], + vec![2; 32], + None, + KeyProviderKind::SevSnp, + vec![], + vec![3; 20], + ); + let mut other = snp.clone(); + other.key_provider = KeyProviderKind::None; + assert_eq!(snp.key_provider_name(), "sev-snp"); + let document = snp.to_canonical_json(); + assert_eq!( + serde_json::from_str::(&document).unwrap()["key_provider"], + "sev-snp" + ); + assert_eq!(MrConfigV3::from_document(&document).unwrap(), snp); + assert_ne!(snp.to_snp_host_data(), other.to_snp_host_data()); + } + #[test] fn mr_config_v3_hash_changes_with_app_identity() { let config = MrConfigV3::new( diff --git a/dstack/dstack-types/src/root_epoch.rs b/dstack/dstack-types/src/root_epoch.rs new file mode 100644 index 0000000000..a289d5be18 --- /dev/null +++ b/dstack/dstack-types/src/root_epoch.rs @@ -0,0 +1,57 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// +// SPDX-License-Identifier: Apache-2.0 + +//! KMS root epoch chain hashes, computed as the DstackKms contract does. + +use sha3::{Digest, Keccak256}; + +/// Chain hashes of root epochs 0, 1, ... given each epoch's +/// `(ca_pubkey, k256_pubkey)`. Epoch `n`'s hash is +/// `keccak256(previous || keccak256(ca_pubkey) || keccak256(k256_pubkey))` +/// with a zero previous hash for epoch 0, so it commits to every key up to `n`; +/// the position in the chain fixes the epoch number. +pub fn chain_hashes<'a>(epochs: impl IntoIterator) -> Vec<[u8; 32]> { + let mut previous = [0u8; 32]; + epochs + .into_iter() + .map(|(ca_pubkey, k256_pubkey)| { + previous = Keccak256::new() + .chain_update(previous) + .chain_update(Keccak256::digest(ca_pubkey)) + .chain_update(Keccak256::digest(k256_pubkey)) + .finalize() + .into(); + previous + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Well-formed root public keys whose point bytes are all `fill`. + fn test_keys(ca_fill: u8, k256_fill: u8) -> (Vec, Vec) { + let mut ca = hex::decode("3059301306072a8648ce3d020106082a8648ce3d03010703420004").unwrap(); + ca.resize(91, ca_fill); + let mut k256 = vec![0x02]; + k256.resize(33, k256_fill); + (ca, k256) + } + + /// Shared with the DstackKms contract and dstack-auth tests. + #[test] + fn matches_the_contract_vectors() { + let epochs = [test_keys(0xa0, 0xb0), test_keys(0xa1, 0xb1)]; + let hashes = chain_hashes(epochs.iter().map(|(ca, k256)| (&ca[..], &k256[..]))); + assert_eq!( + hex::encode(hashes[0]), + "10ab6b6c8e7601901b0f1767985bf40d35bf3129e0866fe12dcc7c8f04a298f2" + ); + assert_eq!( + hex::encode(hashes[1]), + "50152a82023f2219a31723b476c13bc5f608ab4147946dabdec15d4f3d648ed4" + ); + } +} diff --git a/dstack/dstack-types/src/shared_filenames.rs b/dstack/dstack-types/src/shared_filenames.rs index 79944cff61..77c9d0cf68 100644 --- a/dstack/dstack-types/src/shared_filenames.rs +++ b/dstack/dstack-types/src/shared_filenames.rs @@ -8,6 +8,7 @@ pub const SYS_CONFIG: &str = ".sys-config.json"; pub const TEE_SIMULATOR_CONFIG: &str = ".tee-simulator.json"; pub const USER_CONFIG: &str = ".user-config"; pub const ENCRYPTED_ENV: &str = ".encrypted-env"; +pub const SEALED_ENV: &str = ".sealed-env"; pub const DECRYPTED_ENV: &str = ".decrypted-env"; pub const DECRYPTED_ENV_JSON: &str = ".decrypted-env.json"; pub const INSTANCE_INFO: &str = ".instance_info"; diff --git a/dstack/dstack-util/Cargo.toml b/dstack/dstack-util/Cargo.toml index a38f02f411..f55d5b84f2 100644 --- a/dstack/dstack-util/Cargo.toml +++ b/dstack/dstack-util/Cargo.toml @@ -19,18 +19,21 @@ fs-err.workspace = true getrandom = { workspace = true, features = ["std"] } hex.workspace = true hex_fmt.workspace = true +hpke.workspace = true regex.workspace = true scale = { workspace = true, features = ["derive"] } schnorrkel.workspace = true serde.workspace = true serde-human-bytes.workspace = true serde_json.workspace = true +serde_with.workspace = true sd-notify.workspace = true sha2.workspace = true tokio = { workspace = true, features = ["full"] } tracing.workspace = true tracing-subscriber.workspace = true url.workspace = true +zeroize.workspace = true x25519-dalek.workspace = true dstack-kms-rpc.workspace = true @@ -39,6 +42,7 @@ ra-tls = { workspace = true, features = ["quote"] } dstack-gateway-rpc.workspace = true tdx-attest.workspace = true tpm-attest.workspace = true +sev-snp-attest.workspace = true tpm2.workspace = true tpm-qvl = { workspace = true, features = ["crl-download"] } host-api = { workspace = true, features = ["client"] } @@ -47,6 +51,7 @@ cmd_lib.workspace = true toml.workspace = true dcap-qvl.workspace = true k256 = { workspace = true, features = ["ecdsa"] } +dstack-api-auth.workspace = true dstack-types.workspace = true rand.workspace = true regorus.workspace = true @@ -59,7 +64,6 @@ bollard.workspace = true binrw.workspace = true sodiumbox.workspace = true libc.workspace = true -luks2.workspace = true nvml-wrapper.workspace = true lspci.workspace = true scopeguard.workspace = true @@ -68,7 +72,8 @@ ez-hash.workspace = true cc-eventlog.workspace = true safe-write.workspace = true errify.workspace = true +base64.workspace = true +value-spec.workspace = true [dev-dependencies] -base64.workspace = true rand.workspace = true diff --git a/dstack/dstack-util/src/crypto.rs b/dstack/dstack-util/src/crypto.rs index 1f8227f5bb..4f492b5a3a 100644 --- a/dstack/dstack-util/src/crypto.rs +++ b/dstack/dstack-util/src/crypto.rs @@ -68,6 +68,35 @@ pub fn dh_decrypt(secret: [u8; 32], ciphertext: &[u8]) -> Result> { .map_err(|e| anyhow!("Decryption failed: {}", e)) } +/// Encrypt to `remote_public_key` in the format [`dh_decrypt`] reads: +/// ephemeral public key, IV, then the AES-GCM ciphertext. +#[cfg(test)] +pub fn dh_encrypt(remote_public_key: [u8; 32], plaintext: &[u8]) -> Result> { + let mut ephemeral_secret = [0u8; 32]; + getrandom::fill(&mut ephemeral_secret).context("failed to generate ephemeral secret")?; + let ephemeral_secret = StaticSecret::from(ephemeral_secret); + let shared_secret = ephemeral_secret + .diffie_hellman(&PublicKey::from(remote_public_key)) + .to_bytes(); + ensure!( + !shared_secret.iter().all(|byte| *byte == 0), + "invalid X25519 shared secret" + ); + let cipher = Aes256Gcm::new_from_slice(&shared_secret) + .map_err(|e| anyhow!("failed to create cipher: {e}"))?; + let mut iv = [0u8; 12]; + getrandom::fill(&mut iv).context("failed to generate IV")?; + let ciphertext = cipher + .encrypt(Nonce::::from_slice(&iv), plaintext) + .map_err(|e| anyhow!("encryption failed: {e}"))?; + Ok([ + PublicKey::from(&ephemeral_secret).as_bytes(), + &iv[..], + &ciphertext, + ] + .concat()) +} + fn stream_nonce(prefix: &[u8; 8], index: u32) -> [u8; 12] { let mut nonce = [0u8; 12]; nonce[..8].copy_from_slice(prefix); @@ -266,6 +295,15 @@ pub fn dh_decrypt_stream( mod tests { use super::*; + #[test] + fn dh_encrypt_round_trips_through_dh_decrypt() { + let secret = [7u8; 32]; + let public = PublicKey::from(&StaticSecret::from(secret)).to_bytes(); + let ciphertext = dh_encrypt(public, b"env").unwrap(); + assert_eq!(dh_decrypt(secret, &ciphertext).unwrap(), b"env"); + assert!(dh_decrypt([8u8; 32], &ciphertext).is_err()); + } + #[test] fn test_dh_agree() { use rand::Rng; @@ -361,3 +399,95 @@ mod tests { .is_err()); } } + +/// Encrypt a sealed environment with HPKE DHKEM(X25519, HKDF-SHA256) and AES-256-GCM. +pub fn sealed_env_encrypt(public_key: &[u8], info: &[u8], plaintext: &[u8]) -> Result> { + use hpke::{ + aead::AesGcm256, kdf::HkdfSha256, kem::X25519HkdfSha256, Deserializable, OpModeS, + Serializable, + }; + let public_key = ::PublicKey::from_bytes(public_key) + .map_err(|_| anyhow!("invalid sealed env public key"))?; + let (enc, ciphertext) = hpke::single_shot_seal::( + &OpModeS::Base, + &public_key, + info, + plaintext, + &[], + ) + .map_err(|e| anyhow!("sealed env encryption failed: {e}"))?; + Ok([enc.to_bytes().as_ref(), ciphertext.as_slice()].concat()) +} + +/// Decrypt a sealed environment HPKE payload. +pub fn sealed_env_decrypt(secret: &[u8], info: &[u8], payload: &[u8]) -> Result> { + use hpke::{aead::AesGcm256, kdf::HkdfSha256, kem::X25519HkdfSha256, Deserializable, OpModeR}; + let enc = payload + .get(..32) + .ok_or_else(|| anyhow!("sealed env payload is missing encapsulated key"))?; + let ciphertext = payload + .get(32..) + .ok_or_else(|| anyhow!("sealed env payload is missing ciphertext"))?; + let secret = ::PrivateKey::from_bytes(secret) + .map_err(|_| anyhow!("invalid sealed env private key"))?; + let enc = ::EncappedKey::from_bytes(enc) + .map_err(|_| anyhow!("invalid sealed env encapsulated key"))?; + hpke::single_shot_open::( + &OpModeR::Base, + &secret, + &enc, + info, + ciphertext, + &[], + ) + .map_err(|e| anyhow!("sealed env decryption failed: {e}")) +} + +#[cfg(test)] +mod sealed_env_tests { + use super::*; + + #[test] + fn opens_sdk_envelopes() { + use base64::Engine as _; + for source in [ + include_str!("../../../sdk/fixtures/sealed-env/python.json"), + include_str!("../../../sdk/fixtures/sealed-env/javascript.json"), + ] { + let fixture: serde_json::Value = serde_json::from_str(source).unwrap(); + let envelope = &fixture["sealed_env"]; + let decode = |name: &str| { + base64::engine::general_purpose::STANDARD + .decode(envelope[name].as_str().unwrap()) + .unwrap() + }; + let payload = [decode("enc"), decode("ciphertext")].concat(); + let plaintext = sealed_env_decrypt( + &hex::decode(fixture["private_key"].as_str().unwrap()).unwrap(), + b"dstack-sealed-env-v1:3:0", + &payload, + ) + .unwrap(); + let decoded: serde_json::Value = serde_json::from_slice(&plaintext).unwrap(); + assert_eq!(decoded["env"], fixture["env"]); + } + } + + #[test] + fn sealed_env_round_trips_and_binds_info() { + let secret = StaticSecret::random_from_rng(rand::thread_rng()); + let public = PublicKey::from(&secret).to_bytes(); + let info = b"dstack-sealed-env-v1:3:0"; + let payload = sealed_env_encrypt(&public, info, b"secret env").unwrap(); + assert_eq!( + sealed_env_decrypt(&secret.to_bytes(), info, &payload).unwrap(), + b"secret env" + ); + assert!( + sealed_env_decrypt(&secret.to_bytes(), b"dstack-sealed-env-v1:4:0", &payload).is_err() + ); + let mut tampered = payload; + *tampered.last_mut().unwrap() ^= 1; + assert!(sealed_env_decrypt(&secret.to_bytes(), info, &tampered).is_err()); + } +} diff --git a/dstack/dstack-util/src/host_api.rs b/dstack/dstack-util/src/host_api.rs index e038ea3b26..078963251d 100644 --- a/dstack/dstack-util/src/host_api.rs +++ b/dstack/dstack-util/src/host_api.rs @@ -10,7 +10,7 @@ use dstack_types::{ Platform, }; use host_api::{ - client::{new_client, DefaultClient}, + client::{new_client, DefaultClient, StatusError}, Notification, }; use ra_tls::attestation::validate_tcb; @@ -28,6 +28,7 @@ pub(crate) struct KeyProvision { pub(crate) struct HostApi { client: Option, pccs_url: Option, + platform: Platform, } impl Default for HostApi { @@ -41,9 +42,15 @@ impl HostApi { Self { client: base_url.map(new_client), pccs_url, + platform: Platform::detect_or_dstack(), } } + #[cfg(test)] + pub fn on_platform(self, platform: Platform) -> Self { + Self { platform, ..self } + } + pub fn load_or_default(url: Option) -> Result { let api = match url { Some(url) => Self::new(Some(url), None), @@ -58,7 +65,7 @@ impl HostApi { } pub async fn notify(&self, event: &str, payload: &str) -> Result<()> { - match Platform::detect_or_dstack() { + match self.platform { Platform::Dstack => {} Platform::Gcp | Platform::NitroEnclave | Platform::AwsEc2 => { // Skip notify on unsupported platforms @@ -80,6 +87,29 @@ impl HostApi { Ok(()) } + /// Close the host's env update window for this boot, handing it the env + /// re-encrypted to the current root epoch, or an empty one when nothing + /// changed. An error means the window may still be open. + pub async fn update_sealed_env(&self, sealed_env: Vec) -> Result<()> { + if !matches!(self.platform, Platform::Dstack) { + return Ok(()); + } + let Some(client) = &self.client else { + return Ok(()); + }; + let response = tokio::time::timeout( + HOST_API_TIMEOUT, + client.update_sealed_env(host_api::SealedEnv { sealed_env }), + ) + .await + .context("Timed out updating the sealed env on the host")?; + match response { + // A VMM predating UpdateSealedEnv has no window to close. + Err(err) if is_unknown_method(&err) => Ok(()), + response => response.map(drop), + } + } + pub async fn notify_q(&self, event: &str, payload: &str) { if let Err(err) = self.notify(event, payload).await { warn!("Failed to notify event {event} to host: {:?}", err); @@ -141,3 +171,87 @@ impl HostApi { Ok(KeyProvision { sk, mr }) } } + +/// Whether the host does not implement the method at all: a VMM since 0.6 +/// answers 404, and older ones 400 with the pRPC dispatcher's fixed +/// "Service not found" message. +fn is_unknown_method(err: &anyhow::Error) -> bool { + err.chain() + .find_map(|cause| cause.downcast_ref::()) + .is_some_and(|err| { + err.status == 404 + || (err.status == 400 + && err + .message + .as_deref() + .is_some_and(|message| message.starts_with("Service not found: "))) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::{Read, Write}; + + /// A host API answering one request with `status` and a JSON `body`. + fn host(status: u16, body: String) -> HostApi { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let mut request = Vec::new(); + let mut chunk = [0; 4096]; + while !request.windows(4).any(|w| w == b"\r\n\r\n") { + let read = stream.read(&mut chunk).unwrap(); + request.extend_from_slice(&chunk[..read]); + } + write!( + stream, + "HTTP/1.1 {status} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ) + .unwrap(); + }); + HostApi::new(Some(url), None).on_platform(Platform::Dstack) + } + + #[tokio::test] + async fn only_an_answer_or_a_host_without_a_window_closes_the_env_window() { + let unknown = r#"{"error":"Service not found: UpdateSealedEnv"}"#; + for (status, body, closed) in [ + (200, "", true), + // A VMM since 0.6, and one before, that does not know the method. + (404, unknown, true), + (400, unknown, true), + // Anything else may leave the window open. + (400, r#"{"error":"VM not found"}"#, false), + (500, "{}", false), + ] { + let result = host(status, body.into()) + .update_sealed_env(b"env".to_vec()) + .await; + assert_eq!(result.is_ok(), closed, "{status} {body}"); + } + // No host listening at all. + let gone = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}", gone.local_addr().unwrap()); + drop(gone); + assert!(HostApi::new(Some(url.clone()), None) + .on_platform(Platform::Dstack) + .update_sealed_env(Vec::new()) + .await + .is_err()); + // Off dstack there is no window to close, and no host is asked. + HostApi::new(Some(url), None) + .on_platform(Platform::Gcp) + .update_sealed_env(Vec::new()) + .await + .unwrap(); + // No host API configured means no window. + HostApi::new(None, None) + .on_platform(Platform::Dstack) + .update_sealed_env(Vec::new()) + .await + .unwrap(); + } +} diff --git a/dstack/dstack-util/src/main.rs b/dstack/dstack-util/src/main.rs index 87867085bf..9501f413df 100644 --- a/dstack/dstack-util/src/main.rs +++ b/dstack/dstack-util/src/main.rs @@ -2,7 +2,7 @@ // // SPDX-License-Identifier: Apache-2.0 -use anyhow::{Context, Result}; +use anyhow::{bail, Context, Result}; use clap::{Parser, Subcommand}; use dstack_attest::emit_runtime_event; use dstack_types::{KeyProvider, KeyProviderKind}; @@ -14,7 +14,7 @@ use k256::schnorr::SigningKey; use ra_rpc::Attestation; use ra_tls::{ attestation::{AttestationQuote, QuoteContentType, VersionedAttestation}, - cert::{generate_ra_cert, generate_ra_cert_with_app_id}, + cert::{generate_ra_cert, generate_self_signed_ra_cert}, kdf::{derive_key, derive_p256_key_pair_from_bytes}, rcgen::KeyPair, }; @@ -106,6 +106,26 @@ enum Commands { GpuInfo, /// Exec a command with extra environment variables from a JSON object file ExecWithEnv(ExecWithEnvArgs), + /// Check environment variables of this process against value specs + ValidateEnv(ValidateEnvArgs), + /// Copy environment variables from `env` in the user config into the env file + ImportEnv(ImportEnvArgs), +} + +#[derive(Parser)] +struct ValidateEnvArgs { + /// App compose file whose `allowed_envs` specs also apply + #[arg(long)] + compose: Option, + /// JSON object mapping variable names to values, checked instead of the environment + #[arg(long)] + env_file: Option, + /// Accept variables that no spec or `allowed_envs` entry names + #[arg(long)] + allow_unlisted: bool, + /// Variables to allow, as `NAME` or `NAME: spec`; an unset variable counts as empty + #[arg(required_unless_present = "compose", value_parser = env_spec)] + specs: Vec, } #[derive(Parser)] @@ -113,11 +133,144 @@ struct ExecWithEnvArgs { /// JSON object mapping variable names to values #[arg(long)] env_file: PathBuf, + /// App compose file; variables must be in its `allowed_envs` and match the specs there + #[arg(long)] + compose: Option, /// Command to exec, with its arguments #[arg(last = true, required = true)] command: Vec, } +#[derive(Parser)] +struct ImportEnvArgs { + /// Import every variable under `env` in the user config + #[arg(long, conflicts_with = "names")] + all: bool, + /// User config holding the variables under `env` [default: .user-config in the host-shared dir] + #[arg(long)] + user_config: Option, + /// JSON object of variables to merge into [default: .decrypted-env.json in the host-shared + /// dir, with .decrypted-env beside it rewritten to match] + #[arg(long)] + env_file: Option, + /// App compose file whose `allowed_envs` permits and constrains the variables + /// [default: app-compose.json in the host-shared dir] + #[arg(long)] + compose: Option, + /// Variables to import + #[arg(required_unless_present = "all")] + names: Vec, +} + +type Envs = std::collections::BTreeMap; + +#[derive(serde::Deserialize, Default)] +struct UserConfig { + #[serde(default)] + env: Envs, +} + +fn load_envs(path: &Path) -> Result { + utils::deserialize_json_file(path) + .with_context(|| format!("failed to load env from {}", path.display())) +} + +fn load_allowed_envs(path: &Path) -> Result> { + let compose: utils::AppCompose = utils::deserialize_json_file(path) + .with_context(|| format!("failed to load app compose from {}", path.display()))?; + Ok(compose.allowed_envs) +} + +/// A bare name on the command line must be a variable name too, so that a mistyped +/// `:` is not taken as a name that no variable has. +fn env_spec(entry: &str) -> Result { + let (name, _) = value_spec::split_named(entry)?; + value_spec::check_name(name)?; + Ok(entry.into()) +} + +fn cmd_validate_env(args: ValidateEnvArgs) -> Result<()> { + let mut not_utf8 = Vec::new(); + let envs = match &args.env_file { + Some(path) => load_envs(path)?, + None => std::env::vars_os() + .filter_map( + |(name, value)| match (name.into_string(), value.into_string()) { + (Ok(name), Ok(value)) => Some((name, value)), + (name, _) => { + not_utf8 + .push(name.unwrap_or_else(|name| name.to_string_lossy().into_owned())); + None + } + }, + ) + .collect(), + }; + let mut entries = args.specs; + if let Some(compose) = &args.compose { + entries.extend(load_allowed_envs(compose)?); + } + let allowed = parse_env_file::parse_allowed_envs(&entries)?; + let checked = |name: &&String| !args.allow_unlisted || allowed.contains_key(*name); + if let Some(name) = not_utf8.iter().find(checked) { + bail!("env {name} is not valid UTF-8"); + } + if !args.allow_unlisted { + parse_env_file::check_names(&allowed, envs.keys())?; + } + parse_env_file::check_env(&allowed, |name| envs.get(name).cloned()) +} + +fn cmd_import_env(args: ImportEnvArgs) -> Result<()> { + use dstack_types::shared_filenames::{ + host_shared_dir, APP_COMPOSE, DECRYPTED_ENV, DECRYPTED_ENV_JSON, USER_CONFIG, + }; + + let shared = host_shared_dir(); + let user_config = args.user_config.unwrap_or_else(|| shared.join(USER_CONFIG)); + let shell_env_file = args.env_file.is_none().then(|| shared.join(DECRYPTED_ENV)); + let env_file = args + .env_file + .unwrap_or_else(|| shared.join(DECRYPTED_ENV_JSON)); + let compose = args.compose.unwrap_or_else(|| shared.join(APP_COMPOSE)); + + // The VMM writes no user config file for an empty user config. + let mut source = match fs::read_to_string(&user_config) { + Ok(config) => { + serde_json::from_str::(&config) + .with_context(|| format!("failed to parse {}", user_config.display()))? + .env + } + Err(err) if err.kind() == std::io::ErrorKind::NotFound => Envs::new(), + Err(err) => return Err(err.into()), + }; + let names = match args.all { + true => source.keys().cloned().collect(), + false => args.names, + }; + let mut allowed = parse_env_file::parse_allowed_envs(&load_allowed_envs(&compose)?)?; + parse_env_file::check_names(&allowed, &names)?; + allowed.retain(|name, _| names.contains(name)); + + let mut envs = load_envs(&env_file)?; + for (name, value) in names.iter().filter_map(|name| source.remove_entry(name)) { + if envs.get(&name).is_some_and(|existing| *existing != value) { + bail!("env {name} is already set to a different value"); + } + envs.insert(name, value); + } + parse_env_file::check_limits(&envs)?; + parse_env_file::check_env(&allowed, |name| envs.get(name).cloned())?; + let json = serde_json::to_vec(&envs).context("failed to serialize env")?; + safe_write_with_mode(&env_file, json, 0o600) + .with_context(|| format!("failed to write {}", env_file.display()))?; + if let Some(path) = shell_env_file { + safe_write_with_mode(&path, parse_env_file::convert_env_to_str(&envs), 0o600) + .with_context(|| format!("failed to write {}", path.display()))?; + } + Ok(()) +} + #[derive(Parser)] /// Hex encode data struct HexCommand { @@ -388,6 +541,10 @@ struct GetKeysArgs { /// If not provided, TLS certificate verification is skipped for the initial connection. #[arg(long)] root_ca: Option, + + /// File holding the launch ticket to present, for apps that require one + #[arg(long)] + launch_ticket_file: Option, } #[derive(Parser)] @@ -638,10 +795,24 @@ fn cmd_attest_strip(args: AttestStripArgs) -> Result<()> { Ok(()) } -async fn cmd_get_keys(args: GetKeysArgs) -> Result<()> { - use dstack_kms_rpc::kms_client::KmsClient; - use ra_rpc::client::RaClientConfig; +/// Verify the KMS as system setup does: with the collateral service from the +/// guest's sys-config and any trust anchors published in the guest. +fn get_keys_verifier() -> Result> { + use dstack_types::shared_filenames::{host_shared_dir, SYS_CONFIG}; + let path = host_shared_dir().join(SYS_CONFIG); + let collateral_urls = match fs::read_to_string(&path) { + Ok(text) => serde_json::from_str::(&text) + .context("failed to parse sys-config")? + .collateral_urls(), + Err(err) if err.kind() == std::io::ErrorKind::NotFound => Default::default(), + Err(err) => return Err(err).context("failed to read sys-config"), + }; + Ok(std::sync::Arc::new(dstack_attest::default_verifier( + &collateral_urls, + )?)) +} +async fn cmd_get_keys(args: GetKeysArgs) -> Result<()> { let kms_url = normalize_prpc_url(&args.kms_url); // Load root CA if provided for TLS pinning @@ -653,80 +824,56 @@ async fn cmd_get_keys(args: GetKeysArgs) -> Result<()> { None }; - // Step 1: Get temporary CA certificate - eprintln!("Connecting to KMS: {kms_url}"); - let tls_no_check = root_ca_pem.is_none(); - if tls_no_check { - eprintln!("Warning: no --root-ca provided, TLS certificate verification is disabled for initial connection"); - } - let tmp_ca = { - let client = RaClientConfig::builder() - .remote_uri(kms_url.clone()) - .tls_no_check(tls_no_check) - .tls_built_in_root_certs(false) - .maybe_tls_ca_cert(root_ca_pem.clone()) - .build() - .into_client() - .context("failed to create client")?; - let kms_client = KmsClient::new(client); - kms_client - .get_temp_ca_cert() - .await - .context("Failed to get temp CA cert")? - }; - - // Step 2: Generate RA-TLS client certificate let app_id = decode_app_id(args.app_id.as_deref())?; - let cert_pair = generate_ra_cert_with_app_id( - tmp_ca.temp_ca_cert.clone(), - tmp_ca.temp_ca_key.clone(), - app_id, - ) - .context("Failed to generate RA cert")?; - - // Step 3: Create authenticated client and request app keys - let ra_client = RaClientConfig::builder() - .tls_no_check(false) - .tls_built_in_root_certs(false) - .remote_uri(kms_url.clone()) - .tls_client_cert(cert_pair.cert_pem) - .tls_client_key(cert_pair.key_pem) - .tls_ca_cert(tmp_ca.ca_cert.clone()) - .build() - .into_client() - .context("Failed to create RA client")?; - - let kms_client = KmsClient::new(ra_client); - let response = kms_client - .get_app_key(dstack_kms_rpc::GetAppKeyRequest { + let launch_ticket = match &args.launch_ticket_file { + Some(path) => fs::read_to_string(path) + .context("failed to read the launch ticket")? + .trim() + .to_string(), + None => String::new(), + }; + let cert_pair = generate_self_signed_ra_cert(app_id).context("Failed to generate RA cert")?; + let response = cert_client::request_app_keys( + kms_url.clone(), + dstack_kms_rpc::GetAppKeyRequest { + app_epoch: None, api_version: 1, - vm_config: "".to_string(), - }) - .await - .context("Failed to get app key")?; + vm_config: String::new(), + root_epoch: None, + launch_ticket, + }, + cert_pair, + get_keys_verifier()?, + root_ca_pem.clone(), + &[], + ) + .await + .context("Failed to get app keys from the attested KMS")?; + let root_ca = root_ca_pem.unwrap_or(response.ca_cert); - // Step 4: Build AppKeys structure - let (_, ca_pem) = x509_parser::pem::parse_x509_pem(tmp_ca.ca_cert.as_bytes()) - .context("Failed to parse CA cert")?; + // Build AppKeys from the authenticated response. + let (_, ca_pem) = + x509_parser::pem::parse_x509_pem(root_ca.as_bytes()).context("Failed to parse CA cert")?; let x509 = ca_pem.parse_x509().context("Failed to parse CA cert")?; let root_pubkey = x509.public_key().raw.to_vec(); let keys = utils::AppKeys { - ca_cert: tmp_ca.ca_cert, + ca_cert: root_ca, disk_crypt_key: response.disk_crypt_key, env_crypt_key: response.env_crypt_key, + sealed_env_key: response.sealed_env_key, k256_key: response.k256_key, k256_signature: response.k256_signature, gateway_app_id: response.gateway_app_id, key_provider: KeyProvider::Kms { + app_epoch: response.app_epoch, url: kms_url, pubkey: root_pubkey, - tmp_ca_key: tmp_ca.temp_ca_key, - tmp_ca_cert: tmp_ca.temp_ca_cert, + root_epoch: response.root_epoch, }, }; - // Step 5: Output result + // Output result. let json = serde_json::to_string_pretty(&keys).context("Failed to serialize app keys")?; if let Some(output_path) = args.output { safe_write_with_mode(&output_path, &json, 0o600).context("Failed to write app keys")?; @@ -741,9 +888,12 @@ async fn cmd_get_keys(args: GetKeysArgs) -> Result<()> { fn cmd_exec_with_env(args: ExecWithEnvArgs) -> Result<()> { use std::os::unix::process::CommandExt; - let envs: std::collections::BTreeMap = - utils::deserialize_json_file(&args.env_file) - .with_context(|| format!("failed to load env from {}", args.env_file.display()))?; + let envs = load_envs(&args.env_file)?; + if let Some(compose) = &args.compose { + let allowed = parse_env_file::parse_allowed_envs(&load_allowed_envs(compose)?)?; + parse_env_file::check_names(&allowed, envs.keys())?; + parse_env_file::check_env(&allowed, |name| envs.get(name).cloned())?; + } let (program, program_args) = args.command.split_first().context("no command given")?; let err = std::process::Command::new(program) .args(program_args) @@ -823,7 +973,7 @@ async fn cmd_encrypt(args: EncryptArgs) -> Result<()> { .transpose()?; let client = RaClientConfig::builder() .remote_uri(kms_url) - .tls_no_check(false) + .tls_skip_ca_verification(false) .tls_built_in_root_certs(root_ca_pem.is_none()) .maybe_tls_ca_cert(root_ca_pem) .build() @@ -1197,6 +1347,12 @@ fn gen_app_keys_from_seed( key: key.serialize_pem(), pubkey: key.public_key_der(), }, + KeyProviderKind::SevSnp => KeyProvider::SevSnp { + key: key.serialize_pem(), + }, + KeyProviderKind::TdxSeal => KeyProvider::TdxSeal { + key: key.serialize_pem(), + }, KeyProviderKind::Kms => { anyhow::bail!("KMS keys must be fetched from the KMS server") } @@ -1230,6 +1386,7 @@ fn make_app_keys( Ok(AppKeys { disk_crypt_key: sha256(&disk_key.serialize_der()).to_vec(), env_crypt_key: vec![], + sealed_env_key: vec![], k256_key: k256_key.to_bytes().to_vec(), k256_signature: vec![], gateway_app_id: "".to_string(), @@ -1703,6 +1860,8 @@ async fn main() -> Result<()> { gpu_info::cmd_gpu_info()?; } Commands::ExecWithEnv(args) => cmd_exec_with_env(args)?, + Commands::ValidateEnv(args) => cmd_validate_env(args)?, + Commands::ImportEnv(args) => cmd_import_env(args)?, } Ok(()) diff --git a/dstack/dstack-util/src/parse_env_file.rs b/dstack/dstack-util/src/parse_env_file.rs index 8a2a60771b..688eb782c7 100644 --- a/dstack/dstack-util/src/parse_env_file.rs +++ b/dstack/dstack-util/src/parse_env_file.rs @@ -4,8 +4,9 @@ use anyhow::{bail, Context, Result}; use serde::Deserialize; -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeMap; use tracing::warn; +use value_spec::ValueSpec; /// Escape a value for systemd's `EnvironmentFile=` parser. A newline cannot be /// represented there, so it is written as a literal `\n`. @@ -40,28 +41,71 @@ struct Data { env: Vec, } -pub fn parse_env(env_json: &[u8], allowed: &BTreeSet) -> Result> { - const MAX_ITEMS: usize = 1024; - const MAX_TOTAL_SIZE: usize = 1024 * 1024; +/// The specs each allowed name's value must match. +pub type AllowedEnvs = BTreeMap>; - let data: Data = serde_json::from_slice(env_json).context("Failed to parse env")?; +/// Parses `allowed_envs` entries, each a name optionally followed by `:`, +/// optional whitespace and a value spec. +pub fn parse_allowed_envs(entries: &[String]) -> Result { + let mut allowed = AllowedEnvs::new(); + for entry in entries { + let (name, spec) = value_spec::parse_named(entry) + .with_context(|| format!("invalid allowed_envs entry {entry:?}"))?; + allowed.entry(name.to_string()).or_default().extend(spec); + } + Ok(allowed) +} - if data.env.len() > MAX_ITEMS { - bail!("Too many environment variables: {}", data.env.len()); +/// Checks the variables `allowed` names against their specs. An unset +/// variable counts as empty, so only a spec that accepts the empty string +/// leaves its variable optional. +pub fn check_env(allowed: &AllowedEnvs, get: impl Fn(&str) -> Option) -> Result<()> { + for (name, specs) in allowed { + let value = get(name); + if specs + .iter() + .all(|spec| spec.matches(value.as_deref().unwrap_or_default())) + { + continue; + } + match value { + Some(_) => bail!("value of env {name} does not match its spec"), + None => bail!("env {name} is not set and its spec does not accept an empty value"), + } } + Ok(()) +} - const KEY_REGEX: &str = r"^[a-zA-Z_][a-zA-Z0-9_]*$"; - let key_regex = regex::Regex::new(KEY_REGEX) - .context("Failed to compile environment key validation regex")?; +/// Rejects variables that `allowed` does not name. +pub fn check_names<'a>( + allowed: &AllowedEnvs, + names: impl IntoIterator, +) -> Result<()> { + match names.into_iter().find(|name| !allowed.contains_key(*name)) { + Some(name) => bail!("env {name} is not allowed"), + None => Ok(()), + } +} - let mut env = BTreeMap::new(); - let mut total_size = 0; +const MAX_ITEMS: usize = 1024; +const MAX_TOTAL_SIZE: usize = 1024 * 1024; - for Pair { key, value } in data.env { - if !allowed.contains(&key) { - warn!("Skipping unauthorized environment variable: {key}"); - continue; - } +struct Limits { + key_regex: regex::Regex, + total_size: usize, +} + +impl Limits { + fn new() -> Result { + const KEY_REGEX: &str = r"^[a-zA-Z_][a-zA-Z0-9_]*$"; + Ok(Self { + key_regex: regex::Regex::new(KEY_REGEX) + .context("Failed to compile environment key validation regex")?, + total_size: 0, + }) + } + + fn add(&mut self, key: &str, value: &str) -> Result<()> { // Check key length (common Linux limit is 255) if key.len() > 255 { bail!("Environment variable name too long: {}", key); @@ -73,16 +117,54 @@ pub fn parse_env(env_json: &[u8], allowed: &BTreeSet) -> Result MAX_TOTAL_SIZE { + self.total_size += key.len() + value.len(); + if self.total_size > MAX_TOTAL_SIZE { bail!("Environment variables total size too large"); } + Ok(()) + } +} + +/// Applies the limits of [`parse_env`] to variables that did not come through it. +pub fn check_limits(env: &BTreeMap) -> Result<()> { + if env.len() > MAX_ITEMS { + bail!("too many environment variables: {}", env.len()); + } + let mut limits = Limits::new()?; + env.iter() + .try_for_each(|(key, value)| limits.add(key, value)) +} + +/// Keeps the variables `allowed` names and checks their values against its +/// specs. A variable that is absent is not checked here: an `init_script` may +/// still supply it, and [`check_env`] runs before the app starts. +pub fn parse_env(env_json: &[u8], allowed: &AllowedEnvs) -> Result> { + let data: Data = serde_json::from_slice(env_json).context("Failed to parse env")?; + + if data.env.len() > MAX_ITEMS { + bail!("Too many environment variables: {}", data.env.len()); + } + + let mut limits = Limits::new()?; + let mut env = BTreeMap::new(); + + for Pair { key, value } in data.env { + if !allowed.contains_key(&key) { + warn!("Skipping unauthorized environment variable: {key}"); + continue; + } + limits.add(&key, &value)?; env.insert(key, value); } + for (name, value) in &env { + if !allowed[name].iter().all(|spec| spec.matches(value)) { + bail!("value of env {name} does not match its spec"); + } + } Ok(env) } @@ -115,6 +197,113 @@ mod tests { assert_eq!(escape_value("cr\r"), "\"cr\r\""); } + fn parse(allowed: &[&str], env: &[(&str, &str)]) -> Result> { + let allowed = allowed.iter().map(|s| s.to_string()).collect::>(); + let env: Vec<_> = env + .iter() + .map(|(key, value)| serde_json::json!({ "key": key, "value": value })) + .collect(); + let json = serde_json::to_vec(&serde_json::json!({ "env": env }))?; + parse_env(&json, &parse_allowed_envs(&allowed)?) + } + + #[test] + fn values_are_checked_against_specs() { + let allowed = [ + "PORT:int(1..=65535)", + "NET:/main|test/", + "URL:/https://.*/", + "ANY", + ]; + let env = [ + ("PORT", "8080"), + ("NET", "test"), + ("URL", "https://a:1/"), + ("ANY", "x y"), + ]; + assert_eq!(parse(&allowed, &env).unwrap().len(), 4); + for bad in [ + ("PORT", "0"), + ("PORT", "80 "), + ("NET", "mainnet"), + ("URL", "http://a"), + ] { + let env = env.map(|kv| if kv.0 == bad.0 { bad } else { kv }); + let err = parse(&allowed, &env).unwrap_err().to_string(); + assert!(err.contains(bad.0) && !err.contains(bad.1), "{err}"); + } + } + + #[test] + fn absent_variables_are_left_to_check_env() { + let allowed = ["PORT: int(1..=65535)", "NET: /main|test/", "ANY"]; + assert!(parse(&allowed, &[("OTHER", "1")]).unwrap().is_empty()); + assert!(parse(&allowed, &[("PORT", "")]).is_err()); + assert!(parse(&["PORT: int(1..=65535)?"], &[("PORT", "")]).is_ok()); + } + + #[test] + fn limits_apply_outside_parse_env() { + let env = |key: &str, value: String| BTreeMap::from([(key.to_string(), value)]); + assert!(check_limits(&env("A", "x".repeat(128 * 1024))).is_ok()); + assert!(check_limits(&env("A", "x".repeat(128 * 1024 + 1))).is_err()); + assert!(check_limits(&env("A B", String::new())).is_err()); + } + + #[test] + fn the_last_duplicate_is_the_one_checked() { + let allowed = ["N: int(0..=9)"]; + assert_eq!( + parse(&allowed, &[("N", "x"), ("N", "5")]).unwrap()["N"], + "5" + ); + assert!(parse(&allowed, &[("N", "5"), ("N", "x")]).is_err()); + } + + #[test] + fn repeated_names_must_match_every_spec() { + for allowed in [["N:int(0..=9)", "N"], ["N", "N:int(0..=9)"]] { + assert!(parse(&allowed, &[("N", "9")]).is_ok()); + assert!(parse(&allowed, &[("N", "10")]).is_err()); + } + let allowed = ["N: int(0..=9)", "N: int(5..)"]; + assert!(parse(&allowed, &[("N", "5")]).is_ok()); + assert!(parse(&allowed, &[("N", "4")]).is_err()); + } + + #[test] + fn invalid_specs_are_rejected() { + for entry in ["A:", "A: ", "A:int(", "A:string", "A:int:int", "A: int "] { + assert!(parse(&[entry], &[]).is_err(), "{entry}"); + } + } + + #[test] + fn check_env_looks_up_every_allowed_name() { + let get = |name: &str| (name == "PORT").then(|| "8080".to_string()); + let check = |entries: &[&str]| { + let entries = entries.iter().map(|s| s.to_string()).collect::>(); + check_env(&parse_allowed_envs(&entries)?, get) + }; + assert!(check(&["PORT: int(1..=65535)", "PORT", "HOST", "N: int?"]).is_ok()); + assert!(check(&["PORT: int(1..=1024)"]).is_err()); + assert!(check(&["PORT: int", "HOST: /.+/"]).is_err()); + assert!(check(&["PORT: int(8080)", "PORT: int(1..=1024)"]).is_err()); + assert!(check(&["PORT: string"]).is_err()); + } + + #[test] + fn unlisted_names_are_rejected() { + let allowed = parse_allowed_envs(&["PORT: int".to_string(), "HOST".to_string()]).unwrap(); + let check = |names: &[&str]| { + let names = names.iter().map(|s| s.to_string()).collect::>(); + check_names(&allowed, &names) + }; + assert!(check(&[]).is_ok()); + assert!(check(&["HOST", "PORT"]).is_ok()); + assert!(check(&["HOST", "LD_PRELOAD"]).is_err()); + } + /// Round-trip through systemd's own parser; skipped without a user manager. #[test] fn systemd_round_trip() { diff --git a/dstack/dstack-util/src/system_setup.rs b/dstack/dstack-util/src/system_setup.rs index 2aa9df286f..37bd2234a3 100644 --- a/dstack/dstack-util/src/system_setup.rs +++ b/dstack/dstack-util/src/system_setup.rs @@ -4,9 +4,10 @@ use std::sync::Arc; use std::{ - collections::{BTreeMap, BTreeSet}, + collections::BTreeMap, fmt::Display, io::Write as _, + net::{Ipv4Addr, Ipv6Addr}, ops::Deref, path::{Path, PathBuf}, process::{Command, Stdio}, @@ -21,14 +22,13 @@ use dstack_types::{ gpu_policy_hash, shared_filenames::{ APP_COMPOSE, APP_KEYS, DECRYPTED_ENV, DECRYPTED_ENV_JSON, ENCRYPTED_ENV, - HOST_SHARED_DIR_NAME, INSTANCE_INFO, SYS_CONFIG, USER_CONFIG, + HOST_SHARED_DIR_NAME, INSTANCE_INFO, SEALED_ENV, SYS_CONFIG, USER_CONFIG, }, - GpuPolicy, KeyProvider, KeyProviderInfo, GPU_ATTESTATION_OUTPUT, + GpuPolicy, InstanceInfo, KeyProvider, KeyProviderInfo, GPU_ATTESTATION_OUTPUT, }; use fs_err as fs; -use luks2::{ - LuksAf, LuksConfig, LuksDigest, LuksHeader, LuksJson, LuksKdf, LuksKeyslot, LuksSegment, - LuksSegmentSize, +use luks::{ + load_luks_header, sync_luks_epochs, write_luks_epochs, LUKS_INITIALIZING_LABEL, PAYLOAD_OFFSET, }; use ra_rpc::{ client::{CertInfo, RaClient, RaClientConfig}, @@ -36,13 +36,15 @@ use ra_rpc::{ }; use ra_tls::{ attestation::{detect_tee_variant, AttestationVerifier, QuoteContentType, TeeVariant}, - cert::{generate_ra_cert, CertConfigV2, CertSigningRequestV2, Csr}, + cert::{generate_self_signed_ra_cert, CertConfigV2, CertSigningRequestV2, Csr}, + traits::CertExt, }; use rand::Rng as _; use safe_write::{safe_write, safe_write_with_mode}; use scopeguard::defer; use serde::{Deserialize, Serialize}; use tracing::{info, warn}; +use zeroize::Zeroizing; use crate::{ cmd_show_mrs, @@ -54,14 +56,15 @@ use crate::{ deserialize_json_file, sha256, sha256_file, AppCompose, AppKeys, KeyProviderKind, SysConfig, }, }; -use cert_client::{validate_kms_rpc_cert, CertRequestClient}; +use cert_client::{request_app_keys, CertRequestClient}; use cmd_lib::run_fun as cmd; +use dstack_api_auth::jwt; use dstack_gateway_rpc::{ - gateway_client::GatewayClient, PortAttrs as RpcPortAttrs, PortPolicy as RpcPortPolicy, - RegisterCvmRequest, RegisterCvmResponse, WireGuardPeer, + gateway_client::GatewayClient, wg_key_proof, InfoResponse, PortAttrs as RpcPortAttrs, + PortPolicy as RpcPortPolicy, RegisterCvmRequest, RegisterCvmResponse, WgKeyProof, + WireGuardPeer, }; use ra_tls::rcgen::{KeyPair, PKCS_ECDSA_P256_SHA256}; -use serde_human_bytes as hex_bytes; use serde_json::Value; use tpm_attest::{self as tpm, TpmContext}; @@ -93,6 +96,14 @@ async fn sign_cert_request( } mod config_id_verifier; +mod luks; +mod sealed_env; +mod snp; +mod tdx_seal; + +#[cfg(test)] +use sealed_env::seal_env; +use sealed_env::{env_crypt_key, seal_env_at_epochs, sealed_env_info_at_epochs, SealedEnv}; #[derive(clap::Parser)] /// Prepare full disk encryption @@ -119,16 +130,6 @@ pub struct GatewayRefreshArgs { force: bool, } -#[derive(Deserialize, Serialize, Clone, Default)] -struct InstanceInfo { - #[serde(with = "hex_bytes", default)] - instance_id_seed: Vec, - #[serde(with = "hex_bytes", default)] - instance_id: Vec, - #[serde(with = "hex_bytes", default)] - app_id: Vec, -} - #[derive(Debug, Clone, Copy, PartialEq, Default)] enum FsType { #[default] @@ -226,6 +227,10 @@ impl HostShareDir { self.base_dir.join(ENCRYPTED_ENV) } + fn sealed_env_file(&self) -> PathBuf { + self.base_dir.join(SEALED_ENV) + } + fn sys_config_file(&self) -> PathBuf { self.base_dir.join(SYS_CONFIG) } @@ -239,11 +244,34 @@ impl HostShareDir { } } +fn env_file_exists(path: &Path) -> Result { + match fs::symlink_metadata(path) { + Ok(metadata) if metadata.is_file() => Ok(true), + Ok(_) => bail!("env {} is not a regular file", path.display()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false), + Err(error) => { + Err(error).with_context(|| format!("failed to inspect env {}", path.display())) + } + } +} + +fn read_optional_env(path: &Path) -> Result>> { + if !env_file_exists(path)? { + return Ok(None); + } + match fs::read(path) { + Ok(bytes) => Ok(Some(bytes)), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(error).with_context(|| format!("failed to read env {}", path.display())), + } +} + struct HostShared { dir: HostShareDir, sys_config: SysConfig, app_compose: AppCompose, encrypted_env: Vec, + sealed_env: Option>, instance_info: InstanceInfo, } @@ -258,12 +286,18 @@ impl HostShared { } else { InstanceInfo::default() }; - let encrypted_env = fs::read(host_shared_dir.encrypted_env_file()).unwrap_or_default(); + let sealed_env = read_optional_env(&host_shared_dir.sealed_env_file())?; + let encrypted_env = if sealed_env.is_some() { + Vec::new() + } else { + read_optional_env(&host_shared_dir.encrypted_env_file())?.unwrap_or_default() + }; Ok(Self { dir: host_shared_dir.clone(), sys_config, app_compose, encrypted_env, + sealed_env, instance_info, }) } @@ -312,7 +346,16 @@ impl HostShared { copy(APP_COMPOSE, SZ_1MB * 50, false)?; copy(SYS_CONFIG, SZ_1KB * 32, false)?; copy(INSTANCE_INFO, SZ_1KB * 10, true)?; - copy(ENCRYPTED_ENV, SZ_1KB * 256, true)?; + if env_file_exists(&host_shared_dir.join(SEALED_ENV))? { + copy(SEALED_ENV, SZ_1KB * 384, false)?; + } else { + match fs::remove_file(host_shared_copy_dir.join(SEALED_ENV)) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(error).context("failed to remove stale sealed env copy"), + } + copy(ENCRYPTED_ENV, SZ_1KB * 256, true)?; + } copy(USER_CONFIG, SZ_1MB * 50, true)?; info!("Unmounting host-shared"); unmount_host_shared(host_shared_dir)?; @@ -477,6 +520,43 @@ fn wireguard_endpoint_hosts(config: &str) -> Result> { .collect() } +// The gateway's WireGuard fields are rendered into a wg-quick config, and +// wg-quick runs its `PreUp`/`PostUp` hooks as root. Accept only values that +// cannot carry config syntax, so the gateway cannot inject lines. +fn parse_wg_ip(ip: &str) -> Result { + ip.parse() + .with_context(|| format!("invalid WireGuard address: {ip:?}")) +} + +fn parse_wg_public_key(key: &str) -> Result { + use base64::{engine::general_purpose::STANDARD, Engine as _}; + let decoded = STANDARD + .decode(key) + .ok() + .filter(|decoded| decoded.len() == 32) + .with_context(|| format!("invalid WireGuard public key: {key:?}"))?; + Ok(STANDARD.encode(decoded)) +} + +fn validate_wg_endpoint(endpoint: &str) -> Result<&str> { + let valid = endpoint.rsplit_once(':').is_some_and(|(host, port)| { + let host_ok = match host.strip_prefix('[').and_then(|h| h.strip_suffix(']')) { + Some(v6) => v6.parse::().is_ok(), + None => { + !host.is_empty() + && host + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-') + } + }; + host_ok && port.parse::().is_ok() + }); + if !valid { + bail!("invalid WireGuard endpoint: {endpoint:?}"); + } + Ok(endpoint) +} + fn remove_partial_wireguard_config(path: &str, cluster: &str) { if let Err(error) = fs::remove_file(path) { if error.kind() != std::io::ErrorKind::NotFound { @@ -493,6 +573,79 @@ struct GatewayContext<'a> { keys: &'a AppKeys, } +/// The gateway only polls `Health`. Port policy reaches it on registration, so +/// it never needs `Info` from a CVM that can mint this token. +const GATEWAY_AGENT_SCOPES: &[&str] = &[jwt::scope::HEALTH]; + +/// How often the gateway's token changes. `iat` is rounded down to this, and +/// Ed25519 signatures are deterministic, so every registration within one +/// period carries the same token. With `exp` ten years after `iat`, a token +/// never lapses while registration is down. +const GATEWAY_AGENT_TOKEN_PERIOD_SECS: u64 = 365 * 24 * 3600; + +const GATEWAY_AGENT_TOKEN_LIFETIME_SECS: u64 = 10 * GATEWAY_AGENT_TOKEN_PERIOD_SECS; + +/// Mint the token the gateway presents to this CVM's guest agent, signed with +/// the key the agent derives the same way from the app root key. +fn gateway_agent_token(app_id: &[u8], app_root_key: &[u8]) -> Result { + let secret = ra_tls::api_v1::derive_app_key( + app_root_key, + jwt::INTERNAL_ISSUER_DOMAIN, + ra_tls::api_v1::KeyAlgorithm::Ed25519, + )?; + let app_id = hex::encode(app_id); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH)? + .as_secs(); + let iat = now - now % GATEWAY_AGENT_TOKEN_PERIOD_SECS; + let claims = jwt::Claims { + iss: jwt::internal_issuer(&app_id), + aud: app_id, + iat, + exp: iat + GATEWAY_AGENT_TOKEN_LIFETIME_SECS, + scope: GATEWAY_AGENT_SCOPES.join(" "), + }; + jwt::sign(&secret, &claims) +} + +/// The app and instance ids the gateway reads from this CVM's client +/// certificate, which is what a WireGuard key proof is bound to. +fn client_cert_identity(client_cert: &str) -> Result<(Vec, Vec)> { + let (_, pem) = x509_parser::pem::parse_x509_pem(client_cert.as_bytes()) + .context("failed to parse client cert PEM")?; + let cert = pem.parse_x509().context("failed to parse client cert")?; + let app_info = cert + .get_app_info()? + .context("client cert carries no app info")?; + Ok((app_info.app_id, app_info.instance_id)) +} + +/// The WireGuard key proof for the gateway node that answered `info`. +/// +/// `None` when the gateway predates key proofs (no `wg_public_key`) or the +/// proof cannot be built: registering without one is exactly what older CVMs +/// do, and whether that is acceptable is the gateway's call. +fn build_wg_key_proof( + info: Result, + wg_sk: &str, + identity: impl FnOnce() -> Result<(Vec, Vec)>, +) -> Option { + let gateway_pk = match info { + Ok(info) if !info.wg_public_key.is_empty() => info.wg_public_key, + Ok(_) => return None, + Err(err) => { + warn!("failed to get gateway info, registering without a key proof: {err:#}"); + return None; + } + }; + identity() + .and_then(|(app_id, instance_id)| { + wg_key_proof::compute(wg_sk, &gateway_pk, &app_id, &instance_id) + }) + .inspect_err(|err| warn!("failed to build the WireGuard key proof: {err:#}")) + .ok() +} + impl<'a> GatewayContext<'a> { fn new(shared: &'a HostShared, keys: &'a AppKeys) -> Self { Self { shared, keys } @@ -517,7 +670,7 @@ impl<'a> GatewayContext<'a> { .tls_client_key(client_key.to_string()) .tls_ca_cert(ca_cert) .tls_built_in_root_certs(false) - .tls_no_check(gateway_app_id == "any") + .tls_skip_ca_verification(gateway_app_id == "any") .verify_server_attestation(false) .cert_validator(Box::new(move |cert| cert_validator.validate(cert))) .build() @@ -532,6 +685,12 @@ impl<'a> GatewayContext<'a> { key_store: &GatewayKeyStore, gateway_app_id: &str, ) -> Result { + // Not fatal: without a token the gateway's health poll is refused, which + // costs routing but should not cost the boot. + let agent_token = + gateway_agent_token(&self.shared.instance_info.app_id, &self.keys.k256_key) + .inspect_err(|err| warn!("failed to mint the guest agent token: {err:#}")) + .ok(); let port_policy = RpcPortPolicy { ports: self .shared @@ -553,11 +712,21 @@ impl<'a> GatewayContext<'a> { &key_store.client_cert, gateway_app_id, )?; + // Info and RegisterCvm share the client's pooled connection, so behind + // a per-connection balancer both reach the same node. If they do not, + // the proof names the key it targets and that node treats it as invalid. + let wg_key_proof = build_wg_key_proof( + client.info().await.context("failed to get gateway info"), + &key_store.wg_sk, + || client_cert_identity(&key_store.client_cert), + ); let result = client .register_cvm(RegisterCvmRequest { client_public_key: key_store.wg_pk.clone(), port_policy: Some(port_policy.clone()), health_check, + agent_token: agent_token.clone(), + wg_key_proof: wg_key_proof.clone(), }) .await .context("Failed to register CVM"); @@ -581,6 +750,8 @@ impl<'a> GatewayContext<'a> { client_public_key: key_store.wg_pk.clone(), port_policy: Some(port_policy), health_check, + agent_token, + wg_key_proof, }) .await .context("Failed to register CVM") @@ -606,13 +777,9 @@ impl<'a> GatewayContext<'a> { .unwrap_or(0); let cert_not_after = now + CERT_VALIDITY_SECS; let verifier = attestation_verifier(&self.shared.sys_config)?; - let cert_client = CertRequestClient::create( - self.keys, - verifier, - self.shared.sys_config.vm_config.clone(), - ) - .await - .context("Failed to create cert client")?; + let cert_client = CertRequestClient::create(self.keys, verifier, &self.shared.sys_config) + .await + .context("Failed to create cert client")?; let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).context("Failed to generate key")?; @@ -838,12 +1005,15 @@ impl<'a> GatewayContext<'a> { .context("too many gateway clusters")?; let mut wg_info = cluster.response.wg.take().context("missing wg info")?; wg_info.servers.sort_by(|a, b| a.pk.cmp(&b.pk)); + let client_ip = parse_wg_ip(&wg_info.client_ip)?; let mut new_config = format!( - "[Interface]\nPrivateKey = {}\nListenPort = {listen_port}\nAddress = {}/32\n\n", - cluster.key_store.wg_sk, wg_info.client_ip + "[Interface]\nPrivateKey = {}\nListenPort = {listen_port}\nAddress = {client_ip}/32\n\n", + cluster.key_store.wg_sk ); for WireGuardPeer { pk, ip, endpoint } in &wg_info.servers { - let ip = ip.split('/').next().unwrap_or_default(); + let pk = parse_wg_public_key(pk)?; + let ip = parse_wg_ip(ip.split('/').next().unwrap_or_default())?; + let endpoint = validate_wg_endpoint(endpoint)?; new_config.push_str(&format!( "[Peer]\nPublicKey = {pk}\nAllowedIPs = {ip}/32\nEndpoint = {endpoint}\nPersistentKeepalive = 25\n" )); @@ -1208,6 +1378,34 @@ fn verify_health_check_requirement(app_compose: &AppCompose) -> Result<()> { Ok(()) } +/// NTS fixes the absolute time; only a TSC the host cannot move keeps it +/// between syncs. +fn verify_secure_clock(platform: TeeVariant) -> Result<()> { + match platform { + TeeVariant::DstackTdx | TeeVariant::DstackGcpTdx => {} + TeeVariant::DstackAmdSevSnp => { + let secure_tsc = fs::read_to_string("/sys/devices/system/cpu/sev/secure_tsc") + .context("failed to read amd sev-snp Secure TSC status")?; + if secure_tsc.trim() != "1" { + bail!("secure_time requires amd sev-snp Secure TSC, which the host did not enable"); + } + } + TeeVariant::DstackAwsNitroTpm | TeeVariant::DstackNitroEnclave => { + bail!("secure_time is not supported on AWS") + } + } + let clocksource = + fs::read_to_string("/sys/devices/system/clocksource/clocksource0/current_clocksource") + .context("failed to read the current clocksource")?; + if clocksource.trim() != "tsc" { + bail!( + "secure_time requires the tsc clocksource, found {}", + clocksource.trim() + ); + } + Ok(()) +} + fn verify_platform_requirements( app_compose: &AppCompose, current_platform: TeeVariant, @@ -1346,6 +1544,8 @@ pub async fn cmd_sys_setup(args: SetupArgs) -> Result<()> { async fn do_sys_setup(stage0: Stage0<'_>) -> Result<()> { verify_app_compose_policy(&stage0.shared).context("Failed to verify app-compose policy")?; if stage0.shared.app_compose.secure_time { + let platform = detect_tee_variant().context("secure_time requires a TEE platform")?; + verify_secure_clock(platform)?; info!("Waiting for the system time to be synchronized"); cmd! { chronyc waitsync 30 0.1 0 5; @@ -2267,6 +2467,89 @@ struct AppInfo { gpu_attestation_event: Option>, } +impl HostShared { + /// Request app keys of `root_epoch` (`None` = current) from one KMS. + async fn request_app_keys_from_kms( + &self, + kms_url: String, + root_epoch: Option, + app_epoch: Option, + trusted_ca: Option, + ) -> Result<(AppKeys, Vec)> { + info!("Requesting app keys of root epoch {root_epoch:?} from KMS: {kms_url}"); + let cert_pair = + generate_self_signed_ra_cert(None).context("Failed to generate RA-TLS cert")?; + let response = request_app_keys( + kms_url.clone(), + rpc::GetAppKeyRequest { + api_version: 1, + vm_config: self.sys_config.vm_config.clone(), + root_epoch, + app_epoch, + launch_ticket: self.sys_config.launch_ticket.clone().unwrap_or_default(), + }, + cert_pair, + attestation_verifier(&self.sys_config)?, + trusted_ca.clone(), + &self.app_compose.key_provider_id, + ) + .await + .context("Failed to get app keys from the attested KMS")?; + let served = response.root_epoch; + let root_ca = trusted_ca.unwrap_or(response.ca_cert); + + let (_, ca_pem) = x509_parser::pem::parse_x509_pem(root_ca.as_bytes()) + .context("Failed to parse ca cert")?; + let x509 = ca_pem.parse_x509().context("Failed to parse ca cert")?; + let root_pubkey = x509.public_key().raw.to_vec(); + + let keys = AppKeys { + ca_cert: root_ca, + disk_crypt_key: response.disk_crypt_key, + env_crypt_key: response.env_crypt_key, + sealed_env_key: response.sealed_env_key, + k256_key: response.k256_key, + k256_signature: response.k256_signature, + gateway_app_id: response.gateway_app_id, + key_provider: KeyProvider::Kms { + url: kms_url, + pubkey: root_pubkey, + root_epoch: served, + app_epoch: response.app_epoch, + }, + }; + Ok((keys, response.os_image_hash)) + } + + /// Request the app keys of an older root epoch from the KMS that served + /// `keys`. + async fn request_historical_keys( + &self, + keys: &AppKeys, + epoch: u32, + app_epoch: u32, + ) -> Result { + let KeyProvider::Kms { url, .. } = &keys.key_provider else { + bail!("only KMS-provided keys have older root epochs"); + }; + Ok(self + .request_app_keys_from_kms( + url.clone(), + Some(epoch), + Some(app_epoch), + Some(keys.ca_cert.clone()), + ) + .await + .with_context(|| { + format!( + "failed to get the keys of root epoch {epoch}, app epoch {app_epoch}; \ + the policy rows of those epochs must still allow this instance" + ) + })? + .0) + } +} + struct Stage0<'a> { args: &'a SetupArgs, shared: HostShared, @@ -2329,62 +2612,6 @@ impl<'a> Stage0<'a> { self.shared.dir.join(APP_KEYS) } - async fn request_app_keys_from_kms_url(&self, kms_url: String) -> Result<(AppKeys, Vec)> { - info!("Requesting app keys from KMS: {kms_url}"); - let tmp_ca = { - info!("Getting temp ca cert"); - let client = RaClient::new(kms_url.clone(), true)?; - let kms_client = dstack_kms_rpc::kms_client::KmsClient::new(client); - kms_client - .get_temp_ca_cert() - .await - .context("Failed to get temp ca cert")? - }; - let cert_pair = generate_ra_cert(tmp_ca.temp_ca_cert.clone(), tmp_ca.temp_ca_key.clone())?; - let attestation_verifier = attestation_verifier(&self.shared.sys_config)?; - let ra_client = RaClientConfig::builder() - .tls_no_check(false) - .tls_built_in_root_certs(false) - .remote_uri(kms_url.clone()) - .tls_client_cert(cert_pair.cert_pem) - .tls_client_key(cert_pair.key_pem) - .tls_ca_cert(tmp_ca.ca_cert.clone()) - .attestation_verifier(attestation_verifier) - .cert_validator(Box::new(validate_kms_rpc_cert)) - .build() - .into_client() - .context("Failed to create client")?; - let kms_client = dstack_kms_rpc::kms_client::KmsClient::new(ra_client); - let response = kms_client - .get_app_key(rpc::GetAppKeyRequest { - api_version: 1, - vm_config: self.shared.sys_config.vm_config.clone(), - }) - .await - .context("Failed to get app key")?; - - let (_, ca_pem) = x509_parser::pem::parse_x509_pem(tmp_ca.ca_cert.as_bytes()) - .context("Failed to parse ca cert")?; - let x509 = ca_pem.parse_x509().context("Failed to parse ca cert")?; - let root_pubkey = x509.public_key().raw.to_vec(); - - let keys = AppKeys { - ca_cert: tmp_ca.ca_cert, - disk_crypt_key: response.disk_crypt_key, - env_crypt_key: response.env_crypt_key, - k256_key: response.k256_key, - k256_signature: response.k256_signature, - gateway_app_id: response.gateway_app_id, - key_provider: KeyProvider::Kms { - url: kms_url, - pubkey: root_pubkey, - tmp_ca_key: tmp_ca.temp_ca_key, - tmp_ca_cert: tmp_ca.temp_ca_cert, - }, - }; - Ok((keys, response.os_image_hash)) - } - async fn request_app_keys_from_kms(&self) -> Result { if self.shared.sys_config.kms_urls.is_empty() { bail!("No KMS URLs are set"); @@ -2392,7 +2619,11 @@ impl<'a> Stage0<'a> { let mut errors = vec![]; for kms_url in &self.shared.sys_config.kms_urls { let kms_url = kms_rpc_url(kms_url); - match self.request_app_keys_from_kms_url(kms_url.clone()).await { + match self + .shared + .request_app_keys_from_kms(kms_url.clone(), None, None, None) + .await + { Ok((keys, os_image_hash)) => { // Measured here, outside the per-URL request, so that a // failover can never extend os-image-hash twice. @@ -2423,24 +2654,45 @@ impl<'a> Stage0<'a> { } Ok(()) } - async fn get_keys_from_local_key_provider(&self) -> Result { - info!("Getting keys from local key provider"); - let provision = self - .vmm - .get_sealing_key() + /// Whether the encrypted disk a hardware sealing seed unlocks already exists. + fn sealed_disk_initialized(&self, provider: KeyProviderKind) -> Result { + let provider = provider.measurement_name(); + if !parse_dstack_options(&self.shared)?.storage_encrypted { + bail!("the {provider} key provider requires encrypted storage"); + } + let status = Command::new("cryptsetup") + .arg("isLuks") + .arg(&self.args.device) + .status() + .with_context(|| format!("failed to inspect disk before {provider} sealing"))?; + match status.code() { + Some(0) => Ok(true), + Some(1) => Ok(false), + _ => bail!("failed to inspect disk before {provider} sealing: {status}"), + } + } + + /// Persist public sealing parameters before the seed unlocks the disk. The + /// share is read-only in the guest, so use the acknowledged per-VM + /// persistence operation, and stop if it cannot persist. + async fn persist_sealing_parameters( + &self, + provider: KeyProviderKind, + instance_info: &InstanceInfo, + ) -> Result<()> { + let provider = provider.measurement_name(); + self.shared + .sys_config + .host_api_url + .as_ref() + .with_context(|| format!("{provider} sealing requires host API persistence"))?; + self.vmm + .notify("instance.info", &serde_json::to_string(instance_info)?) .await - .context("Failed to get sealing key")?; - // write to fs - let app_keys = gen_app_keys_from_seed( - &provision.sk, - KeyProviderKind::Local, - Some(provision.mr.to_vec()), - ) - .context("Failed to generate app keys")?; - Ok(app_keys) + .with_context(|| format!("failed to persist {provider} sealing parameters")) } - fn generate_tpm_app_keys(&self) -> Result { + fn get_tpm_seed(&self) -> Result> { let tpm = TpmContext::detect().context("failed to detect TPM context")?; // PCR policy: platform-specific (AWS: sha384 PCR4/7/8/12/14) @@ -2457,43 +2709,47 @@ impl<'a> Stage0<'a> { "unsealed root key seed from TPM (PCR policy: {})", pcr_policy.to_arg() ); - return gen_app_keys_from_seed(&seed, KeyProviderKind::Tpm, None) - .context("failed to generate TPM app keys"); + return Ok(Zeroizing::new(seed)); } // No sealed seed exists, generate new one info!("no sealed seed found, generating new seed..."); - let seed: [u8; 32] = tpm.get_random().context("TPM RNG unavailable")?; + let seed = Zeroizing::new(tpm.get_random::<32>().context("TPM RNG unavailable")?); // Seal the new seed under the platform PCR policy tpm.seal( - &seed, + seed.as_ref(), tpm::SEALED_NV_INDEX, tpm::PRIMARY_KEY_HANDLE, &pcr_policy, ) .context("failed to seal seed to TPM")?; - gen_app_keys_from_seed(&seed, KeyProviderKind::Tpm, None) - .context("failed to generate TPM app keys") + Ok(seed) } - async fn request_app_keys(&self) -> Result { + async fn request_app_keys(&self, app_info: &mut AppInfo) -> Result { let key_provider = self.shared.app_compose.key_provider(); validate_key_provider_inputs(key_provider, &self.shared.sys_config.kms_urls)?; - match key_provider { - KeyProviderKind::Kms => self.request_app_keys_from_kms().await, - KeyProviderKind::Local => self.get_keys_from_local_key_provider().await, - KeyProviderKind::None => { - info!("No key provider is enabled, generating temporary app keys"); - let seed: [u8; 32] = rand::thread_rng().gen(); - gen_app_keys_from_seed(&seed, KeyProviderKind::None, None) - .context("Failed to generate app keys") + let (seed, provider_id) = match key_provider { + KeyProviderKind::Kms => return self.request_app_keys_from_kms().await, + KeyProviderKind::Local => { + let provision = self + .vmm + .get_sealing_key() + .await + .context("failed to get SGX sealing key")?; + (Zeroizing::new(provision.sk), Some(provision.mr.to_vec())) } - KeyProviderKind::Tpm => { - info!("Generating app keys from TPM"); - self.generate_tpm_app_keys() + KeyProviderKind::SevSnp => (self.get_snp_seed(app_info).await?, None), + KeyProviderKind::TdxSeal => (self.get_tdx_seal_seed(app_info).await?, None), + KeyProviderKind::Tpm => (self.get_tpm_seed()?, None), + KeyProviderKind::None => { + info!("no key provider is enabled, generating temporary app keys"); + (Zeroizing::new(rand::thread_rng().gen::<[u8; 32]>()), None) } - } + }; + gen_app_keys_from_seed(seed.as_ref(), key_provider, provider_id) + .context("failed to generate app keys") } async fn setup_swap(&self, swap_size: u64, opts: &DstackOptions) -> Result<()> { @@ -2635,7 +2891,7 @@ impl<'a> Stage0<'a> { initialized } - async fn mount_data_disk(&self, disk_crypt_key: &str, opts: &DstackOptions) -> Result<()> { + async fn mount_data_disk(&self, keys: &AppKeys, opts: &DstackOptions) -> Result<()> { let name = "dstack_data_disk"; let mount_point = &self.args.mount_point; @@ -2648,16 +2904,21 @@ impl<'a> Stage0<'a> { cmd!(mkdir -p $mount_point).context("Failed to create mount point")?; - let disk_initialized = self.is_disk_initialized(opts); + let ephemeral = self.shared.app_compose.ephemeral_data_disk(); + if ephemeral { + info!("discarding previous data disk contents (requirements.ephemeral_data_disk)"); + } + let disk_initialized = !ephemeral && self.is_disk_initialized(opts); let has_filesystem = if opts.storage_encrypted && disk_initialized { info!("Mounting encrypted data disk"); - let initializing = - self.open_encrypted_volume(disk_crypt_key, name, opts.storage_discard)?; - if initializing { + let opened = self + .open_encrypted_volume(keys, name, opts.storage_discard, false) + .await?; + if !opened { warn!("data disk initialization was interrupted, initializing it again"); } - !initializing + opened } else { disk_initialized }; @@ -2669,16 +2930,17 @@ impl<'a> Stage0<'a> { if !opts.storage_encrypted { info!("Skipping disk encryption as requested by kernel cmdline"); - } else if !disk_initialized { + } else { info!("Setting up disk encryption"); - self.luks_setup(disk_crypt_key, name, opts.storage_discard)?; + self.luks_setup(keys, name, opts.storage_discard).await?; } match opts.storage_fs { FsType::Zfs => { info!("Creating ZFS filesystem"); - if disk_initialized { - // The interrupted attempt may have left a pool label behind. + if disk_initialized || ephemeral { + // An interrupted attempt or a previous boot may have + // left a pool label behind. cmd!(zpool labelclear -f $fs_dev).ok(); } let autotrim = if opts.storage_discard { "on" } else { "off" }; @@ -2799,7 +3061,8 @@ impl<'a> Stage0<'a> { Ok(()) } - fn luks_setup(&self, disk_crypt_key: &str, name: &str, discard: bool) -> Result<()> { + async fn luks_setup(&self, keys: &AppKeys, name: &str, discard: bool) -> Result<()> { + let disk_crypt_key = hex::encode(&keys.disk_crypt_key); let root_hd = &self.args.device; let sector_offset = PAYLOAD_OFFSET / 512; info!("Formatting encrypted disk"); @@ -2837,19 +3100,28 @@ impl<'a> Stage0<'a> { { bail!("Failed to setup luks volume"); } - self.open_encrypted_volume(disk_crypt_key, name, discard)?; + if let Some(epoch) = kms_root_epoch(keys).filter(|epoch| *epoch > 0 || keys.app_epoch() > 0) + { + write_luks_epochs(root_hd, 0, epoch, keys.app_epoch())?; + } + self.open_encrypted_volume(keys, name, discard, true) + .await?; Ok(()) } - /// Returns whether the header still carries the initializing label. - fn open_encrypted_volume( + /// Open the data disk after bringing it to the current key epochs. + /// + /// Returns `false`, leaving the disk closed, when an earlier + /// initialization was interrupted, unless the disk was just formatted. + async fn open_encrypted_volume( &self, - disk_crypt_key: &str, + keys: &AppKeys, name: &str, discard: bool, + formatted: bool, ) -> Result { let root_hd = &self.args.device; - let disk_crypt_key = disk_crypt_key.trim(); + let disk_crypt_key = hex::encode(&keys.disk_crypt_key); // Create a private tmpfs mount to ensure the header stays in-memory. let tmp_hdr_dir = "/tmp/dstack-luks-header"; let in_mem_hdr = format!("{tmp_hdr_dir}/luks-header"); @@ -2866,14 +3138,30 @@ impl<'a> Stage0<'a> { info "Mounting tmpfs for in-memory LUKS header"; mkdir -p $tmp_hdr_dir; mount -t tmpfs -o size=64M,mode=0700,nosuid,nodev,noexec tmpfs $tmp_hdr_dir; - info "Loading the LUKS2 header"; - cryptsetup luksHeaderBackup --header-backup-file=$in_mem_hdr $root_hd; } - .context("Failed to load LUKS2 header")?; + .context("Failed to mount tmpfs for the LUKS2 header")?; - let hdr_file = fs::File::open(&in_mem_hdr).context("Failed to open LUKS2 header")?; - let initializing = - validate_luks2_headers(hdr_file).context("Failed to validate LUKS2 header")?; + let hdr = Path::new(&in_mem_hdr); + let header = load_luks_header(root_hd, hdr)?; + if header.initializing && !formatted { + return Ok(false); + } + if let Some(current) = kms_root_epoch(keys) { + let old_key = async |root, app| { + if !self.shared.app_compose.unsafe_allow_disk_migration() { + bail!( + "the data disk is at key epochs (root {root}, app {app}); \ + set requirements.unsafe_allow_disk_migration to migrate it" + ); + } + let old = self.shared.request_historical_keys(keys, root, app).await?; + Ok(hex::encode(&old.disk_crypt_key)) + }; + let target = (current, keys.app_epoch()); + sync_luks_epochs(root_hd, hdr, header, &disk_crypt_key, target, old_key) + .await + .context("failed to migrate the data disk key")?; + } info!("Opening the device"); let mut command = Command::new("cryptsetup"); @@ -2917,7 +3205,7 @@ impl<'a> Stage0<'a> { info!("Waiting for device mapper {}...", dm_path); std::thread::sleep(std::time::Duration::from_millis(500)); } - Ok(initializing) + Ok(true) } async fn measure_app_info(&self) -> Result { @@ -2946,6 +3234,15 @@ impl<'a> Stage0<'a> { getrandom::fill(&mut rand_id)?; rand_id }; + } else if instance_info.instance_id_seed.len() != 20 { + // Still used as given: rejecting or replacing it would fail the boot + // or change the instance id of an existing CVM. The id is only + // unique together with the app id; a seed of another length makes + // even that depend on the platform binding. + warn!( + "instance_id_seed is {} bytes, expected 20", + instance_info.instance_id_seed.len() + ); } let instance_id = if self.shared.app_compose.no_instance_id { vec![] @@ -3020,7 +3317,12 @@ impl<'a> Stage0<'a> { }) } - fn verify_app(&self, app_info: &AppInfo, keys: &AppKeys) -> Result<()> { + fn verify_app_config( + &self, + app_info: &AppInfo, + provider: KeyProviderKind, + provider_id: &[u8], + ) -> Result<()> { config_id_verifier::verify_mr_config_id( &app_info.compose_hash, &app_info.gpu_policy_hash, @@ -3033,28 +3335,24 @@ impl<'a> Stage0<'a> { .ok() .context("Invalid app id")?, &app_info.instance_info.instance_id, - keys.key_provider.kind(), - keys.key_provider.id(), + provider, + provider_id, )?; - self.verify_key_provider_id(keys.key_provider.id())?; - // TPM uses an empty id: the instance app-root pubkey is not a stable - // provider identity and must not enter the launch measurement chain. - let kp_info = match &keys.key_provider { - KeyProvider::None { .. } => KeyProviderInfo::new("none".into(), "".into()), - KeyProvider::Local { .. } => { - KeyProviderInfo::new("local-sgx".into(), hex::encode(keys.key_provider.id())) - } - KeyProvider::Tpm { .. } => KeyProviderInfo::new("tpm".into(), "".into()), - KeyProvider::Kms { .. } => { - KeyProviderInfo::new("kms".into(), hex::encode(keys.key_provider.id())) - } - }; + self.verify_key_provider_id(provider_id) + } + + fn verify_app(&self, app_info: &AppInfo, keys: &AppKeys) -> Result<()> { + self.verify_app_config(app_info, keys.key_provider.kind(), keys.key_provider.id())?; + let kp_info = KeyProviderInfo::new( + keys.key_provider.kind().measurement_name().into(), + hex::encode(keys.key_provider.id()), + ); emit_key_provider_info(&kp_info)?; Ok(()) } async fn setup_fs(self) -> Result> { - let app_info = self + let mut app_info = self .measure_app_info() .await .context("Failed to measure app info")?; @@ -3065,7 +3363,7 @@ impl<'a> Stage0<'a> { .notify_q("boot.progress", "requesting app keys") .await; let app_keys = self - .request_app_keys() + .request_app_keys(&mut app_info) .await .context("Failed to request app keys")?; if app_keys.disk_crypt_key.is_empty() { @@ -3102,8 +3400,7 @@ impl<'a> Stage0<'a> { opts.storage_encrypted, opts.storage_fs ); - self.mount_data_disk(&hex::encode(&app_keys.disk_crypt_key), &opts) - .await?; + self.mount_data_disk(&app_keys, &opts).await?; self.setup_swap(self.shared.app_compose.swap_size, &opts) .await?; self.vmm @@ -3128,25 +3425,76 @@ impl<'a> Stage0<'a> { } impl Stage1<'_> { - fn decrypt_env_vars( - &self, - key: &[u8], - ciphertext: &[u8], - allowed: &BTreeSet, - ) -> Result> { - let vars = if !ciphertext.is_empty() { - info!("Processing encrypted env"); - let env_crypt_key: [u8; 32] = key.try_into().ok().context( - "encrypted env is present but the key provider gave no valid env crypt key", + /// Decrypt the host-supplied env, preferring the sealed format. + async fn decrypt_env(&self) -> Result<(Vec, Vec)> { + let current_secret = self.keys.sealed_env_key.as_slice(); + if let Some(sealed_env) = &self.shared.sealed_env { + let envelope: SealedEnv = + serde_json::from_slice(sealed_env).context("failed to parse sealed env")?; + if envelope.version != 1 { + bail!("unsupported sealed env version: {}", envelope.version); + } + if envelope.enc.len() != 32 { + bail!("sealed env encapsulated key must be 32 bytes"); + } + let payload = [envelope.enc, envelope.ciphertext].concat(); + let (current_root, current_app) = (self.keys.root_epoch(), self.keys.app_epoch()); + if envelope.root_epoch > current_root || envelope.app_epoch > current_app { + bail!( + "sealed env epoch (root {}, app {}) exceeds current epoch (root {current_root}, app {current_app})", + envelope.root_epoch, + envelope.app_epoch + ); + } + let historical; + let secret = if envelope.root_epoch == current_root && envelope.app_epoch == current_app + { + current_secret + } else { + historical = self + .shared + .request_historical_keys(&self.keys, envelope.root_epoch, envelope.app_epoch) + .await?; + historical.sealed_env_key.as_slice() + }; + let plaintext = crate::crypto::sealed_env_decrypt( + secret, + &sealed_env_info_at_epochs(envelope.root_epoch, envelope.app_epoch), + &payload, )?; - let decrypted_json = - dh_decrypt(env_crypt_key, ciphertext).context("Failed to decrypt env file")?; - crate::parse_env_file::parse_env(&decrypted_json, allowed)? - } else { - info!("No encrypted env, using default"); - Default::default() + if envelope.root_epoch == current_root && envelope.app_epoch == current_app { + return Ok((plaintext, Vec::new())); + } + let sealed = seal_env_at_epochs(current_secret, current_root, current_app, &plaintext)?; + return Ok((plaintext, sealed)); + } + let ciphertext = &self.shared.encrypted_env; + let current_key = env_crypt_key(&self.keys.env_crypt_key)?; + let plaintext = match dh_decrypt(current_key, ciphertext) { + Ok(plaintext) => return Ok((plaintext, Vec::new())), + Err(_) => { + let current = self.keys.root_epoch(); + // Legacy encryption is only issued at app epoch zero. + let epochs = (0..=current) + .rev() + .filter(|root| *root != current || self.keys.app_epoch() != 0); + decrypt_historical_env(ciphertext, epochs, async |root| { + Ok(self + .shared + .request_historical_keys(&self.keys, root, 0) + .await? + .env_crypt_key) + }) + .await? + } }; - Ok(vars) + let sealed = seal_env_at_epochs( + current_secret, + self.keys.root_epoch(), + self.keys.app_epoch(), + &plaintext, + )?; + Ok((plaintext, sealed)) } fn write_env_file(&self, env_vars: &BTreeMap) -> Result<()> { @@ -3163,26 +3511,35 @@ impl Stage1<'_> { Ok(()) } - fn unseal_env_vars(&self) -> Result> { - let allowed_envs: BTreeSet = self - .shared - .app_compose - .allowed_envs - .iter() - .cloned() - .collect(); - // Decrypt env file - let decrypted_env = self.decrypt_env_vars( - &self.keys.env_crypt_key, - &self.shared.encrypted_env, - &allowed_envs, - )?; + async fn unseal_env_vars(&self) -> Result> { + let allowed_envs = + crate::parse_env_file::parse_allowed_envs(&self.shared.app_compose.allowed_envs)?; + let (decrypted_env, sealed) = + if self.shared.sealed_env.is_none() && self.shared.encrypted_env.is_empty() { + info!("No encrypted env, using default"); + (Default::default(), Vec::new()) + } else { + info!("Processing encrypted env"); + let (plaintext, sealed) = self.decrypt_env().await?; + ( + crate::parse_env_file::parse_env(&plaintext, &allowed_envs)?, + sealed, + ) + }; self.write_env_file(&decrypted_env)?; + // Sent on every boot, empty when nothing changed: it closes the host's + // env update window, which must be shut before any application code + // runs, or that code could replace the env the next boot reads. + close_env_window( + || self.vmm.update_sealed_env(sealed.clone()), + &ENV_WINDOW_RETRY_DELAYS, + ) + .await?; Ok(decrypted_env) } async fn setup(&self) -> Result<()> { - let _envs = self.unseal_env_vars()?; + let _envs = self.unseal_env_vars().await?; self.link_files()?; self.setup_socket_dir()?; self.setup_guest_agent_config()?; @@ -3279,313 +3636,60 @@ impl Stage1<'_> { } } -macro_rules! const_pad { - ($s:expr, $len:expr) => { - const { - assert!($s.len() <= $len, "The s is too long"); - let mut padded: [u8; $len] = [0; $len]; - let mut i = 0; - while i < $s.len() { - padded[i] = $s[i]; - i += 1; - } - padded - } - }; -} - -const PAYLOAD_OFFSET: u64 = 16777216; - -/// Set by luksFormat and cleared once the filesystem exists, so a disk still -/// carrying it was interrupted mid-initialization and holds no data. -const LUKS_INITIALIZING_LABEL: &str = "dstack-initializing"; - -/// Returns whether the primary header carries [`LUKS_INITIALIZING_LABEL`]. -fn validate_luks2_headers(mut reader: impl std::io::Read) -> Result { - let initializing = validate_single_luks2_header(&mut reader, 0)?; - validate_single_luks2_header(&mut reader, 1)?; - Ok(initializing) -} - -fn validate_single_luks2_header(mut reader: impl std::io::Read, hdr_ind: u64) -> Result { - let mut hdr_data = vec![0u8; 4096]; - reader - .read_exact(&mut hdr_data) - .context("Failed to read LUKS header")?; - let header = - LuksHeader::read_from(&mut &hdr_data[..]).context("Failed to decode LUKS header")?; - let LuksHeader { - magic, - version, - hdr_size, - seqid: _, - label, - csum_alg, - salt: _, - uuid: _, - subsystem, - hdr_offset, - csum: _, - .. - } = header; - - let expected_magic = match hdr_ind { - 0 => [76, 85, 75, 83, 186, 190], - 1 => [83, 75, 85, 76, 186, 190], - _ => bail!("Invalid LUKS header index: {hdr_ind}"), - }; - if magic != expected_magic { - bail!("Invalid LUKS magic: {magic:?}"); - } - if version != 2 { - bail!("Invalid LUKS version: {version}"); - } - let initializing = label == const_pad!(LUKS_INITIALIZING_LABEL.as_bytes(), 48); - if !initializing && label != [0; 48] { - bail!("Invalid LUKS label: {:?}", label); - } - if csum_alg != const_pad!(b"sha256", 32) { - bail!("Invalid LUKS checksum algorithm"); - } - if subsystem != [0; 48] { - bail!("Invalid LUKS subsystem"); - } - if hdr_offset != hdr_ind * hdr_size { - bail!("Invalid LUKS header offset: {hdr_offset}"); - } - if !(4096..=1024 * 1024 * 16).contains(&hdr_size) { - bail!("Invalid LUKS header size: {hdr_size}"); - } - - // Check JSON - let json_size = hdr_size - 4096; - let mut jsn_data = vec![0u8; json_size as usize]; - reader - .read_exact(&mut jsn_data) - .context("Failed to read LUKS JSON")?; - let json_end = jsn_data - .iter() - .position(|&b| b == 0) - .unwrap_or(jsn_data.len()); - jsn_data.truncate(json_end); - - let json = LuksJson::read_from(&mut &jsn_data[..]).context("Failed to decode LUKS JSON")?; - let LuksJson { - keyslots, - tokens, - segments, - digests, - config: - LuksConfig { - json_size: _, - keyslots_size: _, - flags, - requirements, - }, - } = json; - - if keyslots.len() != 1 { - bail!("Invalid LUKS keyslots"); - } - if !tokens.is_empty() { - bail!("Invalid LUKS tokens"); - } - if segments.len() != 1 { - bail!("Invalid LUKS segments"); - } - if digests.len() != 1 { - bail!("Invalid LUKS digests"); - } - if flags.is_some() { - bail!("Invalid LUKS flags"); - } - if requirements.is_some() { - bail!("Invalid LUKS requirements"); - } - - { - let first_keyslot = keyslots.get(&0).context("no LUKS keyslot")?; - let LuksKeyslot::luks2 { - key_size, - area, - kdf, - af, - priority, - } = first_keyslot; - if area.encryption() != "aes-xts-plain64" { - bail!("Invalid LUKS keyslot encryption: {}", area.encryption()); - } - // Pin where the encrypted key material is read from. The binary area - // must sit between the two header copies and the encrypted payload; - // otherwise a host with raw disk access could redirect it elsewhere. - let area_end = area.offset().checked_add(area.size()); - if area.offset() < 2 * hdr_size || area_end.is_none_or(|end| end > PAYLOAD_OFFSET) { - bail!( - "Invalid LUKS keyslot area: offset={} size={}", - area.offset(), - area.size() - ); - } - if *key_size != 64 { - bail!("Invalid LUKS keyslot key size: {key_size}"); - } - if area.key_size() != 64 { - bail!("Invalid LUKS keyslot key size: {}", area.key_size()); - } - { - let LuksKdf::pbkdf2 { - hash, - iterations: _, - // Salts are left unchecked on purpose: the passphrase is - // high-entropy and KMS-derived, so an attacker-chosen salt - // buys nothing without it (see security report #552). - salt: _, - } = kdf - else { - bail!("Invalid LUKS keyslot KDF"); - }; - if hash != "sha256" { - bail!("Invalid LUKS keyslot hash: {hash}"); - } - } - { - let LuksAf::luks1 { hash, stripes } = af; - if hash != "sha256" { - bail!("Invalid LUKS keyslot hash: {hash}"); - } - if *stripes != 4000 { - bail!("Invalid LUKS keyslot stripes: {stripes}"); - } - } - if priority.is_some() { - bail!("Invalid LUKS keyslot priority"); - } - } - - { - let first_segment = segments.get(&0).context("no LUKS segment")?; - let LuksSegment::crypt { - offset, - size, - iv_tweak, - encryption, - sector_size, - integrity, - flags, - } = first_segment; - if *offset != PAYLOAD_OFFSET { - bail!("Invalid LUKS segment offset"); - } - if *size != LuksSegmentSize::dynamic { - bail!("Invalid LUKS segment size"); - } - if *iv_tweak != 0 { - bail!("Invalid LUKS segment IV tweak"); - } - if encryption != "aes-xts-plain64" { - bail!("Invalid LUKS segment encryption"); - } - if *sector_size != 512 { - bail!("Invalid LUKS segment sector size"); - } - if integrity.is_some() { - bail!("Invalid LUKS segment integrity"); - } - if flags.is_some() { - bail!("Invalid LUKS segment flags"); +/// Waits between attempts to close the env update window. +const ENV_WINDOW_RETRY_DELAYS: [Duration; 4] = [ + Duration::from_secs(1), + Duration::from_secs(2), + Duration::from_secs(4), + Duration::from_secs(8), +]; + +/// Close the host's env update window, retrying `update` after each delay +/// while the host gives no answer. Fails if the window may still be open. +async fn close_env_window(mut update: F, delays: &[Duration]) -> Result<()> +where + F: FnMut() -> Fut, + Fut: std::future::Future>, +{ + for delay in delays { + match update().await { + Ok(()) => return Ok(()), + Err(err) => warn!("failed to close the env update window, retrying: {err:#}"), } + tokio::time::sleep(*delay).await; } - { - let first_digest = digests.get(&0).context("no LUKS digest")?; - let LuksDigest::pbkdf2 { - keyslots, - segments, - hash, - digest: _, - iterations: _, - salt: _, - } = first_digest; - if hash != "sha256" { - bail!("Invalid LUKS digest hash: {hash}"); - } - if keyslots != &[0] { - bail!("Invalid LUKS digest keyslots: {keyslots:?}"); - } - if segments != &[0] { - bail!("Invalid LUKS digest segments: {segments:?}"); - } - } - Ok(initializing) -} - -#[test] -fn test_validate_luks2_header() { - let mut header_data = include_bytes!("../tests/fixtures/luks_header_good").to_vec(); - assert!( - !validate_luks2_headers(&mut &header_data[..]).expect("Failed to validate LUKS2 header") - ); - header_data[24..24 + LUKS_INITIALIZING_LABEL.len()] - .copy_from_slice(LUKS_INITIALIZING_LABEL.as_bytes()); - assert!(validate_luks2_headers(&mut &header_data[..]).expect("Failed to validate LUKS2 header")); - let header_data = include_bytes!("../tests/fixtures/luks_header_cipher_null").to_vec(); - let error = validate_luks2_headers(&mut &header_data[..]).unwrap_err(); - assert!(error - .to_string() - .contains("Invalid LUKS keyslot encryption")); -} - -#[test] -fn test_validate_luks2_header_rejects_out_of_range_keyslot_area() { - // Redirect the keyslot binary area below the header region. Same length - // so the surrounding header stays intact; "00768" parses to 768, which is - // inside the header copies (< 2 * hdr_size) rather than the metadata gap. - let mut header = include_bytes!("../tests/fixtures/luks_header_good").to_vec(); - let patched = patch_luks_json(&mut header, br#""offset":"32768""#, br#""offset":"00768""#); - assert_eq!(patched, 2, "expected to patch both header copies"); - let error = validate_luks2_headers(&mut &header[..]).unwrap_err(); - assert!(error.to_string().contains("Invalid LUKS keyslot area")); + update().await.context( + "the host did not confirm that the env update window is closed; refusing to start applications", + ) } -/// Replace `needle` with `replacement` inside every LUKS JSON region, keeping -/// each region the same length by giving back trailing NUL padding. -#[cfg(test)] -fn patch_luks_json(header: &mut [u8], needle: &[u8], replacement: &[u8]) -> usize { - assert!(replacement.len() >= needle.len()); - let grow = replacement.len() - needle.len(); - let mut patched = 0; - let mut i = 0; - while i + needle.len() <= header.len() { - if &header[i..i + needle.len()] != needle { - i += 1; - continue; +async fn decrypt_historical_env( + ciphertext: &[u8], + epochs: I, + mut key_at: F, +) -> Result> +where + I: IntoIterator, + F: FnMut(u32) -> Fut, + Fut: std::future::Future>>, +{ + for epoch in epochs { + let decrypted = key_at(epoch) + .await + .and_then(|key| dh_decrypt(env_crypt_key(&key)?, ciphertext)); + match decrypted { + Ok(plaintext) => return Ok(plaintext), + Err(err) => warn!("failed to open legacy env at root epoch {epoch}: {err:#}"), } - let tail = &mut header[i..]; - let end = tail.iter().position(|b| *b == 0).expect("NUL padding"); - assert!(end + grow < tail.len(), "not enough NUL padding"); - tail.copy_within(needle.len()..end, replacement.len()); - tail[..replacement.len()].copy_from_slice(replacement); - patched += 1; - i += replacement.len(); - } - patched + } + bail!("failed to decrypt legacy env with accessible historical keys") } -#[test] -fn test_validate_luks2_header_rejects_keyslot_area_that_overflows() { - let mut header = include_bytes!("../tests/fixtures/luks_header_good").to_vec(); - // 2**64 - 32768 + 1000: added to the accepted offset 32768 it wraps to - // 1000, which is below PAYLOAD_OFFSET. - let patched = patch_luks_json( - &mut header, - br#""size":"258048""#, - br#""size":"18446744073709519848""#, - ); - assert_eq!(patched, 2, "expected to patch both header copies"); - let error = validate_luks2_headers(&mut &header[..]).unwrap_err(); - assert!( - error.to_string().contains("Invalid LUKS keyslot area"), - "{error:#}" - ); +fn kms_root_epoch(keys: &AppKeys) -> Option { + match keys.key_provider { + KeyProvider::Kms { root_epoch, .. } => Some(root_epoch), + _ => None, + } } #[cfg(test)] @@ -3994,11 +4098,54 @@ mod kms_provider_inventory_tests { } } +#[cfg(test)] +mod wg_key_proof_tests { + use super::{build_wg_key_proof, wg_key_proof, InfoResponse}; + use anyhow::anyhow; + + const CLIENT_SK: &str = "WCwzH5ldiytV13648mAYDqvo3TJ7oVO0uk6a+PQRaFM="; + const CLIENT_PK: &str = "un2Su94T3QglHE4DiL4ZrZ2iCIDhZlF2cS71h1pXUlo="; + const GATEWAY_SK: &str = "aP33GjsVN0Pz8E4gsggEIjf7Z3f+g2Pn6/+5QMnG0GI="; + const GATEWAY_PK: &str = "yZccXHB08kzYxfvKq/OXUiGSOwpSTrvZuQ05XmxA5wI="; + + fn info(wg_public_key: &str) -> anyhow::Result { + Ok(InfoResponse { + wg_public_key: wg_public_key.to_string(), + ..Default::default() + }) + } + + fn identity() -> anyhow::Result<(Vec, Vec)> { + Ok((vec![1; 20], vec![2; 20])) + } + + #[test] + fn attaches_proof_when_gateway_reports_its_key() { + let proof = build_wg_key_proof(info(GATEWAY_PK), CLIENT_SK, identity).unwrap(); + assert_eq!(proof.gateway_public_key, GATEWAY_PK); + wg_key_proof::verify(&proof, GATEWAY_SK, CLIENT_PK, &[1; 20], &[2; 20]).unwrap(); + } + + #[test] + fn skips_proof_for_older_or_unreachable_gateways() { + assert!(build_wg_key_proof(info(""), CLIENT_SK, identity).is_none()); + assert!(build_wg_key_proof(Err(anyhow!("down")), CLIENT_SK, identity).is_none()); + } + + #[test] + fn skips_proof_it_cannot_build() { + let no_identity = || Err(anyhow!("no app info")); + assert!(build_wg_key_proof(info(GATEWAY_PK), CLIENT_SK, no_identity).is_none()); + assert!(build_wg_key_proof(info("garbage"), CLIENT_SK, identity).is_none()); + } +} + #[cfg(test)] mod gateway_registration_refresh_tests { use super::{ - carry_cluster_preference, gateway_rpc_url, order_by_stickiness, record_accepting_url, - wireguard_endpoint_hosts, GatewayKeyStore, IssuedClientCerts, + carry_cluster_preference, gateway_rpc_url, order_by_stickiness, parse_wg_ip, + parse_wg_public_key, record_accepting_url, validate_wg_endpoint, wireguard_endpoint_hosts, + GatewayKeyStore, IssuedClientCerts, }; use std::os::unix::fs::PermissionsExt as _; @@ -4349,4 +4496,263 @@ Endpoint = [2001:db8::1]:51822 ); assert!(wireguard_endpoint_hosts("Endpoint = missing-port").is_err()); } + + #[test] + fn wireguard_fields_reject_config_syntax() { + for endpoint in [ + "gateway.example.com:51820", + "192.0.2.1:51821", + "[2001:db8::1]:51822", + ] { + assert_eq!(validate_wg_endpoint(endpoint).unwrap(), endpoint); + } + for endpoint in [ + "", + "192.0.2.1", + "192.0.2.1:99999", + "0.0.0.0/0:1", + "192.0.2.1:51820\n[Interface]\nPostUp = id", + "[not-v6]:51820", + ] { + assert!(validate_wg_endpoint(endpoint).is_err(), "{endpoint:?}"); + } + + let key = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="; + assert_eq!(parse_wg_public_key(key).unwrap(), key); + assert!(parse_wg_public_key(&format!("{key}\nPostUp = id")).is_err()); + assert!(parse_wg_public_key("AAAA").is_err()); + + assert!(parse_wg_ip("10.0.0.2").is_ok()); + assert!(parse_wg_ip("10.0.0.2/32\n[Interface]").is_err()); + } +} + +#[cfg(test)] +mod sealed_env_file_tests { + use super::*; + + fn stage(args: &SetupArgs, sealed_env: Option>, encrypted_env: Vec) -> Stage1<'_> { + Stage1 { + args, + vmm: HostApi::default(), + shared: HostShared { + dir: HostShareDir::new(&args.work_dir), + sys_config: serde_json::from_value(serde_json::json!({"vm_config": ""})).unwrap(), + app_compose: serde_json::from_value(serde_json::json!({ + "manifest_version": "2", "name": "sealed-test", "runner": "docker-compose" + })) + .unwrap(), + instance_info: InstanceInfo::default(), + sealed_env, + encrypted_env, + }, + keys: AppKeys { + disk_crypt_key: vec![], + env_crypt_key: vec![9; 32], + sealed_env_key: vec![7; 32], + k256_key: vec![], + k256_signature: vec![], + gateway_app_id: String::new(), + ca_cert: String::new(), + key_provider: KeyProvider::Kms { + app_epoch: 0, + url: "http://127.0.0.1:1".into(), + pubkey: vec![], + root_epoch: 3, + }, + }, + } + } + + #[tokio::test] + async fn guest_preserves_env_at_the_current_epoch() { + let dir = tempfile::tempdir().unwrap(); + let args = SetupArgs { + work_dir: dir.path().into(), + device: "unused".into(), + mount_point: "unused".into(), + }; + let plaintext = br#"{"env":[{"key":"MESSAGE","value":"test"}]}"#; + let sealed = seal_env(&[7; 32], 3, plaintext).unwrap(); + let current = stage(&args, Some(sealed), b"invalid legacy".to_vec()); + let (opened, update) = current.decrypt_env().await.unwrap(); + assert_eq!(opened, plaintext); + assert!(update.is_empty()); + + let public = x25519_dalek::PublicKey::from(&x25519_dalek::StaticSecret::from([9; 32])); + let legacy = crate::crypto::dh_encrypt(public.to_bytes(), plaintext).unwrap(); + let old = stage(&args, None, legacy.clone()); + let (opened, update) = old.decrypt_env().await.unwrap(); + assert_eq!(opened, plaintext); + assert!(update.is_empty()); + let mut without_sealed_key = stage(&args, None, legacy.clone()); + without_sealed_key.keys.sealed_env_key.clear(); + let (opened, update) = without_sealed_key.decrypt_env().await.unwrap(); + assert_eq!(opened, plaintext); + assert!(update.is_empty()); + + for invalid in [ + Vec::new(), + b"invalid JSON".to_vec(), + br#"{"version":2,"root_epoch":3,"enc":"","ciphertext":""}"#.to_vec(), + ] { + assert!(stage(&args, Some(invalid), legacy.clone()) + .decrypt_env() + .await + .is_err()); + } + let future = seal_env(&[7; 32], 4, plaintext).unwrap(); + assert!(stage(&args, Some(future), legacy) + .decrypt_env() + .await + .unwrap_err() + .to_string() + .contains("exceeds current")); + } + + /// Run `close_env_window` against `answers`, returning its result and how + /// often the host was asked. + async fn close_with(answers: Vec>) -> (Result<()>, usize) { + let mut answers = answers.into_iter(); + let mut calls = 0; + let result = close_env_window( + || { + calls += 1; + std::future::ready(answers.next().unwrap()) + }, + &[Duration::ZERO; 2], + ) + .await; + (result, calls) + } + + #[tokio::test] + async fn applications_start_only_once_the_env_window_is_closed() { + let (result, calls) = close_with(vec![Ok(())]).await; + result.unwrap(); + assert_eq!(calls, 1); + // A lost answer is retried. + let (result, calls) = close_with(vec![Err(anyhow!("connection reset")), Ok(())]).await; + result.unwrap(); + assert_eq!(calls, 2); + // No answer within the retries fails the boot. + let (result, calls) = close_with(vec![ + Err(anyhow!("timed out")), + Err(anyhow!("timed out")), + Err(anyhow!("connection refused")), + ]) + .await; + let err = format!("{:#}", result.unwrap_err()); + assert!(err.contains("refusing to start applications"), "{err}"); + assert!(err.contains("connection refused"), "{err}"); + assert_eq!(calls, 3); + } + + #[tokio::test] + async fn legacy_env_migration_skips_denied_intermediate_epochs() { + let secret = x25519_dalek::StaticSecret::from([8; 32]); + let public = x25519_dalek::PublicKey::from(&secret); + let plaintext = br#"{"env":[{"key":"SECRET","value":"synthetic"}]}"#; + let encrypted = crate::crypto::dh_encrypt(public.to_bytes(), plaintext).unwrap(); + let mut requested = Vec::new(); + let decrypted = decrypt_historical_env(&encrypted, (0..2).rev(), |epoch| { + requested.push(epoch); + std::future::ready(if epoch == 0 { + Ok(secret.to_bytes().to_vec()) + } else { + Err(anyhow::anyhow!("authorization denied")) + }) + }) + .await + .unwrap(); + assert_eq!(requested, [1, 0]); + assert_eq!(decrypted, plaintext); + assert!( + decrypt_historical_env(&encrypted, (0..2).rev(), |_| async { bail!("denied") }) + .await + .is_err() + ); + assert!( + decrypt_historical_env(&encrypted, (0..2).rev(), |_| async { Ok(vec![3; 32]) }) + .await + .is_err() + ); + } + + #[tokio::test] + async fn sealed_env_at_the_current_epochs_opens_and_binds_both_epochs() { + let dir = tempfile::tempdir().unwrap(); + let args = SetupArgs { + work_dir: dir.path().into(), + device: "unused".into(), + mount_point: "unused".into(), + }; + let plaintext = br#"{"env":[{"key":"VALUE","value":"epoch-test"}]}"#; + let sealed = seal_env_at_epochs(&[7; 32], 3, 2, plaintext).unwrap(); + let mut current = stage(&args, Some(sealed.clone()), vec![]); + if let KeyProvider::Kms { app_epoch, .. } = &mut current.keys.key_provider { + *app_epoch = 2; + } + let (opened, update) = current.decrypt_env().await.unwrap(); + assert_eq!(opened, plaintext); + assert!(update.is_empty()); + let mut tampered: Value = serde_json::from_slice(&sealed).unwrap(); + tampered["version"] = 2.into(); + current.shared.sealed_env = Some(serde_json::to_vec(&tampered).unwrap()); + let err = current.decrypt_env().await.unwrap_err(); + assert!( + err.to_string().contains("unsupported sealed env version"), + "{err}" + ); + let envelope: SealedEnv = serde_json::from_slice(&sealed).unwrap(); + assert_eq!(envelope.version, 1); + let payload = [envelope.enc.clone(), envelope.ciphertext.clone()].concat(); + assert!(crate::crypto::sealed_env_decrypt( + &[7; 32], + &sealed_env_info_at_epochs(3, 1), + &payload + ) + .is_err()); + assert!(crate::crypto::sealed_env_decrypt( + &[7; 32], + &sealed_env_info_at_epochs(2, 2), + &payload + ) + .is_err()); + } + + #[test] + fn sealed_file_selection_ignores_legacy_but_rejects_links() { + let dir = tempfile::tempdir().unwrap(); + fs::write(dir.path().join(SYS_CONFIG), br#"{"vm_config":""}"#).unwrap(); + fs::write( + dir.path().join(APP_COMPOSE), + br#"{"manifest_version":"2","name":"test","runner":"docker-compose"}"#, + ) + .unwrap(); + let sealed_path = dir.path().join(SEALED_ENV); + fs::write(&sealed_path, b"sealed bytes").unwrap(); + fs::create_dir(dir.path().join(ENCRYPTED_ENV)).unwrap(); + let shared = HostShared::load(dir.path()).unwrap(); + assert_eq!(shared.sealed_env.unwrap(), b"sealed bytes"); + assert!(shared.encrypted_env.is_empty()); + fs::remove_file(&sealed_path).unwrap(); + std::os::unix::fs::symlink("missing-target", &sealed_path).unwrap(); + assert!(env_file_exists(&sealed_path).is_err()); + assert!(HostShared::load(dir.path()).is_err()); + } + + #[test] + fn missing_empty_and_unreadable_env_are_distinct() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(SEALED_ENV); + assert_eq!(read_optional_env(&path).unwrap(), None); + fs::write(&path, []).unwrap(); + assert_eq!(read_optional_env(&path).unwrap(), Some(Vec::new())); + assert!( + serde_json::from_slice::(&read_optional_env(&path).unwrap().unwrap()) + .is_err() + ); + assert!(read_optional_env(dir.path()).is_err()); + } } diff --git a/dstack/dstack-util/src/system_setup/config_id_verifier.rs b/dstack/dstack-util/src/system_setup/config_id_verifier.rs index 4e4d971427..075b58dd45 100644 --- a/dstack/dstack-util/src/system_setup/config_id_verifier.rs +++ b/dstack/dstack-util/src/system_setup/config_id_verifier.rs @@ -22,15 +22,15 @@ struct LocalMrConfigValues<'a> { key_provider_id: &'a [u8], } +// TDREPORT_STRUCT.TDINFO (offset 512): ATTRIBUTES, XFAM, MRTD, then MRCONFIGID. +const TDREPORT_MR_CONFIG_ID: usize = 512 + 8 + 8 + 48; + +/// Reads the local TDREPORT, so booting does not depend on the host QGS. fn read_mr_config_id() -> Result<[u8; 48]> { - let quote = tdx_attest::get_quote(&[0u8; 64]).context("Failed to get quote")?; - let quote = dcap_qvl::quote::Quote::parse("e).context("Failed to parse quote")?; - let configid = quote - .report - .as_td10() - .context("Failed to get TD10 report")? - .mr_config_id; - Ok(configid) + let report = tdx_attest::get_report(&[0u8; 64]).context("Failed to get TDREPORT")?; + report.0[TDREPORT_MR_CONFIG_ID..TDREPORT_MR_CONFIG_ID + 48] + .try_into() + .context("Failed to read mr_config_id") } fn read_mr_config_document() -> Result { diff --git a/dstack/dstack-util/src/system_setup/luks.rs b/dstack/dstack-util/src/system_setup/luks.rs new file mode 100644 index 0000000000..9d674dcba4 --- /dev/null +++ b/dstack/dstack-util/src/system_setup/luks.rs @@ -0,0 +1,988 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// +// SPDX-License-Identifier: Apache-2.0 + +//! LUKS2 header validation and key epoch migration. +//! Fields validation does not inspect are not modeled; serde ignores them. +//! See . + +use std::{ + collections::HashMap, + io::Write, + path::Path, + process::{Command, Stdio}, +}; + +use anyhow::{bail, Context, Result}; +use fs_err as fs; +use safe_write::safe_write_with_mode; +use scopeguard::defer; +use serde::{de::IgnoredAny, Deserialize}; +use serde_with::{serde_as, DisplayFromStr}; +use tracing::info; + +/// Size of the binary header that precedes each JSON area. +const BINARY_HEADER_SIZE: u64 = 4096; + +struct LuksHeader { + pub magic: [u8; 6], + pub version: u16, + pub hdr_size: u64, + pub label: [u8; 48], + pub csum_alg: [u8; 32], + pub subsystem: [u8; 48], + pub hdr_offset: u64, +} + +impl LuksHeader { + /// Decodes the big-endian binary header. + pub fn parse(data: &[u8]) -> Result { + fn field(data: &[u8], offset: usize) -> Result<[u8; N]> { + let bytes = data + .get(offset..offset + N) + .context("LUKS header is truncated")?; + Ok(bytes.try_into()?) + } + Ok(Self { + magic: field(data, 0)?, + version: u16::from_be_bytes(field(data, 6)?), + hdr_size: u64::from_be_bytes(field(data, 8)?), + label: field(data, 24)?, + csum_alg: field(data, 72)?, + subsystem: field(data, 208)?, + hdr_offset: u64::from_be_bytes(field(data, 256)?), + }) + } +} + +#[derive(Deserialize)] +struct LuksJson { + pub keyslots: HashMap, + pub tokens: HashMap, + pub segments: HashMap, + pub digests: HashMap, + pub config: LuksConfig, +} + +/// Type of the only token dstack writes: the KMS key epochs of one keyslot. +const ROOT_EPOCH_TOKEN_TYPE: &str = "dstack-kms"; + +#[derive(Deserialize)] +struct LuksToken { + #[serde(rename = "type")] + pub kind: String, + pub keyslots: Vec, + #[serde(default)] + pub root_epoch: Option, + #[serde(default)] + pub app_epoch: u32, +} + +#[derive(Deserialize)] +#[serde(tag = "type", rename_all = "lowercase")] +enum LuksKeyslot { + Luks2 { + key_size: u16, + area: LuksArea, + kdf: LuksKdf, + af: LuksAf, + #[serde(default)] + priority: Option, + }, +} + +#[serde_as] +#[derive(Deserialize)] +#[serde(tag = "type", rename_all = "lowercase")] +enum LuksArea { + Raw { + encryption: String, + key_size: u32, + #[serde_as(as = "DisplayFromStr")] + offset: u64, + #[serde_as(as = "DisplayFromStr")] + size: u64, + }, +} + +/// Salt and iterations are left unchecked on purpose: the passphrase is +/// high-entropy and KMS-derived, so attacker-chosen values buy nothing without +/// it (see security report #552). +#[derive(Deserialize)] +#[serde(tag = "type", rename_all = "lowercase")] +enum LuksKdf { + Pbkdf2 { + hash: String, + }, + #[serde(other)] + Unsupported, +} + +#[derive(Deserialize)] +#[serde(tag = "type", rename_all = "lowercase")] +enum LuksAf { + Luks1 { hash: String, stripes: u16 }, +} + +#[serde_as] +#[derive(Deserialize)] +#[serde(tag = "type", rename_all = "lowercase")] +enum LuksSegment { + Crypt { + #[serde_as(as = "DisplayFromStr")] + offset: u64, + size: String, + #[serde_as(as = "DisplayFromStr")] + iv_tweak: u64, + encryption: String, + sector_size: u16, + #[serde(default)] + integrity: Option, + #[serde(default)] + flags: Option, + }, +} + +#[serde_as] +#[derive(Deserialize)] +#[serde(tag = "type", rename_all = "lowercase")] +enum LuksDigest { + Pbkdf2 { + #[serde_as(as = "Vec")] + keyslots: Vec, + #[serde_as(as = "Vec")] + segments: Vec, + hash: String, + }, +} + +#[serde_as] +#[derive(Deserialize)] +struct LuksConfig { + #[serde_as(as = "DisplayFromStr")] + pub keyslots_size: u64, + #[serde(default)] + pub flags: Option, + #[serde(default)] + pub requirements: Option, +} + +macro_rules! const_pad { + ($s:expr, $len:expr) => { + const { + assert!($s.len() <= $len, "The s is too long"); + let mut padded: [u8; $len] = [0; $len]; + let mut i = 0; + while i < $s.len() { + padded[i] = $s[i]; + i += 1; + } + padded + } + }; +} + +pub(super) const PAYLOAD_OFFSET: u64 = 16777216; + +fn cryptsetup(args: &[&str], device: &Path) -> Command { + let mut command = Command::new("cryptsetup"); + command.args(args).arg(device); + command +} + +/// Run `command` with `input` on stdin and return its exit code. +fn run_with_input(mut command: Command, input: &[u8]) -> Result> { + let mut child = command + .stdin(Stdio::piped()) + .spawn() + .context("failed to start cryptsetup")?; + child + .stdin + .take() + .context("cryptsetup stdin is unavailable")? + .write_all(input) + .context("failed to write to cryptsetup")?; + Ok(child + .wait() + .context("failed to wait for cryptsetup")? + .code()) +} + +/// Record that keyslot `slot` holds the key of `epoch` and `app_epoch`. +pub(super) fn write_luks_epochs(device: &Path, slot: u8, epoch: u32, app_epoch: u32) -> Result<()> { + let token = serde_json::json!({ + "type": ROOT_EPOCH_TOKEN_TYPE, + "keyslots": [slot.to_string()], + "root_epoch": epoch, + "app_epoch": app_epoch, + }); + let args = ["token", "import", "--token-id", "0", "--token-replace"]; + let code = run_with_input(cryptsetup(&args, device), token.to_string().as_bytes())?; + if code != Some(0) { + bail!("failed to record root epoch {epoch} in the LUKS header: {code:?}"); + } + Ok(()) +} + +/// Back up the LUKS header of `device` to `header` and validate the copy. +pub(super) fn load_luks_header(device: &Path, header: &Path) -> Result { + if header.exists() { + fs::remove_file(header)?; + } + let status = Command::new("cryptsetup") + .args(["luksHeaderBackup", "--header-backup-file"]) + .arg(header) + .arg(device) + .status() + .context("failed to start cryptsetup luksHeaderBackup")?; + if !status.success() { + bail!("failed to back up the LUKS header"); + } + validate_luks2_headers(fs::File::open(header)?).context("failed to validate the LUKS2 header") +} + +/// The keyslot of the validated `header` that `key` unlocks. +fn unlocked_keyslot(header: &Path, state: &LuksHeaderState, key: &str) -> Result> { + for &slot in &state.keyslots { + if unlocks(header, slot, key)? { + return Ok(Some(slot)); + } + } + Ok(None) +} + +/// Whether `key` unlocks keyslot `slot` of the validated `header`. +fn unlocks(header: &Path, slot: u8, key: &str) -> Result { + let slot_arg = slot.to_string(); + let test = cryptsetup( + &["open", "--test-passphrase", "--key-slot", &slot_arg, "-d-"], + header, + ); + match run_with_input(test, key.as_bytes())? { + Some(0) => Ok(true), + // No key available with this passphrase. + Some(2) => Ok(false), + code => bail!("failed to test the LUKS passphrase: {code:?}"), + } +} + +/// Add `new_key` in keyslot `slot`, authorized by `old_key`. The old key is +/// written next to `header`, which must be in a private in-memory directory. +fn add_luks_key( + device: &Path, + header: &Path, + old_key: &str, + new_key: &str, + slot: u8, +) -> Result<()> { + let old_file = header.with_file_name("old-key"); + defer! { + fs::remove_file(&old_file).ok(); + } + safe_write_with_mode(&old_file, old_key, 0o600)?; + let slot = slot.to_string(); + let args = [ + "luksAddKey", + "--batch-mode", + "--pbkdf", + "pbkdf2", + "--new-key-slot", + &slot, + ]; + let mut command = cryptsetup(&args, device); + command.arg("--key-file").arg(&old_file); + if run_with_input(command, new_key.as_bytes())? != Some(0) { + bail!("cryptsetup luksAddKey failed"); + } + Ok(()) +} + +fn kill_luks_slot(device: &Path, slot: u8) -> Result<()> { + let status = cryptsetup(&["luksKillSlot", "--batch-mode"], device) + .arg(slot.to_string()) + .stdin(Stdio::null()) + .status() + .context("failed to start cryptsetup luksKillSlot")?; + if !status.success() { + bail!("failed to remove LUKS keyslot {slot}"); + } + Ok(()) +} + +/// Bring the data disk to the `target` epochs, so that `key` unlocks its only +/// keyslot and the token records `target`. +/// +/// Each step is a single atomic LUKS2 metadata update: add the new key with +/// the old one, record the new epochs, then remove the old keyslot. Whatever +/// step a crash interrupts, the next boot finds either the old key alone or a +/// keyslot `key` already unlocks, and finishes from there. If another rotation +/// came first, `key` unlocks neither keyslot; the migration then restarts from +/// the keyslot the token records. `old_key` is only called when `key` unlocks +/// no keyslot. An unrotated epoch-0 disk is left +/// untouched, so it stays readable by older OS images. +/// +/// `header` holds the validated in-memory copy of `state` and is refreshed +/// after every change. +pub(super) async fn sync_luks_epochs( + device: &Path, + header: &Path, + mut state: LuksHeaderState, + key: &str, + target: (u32, u32), + old_key: F, +) -> Result +where + F: FnOnce(u32, u32) -> Fut, + Fut: std::future::Future>, +{ + let stored = (state.root_epoch.unwrap_or(0), state.app_epoch); + if stored.0 > target.0 || stored.1 > target.1 { + bail!("the data disk epochs {stored:?} exceed current {target:?}"); + } + let slot = match unlocked_keyslot(header, &state, key)? { + Some(slot) => slot, + None => { + if stored == target { + bail!("the data disk key does not unlock epochs {target:?}"); + } + // The keyslot holding the recorded epochs; a disk without a token + // is epoch 0 in slot 0. + let old_slot = state.token_keyslot.unwrap_or(0); + if !state.keyslots.contains(&old_slot) { + bail!("the recorded LUKS keyslot {old_slot} does not exist"); + } + info!("re-keying the data disk from epochs {stored:?} to {target:?}"); + let old_key = old_key(stored.0, stored.1).await?; + if !unlocks(header, old_slot, &old_key)? { + bail!( + "the key of epochs {stored:?} does not unlock the recorded keyslot {old_slot}" + ); + } + // A migration interrupted before a later rotation leaves a second + // keyslot whose epochs were never recorded, or are no longer the + // recorded ones. Drop it, now that the recorded key is confirmed, + // to make room for the current key. + for &stale in state.keyslots.iter().filter(|&&slot| slot != old_slot) { + kill_luks_slot(device, stale)?; + } + add_luks_key(device, header, &old_key, key, old_slot ^ 1)?; + state = load_luks_header(device, header)?; + unlocked_keyslot(header, &state, key)? + .context("the added LUKS keyslot does not unlock with the data disk key")? + } + }; + let mut changed = false; + let recorded = ( + state.token_keyslot, + state.root_epoch.unwrap_or(0), + state.app_epoch, + ); + let legacy = target == (0, 0) && state.token_keyslot.is_none(); + if !legacy && recorded != (Some(slot), target.0, target.1) { + write_luks_epochs(device, slot, target.0, target.1)?; + changed = true; + } + for &stale in state.keyslots.iter().filter(|&&stale| stale != slot) { + kill_luks_slot(device, stale)?; + changed = true; + } + if changed { + state = load_luks_header(device, header)?; + let recorded = (state.token_keyslot, state.root_epoch, state.app_epoch); + if state.keyslots != [slot] || recorded != (Some(slot), Some(target.0), target.1) { + bail!("the updated LUKS header does not record epochs {target:?}"); + } + } + Ok(state) +} + +/// Set by luksFormat and cleared once the filesystem exists, so a disk still +/// carrying it was interrupted mid-initialization and holds no data. +pub(super) const LUKS_INITIALIZING_LABEL: &str = "dstack-initializing"; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct LuksHeaderState { + /// The header carries [`LUKS_INITIALIZING_LABEL`]. + pub(super) initializing: bool, + /// Root epoch recorded in the dstack token; `None` means epoch 0. + pub(super) root_epoch: Option, + pub(super) app_epoch: u32, + /// Keyslot the dstack token records the epochs of. + pub(super) token_keyslot: Option, + /// Sorted keyslot ids; a second one exists only mid-migration. + pub(super) keyslots: Vec, +} + +pub(super) fn validate_luks2_headers(mut reader: impl std::io::Read) -> Result { + let primary = validate_single_luks2_header(&mut reader, 0)?; + let secondary = validate_single_luks2_header(&mut reader, 1)?; + if primary != secondary { + bail!("LUKS header copies disagree"); + } + Ok(primary) +} + +fn validate_single_luks2_header( + mut reader: impl std::io::Read, + hdr_ind: u64, +) -> Result { + let mut hdr_data = vec![0u8; BINARY_HEADER_SIZE as usize]; + reader + .read_exact(&mut hdr_data) + .context("Failed to read LUKS header")?; + let LuksHeader { + magic, + version, + hdr_size, + label, + csum_alg, + subsystem, + hdr_offset, + } = LuksHeader::parse(&hdr_data).context("Failed to decode LUKS header")?; + + let expected_magic = match hdr_ind { + 0 => [76, 85, 75, 83, 186, 190], + 1 => [83, 75, 85, 76, 186, 190], + _ => bail!("Invalid LUKS header index: {hdr_ind}"), + }; + if magic != expected_magic { + bail!("Invalid LUKS magic: {magic:?}"); + } + if version != 2 { + bail!("Invalid LUKS version: {version}"); + } + let initializing = label == const_pad!(LUKS_INITIALIZING_LABEL.as_bytes(), 48); + if !initializing && label != [0; 48] { + bail!("Invalid LUKS label: {:?}", label); + } + if csum_alg != const_pad!(b"sha256", 32) { + bail!("Invalid LUKS checksum algorithm"); + } + if subsystem != [0; 48] { + bail!("Invalid LUKS subsystem"); + } + if hdr_offset != hdr_ind * hdr_size { + bail!("Invalid LUKS header offset: {hdr_offset}"); + } + if !(4096..=1024 * 1024 * 16).contains(&hdr_size) { + bail!("Invalid LUKS header size: {hdr_size}"); + } + + // Check JSON + let json_size = hdr_size - BINARY_HEADER_SIZE; + let mut jsn_data = vec![0u8; json_size as usize]; + reader + .read_exact(&mut jsn_data) + .context("Failed to read LUKS JSON")?; + let json_end = jsn_data + .iter() + .position(|&b| b == 0) + .unwrap_or(jsn_data.len()); + jsn_data.truncate(json_end); + + let LuksJson { + keyslots, + tokens, + segments, + digests, + config: + LuksConfig { + keyslots_size, + flags, + requirements, + }, + } = serde_json::from_slice(&jsn_data).context("Failed to decode LUKS JSON")?; + + let mut keyslot_ids: Vec = keyslots.keys().copied().collect(); + keyslot_ids.sort_unstable(); + if keyslot_ids != [0] && keyslot_ids != [1] && keyslot_ids != [0, 1] { + bail!("Invalid LUKS keyslots"); + } + let (root_epoch, app_epoch, token_keyslot) = match tokens.len() { + 0 => (None, 0, None), + 1 => { + let token = tokens.get(&0).context("Invalid LUKS token id")?; + let slot = match &token.keyslots[..] { + [slot] => slot.parse::().ok(), + _ => None, + }; + if token.kind != ROOT_EPOCH_TOKEN_TYPE + || !slot.is_some_and(|s| keyslots.contains_key(&s)) + { + bail!("Invalid LUKS token"); + } + let root_epoch = token.root_epoch.context("LUKS token has no root epoch")?; + (Some(root_epoch), token.app_epoch, slot) + } + _ => bail!("Invalid LUKS tokens"), + }; + if segments.len() != 1 { + bail!("Invalid LUKS segments"); + } + if digests.len() != 1 { + bail!("Invalid LUKS digests"); + } + if keyslots_size % 4096 != 0 { + bail!("Invalid LUKS keyslots size: {keyslots_size}"); + } + if flags.is_some() { + bail!("Invalid LUKS flags"); + } + if requirements.is_some() { + bail!("Invalid LUKS requirements"); + } + + for keyslot in keyslots.values() { + let LuksKeyslot::Luks2 { + key_size, + area: + LuksArea::Raw { + encryption, + key_size: area_key_size, + offset, + size, + }, + kdf, + af: + LuksAf::Luks1 { + hash: af_hash, + stripes, + }, + priority, + } = keyslot; + if encryption != "aes-xts-plain64" { + bail!("Invalid LUKS keyslot encryption: {encryption}"); + } + // Pin where the encrypted key material is read from. The binary area + // must sit between the two header copies and the encrypted payload; + // otherwise a host with raw disk access could redirect it elsewhere. + let area_end = offset.checked_add(*size); + if *offset < 2 * hdr_size || area_end.is_none_or(|end| end > PAYLOAD_OFFSET) { + bail!("Invalid LUKS keyslot area: offset={offset} size={size}"); + } + if *key_size != 64 { + bail!("Invalid LUKS keyslot key size: {key_size}"); + } + if *area_key_size != 64 { + bail!("Invalid LUKS keyslot key size: {area_key_size}"); + } + let LuksKdf::Pbkdf2 { hash: kdf_hash } = kdf else { + bail!("Invalid LUKS keyslot KDF"); + }; + if kdf_hash != "sha256" { + bail!("Invalid LUKS keyslot hash: {kdf_hash}"); + } + if af_hash != "sha256" { + bail!("Invalid LUKS keyslot hash: {af_hash}"); + } + if *stripes != 4000 { + bail!("Invalid LUKS keyslot stripes: {stripes}"); + } + if priority.is_some() { + bail!("Invalid LUKS keyslot priority"); + } + } + + { + let LuksSegment::Crypt { + offset, + size, + iv_tweak, + encryption, + sector_size, + integrity, + flags, + } = segments.get(&0).context("no LUKS segment")?; + if *offset != PAYLOAD_OFFSET { + bail!("Invalid LUKS segment offset"); + } + if size != "dynamic" { + bail!("Invalid LUKS segment size"); + } + if *iv_tweak != 0 { + bail!("Invalid LUKS segment IV tweak"); + } + if encryption != "aes-xts-plain64" { + bail!("Invalid LUKS segment encryption"); + } + if *sector_size != 512 { + bail!("Invalid LUKS segment sector size"); + } + if integrity.is_some() { + bail!("Invalid LUKS segment integrity"); + } + if flags.is_some() { + bail!("Invalid LUKS segment flags"); + } + } + { + let LuksDigest::Pbkdf2 { + keyslots, + segments, + hash, + } = digests.get(&0).context("no LUKS digest")?; + if hash != "sha256" { + bail!("Invalid LUKS digest hash: {hash}"); + } + let mut keyslots = keyslots.clone(); + keyslots.sort_unstable(); + if keyslots != keyslot_ids { + bail!("Invalid LUKS digest keyslots: {keyslots:?}"); + } + if segments != &[0] { + bail!("Invalid LUKS digest segments: {segments:?}"); + } + } + Ok(LuksHeaderState { + initializing, + root_epoch, + app_epoch, + token_keyslot, + keyslots: keyslot_ids, + }) +} + +#[test] +fn test_validate_luks2_header() { + let mut header_data = include_bytes!("../../tests/fixtures/luks_header_good").to_vec(); + let state = + validate_luks2_headers(&mut &header_data[..]).expect("Failed to validate LUKS2 header"); + assert_eq!( + state, + LuksHeaderState { + initializing: false, + root_epoch: None, + app_epoch: 0, + token_keyslot: None, + keyslots: vec![0], + } + ); + let hdr_size = LuksHeader::parse(&header_data).unwrap().hdr_size as usize; + for copy in [0, hdr_size] { + header_data[copy + 24..copy + 24 + LUKS_INITIALIZING_LABEL.len()] + .copy_from_slice(LUKS_INITIALIZING_LABEL.as_bytes()); + } + assert!( + validate_luks2_headers(&mut &header_data[..]) + .expect("Failed to validate LUKS2 header") + .initializing + ); + let header_data = include_bytes!("../../tests/fixtures/luks_header_cipher_null").to_vec(); + let error = validate_luks2_headers(&mut &header_data[..]).unwrap_err(); + assert!(error + .to_string() + .contains("Invalid LUKS keyslot encryption")); +} + +#[test] +fn test_validate_luks2_header_rejects_out_of_range_keyslot_area() { + // Redirect the keyslot binary area below the header region. Same length + // so the surrounding header stays intact; "00768" parses to 768, which is + // inside the header copies (< 2 * hdr_size) rather than the metadata gap. + let mut header = include_bytes!("../../tests/fixtures/luks_header_good").to_vec(); + let patched = patch_luks_json(&mut header, br#""offset":"32768""#, br#""offset":"00768""#); + assert_eq!(patched, 2, "expected to patch both header copies"); + let error = validate_luks2_headers(&mut &header[..]).unwrap_err(); + assert!(error.to_string().contains("Invalid LUKS keyslot area")); +} + +/// Replace `needle` with `replacement` inside every LUKS JSON region, keeping +/// each region the same length by giving back trailing NUL padding. +#[cfg(test)] +fn patch_luks_json(header: &mut [u8], needle: &[u8], replacement: &[u8]) -> usize { + assert!(replacement.len() >= needle.len()); + let grow = replacement.len() - needle.len(); + let mut patched = 0; + let mut i = 0; + while i + needle.len() <= header.len() { + if &header[i..i + needle.len()] != needle { + i += 1; + continue; + } + let tail = &mut header[i..]; + let end = tail.iter().position(|b| *b == 0).expect("NUL padding"); + assert!(end + grow < tail.len(), "not enough NUL padding"); + tail.copy_within(needle.len()..end, replacement.len()); + tail[..replacement.len()].copy_from_slice(replacement); + patched += 1; + i += replacement.len(); + } + patched +} + +#[cfg(test)] +struct TestDisk { + dir: tempfile::TempDir, + image: std::path::PathBuf, + header: std::path::PathBuf, +} + +#[cfg(test)] +impl TestDisk { + /// A disk formatted with `key` and recording `epochs`, or `None` without + /// cryptsetup. + fn new(key: &str, epochs: Option<(u32, u32)>) -> Option { + if Command::new("cryptsetup") + .arg("--version") + .output() + .is_err() + { + eprintln!("cryptsetup is unavailable; skipping"); + return None; + } + let dir = tempfile::tempdir().unwrap(); + let image = dir.path().join("disk.img"); + let header = dir.path().join("header"); + fs::File::create(&image) + .unwrap() + .set_len(2 * PAYLOAD_OFFSET) + .unwrap(); + let offset = (PAYLOAD_OFFSET / 512).to_string(); + let format = cryptsetup( + &[ + "luksFormat", + "--batch-mode", + "--type", + "luks2", + "--offset", + &offset, + "--cipher", + "aes-xts-plain64", + "--pbkdf", + "pbkdf2", + "--sector-size", + "512", + "-d-", + ], + &image, + ); + assert_eq!(run_with_input(format, key.as_bytes()).unwrap(), Some(0)); + if let Some((root, app)) = epochs { + write_luks_epochs(&image, 0, root, app).unwrap(); + } + Some(Self { dir, image, header }) + } + + fn state(&self) -> LuksHeaderState { + load_luks_header(&self.image, &self.header).unwrap() + } + + fn unlocks(&self, key: &str) -> bool { + let test = cryptsetup(&["open", "--test-passphrase", "-d-"], &self.image); + run_with_input(test, key.as_bytes()).unwrap() == Some(0) + } + + fn add_key(&self, old: &str, new: &str, slot: u8) { + add_luks_key(&self.image, &self.header, old, new, slot).unwrap(); + } + + /// Sync to `target`; `old` is the only key the KMS would hand out. + async fn sync( + &self, + key: &str, + target: (u32, u32), + old: Option<(u32, u32, &str)>, + ) -> Result { + let old_key = |root, app| { + let key = old + .filter(|(r, a, _)| (*r, *a) == (root, app)) + .map(|(_, _, key)| key.to_owned()) + .context("the KMS does not serve this epoch"); + std::future::ready(key) + }; + sync_luks_epochs( + &self.image, + &self.header, + self.state(), + key, + target, + old_key, + ) + .await + } + + fn assert_synced(&self, key: &str, target: (u32, u32), slot: u8) { + let state = self.state(); + assert_eq!(state.keyslots, [slot]); + assert_eq!(state.token_keyslot, Some(slot)); + assert_eq!( + (state.root_epoch, state.app_epoch), + (Some(target.0), target.1) + ); + assert!(self.unlocks(key)); + assert!(!self.dir.path().join("old-key").exists()); + } +} + +#[tokio::test] +async fn test_luks_epoch_migration() { + let Some(disk) = TestDisk::new("k1", Some((1, 0))) else { + return; + }; + disk.sync("k2", (2, 0), Some((1, 0, "k1"))).await.unwrap(); + disk.assert_synced("k2", (2, 0), 1); + assert!(!disk.unlocks("k1")); + disk.sync("k3", (2, 1), Some((2, 0, "k2"))).await.unwrap(); + disk.assert_synced("k3", (2, 1), 0); + assert!(!disk.unlocks("k2")); + // Already current: no key is requested. + disk.sync("k3", (2, 1), None).await.unwrap(); + disk.assert_synced("k3", (2, 1), 0); +} + +#[tokio::test] +async fn test_luks_epoch_migration_resumes_after_each_step() { + // Crash after luksAddKey, then after the token import as well. + for record in [false, true] { + let Some(disk) = TestDisk::new("k1", Some((1, 0))) else { + return; + }; + disk.add_key("k1", "k2", 1); + if record { + write_luks_epochs(&disk.image, 1, 2, 0).unwrap(); + } + disk.sync("k2", (2, 0), None).await.unwrap(); + disk.assert_synced("k2", (2, 0), 1); + assert!(!disk.unlocks("k1")); + } +} + +#[tokio::test] +async fn test_luks_epoch_migration_resumes_after_a_later_rotation() { + // Interrupted while migrating to epoch 1, then rotated to epoch 2 before + // the next boot: the current key unlocks neither keyslot. + for record in [false, true] { + let Some(disk) = TestDisk::new("k0", None) else { + return; + }; + disk.add_key("k0", "k1", 1); + let old = if record { + write_luks_epochs(&disk.image, 1, 1, 0).unwrap(); + (1, 0, "k1") + } else { + (0, 0, "k0") + }; + disk.sync("k2", (2, 0), Some(old)).await.unwrap(); + disk.assert_synced("k2", (2, 0), if record { 0 } else { 1 }); + assert!(!disk.unlocks("k0")); + assert!(!disk.unlocks("k1")); + } +} + +#[tokio::test] +async fn test_luks_stale_keyslot_is_kept_until_the_recorded_key_is_confirmed() { + let Some(disk) = TestDisk::new("k0", None) else { + return; + }; + disk.add_key("k0", "k1", 1); + let interrupted = disk.state(); + // The KMS denies the recorded epoch, or hands out a key that does not + // unlock its keyslot: both keyslots stay. + assert!(disk.sync("k2", (2, 0), None).await.is_err()); + let err = disk + .sync("k2", (2, 0), Some((0, 0, "k1"))) + .await + .unwrap_err(); + assert!( + err.to_string() + .contains("does not unlock the recorded keyslot 0"), + "{err:#}" + ); + assert_eq!(disk.state(), interrupted); + assert!(disk.unlocks("k0") && disk.unlocks("k1")); +} + +#[tokio::test] +async fn test_luks_epoch_migration_with_disagreeing_header_copies() { + let Some(disk) = TestDisk::new("k1", Some((1, 0))) else { + return; + }; + disk.add_key("k1", "k2", 1); + let before = fs::read(&disk.image).unwrap(); + write_luks_epochs(&disk.image, 1, 2, 0).unwrap(); + let after = fs::read(&disk.image).unwrap(); + let hdr_size = LuksHeader::parse(&before).unwrap().hdr_size as usize; + // Interrupted between writing the two header copies, in either order. + for (primary, secondary) in [(&after, &before), (&before, &after)] { + let mut image = primary.clone(); + image[hdr_size..2 * hdr_size].copy_from_slice(&secondary[hdr_size..2 * hdr_size]); + fs::write(&disk.image, image).unwrap(); + disk.sync("k2", (2, 0), None).await.unwrap(); + disk.assert_synced("k2", (2, 0), 1); + } +} + +#[tokio::test] +async fn test_luks_epoch_migration_failures_keep_the_old_epochs() { + let Some(disk) = TestDisk::new("k1", Some((1, 0))) else { + return; + }; + let unchanged = disk.state(); + // The KMS denies the old epoch. + assert!(disk.sync("k2", (2, 0), None).await.is_err()); + // luksAddKey fails: the KMS answers with a key that does not unlock. + assert!(disk.sync("k2", (2, 0), Some((1, 0, "bad"))).await.is_err()); + // The disk records a root epoch newer than the current one. + let err = disk.sync("k0", (0, 3), None).await.unwrap_err(); + assert!(err.to_string().contains("exceed"), "{err:#}"); + assert_eq!(disk.state(), unchanged); + assert!(disk.unlocks("k1")); + + let app_ahead = TestDisk::new("k1", Some((1, 2))).unwrap(); + let err = app_ahead.sync("k1", (1, 1), None).await.unwrap_err(); + assert!(err.to_string().contains("exceed"), "{err:#}"); + + // A failed token import is an error. + let not_luks = disk.dir.path().join("not-luks"); + fs::write(¬_luks, [0; 4096]).unwrap(); + assert!(write_luks_epochs(¬_luks, 0, 2, 0).is_err()); +} + +#[tokio::test] +async fn test_luks_epoch_zero_disk_is_left_untouched() { + let Some(disk) = TestDisk::new("k0", None) else { + return; + }; + let unchanged = disk.state(); + disk.sync("k0", (0, 0), None).await.unwrap(); + assert_eq!(disk.state(), unchanged); + assert_eq!(unchanged.token_keyslot, None); +} + +#[test] +fn test_validate_luks2_header_root_epoch_token() { + let with_token = |token: &str| { + let mut header = include_bytes!("../../tests/fixtures/luks_header_good").to_vec(); + let replacement = format!(r#""tokens":{{"0":{token}}}"#); + let patched = patch_luks_json(&mut header, br#""tokens":{}"#, replacement.as_bytes()); + assert_eq!(patched, 2, "expected to patch both header copies"); + validate_luks2_headers(&mut &header[..]) + }; + let state = with_token(r#"{"type":"dstack-kms","keyslots":["0"],"root_epoch":2}"#).unwrap(); + assert_eq!(state.root_epoch, Some(2)); + for token in [ + r#"{"type":"luks2-keyring","keyslots":["0"],"root_epoch":2}"#, + r#"{"type":"dstack-kms","keyslots":["1"],"root_epoch":2}"#, + r#"{"type":"dstack-kms","keyslots":["0"]}"#, + ] { + assert!(with_token(token).is_err(), "{token}"); + } +} + +#[test] +fn test_validate_luks2_header_rejects_keyslot_area_that_overflows() { + let mut header = include_bytes!("../../tests/fixtures/luks_header_good").to_vec(); + // 2**64 - 32768 + 1000: added to the accepted offset 32768 it wraps to + // 1000, which is below PAYLOAD_OFFSET. + let patched = patch_luks_json( + &mut header, + br#""size":"258048""#, + br#""size":"18446744073709519848""#, + ); + assert_eq!(patched, 2, "expected to patch both header copies"); + let error = validate_luks2_headers(&mut &header[..]).unwrap_err(); + assert!( + error.to_string().contains("Invalid LUKS keyslot area"), + "{error:#}" + ); +} diff --git a/dstack/dstack-util/src/system_setup/sealed_env.rs b/dstack/dstack-util/src/system_setup/sealed_env.rs new file mode 100644 index 0000000000..ef7a717f60 --- /dev/null +++ b/dstack/dstack-util/src/system_setup/sealed_env.rs @@ -0,0 +1,57 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// +// SPDX-License-Identifier: Apache-2.0 + +//! Environment envelope encoding and encryption for guest boot migration. + +use anyhow::{Context, Result}; +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize)] +pub(super) struct SealedEnv { + pub(super) version: u32, + pub(super) root_epoch: u32, + pub(super) app_epoch: u32, + #[serde(with = "serde_human_bytes::base64")] + pub(super) enc: Vec, + #[serde(with = "serde_human_bytes::base64")] + pub(super) ciphertext: Vec, +} + +pub(super) fn sealed_env_info_at_epochs(root: u32, app: u32) -> Vec { + format!("dstack-sealed-env-v1:{root}:{app}").into_bytes() +} + +pub(super) fn seal_env_at_epochs( + secret: &[u8], + epoch: u32, + app_epoch: u32, + plaintext: &[u8], +) -> Result> { + let secret: [u8; 32] = secret.try_into().context("invalid sealed env key")?; + let public = x25519_dalek::PublicKey::from(&x25519_dalek::StaticSecret::from(secret)); + let payload = crate::crypto::sealed_env_encrypt( + &public.to_bytes(), + &sealed_env_info_at_epochs(epoch, app_epoch), + plaintext, + )?; + let (enc, ciphertext) = payload.split_at(32); + Ok(serde_json::to_vec(&SealedEnv { + version: 1, + root_epoch: epoch, + app_epoch, + enc: enc.to_vec(), + ciphertext: ciphertext.to_vec(), + })?) +} + +pub(super) fn env_crypt_key(key: &[u8]) -> Result<[u8; 32]> { + key.try_into() + .ok() + .context("encrypted env is present but the key provider gave no valid env crypt key") +} + +#[cfg(test)] +pub(super) fn seal_env(secret: &[u8], epoch: u32, plaintext: &[u8]) -> Result> { + seal_env_at_epochs(secret, epoch, 0, plaintext) +} diff --git a/dstack/dstack-util/src/system_setup/snp.rs b/dstack/dstack-util/src/system_setup/snp.rs new file mode 100644 index 0000000000..27c561dac1 --- /dev/null +++ b/dstack/dstack-util/src/system_setup/snp.rs @@ -0,0 +1,111 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// +// SPDX-License-Identifier: Apache-2.0 + +use anyhow::{bail, Context, Result}; +use dstack_types::{KeyProviderKind, SnpSealingParameters}; +use zeroize::Zeroizing; + +use super::{detect_tee_variant, AppInfo, Stage0, TeeVariant}; + +const SEALING_VERSION: u32 = 1; + +fn parameters_for_boot( + stored: Option, + disk_initialized: bool, + initial_tcb: impl FnOnce() -> Result, +) -> Result { + // A new disk is always sealed to the running TCB: stored values are + // host-supplied, and an older TCB would stay able to derive the key. + if disk_initialized { + let parameters = + stored.context("snp sealing parameters are missing for an existing encrypted disk")?; + if parameters.version != SEALING_VERSION { + bail!( + "unsupported SNP sealing parameter version: {}", + parameters.version + ); + } + return Ok(parameters); + } + Ok(SnpSealingParameters { + version: SEALING_VERSION, + tcb_version: initial_tcb()?, + }) +} + +impl Stage0<'_> { + pub(super) async fn get_snp_seed(&self, app_info: &mut AppInfo) -> Result> { + if detect_tee_variant()? != TeeVariant::DstackAmdSevSnp { + bail!("the SEV-SNP key provider requires an AMD SEV-SNP guest"); + } + // HOST_DATA is host-supplied. The measured OS must validate its binding + // to the actual app/config before deriving or using a sealing seed. + self.verify_app_config(app_info, KeyProviderKind::SevSnp, &[])?; + let disk_initialized = self.sealed_disk_initialized(KeyProviderKind::SevSnp)?; + let parameters = parameters_for_boot( + app_info.instance_info.snp_sealing, + disk_initialized, + sev_snp_attest::sealing::initial_tcb_version, + )?; + app_info.instance_info.snp_sealing = Some(parameters); + + // An existing disk reuses the stored parameters, so only a new disk + // has to persist them. They are public derivation metadata. + if !disk_initialized { + self.persist_sealing_parameters(KeyProviderKind::SevSnp, &app_info.instance_info) + .await?; + } + sev_snp_attest::sealing::derive_sealing_seed(parameters.tcb_version) + .context("failed to derive SNP sealing seed") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn preserves_initial_tcb_on_later_boots() { + let stored = SnpSealingParameters { + version: 1, + tcb_version: 0x0101, + }; + let actual = + parameters_for_boot(Some(stored), true, || panic!("must not select a new TCB")); + assert_eq!(actual.unwrap(), stored); + } + + #[test] + fn initializes_only_a_new_disk() { + let host_supplied = SnpSealingParameters { + version: 1, + tcb_version: 0, + }; + let parameters = parameters_for_boot(Some(host_supplied), false, || Ok(0x0202)).unwrap(); + assert_eq!( + parameters, + SnpSealingParameters { + version: 1, + tcb_version: 0x0202 + } + ); + assert!( + parameters_for_boot(None, true, || panic!("must not replace missing metadata")) + .is_err() + ); + } + + #[test] + fn rejects_unknown_policy_and_derivation_errors() { + let stored = SnpSealingParameters { + version: 2, + tcb_version: 1, + }; + assert!(parameters_for_boot(Some(stored), true, || panic!( + "must not replace unknown policy" + )) + .is_err()); + assert!(parameters_for_boot(None, false, || bail!("unsupported platform")).is_err()); + } +} diff --git a/dstack/dstack-util/src/system_setup/tdx_seal.rs b/dstack/dstack-util/src/system_setup/tdx_seal.rs new file mode 100644 index 0000000000..83a652d54c --- /dev/null +++ b/dstack/dstack-util/src/system_setup/tdx_seal.rs @@ -0,0 +1,127 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// +// SPDX-License-Identifier: Apache-2.0 + +use anyhow::{bail, Context, Result}; +use dstack_types::{KeyProviderKind, TdxSealingParameters}; +use tdx_attest::sealing::SealingSvns; +use zeroize::Zeroizing; + +use super::{detect_tee_variant, AppInfo, Stage0, TeeVariant}; + +const SEALING_VERSION: u32 = 1; + +fn parameters_for_boot( + stored: Option, + disk_initialized: bool, + initial_svns: impl FnOnce() -> Result, +) -> Result { + // A new disk is always sealed to the running TCB: stored values are + // host-supplied, and an older TCB would stay able to derive the key. + if disk_initialized { + let parameters = + stored.context("tdx sealing parameters are missing for an existing encrypted disk")?; + if parameters.version != SEALING_VERSION { + bail!( + "unsupported TDX sealing parameter version: {}", + parameters.version + ); + } + return Ok(parameters); + } + let svns = initial_svns()?; + Ok(TdxSealingParameters { + version: SEALING_VERSION, + cpusvn: svns.cpusvn, + tee_tcb_svn: svns.tee_tcb_svn, + }) +} + +impl Stage0<'_> { + /// Must run after `boot-mr-done` and before any later RTMR3 event: the seed + /// is bound to RTMR3 as it stands at that point. + pub(super) async fn get_tdx_seal_seed( + &self, + app_info: &mut AppInfo, + ) -> Result> { + if detect_tee_variant()? != TeeVariant::DstackTdx { + bail!("the tdx-seal key provider requires a dstack TDX guest"); + } + self.verify_app_config(app_info, KeyProviderKind::TdxSeal, &[])?; + let disk_initialized = self.sealed_disk_initialized(KeyProviderKind::TdxSeal)?; + let parameters = parameters_for_boot( + app_info.instance_info.tdx_sealing, + disk_initialized, + tdx_attest::sealing::current_svns, + )?; + app_info.instance_info.tdx_sealing = Some(parameters); + + // An existing disk reuses the stored parameters, so only a new disk + // has to persist them. They are public derivation metadata. + if !disk_initialized { + self.persist_sealing_parameters(KeyProviderKind::TdxSeal, &app_info.instance_info) + .await?; + } + tdx_attest::sealing::derive_sealing_seed(&SealingSvns { + cpusvn: parameters.cpusvn, + tee_tcb_svn: parameters.tee_tcb_svn, + }) + .context("failed to derive TDX sealing seed") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const SVNS: SealingSvns = SealingSvns { + cpusvn: [8; 16], + tee_tcb_svn: [9; 16], + }; + + #[test] + fn preserves_initial_svns_on_later_boots() { + let stored = TdxSealingParameters { + version: 1, + cpusvn: [1; 16], + tee_tcb_svn: [2; 16], + }; + let actual = parameters_for_boot(Some(stored), true, || panic!("must not select new SVNs")); + assert_eq!(actual.unwrap(), stored); + } + + #[test] + fn initializes_only_a_new_disk() { + let host_supplied = TdxSealingParameters { + version: 1, + cpusvn: [0; 16], + tee_tcb_svn: [0; 16], + }; + let parameters = parameters_for_boot(Some(host_supplied), false, || Ok(SVNS)).unwrap(); + assert_eq!( + parameters, + TdxSealingParameters { + version: 1, + cpusvn: SVNS.cpusvn, + tee_tcb_svn: SVNS.tee_tcb_svn, + } + ); + assert!( + parameters_for_boot(None, true, || panic!("must not replace missing metadata")) + .is_err() + ); + } + + #[test] + fn rejects_unknown_versions() { + let stored = TdxSealingParameters { + version: 2, + cpusvn: [0; 16], + tee_tcb_svn: [0; 16], + }; + assert!(parameters_for_boot(Some(stored), true, || panic!( + "must not replace unknown policy" + )) + .is_err()); + } +} diff --git a/dstack/gateway/Cargo.toml b/dstack/gateway/Cargo.toml index e682bb690b..e2a9df7a72 100644 --- a/dstack/gateway/Cargo.toml +++ b/dstack/gateway/Cargo.toml @@ -55,6 +55,7 @@ http-body-util.workspace = true x509-parser.workspace = true jemallocator.workspace = true proxy-protocol.workspace = true +rocket-proxy-listener.workspace = true wavekv.workspace = true tdx-attest.workspace = true flate2.workspace = true diff --git a/dstack/gateway/docs/cluster-deployment.md b/dstack/gateway/docs/cluster-deployment.md index f74a73342b..d8870c04f4 100644 --- a/dstack/gateway/docs/cluster-deployment.md +++ b/dstack/gateway/docs/cluster-deployment.md @@ -63,12 +63,13 @@ When a CVM starts, it registers with one of the Gateways. The Gateway cluster au Production security configuration example: ```toml -[core.debug] -insecure_enable_debug_rpc = false # Disable Debug port +[listeners.debug] +enabled = false # Disable Debug port -[core.admin] +[listeners.admin] enabled = true address = "unix:/run/dstack/admin.sock" # Use Unix Domain Socket +proxy_protocol = false # PROXY protocol needs TCP; required if [listeners.default] enables it ``` ### Resource Sizing @@ -219,28 +220,31 @@ node loses its store while retaining its identity. gateway-1.toml: ```toml +[listeners.default] log_level = "info" + +[listeners.guest] address = "0.0.0.0" port = 9012 -[tls] +[listeners.guest.tls] key = "/var/lib/gateway/certs/gateway-rpc.key" certs = "/var/lib/gateway/certs/gateway-rpc.cert" -[tls.mutual] +[listeners.guest.tls.mutual] ca_certs = "/var/lib/gateway/certs/gateway-ca.cert" mandatory = false [core] rpc_domain = "rpc.gateway-1.demo.dstack.org" -[core.admin] +[listeners.admin] enabled = true port = 9016 address = "0.0.0.0" -[core.debug] -insecure_enable_debug_rpc = true +[listeners.debug] +enabled = true port = 9015 address = "0.0.0.0" @@ -272,15 +276,18 @@ listen_port = 9014 gateway-2.toml: ```toml +[listeners.default] log_level = "info" + +[listeners.guest] address = "0.0.0.0" port = 9012 -[tls] +[listeners.guest.tls] key = "/var/lib/gateway/certs/gateway-rpc.key" certs = "/var/lib/gateway/certs/gateway-rpc.cert" -[tls.mutual] +[listeners.guest.tls.mutual] ca_certs = "/var/lib/gateway/certs/gateway-ca.cert" mandatory = false @@ -332,7 +339,7 @@ Important: ### 2.8 Verify Cluster Sync -The admin API requires a bearer token (see `core.admin.auth_token` in `gateway.toml`, +The admin API requires a bearer token (see `listeners.admin.auth_token` in `gateway.toml`, or the `ADMIN_API_TOKEN` env injected by `deploy-to-vmm.sh`). Export it once: ```bash @@ -516,7 +523,7 @@ BOOTNODE_URL=https://gateway-2.example.com:19702 EOF # Update and restart -vmm-cli.py --url update-env --env-file updated.env +vmm-cli.py --url update --env-file updated.env --kms-encrypt-url vmm-cli.py --url stop vmm-cli.py --url start ``` diff --git a/dstack/gateway/dstack-app/builder/Dockerfile b/dstack/gateway/dstack-app/builder/Dockerfile index 1c2294da65..8a0e7dec02 100644 --- a/dstack/gateway/dstack-app/builder/Dockerfile +++ b/dstack/gateway/dstack-app/builder/Dockerfile @@ -3,8 +3,8 @@ # SPDX-License-Identifier: Apache-2.0 FROM rust:1.92.0@sha256:48851a839d6a67370c9dbe0e709bedc138e3e404b161c5233aedcf2b717366e4 AS gateway-builder -COPY --from=build-shared pin-packages.sh /build/ -COPY ./shared/*-pinned-packages.txt /build/ +COPY --chmod=0755 --from=build-shared pin-packages.sh /build/ +COPY --chmod=0644 ./shared/*-pinned-packages.txt /build/ ARG DSTACK_REV ARG DSTACK_SRC_URL=https://github.com/Dstack-TEE/dstack.git WORKDIR /build @@ -27,8 +27,8 @@ RUN cd repo/dstack && cargo build --release --locked -p dstack-gateway --target RUN echo "${DSTACK_REV}" > /build/.GIT_REV FROM debian:bookworm@sha256:0d8498a0e9e6a60011df39aab78534cfe940785e7c59d19dfae1eb53ea59babe -COPY --from=build-shared pin-packages.sh /build/ -COPY ./shared/pinned-packages.txt /build/ +COPY --chmod=0755 --from=build-shared pin-packages.sh /build/ +COPY --chmod=0644 ./shared/pinned-packages.txt /build/ WORKDIR /build RUN ./pin-packages.sh ./pinned-packages.txt && \ apt-get update -o APT::Update::Error-Mode=any && \ @@ -47,7 +47,7 @@ COPY --from=gateway-builder /build/.GIT_REV /etc/ ARG IMAGE_METADATA RUN mkdir -p /etc/dstack-gateway && printf '%s\n' "${IMAGE_METADATA}" > /etc/dstack-gateway/build-info WORKDIR /app -COPY entrypoint.sh /app/entrypoint.sh +COPY --chmod=0755 entrypoint.sh /app/entrypoint.sh RUN chmod +x /app/entrypoint.sh ENTRYPOINT ["/app/entrypoint.sh"] CMD ["dstack-gateway", "-c", "/data/gateway/gateway.toml"] diff --git a/dstack/gateway/dstack-app/builder/README.md b/dstack/gateway/dstack-app/builder/README.md index b8aedad533..52e406be3d 100644 --- a/dstack/gateway/dstack-app/builder/README.md +++ b/dstack/gateway/dstack-app/builder/README.md @@ -46,6 +46,11 @@ that tag, rather than building the branch selected in the workflow UI. ## Reproducing a released image +Files copied from the checkout have explicit permissions in the Dockerfile, +so the caller's clone-time umask does not affect their image layers. For older +release tags without these permissions, set `umask 0022` before cloning to +match the release checkout. + Release CI runs this same script, so a published image can be rebuilt and checked digest-for-digest. Use a clean checkout of the release commit so the Dockerfile, package lists, shared scripts and copied files also match the release. diff --git a/dstack/gateway/dstack-app/builder/entrypoint.sh b/dstack/gateway/dstack-app/builder/entrypoint.sh index 179d26ad18..d406d6bf57 100755 --- a/dstack/gateway/dstack-app/builder/entrypoint.sh +++ b/dstack/gateway/dstack-app/builder/entrypoint.sh @@ -63,18 +63,23 @@ echo "RPC_DOMAIN: $RPC_DOMAIN" # Create gateway.toml configuration cat >$CONFIG_PATH <`, `X-Admin-Token`, +# or (GET only, for dashboard links) `?token=...`. Required unless +# `insecure_no_auth = true`. (The legacy key `admin_token` is still accepted.) +auth_token = "" +# Optional Apache htpasswd file for HTTP Basic authentication. +htpasswd_file = "" +# Development/testing escape hatch only. Never enable this on an admin +# interface that is reachable from the network. +insecure_no_auth = false + +# Debug RPCs, unauthenticated: development only. +[listeners.debug] +enabled = false +address = "127.0.0.1:8012" + [core] # auto set soft ulimit to hard ulimit set_ulimit = true @@ -41,30 +77,6 @@ enabled = false url = "http://localhost/app-auth" timeout = "5s" -[core.admin] -enabled = false -address = "127.0.0.1:8011" -# Shared secret required by every admin endpoint (RPC + dashboard). Can also -# be supplied via the `DSTACK_GATEWAY_ADMIN_TOKEN` or `ADMIN_API_TOKEN` env -# vars. Clients send it as `Authorization: Bearer `, `X-Admin-Token`, -# or (GET only, for dashboard links) `?token=...`. Required unless -# `insecure_no_auth = true`. (The legacy key `admin_token` is still accepted.) -auth_token = "" -# Optional Apache htpasswd file for HTTP Basic authentication. -htpasswd_file = "" -# Development/testing escape hatch only. Never enable this on an admin -# interface that is reachable from the network. -insecure_no_auth = false - -[core.debug] -insecure_enable_debug_rpc = false -# Route the app address "localhost" to 127.0.0.1 on the gateway host. Off by -# default: the app address also comes from the _dstack-app-address TXT record of -# arbitrary custom domains, so enabling this lets any DNS zone owner reach the -# gateway's own loopback on a port of their choosing, bypassing port_policy. -insecure_localhost_backend = false -address = "127.0.0.1:8012" - [core.wg] public_key = "" private_key = "" @@ -87,6 +99,11 @@ buffer_size = 65536 connect_top_n = 3 app_address_ns_prefix = "_dstack-app-address" app_address_ns_compat = true +# Route the app address "localhost" to 127.0.0.1 on the gateway host. Off by +# default: the app address also comes from the _dstack-app-address TXT record of +# arbitrary custom domains, so enabling this lets any DNS zone owner reach the +# gateway's own loopback on a port of their choosing, bypassing port_policy. +insecure_localhost_backend = false workers = 32 # One runtime + SO_REUSEPORT listener per worker (thread-per-core). Linux only. thread_per_core = true diff --git a/dstack/gateway/rpc/Cargo.toml b/dstack/gateway/rpc/Cargo.toml index 3a38ad25bc..3c20f387cb 100644 --- a/dstack/gateway/rpc/Cargo.toml +++ b/dstack/gateway/rpc/Cargo.toml @@ -16,6 +16,11 @@ serde = { workspace = true, features = ["derive"] } serde_json.workspace = true anyhow.workspace = true scale = { workspace = true, features = ["derive"] } +base64.workspace = true +hkdf.workspace = true +hmac.workspace = true +sha2.workspace = true +x25519-dalek.workspace = true [build-dependencies] prpc-build.workspace = true diff --git a/dstack/gateway/rpc/proto/gateway_rpc.proto b/dstack/gateway/rpc/proto/gateway_rpc.proto index 6a23982ca9..a5a729d6c9 100644 --- a/dstack/gateway/rpc/proto/gateway_rpc.proto +++ b/dstack/gateway/rpc/proto/gateway_rpc.proto @@ -31,6 +31,40 @@ message RegisterCvmRequest { // gateway falls back to fetching app-compose via Info()) from "reported // empty" (new CVM with no special port behaviour). optional PortPolicy port_policy = 2; + // Ed25519 JWT the CVM minted for its own guest agent, so the gateway can + // call the agent's external listener now that it refuses anonymous callers + // by default. Bound to this CVM's app id and expiring within the hour; the + // CVM re-registers every three minutes, so a stale copy never outlives its + // usefulness. + // + // Empty from a CVM that predates the field, or one that could not mint it. + // The gateway then calls without a token and gets whatever the host left + // open -- possibly nothing, which is the intended default. + optional string agent_token = 4; + // Proof that this CVM holds the private key behind `client_public_key`. + // + // Without it the key is taken on trust, and a CVM that learned another + // CVM's public key could register with it while that CVM's record is + // recycled, then win the oldest-record-wins resolution on its return. + // + // Absent from a CVM that predates the field, or one whose gateway did not + // report a WireGuard key in `Info`. The gateway accepts that unless the + // cluster's key proof policy (`SetWgKeyProofConfig`) requires a proof. + WgKeyProof wg_key_proof = 5; +} + +// WgKeyProof proves possession of a WireGuard private key to one gateway node. +// +// `mac` is HMAC-SHA256 keyed by HKDF-SHA256 over X25519(client key, gateway +// key), and covers both public keys plus the CVM's attested app and instance +// ids, so it convinces only the node holding the named gateway key, and only +// for this CVM. +message WgKeyProof { + // The WireGuard public key of the gateway node the proof is made for, as + // returned by its `Info`. A node refuses a proof naming another key. + string gateway_public_key = 1; + // The MAC, 32 bytes. + bytes mac = 2; } // PortPolicy carries the gateway-relevant per-port configuration declared by @@ -262,6 +296,9 @@ message InfoResponse { string app_address_ns_prefix = 3; // The version of the gateway string version = 4; + // This node's WireGuard public key, the target of `WgKeyProof`. Empty from + // a gateway that predates key proofs. + string wg_public_key = 5; } // Peer info for GetPeers response @@ -579,6 +616,13 @@ service Admin { // write-count boundaries. Zero disables collection cluster-wide. rpc SetTombstoneGcConfig(SetTombstoneGcConfigRequest) returns (google.protobuf.Empty) {} + // ==================== WireGuard Key Proof Policy ==================== + // Get the cluster-wide WireGuard key proof policy + rpc GetWgKeyProofConfig(google.protobuf.Empty) returns (WgKeyProofConfig) {} + // Store the WireGuard key proof policy in the replicated KV. Takes effect on + // the next registration on every node, without a restart. + rpc SetWgKeyProofConfig(WgKeyProofConfig) returns (google.protobuf.Empty) {} + // ==================== Per-Instance Port Policy Override ==================== // Set an admin override for an instance's port policy. Takes precedence // over the policy reported by the instance itself, and survives app @@ -922,6 +966,14 @@ message SetTombstoneGcConfigRequest { uint64 writes_per_collection = 1; } +// ==================== WireGuard Key Proof Policy Messages ==================== + +// Cluster-wide WireGuard key proof policy +message WgKeyProofConfig { + // Refuse registrations without a valid WireGuard key proof + bool require_key_proof = 1; +} + // ==================== Per-Instance Port Policy Override Messages ==================== // Set an admin override for an instance. diff --git a/dstack/gateway/rpc/src/lib.rs b/dstack/gateway/rpc/src/lib.rs index 089da7c607..c84471d5db 100644 --- a/dstack/gateway/rpc/src/lib.rs +++ b/dstack/gateway/rpc/src/lib.rs @@ -7,3 +7,4 @@ extern crate alloc; pub use generated::*; mod generated; +pub mod wg_key_proof; diff --git a/dstack/gateway/rpc/src/wg_key_proof.rs b/dstack/gateway/rpc/src/wg_key_proof.rs new file mode 100644 index 0000000000..6016bd5beb --- /dev/null +++ b/dstack/gateway/rpc/src/wg_key_proof.rs @@ -0,0 +1,188 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// +// SPDX-License-Identifier: Apache-2.0 + +//! WireGuard key proof-of-possession for `RegisterCvm`. +//! +//! The CVM computes `X25519(client_sk, gateway_pk)`, which only it and the +//! named gateway node can compute, derives a MAC key from it with HKDF-SHA256, +//! and MACs both public keys plus its attested app and instance ids. The node +//! recomputes the shared secret from its own private key and the claimed +//! client key; a match shows the registrant holds the client private key. + +use anyhow::{bail, Context, Result}; +use base64::{engine::general_purpose::STANDARD, Engine}; +use hkdf::Hkdf; +use hmac::{Hmac, Mac}; +use sha2::Sha256; +use x25519_dalek::{PublicKey, StaticSecret}; + +use crate::WgKeyProof; + +const LABEL: &[u8] = b"dstack-gateway-wg-key-proof-v1"; + +/// Build the proof for `gateway_public_key` from the CVM's WireGuard private +/// key and its attested identity. +pub fn compute( + client_private_key: &str, + gateway_public_key: &str, + app_id: &[u8], + instance_id: &[u8], +) -> Result { + let client_sk = + StaticSecret::from(decode_key(client_private_key).context("client private key")?); + let gateway_pk = decode_key(gateway_public_key).context("gateway public key")?; + let client_pk = PublicKey::from(&client_sk).to_bytes(); + let mac = new_mac( + &client_sk, + gateway_pk, + client_pk, + gateway_pk, + app_id, + instance_id, + )?; + Ok(WgKeyProof { + gateway_public_key: gateway_public_key.to_string(), + mac: mac.finalize().into_bytes().to_vec(), + }) +} + +/// Check `proof` on the gateway node holding `gateway_private_key`. +pub fn verify( + proof: &WgKeyProof, + gateway_private_key: &str, + client_public_key: &str, + app_id: &[u8], + instance_id: &[u8], +) -> Result<()> { + let gateway_sk = + StaticSecret::from(decode_key(gateway_private_key).context("gateway private key")?); + let gateway_pk = PublicKey::from(&gateway_sk).to_bytes(); + let target = decode_key(&proof.gateway_public_key).context("proof gateway public key")?; + if target != gateway_pk { + bail!( + "proof targets gateway key {}, not this node's", + proof.gateway_public_key + ); + } + let client_pk = decode_key(client_public_key).context("client public key")?; + new_mac( + &gateway_sk, + client_pk, + client_pk, + gateway_pk, + app_id, + instance_id, + )? + .verify_slice(&proof.mac) + .ok() + .context("proof MAC does not verify for this key and identity") +} + +fn new_mac( + our_sk: &StaticSecret, + their_pk: [u8; 32], + client_pk: [u8; 32], + gateway_pk: [u8; 32], + app_id: &[u8], + instance_id: &[u8], +) -> Result> { + let shared = our_sk.diffie_hellman(&PublicKey::from(their_pk)); + // A low-order point yields a secret anyone can compute. + if !shared.was_contributory() { + bail!("low-order WireGuard public key"); + } + let mut key = [0u8; 32]; + Hkdf::::new(None, shared.as_bytes()) + .expand(LABEL, &mut key) + .ok() + .context("hkdf expand failed")?; + let mut mac = Hmac::::new_from_slice(&key) + .ok() + .context("bad hmac key")?; + for field in [&client_pk[..], &gateway_pk[..], app_id, instance_id] { + mac.update(&(field.len() as u32).to_be_bytes()); + mac.update(field); + } + Ok(mac) +} + +/// Decode a WireGuard key in the padded base64 form `wg` uses. +fn decode_key(key: &str) -> Result<[u8; 32]> { + let bytes = STANDARD.decode(key).context("invalid base64")?; + bytes + .try_into() + .ok() + .context("WireGuard key must be 32 bytes") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn keypair(seed: u8) -> (String, String) { + let sk = StaticSecret::from([seed; 32]); + let pk = PublicKey::from(&sk); + ( + STANDARD.encode(sk.to_bytes()), + STANDARD.encode(pk.to_bytes()), + ) + } + + #[test] + fn round_trip_verifies() { + let (client_sk, client_pk) = keypair(1); + let (gw_sk, gw_pk) = keypair(2); + let proof = compute(&client_sk, &gw_pk, b"app", b"instance").unwrap(); + verify(&proof, &gw_sk, &client_pk, b"app", b"instance").unwrap(); + } + + #[test] + fn rejects_another_client_key() { + let (client_sk, _) = keypair(1); + let (_, victim_pk) = keypair(3); + let (gw_sk, gw_pk) = keypair(2); + let proof = compute(&client_sk, &gw_pk, b"app", b"instance").unwrap(); + assert!(verify(&proof, &gw_sk, &victim_pk, b"app", b"instance").is_err()); + } + + #[test] + fn rejects_another_gateway_key() { + let (client_sk, client_pk) = keypair(1); + let (_, gw_pk) = keypair(2); + let (other_sk, _) = keypair(4); + let proof = compute(&client_sk, &gw_pk, b"app", b"instance").unwrap(); + let err = verify(&proof, &other_sk, &client_pk, b"app", b"instance").unwrap_err(); + assert!(format!("{err:#}").contains("targets gateway key")); + } + + #[test] + fn rejects_another_identity() { + let (client_sk, client_pk) = keypair(1); + let (gw_sk, gw_pk) = keypair(2); + let proof = compute(&client_sk, &gw_pk, b"app", b"instance").unwrap(); + assert!(verify(&proof, &gw_sk, &client_pk, b"app", b"other").is_err()); + assert!(verify(&proof, &gw_sk, &client_pk, b"other", b"instance").is_err()); + // Length prefixes keep the boundary between the ids significant. + assert!(verify(&proof, &gw_sk, &client_pk, b"appi", b"nstance").is_err()); + } + + #[test] + fn rejects_low_order_point() { + let (client_sk, _) = keypair(1); + let (gw_sk, _) = keypair(2); + let low_order = STANDARD.encode([0u8; 32]); + assert!(compute(&client_sk, &low_order, b"app", b"instance").is_err()); + let mut proof = compute(&client_sk, &keypair(2).1, b"app", b"instance").unwrap(); + proof.mac = vec![0; 32]; + let err = verify(&proof, &gw_sk, &low_order, b"app", b"instance").unwrap_err(); + assert!(format!("{err:#}").contains("low-order")); + } + + #[test] + fn rejects_malformed_keys() { + let (client_sk, _) = keypair(1); + assert!(compute(&client_sk, "not base64!", b"app", b"instance").is_err()); + assert!(compute(&client_sk, &STANDARD.encode([1u8; 31]), b"a", b"i").is_err()); + } +} diff --git a/dstack/gateway/src/admin_auth.rs b/dstack/gateway/src/admin_auth.rs index 06c9f0b62a..dbd6d40773 100644 --- a/dstack/gateway/src/admin_auth.rs +++ b/dstack/gateway/src/admin_auth.rs @@ -35,8 +35,8 @@ impl AdminAuthFairing { if token.is_empty() && config.htpasswd_file.as_os_str().is_empty() { bail!( "admin API is enabled but neither auth_token nor htpasswd_file is configured; \ - set core.admin.auth_token, {ENV_ADMIN_TOKEN}, {ENV_ADMIN_TOKEN_COMPAT}, \ - core.admin.htpasswd_file, or insecure_no_auth = true (testing only)" + set listeners.admin.auth_token, {ENV_ADMIN_TOKEN}, {ENV_ADMIN_TOKEN_COMPAT}, \ + listeners.admin.htpasswd_file, or insecure_no_auth = true (testing only)" ); } let mut auth = Authenticator::from_tokens([token]); diff --git a/dstack/gateway/src/admin_service.rs b/dstack/gateway/src/admin_service.rs index 1ce6b78103..e6a87a23ac 100644 --- a/dstack/gateway/src/admin_service.rs +++ b/dstack/gateway/src/admin_service.rs @@ -24,17 +24,20 @@ use dstack_gateway_rpc::{ SetCertbotConfigRequest, SetDefaultDnsCredentialRequest, SetInstancePortPolicyRequest, SetInstanceReadyRequest, SetNodeStatusRequest, SetNodeUrlRequest, SetTombstoneGcConfigRequest, StatusResponse, StoreSyncStatus, TombstoneGcConfigResponse, UpdateDnsCredentialRequest, - WaveKvStatusResponse, ZtDomainCertStatus, ZtDomainConfig as ProtoZtDomainConfig, ZtDomainInfo, + WaveKvStatusResponse, WgKeyProofConfig, ZtDomainCertStatus, + ZtDomainConfig as ProtoZtDomainConfig, ZtDomainInfo, }; -use ra_rpc::{CallContext, RpcCall}; +use ra_rpc::{CallContext, RemoteEndpoint, RpcCall}; use tracing::{info, warn}; use wavekv::node::NodeStatus as WaveKvNodeStatus; use crate::{ cert_store::get_cert_expiry, + distributed_certbot::MAX_RENEW_TIMEOUT_SECS, kv::{ import::Rejection, CertData, DnsCredential, DnsProvider, GlobalCertbotConfig, - GlobalTombstoneGcConfig, NodeStatus, PortFlags, PortPolicy, ZtDomainConfig, + GlobalTombstoneGcConfig, GlobalWgKeyProofConfig, NodeStatus, PortFlags, PortPolicy, + ZtDomainConfig, }, main_service::Proxy, models::PortPolicyView, @@ -44,9 +47,30 @@ use crate::{ pub struct AdminRpcHandler { state: Proxy, + remote_endpoint: Option, } impl AdminRpcHandler { + /// Log a state-changing admin operation and its outcome to the audit target. + fn audit(&self, operation: &str, subject: &str, result: Result) -> Result { + match &result { + Ok(_) => info!( + target: "dstack_gateway::audit", + operation, + remote = ?self.remote_endpoint, + "admin: {subject}" + ), + Err(err) => warn!( + target: "dstack_gateway::audit", + operation, + remote = ?self.remote_endpoint, + error = %ra_rpc::log_text(&format_args!("{err:#}")), + "admin refused: {subject}" + ), + } + result + } + pub(crate) async fn status(self) -> Result { tokio::task::spawn_blocking(move || { self.state.refresh_state()?; @@ -108,31 +132,51 @@ impl AdminRpcHandler { impl AdminRpc for AdminRpcHandler { async fn exit(self, request: ExitRequest) -> Result<()> { - self.state.lock().exit(request.force) + let subject = format!("force={}", request.force); + if request.force { + // A forced exit never returns, so record it before it happens. + self.audit("exit", &subject, Ok(()))?; + } + let result = async { self.state.lock().exit(request.force) }.await; + self.audit("exit", &subject, result) } async fn renew_cert(self) -> Result { - // Renew all domains with force=true - let renewed = self.state.renew_cert(None, true).await?; - Ok(RenewCertResponse { renewed }) + let subject = "all domains, forced".to_string(); + let result = async { + // Renew all domains with force=true + let renewed = self.state.renew_cert(None, true).await?; + Ok(RenewCertResponse { renewed }) + } + .await; + self.audit("renew_cert", &subject, result) } async fn set_caa(self) -> Result<()> { - self.state.certbot.set_caa_all().await + let subject = "all domains".to_string(); + let result = async { self.state.certbot.set_caa_all().await }.await; + self.audit("set_caa", &subject, result) } async fn reload_cert(self) -> Result<()> { - self.state.reload_all_certs_from_kvstore() + let subject = "all domains".to_string(); + let result = async { self.state.reload_all_certs_from_kvstore() }.await; + self.audit("reload_cert", &subject, result) } async fn rotate_acme_credentials(self) -> Result { - let outcome = self.state.rotate_acme_credentials().await?; - Ok(RotateAcmeCredentialsResponse { - account_uri: outcome.account_uri, - domains_updated: outcome.domains_updated.try_into().unwrap_or(u32::MAX), - required_dns_records: outcome.required_dns_records, - repin_failed_domains: outcome.repin_failed, - }) + let subject = String::new(); + let result = async { + let outcome = self.state.rotate_acme_credentials().await?; + Ok(RotateAcmeCredentialsResponse { + account_uri: outcome.account_uri, + domains_updated: outcome.domains_updated.try_into().unwrap_or(u32::MAX), + required_dns_records: outcome.required_dns_records, + repin_failed_domains: outcome.repin_failed, + }) + } + .await; + self.audit("rotate_acme_credentials", &subject, result) } async fn status(self) -> Result { @@ -205,27 +249,35 @@ impl AdminRpc for AdminRpcHandler { } async fn set_node_url(self, request: SetNodeUrlRequest) -> Result<()> { - let kv_store = self.state.kv_store(); - // Writing a node's address back is the explicit re-admission - // decision, so it clears the removal marker the sync lockout reads. - if kv_store.clear_peer_removed(request.id)? { - info!("cleared the removal marker for node {}", request.id); + let subject = format!("node {} url {}", request.id, request.url); + let result = async { + let kv_store = self.state.kv_store(); + // Writing a node's address back is the explicit re-admission + // decision, so it clears the removal marker the sync lockout reads. + if kv_store.clear_peer_removed(request.id)? { + info!("cleared the removal marker for node {}", request.id); + } + kv_store.register_peer_url(request.id, &request.url)?; + Ok(()) } - kv_store.register_peer_url(request.id, &request.url)?; - info!("Updated peer URL: node {} -> {}", request.id, request.url); - Ok(()) + .await; + self.audit("set_node_url", &subject, result) } async fn set_node_status(self, request: SetNodeStatusRequest) -> Result<()> { - let kv_store = self.state.kv_store(); - let status = match request.status.as_str() { - "up" => NodeStatus::Up, - "down" => NodeStatus::Down, - _ => anyhow::bail!("invalid status: expected 'up' or 'down'"), - }; - kv_store.set_node_status(request.id, status)?; - info!("Updated node status: node {} -> {:?}", request.id, status); - Ok(()) + let subject = format!("node {} status {}", request.id, request.status); + let result = async { + let kv_store = self.state.kv_store(); + let status = match request.status.as_str() { + "up" => NodeStatus::Up, + "down" => NodeStatus::Down, + _ => anyhow::bail!("invalid status: expected 'up' or 'down'"), + }; + kv_store.set_node_status(request.id, status)?; + Ok(()) + } + .await; + self.audit("set_node_status", &subject, result) } async fn wave_kv_status(self) -> Result { @@ -352,22 +404,27 @@ impl AdminRpc for AdminRpcHandler { } async fn remove_cvm(self, request: RemoveCvmRequest) -> Result { - let instance_id = request.instance_id.as_str(); - // Same bound the KV import boundary puts on identifiers. Legitimate - // gateways never write an instance_id outside it, so this rejects only - // typos — and keeps the ID safe to embed in logs and KV keys. - crate::kv::import::validate_id("instance_id", instance_id)?; - - let removal = self.state.remove_cvm(instance_id)?; - warn!( - "admin removed CVM {instance_id} from WaveKV and the local data plane \ - (record existed: {}, present locally: {})", - removal.record_existed, removal.removed_locally - ); - Ok(RemoveCvmResponse { - record_existed: removal.record_existed, - removed_locally: removal.removed_locally, - }) + let subject = format!("instance {}", request.instance_id); + let result = async { + let instance_id = request.instance_id.as_str(); + // Same bound the KV import boundary puts on identifiers. Legitimate + // gateways never write an instance_id outside it, so this rejects only + // typos — and keeps the ID safe to embed in logs and KV keys. + crate::kv::import::validate_id("instance_id", instance_id)?; + + let removal = self.state.remove_cvm(instance_id)?; + warn!( + "admin removed CVM {instance_id} from WaveKV and the local data plane \ + (record existed: {}, present locally: {})", + removal.record_existed, removal.removed_locally + ); + Ok(RemoveCvmResponse { + record_existed: removal.record_existed, + removed_locally: removal.removed_locally, + }) + } + .await; + self.audit("remove_cvm", &subject, result) } async fn list_rejected_instances(self) -> Result { @@ -389,16 +446,21 @@ impl AdminRpc for AdminRpcHandler { } async fn remove_node(self, request: RemoveNodeRequest) -> Result { - let removal = self.state.remove_node(request.node_id)?; - warn!( - "admin removed node {} from WaveKV and the sync peer set \ - (record existed: {}, was a sync peer: {})", - request.node_id, removal.record_existed, removal.removed_from_peer_set - ); - Ok(RemoveNodeResponse { - record_existed: removal.record_existed, - removed_from_peer_set: removal.removed_from_peer_set, - }) + let subject = format!("node {}", request.node_id); + let result = async { + let removal = self.state.remove_node(request.node_id)?; + warn!( + "admin removed node {} from WaveKV and the sync peer set \ + (record existed: {}, was a sync peer: {})", + request.node_id, removal.record_existed, removal.removed_from_peer_set + ); + Ok(RemoveNodeResponse { + record_existed: removal.record_existed, + removed_from_peer_set: removal.removed_from_peer_set, + }) + } + .await; + self.audit("remove_node", &subject, result) } // ==================== DNS Credential Management ==================== @@ -432,108 +494,128 @@ impl AdminRpc for AdminRpcHandler { self, request: CreateDnsCredentialRequest, ) -> Result { - let kv_store = self.state.kv_store(); + let id = generate_cred_id(); + let subject = format!( + "id {id} name {} provider {}", + request.name, request.provider_type + ); + let result = async { + let kv_store = self.state.kv_store(); - // Validate provider type - let provider = match request.provider_type.as_str() { - "cloudflare" => DnsProvider::Cloudflare { - api_token: request.cf_api_token, - api_url: request.cf_api_url, - }, - _ => bail!("unsupported provider type: {}", request.provider_type), - }; + // Validate provider type + let provider = match request.provider_type.as_str() { + "cloudflare" => DnsProvider::Cloudflare { + api_token: request.cf_api_token, + api_url: request.cf_api_url, + }, + _ => bail!("unsupported provider type: {}", request.provider_type), + }; - let now = now_secs(); - let id = generate_cred_id(); - let dns_txt_ttl = request.dns_txt_ttl.unwrap_or(60); - let max_dns_wait_secs = request.max_dns_wait.unwrap_or(60 * 5); - if dns_txt_ttl == 0 { - bail!("dns_txt_ttl must be greater than zero"); - } - if max_dns_wait_secs == 0 { - bail!("max_dns_wait must be greater than zero"); - } - let max_dns_wait = Duration::from_secs(max_dns_wait_secs.into()); - let cred = DnsCredential { - id: id.clone(), - name: request.name, - provider, - created_at: now, - updated_at: now, - dns_txt_ttl, - max_dns_wait, - }; + let now = now_secs(); + let dns_txt_ttl = request.dns_txt_ttl.unwrap_or(60); + let max_dns_wait_secs = request.max_dns_wait.unwrap_or(60 * 5); + if dns_txt_ttl == 0 { + bail!("dns_txt_ttl must be greater than zero"); + } + if max_dns_wait_secs == 0 { + bail!("max_dns_wait must be greater than zero"); + } + let max_dns_wait = Duration::from_secs(max_dns_wait_secs.into()); + let cred = DnsCredential { + id: id.clone(), + name: request.name, + provider, + created_at: now, + updated_at: now, + dns_txt_ttl, + max_dns_wait, + }; - kv_store.save_dns_credential(&cred)?; - info!("Created DNS credential: {} ({})", cred.name, cred.id); + kv_store.save_dns_credential(&cred)?; - // Set as default if requested - if request.set_as_default { - kv_store.set_default_dns_credential_id(&id)?; - info!("Set DNS credential {} as default", id); - } + // Set as default if requested + if request.set_as_default { + kv_store + .set_default_dns_credential_id(&id) + .context("created the credential but failed to set it as default")?; + info!("Set DNS credential {} as default", id); + } - Ok(dns_cred_to_proto(cred)) + Ok(dns_cred_to_proto(cred)) + } + .await; + self.audit("create_dns_credential", &subject, result) } async fn update_dns_credential( self, request: UpdateDnsCredentialRequest, ) -> Result { - let kv_store = self.state.kv_store(); + let subject = format!("id {}", request.id); + let result = async { + let kv_store = self.state.kv_store(); - let mut cred = kv_store - .get_dns_credential(&request.id)? - .context("dns credential not found")?; + let mut cred = kv_store + .get_dns_credential(&request.id)? + .context("dns credential not found")?; - // Update name if provided - if let Some(name) = request.name { - cred.name = name; - } + // Update name if provided + if let Some(name) = request.name { + cred.name = name; + } - // Update provider fields if provided - match &mut cred.provider { - DnsProvider::Cloudflare { api_token, api_url } => { - if let Some(new_token) = request.cf_api_token { - *api_token = new_token; - } - if let Some(new_url) = request.cf_api_url { - *api_url = Some(new_url); + // Update provider fields if provided + match &mut cred.provider { + DnsProvider::Cloudflare { api_token, api_url } => { + if let Some(new_token) = request.cf_api_token { + *api_token = new_token; + } + if let Some(new_url) = request.cf_api_url { + *api_url = Some(new_url); + } } } - } - cred.updated_at = now_secs(); - kv_store.save_dns_credential(&cred)?; - info!("Updated DNS credential: {} ({})", cred.name, cred.id); + cred.updated_at = now_secs(); + kv_store.save_dns_credential(&cred)?; + info!("Updated DNS credential: {} ({})", cred.name, cred.id); - Ok(dns_cred_to_proto(cred)) + Ok(dns_cred_to_proto(cred)) + } + .await; + self.audit("update_dns_credential", &subject, result) } async fn delete_dns_credential(self, request: DeleteDnsCredentialRequest) -> Result<()> { - let kv_store = self.state.kv_store(); + let subject = format!("id {}", request.id); + let result = async { + let kv_store = self.state.kv_store(); - // Check if this is the default credential - if let Some(default_id) = kv_store.get_default_dns_credential_id()? { - if default_id == request.id { - bail!("cannot delete the default DNS credential; set a different default first"); + // Check if this is the default credential + if let Some(default_id) = kv_store.get_default_dns_credential_id()? { + if default_id == request.id { + bail!( + "cannot delete the default DNS credential; set a different default first" + ); + } } - } - // Check if any ZT-Domain configs reference this credential - let configs = kv_store.list_zt_domain_configs(); - for config in configs { - if config.dns_cred_id.as_deref() == Some(&request.id) { - bail!( - "cannot delete DNS credential: domain {} uses it", - config.domain - ); + // Check if any ZT-Domain configs reference this credential + let configs = kv_store.list_zt_domain_configs(); + for config in configs { + if config.dns_cred_id.as_deref() == Some(&request.id) { + bail!( + "cannot delete DNS credential: domain {} uses it", + config.domain + ); + } } - } - kv_store.delete_dns_credential(&request.id)?; - info!("Deleted DNS credential: {}", request.id); - Ok(()) + kv_store.delete_dns_credential(&request.id)?; + Ok(()) + } + .await; + self.audit("delete_dns_credential", &subject, result) } async fn get_default_dns_credential(self) -> Result { @@ -554,16 +636,20 @@ impl AdminRpc for AdminRpcHandler { self, request: SetDefaultDnsCredentialRequest, ) -> Result<()> { - let kv_store = self.state.kv_store(); + let subject = format!("id {}", request.id); + let result = async { + let kv_store = self.state.kv_store(); - // Verify the credential exists - kv_store - .get_dns_credential(&request.id)? - .context("dns credential not found")?; + // Verify the credential exists + kv_store + .get_dns_credential(&request.id)? + .context("dns credential not found")?; - kv_store.set_default_dns_credential_id(&request.id)?; - info!("Set default DNS credential: {}", request.id); - Ok(()) + kv_store.set_default_dns_credential_id(&request.id)?; + Ok(()) + } + .await; + self.audit("set_default_dns_credential", &subject, result) } // ==================== ZT-Domain Management ==================== @@ -599,93 +685,118 @@ impl AdminRpc for AdminRpcHandler { } async fn add_zt_domain(self, request: ProtoZtDomainConfig) -> Result { - let kv_store = self.state.kv_store(); - let cert_resolver = &self.state.cert_resolver; + let subject = domain_subject(&request.domain); + let result = async { + let kv_store = self.state.kv_store(); + let cert_resolver = &self.state.cert_resolver; - // Nothing stored to preserve: an omitted challenge is the default. - let config = proto_to_zt_domain_config(&request, kv_store, None)?; + // Nothing stored to preserve: an omitted challenge is the default. + let config = proto_to_zt_domain_config(&request, kv_store, None)?; - // Uniqueness is checked after normalization so wildcard, case, and a - // trailing root dot cannot silently overwrite the same DNS name. - if kv_store.get_zt_domain_config(&config.domain).is_some() { - bail!("ZT-Domain config already exists: {}", config.domain); - } + // Uniqueness is checked after normalization so wildcard, case, and a + // trailing root dot cannot silently overwrite the same DNS name. + if kv_store.get_zt_domain_config(&config.domain).is_some() { + bail!("ZT-Domain config already exists: {}", config.domain); + } - kv_store.save_zt_domain_config(&config)?; - info!("Added ZT-Domain config: {}", config.domain); + kv_store.save_zt_domain_config(&config)?; - let records = self.state.certbot.required_dns_records(&config); - Ok(zt_domain_to_proto(config, kv_store, cert_resolver, records)) + let records = self.state.certbot.required_dns_records(&config); + Ok(zt_domain_to_proto(config, kv_store, cert_resolver, records)) + } + .await; + self.audit("add_zt_domain", &subject, result) } async fn update_zt_domain(self, request: ProtoZtDomainConfig) -> Result { - let kv_store = self.state.kv_store(); - let cert_resolver = &self.state.cert_resolver; + let subject = domain_subject(&request.domain); + let result = async { + let kv_store = self.state.kv_store(); + let cert_resolver = &self.state.cert_resolver; - // Read the stored record first: an omitted `challenge` means "leave it - // alone", and this is the only place its current value is known. Looked - // up on the normalized key rather than the caller's presentation. - let domain = normalize_zt_domain(&request.domain)?; - let stored = kv_store - .get_zt_domain_config(&domain) - .context("ZT-Domain config not found")?; + // Read the stored record first: an omitted `challenge` means "leave it + // alone", and this is the only place its current value is known. Looked + // up on the normalized key rather than the caller's presentation. + let domain = normalize_zt_domain(&request.domain)?; + let stored = kv_store + .get_zt_domain_config(&domain) + .context("ZT-Domain config not found")?; - let config = proto_to_zt_domain_config(&request, kv_store, Some(stored.challenge))?; + let config = proto_to_zt_domain_config(&request, kv_store, Some(stored.challenge))?; - kv_store.save_zt_domain_config(&config)?; - info!("Updated ZT-Domain config: {}", config.domain); + kv_store.save_zt_domain_config(&config)?; - let records = self.state.certbot.required_dns_records(&config); - Ok(zt_domain_to_proto(config, kv_store, cert_resolver, records)) + let records = self.state.certbot.required_dns_records(&config); + Ok(zt_domain_to_proto(config, kv_store, cert_resolver, records)) + } + .await; + self.audit("update_zt_domain", &subject, result) } async fn delete_zt_domain(self, request: DeleteZtDomainRequest) -> Result<()> { - let kv_store = self.state.kv_store(); + let subject = domain_subject(&request.domain); + let result = async { + let kv_store = self.state.kv_store(); - let domain = normalize_zt_domain(&request.domain)?; - // A corrupt config must still be deletable, so check for the record - // itself: get_zt_domain_config cannot tell missing from unreadable, - // and refusing would leave a corrupt record permanently stuck. - ensure!( - kv_store.zt_domain_config_exists(&domain), - "ZT-Domain config not found" - ); + let domain = normalize_zt_domain(&request.domain)?; + // A corrupt config must still be deletable, so check for the record + // itself: get_zt_domain_config cannot tell missing from unreadable, + // and refusing would leave a corrupt record permanently stuck. + ensure!( + kv_store.zt_domain_config_exists(&domain), + "ZT-Domain config not found" + ); - // Delete config (cert data, acme, attestations are kept for historical purposes) - kv_store.delete_zt_domain_config(&domain)?; - info!("Deleted ZT-Domain config: {domain}"); - Ok(()) + // Delete config (cert data, acme, attestations are kept for historical purposes) + kv_store.delete_zt_domain_config(&domain)?; + Ok(()) + } + .await; + self.audit("delete_zt_domain", &subject, result) } async fn renew_zt_domain_cert( self, request: RenewZtDomainCertRequest, ) -> Result { - let domain = normalize_zt_domain(&request.domain)?; - let certbot = &self.state.certbot; - let renewed = certbot - .try_renew(&domain, request.force) - .await - .context("certificate renewal failed")?; - - if renewed { - // Get the new certificate data for response - let kv_store = self.state.kv_store(); - let cert_data = kv_store.get_cert_data(&domain); - let not_after = cert_data.map(|d| d.not_after).unwrap_or(0); - Ok(RenewZtDomainCertResponse { renewed, not_after }) - } else { - Ok(RenewZtDomainCertResponse { - renewed: false, - not_after: 0, - }) + let subject = format!( + "{} force {}", + domain_subject(&request.domain), + request.force + ); + let result = async { + let domain = normalize_zt_domain(&request.domain)?; + let certbot = &self.state.certbot; + let renewed = certbot + .try_renew(&domain, request.force) + .await + .context("certificate renewal failed")?; + + if renewed { + // Get the new certificate data for response + let kv_store = self.state.kv_store(); + let cert_data = kv_store.get_cert_data(&domain); + let not_after = cert_data.map(|d| d.not_after).unwrap_or(0); + Ok(RenewZtDomainCertResponse { renewed, not_after }) + } else { + Ok(RenewZtDomainCertResponse { + renewed: false, + not_after: 0, + }) + } } + .await; + self.audit("renew_zt_domain_cert", &subject, result) } async fn force_release_cert_lock(self, request: ForceReleaseCertLockRequest) -> Result<()> { - let domain = force_release_zt_domain_cert_lock(self.state.kv_store(), &request.domain)?; - info!("force released certificate lock for domain: {domain}"); - Ok(()) + let subject = domain_subject(&request.domain); + let result = async { + force_release_zt_domain_cert_lock(self.state.kv_store(), &request.domain)?; + Ok(()) + } + .await; + self.audit("force_release_cert_lock", &subject, result) } async fn list_cert_attestations( @@ -726,20 +837,27 @@ impl AdminRpc for AdminRpcHandler { } async fn import_cert(self, request: ImportCertRequest) -> Result<()> { - let domain = normalize_zt_domain(&request.domain)?; - let not_after = - get_cert_expiry(&request.cert_pem).context("failed to read the certificate expiry")?; - let data = CertData { - cert_pem: request.cert_pem, - key_pem: request.key_pem, - not_after, - issued_by: self.state.kv_store().my_node_id(), - issued_at: now_secs(), - }; - self.state.cert_resolver.update_cert(&domain, &data)?; - self.state.kv_store().save_cert_data(&domain, &data)?; - info!("imported certificate for *.{domain}"); - Ok(()) + let subject = domain_subject(&request.domain); + let result = async { + let domain = normalize_zt_domain(&request.domain)?; + let not_after = get_cert_expiry(&request.cert_pem) + .context("failed to read the certificate expiry")?; + let data = CertData { + cert_pem: request.cert_pem, + key_pem: request.key_pem, + not_after, + issued_by: self.state.kv_store().my_node_id(), + issued_at: now_secs(), + }; + self.state.cert_resolver.update_cert(&domain, &data)?; + self.state + .kv_store() + .save_cert_data(&domain, &data) + .context("serving the certificate but failed to persist it")?; + Ok(()) + } + .await; + self.audit("import_cert", &subject, result) } // ==================== Global Certbot Configuration ==================== @@ -756,18 +874,23 @@ impl AdminRpc for AdminRpcHandler { } async fn set_certbot_config(self, request: SetCertbotConfigRequest) -> Result<()> { - let kv_store = self.state.kv_store(); - let config = merge_certbot_config(kv_store.get_certbot_config(), request)?; - kv_store.set_certbot_config(&config)?; - info!( - "Updated certbot config: renew_interval={:?}, renew_before_expiration={:?}, renew_timeout={:?}, acme_url={:?}, issuer_domain_name={:?}", - config.renew_interval, - config.renew_before_expiration, - config.renew_timeout, - config.acme_url, - config.issuer_domain_name - ); - Ok(()) + let subject = String::new(); + let result = async { + let kv_store = self.state.kv_store(); + let config = merge_certbot_config(kv_store.get_certbot_config(), request)?; + kv_store.set_certbot_config(&config)?; + info!( + "Updated certbot config: renew_interval={:?}, renew_before_expiration={:?}, renew_timeout={:?}, acme_url={:?}, issuer_domain_name={:?}", + config.renew_interval, + config.renew_before_expiration, + config.renew_timeout, + config.acme_url, + config.issuer_domain_name + ); + Ok(()) + } + .await; + self.audit("set_certbot_config", &subject, result) } // ==================== Tombstone GC Configuration ==================== @@ -786,32 +909,65 @@ impl AdminRpc for AdminRpcHandler { } async fn set_tombstone_gc_config(self, request: SetTombstoneGcConfigRequest) -> Result<()> { - let config = GlobalTombstoneGcConfig { - writes_per_collection: request.writes_per_collection, - }; - self.state.kv_store().set_tombstone_gc_config(&config)?; - info!( - "updated tombstone GC config: writes_per_collection={}", - config.writes_per_collection - ); - Ok(()) + let subject = format!("writes_per_collection {:?}", request.writes_per_collection); + let result = async { + let config = GlobalTombstoneGcConfig { + writes_per_collection: request.writes_per_collection, + }; + self.state.kv_store().set_tombstone_gc_config(&config)?; + Ok(()) + } + .await; + self.audit("set_tombstone_gc_config", &subject, result) + } + + // ==================== WireGuard Key Proof Policy ==================== + + async fn get_wg_key_proof_config(self) -> Result { + let stored = self.state.kv_store().get_wg_key_proof_config()?; + Ok(WgKeyProofConfig { + require_key_proof: stored.is_some_and(|c| c.require_key_proof), + }) + } + + async fn set_wg_key_proof_config(self, request: WgKeyProofConfig) -> Result<()> { + let subject = format!("require_key_proof {}", request.require_key_proof); + let result = async { + let config = GlobalWgKeyProofConfig { + require_key_proof: request.require_key_proof, + }; + self.state.kv_store().set_wg_key_proof_config(&config)?; + Ok(()) + } + .await; + self.audit("set_wg_key_proof_config", &subject, result) } async fn set_instance_port_policy(self, request: SetInstancePortPolicyRequest) -> Result<()> { - let proto = request.policy.context("port policy is required")?; - let policy = port_policy_from_proto(proto)?; - self.state - .lock() - .set_admin_port_policy(&request.instance_id, policy) + let subject = format!("instance {}", request.instance_id); + let result = async { + let proto = request.policy.context("port policy is required")?; + let policy = port_policy_from_proto(proto)?; + self.state + .lock() + .set_admin_port_policy(&request.instance_id, policy) + } + .await; + self.audit("set_instance_port_policy", &subject, result) } async fn clear_instance_port_policy( self, request: ClearInstancePortPolicyRequest, ) -> Result<()> { - self.state - .lock() - .clear_admin_port_policy(&request.instance_id) + let subject = format!("instance {}", request.instance_id); + let result = async { + self.state + .lock() + .clear_admin_port_policy(&request.instance_id) + } + .await; + self.audit("clear_instance_port_policy", &subject, result) } async fn get_instance_port_policy( @@ -827,14 +983,19 @@ impl AdminRpc for AdminRpcHandler { } async fn set_instance_ready(self, request: SetInstanceReadyRequest) -> Result<()> { - // Absent is not false. Over the JSON transport an omitted -- or - // misspelled, since unknown keys are ignored -- `ready` would decode to - // the field's default and quietly pull the instance out of rotation, - // answering 200 while doing the opposite of nothing. - let ready = request - .ready - .context("`ready` is required: say true to put the instance back into rotation, false to take it out")?; - self.state.lock().set_ready(&request.instance_id, ready) + let subject = format!("instance {} ready {:?}", request.instance_id, request.ready); + let result = async { + // Absent is not false. Over the JSON transport an omitted -- or + // misspelled, since unknown keys are ignored -- `ready` would decode to + // the field's default and quietly pull the instance out of rotation, + // answering 200 while doing the opposite of nothing. + let ready = request + .ready + .context("`ready` is required: say true to put the instance back into rotation, false to take it out")?; + self.state.lock().set_ready(&request.instance_id, ready) + } + .await; + self.audit("set_instance_ready", &subject, result) } } @@ -921,6 +1082,7 @@ impl RpcCall for AdminRpcHandler { fn construct(context: CallContext<'_, Proxy>) -> Result { Ok(AdminRpcHandler { state: context.state.clone(), + remote_endpoint: context.remote_endpoint, }) } } @@ -982,6 +1144,11 @@ fn force_release_zt_domain_cert_lock( Ok(domain) } +fn domain_subject(domain: &str) -> String { + let normalized = normalize_zt_domain(domain); + format!("domain {}", normalized.as_deref().unwrap_or(domain)) +} + fn normalize_zt_domain(domain: &str) -> Result { let domain = domain.trim().trim_end_matches('.'); let domain = domain @@ -1158,6 +1325,12 @@ fn merge_certbot_config( // Zero would abort every order before it starts, and the DNS wait is // derived from this value. ensure!(secs > 0, "renew_timeout_secs must be greater than zero"); + ensure!( + secs <= MAX_RENEW_TIMEOUT_SECS, + "renew_timeout_secs must be at most {MAX_RENEW_TIMEOUT_SECS}: half the renew \ + lock lease, so an order and the work around it finish before the lease expires \ + and another node may take over" + ); config.renew_timeout = Duration::from_secs(secs); } if let Some(url) = request.acme_url { @@ -1286,6 +1459,22 @@ mod certbot_config_tests { assert!(err.to_string().contains("renew_timeout_secs"), "{err:#}"); } + #[test] + fn a_renew_timeout_beyond_half_the_lease_is_refused() { + let set = |secs| { + merge_certbot_config( + Ok(stored()), + SetCertbotConfigRequest { + renew_timeout_secs: Some(secs), + ..Default::default() + }, + ) + }; + set(MAX_RENEW_TIMEOUT_SECS).expect("the bound itself is accepted"); + let err = set(MAX_RENEW_TIMEOUT_SECS + 1).expect_err("past the bound must be refused"); + assert!(err.to_string().contains("renew_timeout_secs"), "{err:#}"); + } + /// The name the CA is known by has to be settable, or a deployment pointed /// at a non-Let's-Encrypt ACME server publishes records naming the wrong CA /// with no way to correct them. diff --git a/dstack/gateway/src/cert_store.rs b/dstack/gateway/src/cert_store.rs index 6e84ffe549..85c5b06b6e 100644 --- a/dstack/gateway/src/cert_store.rs +++ b/dstack/gateway/src/cert_store.rs @@ -34,8 +34,6 @@ use crate::kv::CertData; /// This struct is designed for maximum read performance - no locks required for lookups. /// Updates are done by creating a new instance and atomically swapping via outer RwLock>. pub struct CertStore { - /// Exact domain -> CertifiedKey - exact_certs: HashMap>, /// Parent domain -> CertifiedKey (for wildcard certs) /// e.g., "example.com" -> cert for "*.example.com" wildcard_certs: HashMap>, @@ -47,7 +45,6 @@ impl CertStore { /// Create a new empty certificate store pub fn new() -> Self { Self { - exact_certs: HashMap::new(), wildcard_certs: HashMap::new(), cert_data: HashMap::new(), } @@ -55,18 +52,13 @@ impl CertStore { /// Resolve certificate for a given SNI hostname (lock-free) fn resolve_cert(&self, sni: &str) -> Option> { - // 1. Try exact match first - if let Some(cert) = self.exact_certs.get(sni) { - return Some(cert.clone()); - } - - // 2. Try wildcard match (only one level deep per TLS spec) + // Wildcard match (only one level deep per TLS spec) // For "foo.bar.example.com", only try "bar.example.com" - if let Some((_, parent)) = sni.split_once('.') { - self.wildcard_certs.get(parent).cloned() - } else { - None + let (label, parent) = sni.split_once('.')?; + if label.is_empty() { + return None; } + self.wildcard_certs.get(parent).cloned() } /// Check if a certificate exists for a domain @@ -93,7 +85,6 @@ impl CertStore { impl fmt::Debug for CertStore { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let exact_domains: Vec<_> = self.exact_certs.keys().cloned().collect(); let wildcard_domains: Vec<_> = self .wildcard_certs .keys() @@ -101,7 +92,6 @@ impl fmt::Debug for CertStore { .collect(); f.debug_struct("CertStore") - .field("exact_domains", &exact_domains) .field("wildcard_domains", &wildcard_domains) .finish() } @@ -209,7 +199,6 @@ impl ResolvesServerCert for CertResolver { /// /// Use this to build a complete certificate store, then call `build()` to get the immutable CertStore. pub struct CertStoreBuilder { - exact_certs: HashMap>, wildcard_certs: HashMap>, cert_data: HashMap, } @@ -218,7 +207,6 @@ impl CertStoreBuilder { /// Create a new empty builder pub fn new() -> Self { Self { - exact_certs: HashMap::new(), wildcard_certs: HashMap::new(), cert_data: HashMap::new(), } @@ -226,7 +214,6 @@ impl CertStoreBuilder { fn from_store(store: &CertStore) -> Self { Self { - exact_certs: store.exact_certs.clone(), wildcard_certs: store.wildcard_certs.clone(), cert_data: store.cert_data.clone(), } @@ -283,7 +270,6 @@ impl CertStoreBuilder { /// Build the immutable CertStore pub fn build(self) -> CertStore { CertStore { - exact_certs: self.exact_certs, wildcard_certs: self.wildcard_certs, cert_data: self.cert_data, } @@ -467,6 +453,9 @@ mod tests { // Should not resolve different domain assert!(!store.has_cert_for_sni("example.org")); + + // An empty label is not a subdomain + assert!(!store.has_cert_for_sni(".example.com")); } /// A certificate whose chain has already expired, described by a record diff --git a/dstack/gateway/src/config.rs b/dstack/gateway/src/config.rs index 88b5b68b2a..814886c740 100644 --- a/dstack/gateway/src/config.rs +++ b/dstack/gateway/src/config.rs @@ -227,6 +227,19 @@ pub struct ProxyConfig { pub connection_rebalance: bool, pub app_address_ns_prefix: String, pub app_address_ns_compat: bool, + /// Let the app-address `localhost` resolve to 127.0.0.1, so a hostname can + /// be routed to a service on the gateway host itself. + /// + /// This carries the `insecure_` prefix because the app address is not only + /// read from the platform's own `.` grammar: it also comes + /// from the `_dstack-app-address` TXT record of an arbitrary custom domain. + /// With this on, anyone who controls any DNS zone can point the gateway at + /// its own loopback -- where the admin and debug listeners bind precisely + /// because being unreachable is their access control -- and pick the port, + /// since the `localhost` shortcut is not a registered instance and so + /// bypasses `port_policy` entirely. + #[serde(default)] + pub insecure_localhost_backend: bool, /// Dedicated DNS servers for app-address TXT lookups. /// The system resolver is used when this list is empty. #[serde(default)] @@ -621,33 +634,10 @@ pub struct Config { pub recycle: RecycleConfig, pub set_ulimit: bool, pub rpc_domain: String, - pub admin: AdminConfig, - /// Debug server configuration (separate port for debug RPCs) - pub debug: DebugConfig, pub sync: SyncConfig, pub auth: AuthConfig, } -#[derive(Debug, Clone, Deserialize, Default)] -pub struct DebugConfig { - /// Enable debug server - #[serde(default)] - pub insecure_enable_debug_rpc: bool, - /// Let the app-address `localhost` resolve to 127.0.0.1, so a hostname can - /// be routed to a service on the gateway host itself. - /// - /// This lives under `debug` and carries the `insecure_` prefix because the - /// app address is not only read from the platform's own `.` - /// grammar: it also comes from the `_dstack-app-address` TXT record of an - /// arbitrary custom domain. With this on, anyone who controls any DNS zone - /// can point the gateway at its own loopback -- where the admin and debug - /// listeners bind precisely because being unreachable is their access - /// control -- and pick the port, since the `localhost` shortcut is not a - /// registered instance and so bypasses `port_policy` entirely. - #[serde(default)] - pub insecure_localhost_backend: bool, -} - #[derive(Debug, Clone, Deserialize)] pub struct AuthConfig { pub enabled: bool, @@ -695,6 +685,29 @@ impl Config { } } +/// The optional listeners. Their bind settings (`address`, `tls`, +/// `proxy_protocol`) are read by Rocket, see [`listener_figment`]. +#[derive(Debug, Clone, Deserialize)] +pub struct ListenersConfig { + pub admin: AdminConfig, + pub debug: DebugConfig, +} + +impl ListenersConfig { + pub fn load(figment: &Figment) -> Result { + Ok(figment.extract_inner("listeners")?) + } +} + +/// `[listeners.debug]`: unauthenticated debug RPCs, for development only. +#[derive(Debug, Clone, Deserialize)] +pub struct DebugConfig { + #[serde(default)] + pub enabled: bool, +} + +/// `[listeners.admin]`: whether the admin listener is served, and its +/// authentication. #[derive(Debug, Clone, Deserialize)] pub struct AdminConfig { pub enabled: bool, @@ -732,6 +745,34 @@ pub fn load_config_figment(config_file: Option<&str>) -> Figment { load_config("gateway", DEFAULT_CONFIG, config_file, false) } +/// Settings that moved to `[listeners.*]` or `[core.proxy]`. Other top-level +/// keys of a config file move to `[listeners.default]`. +const MOVED_SETTINGS: [(&str, &str); 6] = [ + ("address", "listeners.guest.address"), + ("port", "listeners.guest.port"), + ("tls", "listeners.guest.tls"), + ("core.admin", "listeners.admin"), + ( + "core.debug.insecure_localhost_backend", + "core.proxy.insecure_localhost_backend", + ), + ( + "core.debug", + "listeners.debug (insecure_enable_debug_rpc is now enabled)", + ), +]; + +/// Refuse a config that sets a moved setting. +pub fn reject_moved_settings(figment: &Figment) -> Result<()> { + load_config::reject_moved_settings(figment, &MOVED_SETTINGS) +} + +/// The Rocket config of listener `name`: `[listeners.default]` overridden by +/// `[listeners.]`. +pub fn listener_figment(figment: &Figment, name: &str) -> Result { + load_config::listener_figment(figment, name, &[]) +} + pub fn setup_wireguard(config: &WgConfig) -> Result<()> { config.validate().context("Invalid wireguard config")?; @@ -764,6 +805,33 @@ mod tests { use rocket::figment::providers::{Format, Toml}; use std::str::FromStr; + #[test] + fn moved_listener_settings_are_refused() { + let defaults = load_config_figment(None); + reject_moved_settings(&defaults).expect("gateway.toml uses the new names"); + let listeners = ListenersConfig::load(&defaults).unwrap(); + assert!(!listeners.admin.enabled && !listeners.debug.enabled); + for (toml, moved) in [ + ("[tls]\nkey = \"k\"\n", "tls -> listeners.guest.tls"), + ( + "[core.admin]\nenabled = true\n", + "core.admin -> listeners.admin", + ), + ( + "[core.debug]\ninsecure_localhost_backend = true\n", + "-> core.proxy.insecure_localhost_backend", + ), + ( + "proxy_protocol = true\n", + "-> listeners.default.proxy_protocol", + ), + ] { + let figment = load_config_figment(None).merge(Toml::string(toml)); + let err = reject_moved_settings(&figment).unwrap_err().to_string(); + assert!(err.contains(moved), "{err}"); + } + } + #[test] fn admin_auth_token_reads_new_and_legacy_keys() { // new key diff --git a/dstack/gateway/src/debug_service.rs b/dstack/gateway/src/debug_service.rs index 31ed5f3580..add0d05911 100644 --- a/dstack/gateway/src/debug_service.rs +++ b/dstack/gateway/src/debug_service.rs @@ -61,6 +61,7 @@ impl DebugRpc for DebugRpcHandler { external_port: port.into(), app_address_ns_prefix: config.proxy.app_address_ns_prefix.clone(), version: env!("CARGO_PKG_VERSION").to_string(), + wg_public_key: config.wg.public_key.clone(), }) } diff --git a/dstack/gateway/src/distributed_certbot.rs b/dstack/gateway/src/distributed_certbot.rs index 60d9e6912b..e9f517b4db 100644 --- a/dstack/gateway/src/distributed_certbot.rs +++ b/dstack/gateway/src/distributed_certbot.rs @@ -10,7 +10,7 @@ use std::sync::Arc; use std::time::Duration; -use anyhow::{bail, Context, Result}; +use anyhow::{bail, ensure, Context, Result}; use certbot::{ advisory_dns_wait, resolve_issuer_domain_name, AcmeAccount, AcmeClient, ChallengeKind, Dns01Client, ValidationMethod, @@ -22,14 +22,19 @@ use tracing::{error, info, warn}; use crate::cert_store::{get_cert_expiry, CertResolver}; use crate::kv::{ - AcmeAttestation, CertAttestation, CertCredentials, CertData, DnsCredential, DnsProvider, - KvStore, PersistentWriteNotifier, ZtDomainConfig, + AcmeAttestation, CertAttestation, CertCredentials, CertData, CertRenewLock, DnsCredential, + DnsProvider, KvStore, PersistentWriteNotifier, ZtDomainConfig, }; use crate::time::now_secs; /// Lock timeout for certificate renewal (10 minutes) const RENEW_LOCK_TIMEOUT_SECS: u64 = 600; +/// Upper bound on `renew_timeout`: half the renew lease, leaving the other +/// half for the work around the order (DNS client setup, attestation) and for +/// clock skew, so the certificate is saved while the lease is still held. +pub(crate) const MAX_RENEW_TIMEOUT_SECS: u64 = RENEW_LOCK_TIMEOUT_SECS / 2; + /// Lock timeout for ACME credential rotation (10 minutes) const ROTATION_LOCK_TIMEOUT_SECS: u64 = 600; @@ -160,7 +165,8 @@ impl DistributedCertBot { } fn release_rotation_lock(&self, lock: &crate::kv::CertRenewLock) -> Result<()> { - self.kv_store.release_rotation_lock(lock)?; + self.kv_store + .release_rotation_lock(lock, ROTATION_LOCK_TIMEOUT_SECS)?; self.notify_lock_write(); Ok(()) } @@ -174,11 +180,30 @@ impl DistributedCertBot { } fn release_cert_lock(&self, domain: &str, lock: &crate::kv::CertRenewLock) -> Result<()> { - self.kv_store.release_cert_lock(domain, lock)?; + self.kv_store + .release_cert_lock(domain, lock, RENEW_LOCK_TIMEOUT_SECS)?; self.notify_lock_write(); Ok(()) } + fn ensure_cert_lock_held(&self, domain: &str, lock: &CertRenewLock) -> Result<()> { + ensure!( + self.kv_store + .cert_lock_still_held(domain, lock, RENEW_LOCK_TIMEOUT_SECS), + "renew lock for {domain} has expired or been taken over; not committing" + ); + Ok(()) + } + + fn ensure_rotation_lock_held(&self, lock: &CertRenewLock) -> Result<()> { + ensure!( + self.kv_store + .rotation_lock_still_held(lock, ROTATION_LOCK_TIMEOUT_SECS), + "ACME lock has expired or been taken over; not committing" + ); + Ok(()) + } + async fn dns_client(&self, domain: &str, dns_cred: &DnsCredential) -> Result { match &dns_cred.provider { DnsProvider::Cloudflare { api_token, api_url } => { @@ -303,14 +328,14 @@ impl DistributedCertBot { /// first-use registration on any node is refused for the duration. pub async fn rotate_acme_credentials(&self) -> Result { let rotation_lock = self.acquire_acme_lock("rotate ACME credentials")?; - let result = self.do_rotate_acme_credentials().await; + let result = self.do_rotate_acme_credentials(&rotation_lock).await; if let Err(err) = self.release_rotation_lock(&rotation_lock) { error!("failed to release ACME rotation lock: {err:?}"); } result } - async fn do_rotate_acme_credentials(&self) -> Result { + async fn do_rotate_acme_credentials(&self, lock: &CertRenewLock) -> Result { let configs = self.kv_store.list_zt_domain_configs(); let certbot_config = self.config()?; let acme_url = if certbot_config.acme_url.is_empty() { @@ -350,6 +375,7 @@ impl DistributedCertBot { // account, and recovering from a partial re-pin below never needs to // register another account. Readers create an ACME client per // operation, so all nodes pick this up after WaveKV propagates it. + self.ensure_rotation_lock_held(lock)?; self.kv_store.save_acme_credentials(&CertCredentials { acme_credentials: credentials.clone(), })?; @@ -381,6 +407,7 @@ impl DistributedCertBot { AcmeClient::load(validation.method, &credentials, validation.max_dns_wait) .await .context("failed to prepare ACME client")?; + self.ensure_rotation_lock_held(lock)?; client .set_caa_records(std::slice::from_ref(&config.domain)) .await @@ -403,7 +430,10 @@ impl DistributedCertBot { // window where the published account and the CAA records disagree. // Run it even when some domains failed so the new account is still // recorded. - if let Err(err) = self.generate_and_save_acme_attestation(&account_uri).await { + if let Err(err) = self + .generate_and_save_acme_attestation(lock, &account_uri) + .await + { warn!("failed to attest rotated ACME account: {err:?}"); } @@ -486,7 +516,7 @@ impl DistributedCertBot { // Before the lock, never under it: registration takes the same lock. self.ensure_acme_account(&configs).await?; let rotation_lock = self.acquire_acme_lock("reconcile CAA records")?; - let result = self.do_set_caa_all(configs).await; + let result = self.do_set_caa_all(configs, &rotation_lock).await; if let Err(err) = self.release_rotation_lock(&rotation_lock) { error!("failed to release ACME rotation lock: {err:?}"); } @@ -521,7 +551,11 @@ impl DistributedCertBot { Ok(()) } - async fn do_set_caa_all(&self, configs: Vec) -> Result<()> { + async fn do_set_caa_all( + &self, + configs: Vec, + lock: &CertRenewLock, + ) -> Result<()> { let total = configs.len(); let mut failed = Vec::new(); let mut skipped = 0usize; @@ -535,7 +569,7 @@ impl DistributedCertBot { skipped += 1; continue; } - match self.set_caa(&domain, &config).await { + match self.set_caa(&domain, &config, lock).await { Ok(()) => info!("cert[{domain}]: CAA records reconciled"), Err(err) => { error!("cert[{domain}]: failed to set CAA records: {err:?}"); @@ -571,7 +605,12 @@ impl DistributedCertBot { /// /// The written CAA value pins `accounturi` to the global ACME account, which /// the caller has already registered; see [`Self::ensure_acme_account`]. - async fn set_caa(&self, domain: &str, config: &ZtDomainConfig) -> Result<()> { + async fn set_caa( + &self, + domain: &str, + config: &ZtDomainConfig, + lock: &CertRenewLock, + ) -> Result<()> { // Load only. This runs under the ACME lock, which is not reentrant, so // registering here would refuse the run that took it -- and the caller // has already registered the account before taking it. Nothing under @@ -584,6 +623,7 @@ impl DistributedCertBot { .await .context("failed to initialize ACME client")? .context("no shared ACME account is registered for this cluster")?; + self.ensure_rotation_lock_held(lock)?; acme_client .set_caa_records(&[domain.to_string()]) .await @@ -637,11 +677,13 @@ impl DistributedCertBot { // Perform renewal or initial issuance let result = if cert_data.is_some() { - self.do_renew(domain, &config).await + self.do_renew(domain, &config, &lock).await } else { // No existing certificate, request new one info!("no existing certificate, requesting new one"); - self.do_request_new(domain, &config).await.map(|_| true) + self.do_request_new(domain, &config, &lock) + .await + .map(|_| true) }; // Release lock regardless of result @@ -652,7 +694,12 @@ impl DistributedCertBot { result } - async fn do_request_new(&self, domain: &str, config: &ZtDomainConfig) -> Result<()> { + async fn do_request_new( + &self, + domain: &str, + config: &ZtDomainConfig, + lock: &CertRenewLock, + ) -> Result<()> { let acme_client = self.get_or_create_acme_client(domain, config).await?; // Generate new key pair (always use new key for security) @@ -677,11 +724,11 @@ impl DistributedCertBot { let not_after = get_cert_expiry(&cert_pem).context("failed to parse certificate expiry")?; // Save certificate to KvStore - self.save_cert_to_kvstore(domain, &cert_pem, &key_pem, not_after)?; + self.save_cert_to_kvstore(domain, lock, &cert_pem, &key_pem, not_after)?; info!("new certificate obtained from ACME, saved to KvStore"); // Generate and save attestation - self.generate_and_save_attestation(domain, &public_key_der) + self.generate_and_save_attestation(domain, lock, &public_key_der) .await?; // Load into memory cert store @@ -701,7 +748,12 @@ impl DistributedCertBot { Ok(()) } - async fn do_renew(&self, domain: &str, config: &ZtDomainConfig) -> Result { + async fn do_renew( + &self, + domain: &str, + config: &ZtDomainConfig, + lock: &CertRenewLock, + ) -> Result { let acme_client = self.get_or_create_acme_client(domain, config).await?; // Generate new key pair (always use new key for each renewal) @@ -733,11 +785,11 @@ impl DistributedCertBot { get_cert_expiry(&new_cert_pem).context("failed to parse certificate expiry")?; // Save to KvStore - self.save_cert_to_kvstore(domain, &new_cert_pem, &key_pem, not_after)?; + self.save_cert_to_kvstore(domain, lock, &new_cert_pem, &key_pem, not_after)?; info!("renewed certificate saved to KvStore"); // Generate and save attestation - self.generate_and_save_attestation(domain, &public_key_der) + self.generate_and_save_attestation(domain, lock, &public_key_der) .await?; // Load into memory cert store @@ -783,7 +835,7 @@ impl DistributedCertBot { // lock and look again before spending a registration. let rotation_lock = self.acquire_acme_lock("register the shared ACME account")?; let client = self - .register_or_adopt_account(domain, config, &acme_url) + .register_or_adopt_account(domain, config, &acme_url, &rotation_lock) .await; if let Err(err) = self.release_rotation_lock(&rotation_lock) { error!("failed to release ACME rotation lock: {err:?}"); @@ -832,17 +884,19 @@ impl DistributedCertBot { Ok(Some(client)) } - /// Register the cluster's shared ACME account, or adopt the one that - /// appeared while this call was waiting for the lock. + /// Register the cluster's shared ACME account, or adopt the one the + /// previous lock holder registered after this call last looked. /// - /// Called with the ACME lock held. The re-read is the point: without it - /// every waiter registers an account of its own the moment it is let - /// through, which is the race the lock was taken to avoid. + /// Called with the ACME lock held. The re-read is the point: without it a + /// caller that found no account, then took the lock once it was released, + /// would register one of its own, which is the race the lock was taken to + /// avoid. async fn register_or_adopt_account( &self, domain: &str, config: &ZtDomainConfig, acme_url: &str, + lock: &CertRenewLock, ) -> Result { if let Some(client) = self .load_stored_acme_client(domain, config, acme_url) @@ -863,20 +917,25 @@ impl DistributedCertBot { .context("failed to dump ACME credentials")?; // Save global ACME credentials to KvStore + self.ensure_rotation_lock_held(lock)?; self.kv_store.save_acme_credentials(&CertCredentials { acme_credentials: creds_json.clone(), })?; // Generate and save ACME account attestation if let Some(account_uri) = extract_account_uri(&creds_json) { - self.generate_and_save_acme_attestation(&account_uri) + self.generate_and_save_acme_attestation(lock, &account_uri) .await?; } Ok(client) } - async fn generate_and_save_acme_attestation(&self, account_uri: &str) -> Result<()> { + async fn generate_and_save_acme_attestation( + &self, + lock: &CertRenewLock, + account_uri: &str, + ) -> Result<()> { let agent = match crate::dstack_agent() { Ok(a) => a, Err(err) => { @@ -926,6 +985,7 @@ impl DistributedCertBot { generated_at: now_secs(), }; + self.ensure_rotation_lock_held(lock)?; self.kv_store.save_acme_attestation(&attestation)?; info!("ACME account attestation saved to KvStore"); Ok(()) @@ -934,6 +994,7 @@ impl DistributedCertBot { fn save_cert_to_kvstore( &self, domain: &str, + lock: &CertRenewLock, cert_pem: &str, key_pem: &str, not_after: u64, @@ -945,12 +1006,14 @@ impl DistributedCertBot { issued_by: self.kv_store.my_node_id(), issued_at: now_secs(), }; + self.ensure_cert_lock_held(domain, lock)?; self.kv_store.save_cert_data(domain, &cert_data) } async fn generate_and_save_attestation( &self, domain: &str, + lock: &CertRenewLock, public_key_der: &[u8], ) -> Result<()> { let agent = match crate::dstack_agent() { @@ -1002,6 +1065,7 @@ impl DistributedCertBot { generated_at: now_secs(), }; + self.ensure_cert_lock_held(domain, lock)?; self.kv_store.save_cert_attestation(domain, &attestation)?; info!(domain, "attestation saved to KvStore"); Ok(()) @@ -1152,6 +1216,39 @@ mod tests { assert_eq!(notifier.0.load(Ordering::Relaxed), 4); } + /// A renewal that outlived its lease, or lost it to a force release, may + /// be racing a successor; its certificate must not overwrite theirs. + #[test] + fn a_holder_that_lost_its_lease_does_not_save_its_certificate() { + let data_dir = tempfile::tempdir().expect("failed to create temp dir"); + let certbot = test_certbot(data_dir.path()); + let domain = "example.com"; + + let stale = certbot + .try_acquire_cert_lock(domain) + .expect("renewal lock should be free"); + certbot + .kv_store + .force_release_cert_lock(domain) + .expect("force release should succeed"); + let successor = certbot + .try_acquire_cert_lock(domain) + .expect("renewal lock should be free after the force release"); + + assert!(certbot + .save_cert_to_kvstore(domain, &stale, "stale", "stale", 0) + .is_err()); + assert!(certbot.kv_store.get_cert_data(domain).is_none()); + + certbot + .save_cert_to_kvstore(domain, &successor, "cert", "key", 0) + .expect("the current holder saves"); + assert_eq!( + certbot.kv_store.get_cert_data(domain).map(|c| c.cert_pem), + Some("cert".to_string()) + ); + } + #[tokio::test] async fn set_caa_all_succeeds_without_configured_domains() { let data_dir = tempfile::tempdir().expect("failed to create temp dir"); @@ -1224,7 +1321,7 @@ mod tests { /// built only after the lock is granted, so an unreachable provider (as /// configured here) cannot be what this run fails on. #[tokio::test] - async fn first_use_registration_waits_for_the_rotation_lock() { + async fn first_use_registration_is_refused_while_the_rotation_lock_is_held() { let data_dir = tempfile::tempdir().expect("failed to create temp dir"); let certbot = certbot_with_domain(data_dir.path()); let config = test_zt_domain_config(); @@ -1287,12 +1384,16 @@ mod tests { // The account that appeared while this call waited is registered at a // different ACME directory than the one this run is configured for. save_credentials_for(&certbot, "https://acme.test/directory"); + let lock = certbot + .try_acquire_rotation_lock() + .expect("rotation lock should be free"); let err = match certbot .register_or_adopt_account( "app.example.com", &test_zt_domain_config(), DEFAULT_ACME_URL, + &lock, ) .await { @@ -1453,10 +1554,11 @@ mod tests { let stale = crate::kv::CertRenewLock { started_at: current.started_at.saturating_sub(100), started_by: 99, + nonce: 0, }; certbot .kv_store - .release_rotation_lock(&stale) + .release_rotation_lock(&stale, ROTATION_LOCK_TIMEOUT_SECS) .expect("stale release should be a no-op, not an error"); assert!( certbot @@ -1467,7 +1569,7 @@ mod tests { ); certbot .kv_store - .release_rotation_lock(¤t) + .release_rotation_lock(¤t, ROTATION_LOCK_TIMEOUT_SECS) .expect("owner release should succeed"); assert!(certbot .kv_store diff --git a/dstack/gateway/src/kv/import.rs b/dstack/gateway/src/kv/import.rs index 5937153796..0ac952e7bf 100644 --- a/dstack/gateway/src/kv/import.rs +++ b/dstack/gateway/src/kv/import.rs @@ -144,10 +144,6 @@ fn validate_instance( validate_id("instance_id", instance_id)?; validate_id("app_id", &data.app_id)?; validate_wg_public_key(&data.public_key)?; - ensure!( - data.public_key != wg.public_key, - "public key belongs to this gateway" - ); // The routable network, not this node's allocation share: in a cluster // every node carries peers for the CVMs registered on the other nodes, and // those hold addresses from the other nodes' shares by design. @@ -180,11 +176,25 @@ fn validate_instance( /// wins, ties broken by instance ID) so that every node reaches the same /// decision from the same KV contents — the local registration path resolves /// them the same way, by refusing the newcomer. -pub fn accept_instances(wg: &WgConfig, loaded: LoadedInstances) -> AcceptedInstances { - accept_instances_at(wg, loaded, now_secs()) +/// +/// `gateway_keys` are the WireGuard keys of the gateway nodes in the KV. A +/// record carrying one of them loses to that gateway on every node, not only +/// on the gateway whose key it is: judged by this node's own key alone, the +/// nodes would disagree on which instances exist. +pub fn accept_instances( + wg: &WgConfig, + gateway_keys: &HashSet, + loaded: LoadedInstances, +) -> AcceptedInstances { + accept_instances_at(wg, gateway_keys, loaded, now_secs()) } -fn accept_instances_at(wg: &WgConfig, loaded: LoadedInstances, now: u64) -> AcceptedInstances { +fn accept_instances_at( + wg: &WgConfig, + gateway_keys: &HashSet, + loaded: LoadedInstances, + now: u64, +) -> AcceptedInstances { let LoadedInstances { decoded, undecodable, @@ -213,6 +223,12 @@ fn accept_instances_at(wg: &WgConfig, loaded: LoadedInstances, now: u64) -> Acce let checked = validate_instance(wg, now, &instance_id, &data) .map_err(|reason| (Rejection::Unusable, reason)) .and_then(|()| { + if data.public_key == wg.public_key || gateway_keys.contains(&data.public_key) { + return Err(( + Rejection::LostConflict, + anyhow::anyhow!("public key belongs to a gateway node"), + )); + } if let Some(owner) = claimed_ips.get(&data.ip) { return Err(( Rejection::LostConflict, @@ -282,6 +298,7 @@ mod tests { port_policy: None, port_policy_hash: String::new(), health_check: None, + agent_token: None, } } @@ -296,7 +313,7 @@ mod tests { } fn accept(records: Vec<(&str, InstanceRecord)>) -> AcceptedInstances { - accept_instances_at(&wg_config(), loaded(records), NOW) + accept_instances_at(&wg_config(), &HashSet::new(), loaded(records), NOW) } #[test] @@ -364,6 +381,7 @@ mod tests { let wg = wg_config(); let accepted = accept_instances_at( &wg, + &HashSet::new(), loaded(vec![( "self-peer", instance("10.0.0.20", &wg.public_key, 100), @@ -374,6 +392,28 @@ mod tests { assert_eq!(accepted.rejected.len(), 1); } + #[test] + fn every_node_rejects_another_gateways_public_key() { + // A CVM can register with one node under a peer gateway's key. Judged by + // each node's own key only, the peer refuses the record while every other + // node accepts it, and the nodes disagree on which instances exist. + let peer_gateway = key(8); + let accepted = accept_instances_at( + &wg_config(), + &HashSet::from([peer_gateway.clone()]), + loaded(vec![ + ("steals-peer-key", instance("10.0.0.20", &peer_gateway, 100)), + ("good", instance("10.0.0.21", &key(1), 200)), + ]), + NOW, + ); + assert!(!accepted.instances.contains_key("steals-peer-key")); + assert!(accepted.instances.contains_key("good")); + // The gateway owns the key, so the instance has to stop being routable + // rather than keep whatever the data plane already holds. + assert!(accepted.unreadable().is_empty()); + } + #[test] fn duplicate_ip_and_key_claims_resolve_to_the_older_registration() { let accepted = accept(vec![ @@ -433,6 +473,7 @@ mod tests { }; let accepted = accept_instances( &wg, + &HashSet::new(), loaded(vec![ ("mine", instance(mine, &key(1), 100)), ("peers", instance(peers, &key(2), 100)), @@ -498,6 +539,7 @@ mod tests { fn an_undecodable_record_is_reported_as_unreadable_not_as_absent() { let accepted = accept_instances_at( &wg_config(), + &HashSet::new(), LoadedInstances { decoded: [("good".to_string(), instance("10.0.0.20", &key(1), 100))] .into_iter() diff --git a/dstack/gateway/src/kv/mod.rs b/dstack/gateway/src/kv/mod.rs index 81486a8590..c7aa33b63f 100644 --- a/dstack/gateway/src/kv/mod.rs +++ b/dstack/gateway/src/kv/mod.rs @@ -50,7 +50,7 @@ pub use sync_service::{fetch_peers_from_bootnode, PersistentWriteNotifier, WaveK use tracing::{error, warn}; use std::{ - collections::{BTreeMap, BTreeSet}, + collections::{BTreeMap, BTreeSet, HashSet}, net::Ipv4Addr, path::Path, time::Duration, @@ -130,6 +130,15 @@ pub struct InstanceRecord { /// a rollback and forward again. #[serde(default)] pub health_check: Option, + /// Token this CVM minted for the gateway's `Health` poll. `None` for a CVM + /// that predates the field, or one that could not mint it. + /// + /// Per-instance rather than per-app: the token is bound to the instance's + /// app id and expires within the hour, and the CVM re-registers every + /// three minutes anyway. `Option` for the same reason as `health_check`: + /// a pre-field record has to read as "not known", not "empty token". + #[serde(default)] + pub agent_token: Option, } /// What an operator has said about an instance's ports, under @@ -193,6 +202,7 @@ impl From<&InstanceInfo> for InstanceRecord { // `Health` is this node's own observation, and a shared one would // outlive the instance that earned it. health_check: Some(info.health_check()), + agent_token: info.agent_token.clone(), } } } @@ -306,6 +316,10 @@ pub struct CertData { pub struct CertRenewLock { pub started_at: u64, pub started_by: NodeId, + /// Tells apart two acquisitions by one node within one second, e.g. right + /// after a force release. + #[serde(default)] + pub nonce: u64, } /// Certificate attestation (TDX Quote of certificate public key) @@ -455,6 +469,19 @@ pub struct GlobalTombstoneGcConfig { pub writes_per_collection: u64, } +/// WireGuard key proof policy (stored in KV, synced across nodes). +/// +/// A node verifies only the registrations it receives and its peers trust +/// what it replicates, so the policy only protects the cluster when every node +/// enforces it. Storing it in the replicated KV makes it one switch, toggled at +/// runtime. An absent record means "not required"; a corrupt one means +/// "required". +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +pub struct GlobalWgKeyProofConfig { + /// Refuse registrations without a valid WireGuard key proof. + pub require_key_proof: bool, +} + // Key prefixes and builders pub mod keys { use super::NodeId; @@ -480,6 +507,7 @@ pub mod keys { pub const GLOBAL_PREFIX: &str = "global/"; pub const GLOBAL_CERTBOT_CONFIG: &str = "global/certbot_config"; pub const GLOBAL_TOMBSTONE_GC_CONFIG: &str = "global/tombstone_gc_config"; + pub const GLOBAL_WG_KEY_PROOF_CONFIG: &str = "global/wg_key_proof_config"; pub const GLOBAL_ACME_CREDENTIALS: &str = "global/acme_credentials"; pub const GLOBAL_ACME_ATTESTATION: &str = "global/acme_attestation"; pub const GLOBAL_ACME_ROTATION_LOCK: &str = "global/acme_rotation_lock"; @@ -1362,6 +1390,15 @@ impl KvStore { .collect() } + /// WireGuard public keys of every gateway node in the store. + pub fn gateway_wg_public_keys(&self) -> HashSet { + self.load_all_nodes() + .into_values() + .map(|node| node.wg_public_key) + .filter(|key| !key.is_empty()) + .collect() + } + /// Remove a gateway node from replicated state. /// /// Writes tombstones for the node's info, status, and sync address, and @@ -1662,6 +1699,26 @@ impl KvStore { Ok(()) } + /// Get the WireGuard key proof policy, if an operator has stored one. + /// + /// `None` means "not required". A corrupt record is an error, which registration reads as "required" (fails closed, see + /// `ProxyInner::require_wg_key_proof`). + pub fn get_wg_key_proof_config(&self) -> Result> { + self.persistent + .read() + .decode_strict(keys::GLOBAL_WG_KEY_PROOF_CONFIG) + } + + /// Store the WireGuard key proof policy, replicating it to every node. + pub fn set_wg_key_proof_config(&self, config: &GlobalWgKeyProofConfig) -> Result<()> { + self.persistent.write().put_encoded( + keys::GLOBAL_WG_KEY_PROOF_CONFIG.to_string(), + config, + true, + )?; + Ok(()) + } + pub fn persist_if_dirty(&self) -> Result { self.persistent.persist_if_dirty() } @@ -2118,48 +2175,86 @@ impl KvStore { // ==================== Renew / Rotation Locks ==================== - /// Try to take the lease at `key`, returning the value written; pass it to - /// [`Self::release_lock`]. A crashed holder is covered by the timeout. + /// Try to take the lease at `key`; pass the result to [`Self::release_lock`]. + /// A crashed holder is covered by the timeout. /// /// Read, expiry check and write share one write guard, so this is mutual /// exclusion within a node. Across nodes it is best-effort: WaveKV is /// last-writer-wins without compare-and-swap, so two nodes can both acquire - /// during a replication gap, which the loser's release then detects. + /// during a replication gap. fn try_acquire_lock(&self, key: String, lock_timeout_secs: u64) -> Option { let now = now_secs(); let mut state = self.persistent.write(); // A corrupt record decodes as absent (logged and counted) and is // overwritten here, so it heals instead of wedging the key. + // A lease stamped beyond the drift bound (a clock since stepped back, + // or a corrupt value) would otherwise hold the key until wall time + // catches up; treat it as expired. if let Some(existing) = state.decode::(&key) { - if now < existing.started_at.saturating_add(lock_timeout_secs) { + let plausible = existing.started_at <= now.saturating_add(MAX_CLOCK_DRIFT_SECS); + if plausible && now < existing.started_at.saturating_add(lock_timeout_secs) { return None; } } let lock = CertRenewLock { started_at: now, started_by: self.my_node_id, + nonce: rand::random(), }; state.put_encoded(key, &lock, false).ok()?; Some(lock) } - /// Release the lease at `key` only if it still holds `acquired`, so a - /// holder that outlived the timeout cannot delete its successor's lock. - fn release_lock(&self, key: String, acquired: &CertRenewLock) -> Result<()> { + /// Release the lease at `key` if it still holds `acquired` and has not + /// expired by the local clock. + /// + /// A delete is stamped with local wall time, and a peer can take over only + /// once its own clock reads `started_at + lock_timeout_secs`, stamping its + /// lock no earlier. So a delete before the local clock reaches that point + /// cannot beat a takeover, whatever the clock skew; past it, the delete + /// could wipe a successor's lock this node has not received yet, so the + /// lease is left to expire instead. The same holds for a successor after a + /// force release, which did not wait for expiry: hence the delete only + /// when the current value is `acquired`, told apart by its nonce from a + /// same-second re-acquisition, and never for an already-released key. + fn release_lock( + &self, + key: String, + acquired: &CertRenewLock, + lock_timeout_secs: u64, + ) -> Result<()> { + if now_secs() >= acquired.started_at.saturating_add(lock_timeout_secs) { + warn!("not releasing lock {key}: it has expired, leaving it to be taken over"); + return Ok(()); + } let mut state = self.persistent.write(); - if let Some(current) = state.decode::(&key) { - if current != *acquired { - warn!( - "not releasing lock {key}: node {} took it over after this holder exceeded the lock timeout", - current.started_by - ); - return Ok(()); + match state.decode::(&key) { + Some(current) if current == *acquired => { + state.delete(key)?; } + Some(current) => warn!( + "not releasing lock {key}: node {} holds it now", + current.started_by + ), + None => warn!("not releasing lock {key}: it was already released"), } - state.delete(key)?; Ok(()) } + /// Whether the lease at `key` still holds `acquired` and has not expired by + /// the local clock, the same condition [`Self::release_lock`] deletes on. + /// Checked before each write made under the lease: past this point a + /// successor may be doing the same work. + fn lease_still_held( + &self, + key: &str, + acquired: &CertRenewLock, + lock_timeout_secs: u64, + ) -> bool { + now_secs() < acquired.started_at.saturating_add(lock_timeout_secs) + && self.persistent.read().decode::(key).as_ref() == Some(acquired) + } + /// Try to acquire the per-domain certificate renew lock. pub fn try_acquire_cert_lock( &self, @@ -2169,8 +2264,22 @@ impl KvStore { self.try_acquire_lock(keys::cert_lock(domain), lock_timeout_secs) } - pub fn release_cert_lock(&self, domain: &str, acquired: &CertRenewLock) -> Result<()> { - self.release_lock(keys::cert_lock(domain), acquired) + pub fn release_cert_lock( + &self, + domain: &str, + acquired: &CertRenewLock, + lock_timeout_secs: u64, + ) -> Result<()> { + self.release_lock(keys::cert_lock(domain), acquired, lock_timeout_secs) + } + + pub fn cert_lock_still_held( + &self, + domain: &str, + acquired: &CertRenewLock, + lock_timeout_secs: u64, + ) -> bool { + self.lease_still_held(&keys::cert_lock(domain), acquired, lock_timeout_secs) } /// Delete the certificate renew lock whoever holds it, for @@ -2190,8 +2299,24 @@ impl KvStore { self.try_acquire_lock(keys::GLOBAL_ACME_ROTATION_LOCK.into(), lock_timeout_secs) } - pub fn release_rotation_lock(&self, acquired: &CertRenewLock) -> Result<()> { - self.release_lock(keys::GLOBAL_ACME_ROTATION_LOCK.into(), acquired) + pub fn release_rotation_lock( + &self, + acquired: &CertRenewLock, + lock_timeout_secs: u64, + ) -> Result<()> { + self.release_lock( + keys::GLOBAL_ACME_ROTATION_LOCK.into(), + acquired, + lock_timeout_secs, + ) + } + + pub fn rotation_lock_still_held( + &self, + acquired: &CertRenewLock, + lock_timeout_secs: u64, + ) -> bool { + self.lease_still_held(keys::GLOBAL_ACME_ROTATION_LOCK, acquired, lock_timeout_secs) } // ==================== Certificate Attestation ==================== @@ -2349,42 +2474,41 @@ mod acme_credentials_tests { ); } + /// A lease from a clock within the drift bound is honoured; one stamped + /// beyond it (here `u64::MAX`) would otherwise wedge the key until wall + /// time catches up, so it is treated as expired. #[test] - fn lease_expiry_does_not_overflow() { + fn a_lease_stamped_beyond_the_drift_bound_is_treated_as_expired() { let dir = tempfile::tempdir().expect("failed to create temp dir"); let kv = test_kv(dir.path()); - kv.persistent - .write() - .put_encoded( - keys::GLOBAL_ACME_ROTATION_LOCK.to_string(), - &CertRenewLock { - started_at: u64::MAX, - started_by: 2, - }, - false, - ) - .expect("lock write should succeed"); + let plant = |key: String, started_at: u64| { + kv.persistent + .write() + .put_encoded( + key, + &CertRenewLock { + started_at, + started_by: 2, + nonce: 0, + }, + false, + ) + .expect("lock write should succeed"); + }; - assert!( - kv.try_acquire_rotation_lock(600).is_none(), - "a non-expired lock with a saturated expiry must remain held" + plant( + keys::cert_lock("ahead.example"), + now_secs() + MAX_CLOCK_DRIFT_SECS / 2, ); - - kv.persistent - .write() - .put_encoded( - keys::cert_lock("overflow.example"), - &CertRenewLock { - started_at: u64::MAX, - started_by: 2, - }, - false, - ) - .expect("certificate lock write should succeed"); assert!( - kv.try_acquire_cert_lock("overflow.example", 600).is_none(), - "a non-expired certificate lock with a saturated expiry must remain held" + kv.try_acquire_cert_lock("ahead.example", 600).is_none(), + "a peer clock ahead within the drift bound still holds the lease" ); + + plant(keys::GLOBAL_ACME_ROTATION_LOCK.to_string(), u64::MAX); + assert!(kv.try_acquire_rotation_lock(600).is_some()); + plant(keys::cert_lock("overflow.example"), u64::MAX); + assert!(kv.try_acquire_cert_lock("overflow.example", 600).is_some()); } } @@ -2411,12 +2535,13 @@ mod cert_lock_tests { &CertRenewLock { started_at: acquired.started_at + 1, started_by: 2, + nonce: 0, }, false, ) .expect("takeover write should succeed"); - kv.release_cert_lock("takeover.example", &acquired) + kv.release_cert_lock("takeover.example", &acquired, 600) .expect("release should not error"); assert!( kv.try_acquire_cert_lock("takeover.example", 600).is_none(), @@ -2424,6 +2549,75 @@ mod cert_lock_tests { ); } + /// After a force release the same node can re-acquire within the same + /// second, writing the same started_at and started_by; the nonce keeps the + /// stale holder's release from matching. + #[test] + fn a_force_released_holder_does_not_release_a_same_second_successor() { + let dir = tempfile::tempdir().expect("failed to create temp dir"); + let kv = test_kv(dir.path()); + let stale = kv + .try_acquire_cert_lock("forced.example", 600) + .expect("first acquisition should succeed"); + kv.force_release_cert_lock("forced.example") + .expect("force release should succeed"); + // The successor's value differs from the stale one only in its nonce. + kv.persistent + .write() + .put_encoded( + keys::cert_lock("forced.example"), + &CertRenewLock { + nonce: stale.nonce.wrapping_add(1), + ..stale.clone() + }, + false, + ) + .expect("successor write should succeed"); + + kv.release_cert_lock("forced.example", &stale, 600) + .expect("release should not error"); + assert!( + kv.try_acquire_cert_lock("forced.example", 600).is_none(), + "the successor lock must survive the stale release" + ); + } + + /// A released key holds a tombstone; releasing again must not write a + /// fresh one, which would beat a successor's lock not yet received. + #[test] + fn releasing_an_absent_lock_writes_nothing() { + let dir = tempfile::tempdir().expect("failed to create temp dir"); + let kv = test_kv(dir.path()); + let held = kv + .try_acquire_cert_lock("absent.example", 600) + .expect("acquisition should succeed"); + kv.force_release_cert_lock("absent.example") + .expect("force release should succeed"); + let key = keys::cert_lock("absent.example"); + let tombstone = || kv.persistent.read().get_including_tombstones(&key); + let before = tombstone().expect("force release leaves a tombstone"); + + kv.release_cert_lock("absent.example", &held, 600) + .expect("release should not error"); + assert_eq!(tombstone().map(|e| e.meta), Some(before.meta)); + } + + /// Past its expiry a peer may already have taken the lease over unseen, + /// and a delete now would beat that takeover, so the holder leaves it. + #[test] + fn an_expired_lease_is_left_to_be_taken_over() { + let dir = tempfile::tempdir().expect("failed to create temp dir"); + let kv = test_kv(dir.path()); + let held = kv + .try_acquire_cert_lock("slow.example", 600) + .expect("acquisition should succeed"); + + // Released as if under a timeout that has already run out. + kv.release_cert_lock("slow.example", &held, 0) + .expect("release should not error"); + assert!(kv.try_acquire_cert_lock("slow.example", 600).is_none()); + } + #[test] fn two_tasks_on_one_node_cannot_both_acquire() { let dir = tempfile::tempdir().expect("failed to create temp dir"); @@ -2488,6 +2682,7 @@ mod value_encoding_tests { let encoded = encode(&CertRenewLock { started_at: 1_700_000_000, started_by: 7, + nonce: 0, }) .expect("encode should succeed"); @@ -2503,6 +2698,7 @@ mod value_encoding_tests { let encoded = encode(&CertRenewLock { started_at: 1_700_000_000, started_by: 7, + nonce: 0, }) .expect("encode should succeed"); @@ -2518,11 +2714,9 @@ mod value_encoding_tests { let dir = tempfile::tempdir().expect("failed to create temp dir"); let kv = KvStore::new(1, vec![], dir.path(), None).expect("failed to create kv store"); - let legacy = rmp_serde::encode::to_vec(&CertRenewLock { - started_at: 1_700_000_000, - started_by: 7, - }) - .expect("legacy encode should succeed"); + // An older gateway's two-field `CertRenewLock`, as a positional array. + let legacy = rmp_serde::encode::to_vec(&(1_700_000_000u64, 7 as NodeId)) + .expect("legacy encode should succeed"); assert!( starts_with_msgpack_array(&legacy), "fixture must be a positional array to exercise the legacy path" @@ -2541,6 +2735,7 @@ mod value_encoding_tests { .expect("a record written by an older gateway must stay readable"); assert_eq!(decoded.started_at, 1_700_000_000); assert_eq!(decoded.started_by, 7); + assert_eq!(decoded.nonce, 0); } /// `DnsCredential` is the most demanding value type in the set: it nests an @@ -2729,6 +2924,7 @@ mod value_encoding_tests { port_policy: None, port_policy_hash: String::new(), health_check: None, + agent_token: None, }, ) .expect("sync should succeed"); @@ -3003,6 +3199,7 @@ mod corruption_tests { port_policy: None, port_policy_hash: String::new(), health_check: None, + agent_token: None, }, ) .expect("seed"); @@ -3473,6 +3670,7 @@ mod corruption_tests { port_policy: None, port_policy_hash: String::new(), health_check: None, + agent_token: None, }, ) .expect("sync should succeed"); @@ -3659,6 +3857,7 @@ mod tombstone_gc_tests { port_policy: None, port_policy_hash: String::new(), health_check: None, + agent_token: None, }, ) .expect("seed"); @@ -3756,10 +3955,11 @@ mod tombstone_gc_tests { } /// The property the ack watermark buys, and the one a TTL cannot: age plays - /// no part. A tombstone written a moment ago is collectable the instant - /// every peer covers the delete -- and until then it is kept no matter how - /// long that takes, where a TTL would drop it and let the peer push the - /// record it still holds back as a live value. + /// no part. A tombstone written a moment ago is collected by the second GC + /// call after every peer covers the delete (wavekv keeps it for one call so + /// an envelope still in flight meets it) -- and until then it is kept no + /// matter how long that takes, where a TTL would drop it and let the peer + /// push the record it still holds back as a live value. #[test] fn a_tombstone_is_collected_on_coverage_not_on_age() { let left_dir = tempfile::tempdir().expect("temp dir"); @@ -3790,6 +3990,14 @@ mod tombstone_gc_tests { right.load_all_instances().decoded.is_empty(), "the peer must have applied the delete" ); + assert_eq!( + left.collect_tombstone_garbage() + .expect("collect") + .persistent, + 0, + "the first call after coverage only marks the tombstone" + ); + assert!(key_is_held(&left, &keys::inst("cvm"))); assert!( left.collect_tombstone_garbage() .expect("collect") diff --git a/dstack/gateway/src/main.rs b/dstack/gateway/src/main.rs index d4a9184afd..712abe623e 100644 --- a/dstack/gateway/src/main.rs +++ b/dstack/gateway/src/main.rs @@ -9,10 +9,8 @@ use dstack_guest_agent_rpc::v0::{dstack_guest_client::DstackGuestClient, GetTlsK use http_client::prpc::PrpcClient; use ra_rpc::{prpc_routes as prpc, rocket_helper::QuoteVerifier}; use ra_tls::attestation::AttestationVerifier; -use rocket::{ - fairing::AdHoc, - figment::{providers::Serialized, Figment}, -}; +use rocket::fairing::AdHoc; +use rocket_proxy_listener::launch; use std::sync::Arc; use tracing::{info, warn}; @@ -132,15 +130,18 @@ async fn main() -> Result<()> { let args = Args::parse(); let figment = config::load_config_figment(args.config.as_deref()); + config::reject_moved_settings(&figment)?; let mut config = figment.focus("core").extract::()?; + let listeners = config::ListenersConfig::load(&figment)?; + let guest_figment = config::listener_figment(&figment, "guest")?; // Validate node_id if config.sync.enabled && config.sync.node_id == 0 { anyhow::bail!("node_id must be greater than 0"); } - if config.debug.insecure_localhost_backend { + if config.proxy.insecure_localhost_backend { warn!( - "core.debug.insecure_localhost_backend = true; the app address \"localhost\" now \ + "core.proxy.insecure_localhost_backend = true; the app address \"localhost\" now \ resolves to 127.0.0.1 on this host. App addresses also come from the \ _dstack-app-address TXT record of arbitrary custom domains, so any DNS zone owner \ can reach this host's loopback on a port of their choosing, bypassing port_policy. \ @@ -153,7 +154,7 @@ async fn main() -> Result<()> { config::setup_wireguard(&config.wg)?; - let tls_config = figment + let tls_config = guest_figment .focus("tls") .extract::() .context("Failed to extract tls config")?; @@ -180,13 +181,13 @@ async fn main() -> Result<()> { AttestationVerifier::load(&config.attestation) .context("failed to load attestation verifier")?, ); - let admin_auth = if config.admin.enabled { - Some(admin_auth::AdminAuthFairing::from_config(&config.admin)?) + let admin_auth = if listeners.admin.enabled { + Some(admin_auth::AdminAuthFairing::from_config(&listeners.admin)?) } else { None }; - let admin_insecure = config.admin.insecure_no_auth; - let debug_config = config.debug.clone(); + let admin_insecure = listeners.admin.insecure_no_auth; + let debug_enabled = listeners.debug.enabled; let state = Proxy::new(ProxyOptions { config, my_app_id, @@ -199,22 +200,10 @@ async fn main() -> Result<()> { proxy::start(proxy_config, state.clone()).context("failed to start the proxy")?; - let admin_value = figment - .find_value("core.admin") - .context("admin section not found")?; - let debug_value = figment - .find_value("core.debug") - .context("debug section not found")?; + let admin_figment = config::listener_figment(&figment, "admin")?; + let debug_figment = config::listener_figment(&figment, "debug")?; - let admin_figment = Figment::new() - .merge(rocket::Config::default()) - .merge(Serialized::defaults(admin_value)); - - let debug_figment = Figment::new() - .merge(rocket::Config::default()) - .merge(Serialized::defaults(debug_value)); - - let mut rocket = rocket::custom(figment) + let mut rocket = rocket::custom(guest_figment) .mount("/prpc", prpc!(Proxy, RpcHandler, trim: "Tproxy.")) .mount("/", web_routes::health_routes()) // Mount WaveKV sync endpoint (requires mTLS gateway auth) @@ -227,7 +216,7 @@ async fn main() -> Result<()> { .manage(state.clone()); let verifier = QuoteVerifier::new(attestation_verifier); rocket = rocket.manage(verifier); - let main_srv = rocket.launch(); + let main_srv = launch(rocket); let admin_state = state.clone(); let debug_state = state; let admin_srv = async move { @@ -251,19 +240,18 @@ async fn main() -> Result<()> { admin_state .lock() .set_admin_shutdown(admin_rocket.shutdown()); - admin_rocket.launch().await + launch(admin_rocket).await } else { std::future::pending().await } }; let debug_srv = async move { - if debug_config.insecure_enable_debug_rpc { - rocket::custom(debug_figment) + if debug_enabled { + let debug_rocket = rocket::custom(debug_figment) .mount("/prpc", prpc!(Proxy, DebugRpcHandler, trim: "Debug.")) .mount("/", web_routes::health_routes()) - .manage(debug_state) - .launch() - .await + .manage(debug_state); + launch(debug_rocket).await } else { std::future::pending().await } diff --git a/dstack/gateway/src/main_service.rs b/dstack/gateway/src/main_service.rs index 70cd0cec26..052748e815 100644 --- a/dstack/gateway/src/main_service.rs +++ b/dstack/gateway/src/main_service.rs @@ -17,11 +17,12 @@ use crate::distributed_certbot::DistributedCertBot; use cmd_lib::run_cmd as cmd; use dstack_gateway_rpc::{ gateway_server::{GatewayRpc, GatewayServer}, - AcmeInfoResponse, GatewayNodeInfo, GetPeersResponse, GuestAgentConfig, InfoResponse, PeerInfo, - QuotedPublicKey, RegisterCvmRequest, RegisterCvmResponse, WireGuardConfig, WireGuardPeer, + wg_key_proof, AcmeInfoResponse, GatewayNodeInfo, GetPeersResponse, GuestAgentConfig, + InfoResponse, PeerInfo, QuotedPublicKey, RegisterCvmRequest, RegisterCvmResponse, + WireGuardConfig, WireGuardPeer, }; use or_panic::ResultOrPanic; -use ra_rpc::{CallContext, RpcCall, VerifiedAttestation}; +use ra_rpc::{CallContext, RemoteEndpoint, RpcCall, VerifiedAttestation}; use ra_tls::attestation::AppInfo; use rand::seq::IteratorRandom; use rinja::Template as _; @@ -37,7 +38,7 @@ use wavekv::types::NodeId; use crate::{ cert_store::{CertResolver, CertStoreBuilder}, - config::{Config, TlsConfig}, + config::{Config, TlsConfig, WgConfig}, kv::{ fetch_peers_from_bootnode, import, AppIdValidator, HttpsClientConfig, InstanceRecord, KvStore, LegacyOverrides, LoadedInstances, NodeData, NodeStatus, PortPolicy, @@ -234,8 +235,12 @@ impl Proxy { /// cached rejection log, so the answer is current even right after a /// restart and does not depend on when the last reload ran. pub fn rejected_instances(&self) -> Vec { - let rejected = - import::accept_instances(&self.config.wg, self.kv_store.load_all_instances()).rejected; + let rejected = import::accept_instances( + &self.config.wg, + &self.kv_store.gateway_wg_public_keys(), + self.kv_store.load_all_instances(), + ) + .rejected; let state = self.lock(); rejected .into_iter() @@ -310,6 +315,25 @@ impl ProxyInner { self.state.lock().or_panic("Failed to lock AppState") } + /// Whether registrations must carry a valid WireGuard key proof: the + /// replicated policy, or not required when none is stored. + /// + /// Read per registration, so a toggle applies without a restart. A corrupt + /// record fails closed, like the ACME credentials: reading it as "not + /// required" could silently drop a cluster-wide "required" on one node, and + /// that node would then accept unproven keys every peer trusts once + /// replicated. CVMs that do not send proofs yet cannot register until an + /// operator overwrites the record with `SetWgKeyProofConfig`. + pub(crate) fn require_wg_key_proof(&self) -> bool { + match self.kv_store.get_wg_key_proof_config() { + Ok(stored) => stored.is_some_and(|c| c.require_key_proof), + Err(err) => { + error!("the WireGuard key proof policy is unreadable, requiring proofs: {err:?}"); + true + } + } + } + /// Render the WireGuard config under the routing lock, then write and apply /// it after releasing that lock. Only the apply worker calls this. fn reconfigure_wg(&self) -> Result<()> { @@ -1053,6 +1077,7 @@ fn instance_info_from_record( // cached selection on a record that never claimed the app opted out. health: data.health_check.unwrap_or(known_gated).into(), connections: Default::default(), + agent_token: data.agent_token, }; (info, unreadable) } @@ -1107,7 +1132,7 @@ fn build_state_from_kv_store( ) -> ProxyStateMut { let mut state = ProxyStateMut::default(); - let accepted = import::accept_instances(&config.wg, instances); + let accepted = import::accept_instances(&config.wg, &store.gateway_wg_public_keys(), instances); report_rejected_instances(&accepted.rejected); // Build instances @@ -1494,6 +1519,7 @@ fn start_wavekv_watch_task(proxy: Proxy) -> Result<()> { // closing a traffic gate does not touch `inst/` and would never wake the // watcher above. let mut overrides_rx = store_clone.watch_instance_overrides(); + let mut nodes_rx = store_clone.watch_nodes(); reload_instances_from_kv_store(&proxy_clone, &store_clone) .context("Failed to initial load instances from KvStore")?; tokio::spawn(async move { @@ -1511,6 +1537,13 @@ fn start_wavekv_watch_task(proxy: Proxy) -> Result<()> { } "operator override" } + // A record is judged against the gateway nodes' keys too. + changed = nodes_rx.changed() => { + if changed.is_err() { + break; + } + "node" + } }; info!("WaveKV: detected remote {reason} changes, reloading..."); if let Err(err) = reload_instances_from_kv_store(&proxy_clone, &store_clone) { @@ -1525,12 +1558,15 @@ fn start_wavekv_watch_task(proxy: Proxy) -> Result<()> { // Watch for node changes and reconfigure WireGuard let mut rx = kv_store.watch_nodes(); let proxy_for_nodes = proxy.clone(); + let mut warned_overlaps = BTreeSet::new(); + warn_peer_addresses_in_pool(&proxy, &mut warned_overlaps); tokio::spawn(async move { loop { if rx.changed().await.is_err() { break; } info!("WaveKV: detected remote node changes, reconfiguring WireGuard..."); + warn_peer_addresses_in_pool(&proxy_for_nodes, &mut warned_overlaps); proxy_for_nodes.request_wg_apply(); } }); @@ -1678,7 +1714,11 @@ fn reload_instances_from_kv_store(proxy: &Proxy, store: &KvStore) -> Result<()> ); } let legacy_overrides = store.legacy_instance_overrides(); - let accepted = import::accept_instances(&proxy.config.wg, store.load_all_instances()); + let accepted = import::accept_instances( + &proxy.config.wg, + &store.gateway_wg_public_keys(), + store.load_all_instances(), + ); // An unreadable record is not a deletion. Its instance keeps whatever the // data plane already holds, so it must be exempt from the removal pass // below; a record that lost an IP or key conflict is not exempt, because @@ -1759,7 +1799,7 @@ fn reload_instances_from_kv_store(proxy: &Proxy, store: &KvStore) -> Result<()> // Release old IP if it changed (prevent IP leak) if let Some(existing) = &existing { if existing.ip != new_info.ip { - state.state.allocated_addresses.remove(&existing.ip); + state.release_ip(existing.ip, &instance_id); } if existing.app_id != new_info.app_id { if let Some(app_instances) = state.state.apps.get_mut(&existing.app_id) { @@ -1908,6 +1948,20 @@ impl ProxyState { fn valid_ip(&self, ip: Ipv4Addr) -> bool { self.config.wg.is_valid_client_ip(ip) } + /// Return `ip` to the pool unless an instance other than `id` still holds + /// it. Two live instances can share an address while a conflict loser is + /// kept through its grace period, or while its record is unreadable. + fn release_ip(&mut self, ip: Ipv4Addr, id: &str) { + let held = self + .state + .instances + .iter() + .any(|(other, info)| other != id && info.ip == ip); + if !held { + self.state.allocated_addresses.remove(&ip); + } + } + fn alloc_ip(&mut self) -> Option { for ip in self.config.wg.client_ip_range.hosts() { if !self.valid_ip(ip) { @@ -1968,6 +2022,7 @@ impl ProxyState { let ReportedCapabilities { port_policy, health_check, + agent_token, } = reported; if id.is_empty() { bail!("instance_id is empty (no_instance_id is set?)"); @@ -1987,6 +2042,13 @@ impl ProxyState { { bail!("WireGuard public key is already registered to another instance"); } + // Every node refuses such a record on import, so accepting it here + // would leave this node alone in routing it. + if public_key == self.config.wg.public_key + || self.kv_store.gateway_wg_public_keys().contains(public_key) + { + bail!("WireGuard public key belongs to a gateway node"); + } // The rebuild path below reconstructs the instance from scratch -- it // does that when the recorded IP is no longer inside the configured // range -- and everything the registration does not re-state has to @@ -2064,6 +2126,11 @@ impl ProxyState { if port_policy.is_some() { existing.port_policy = port_policy.clone(); } + // Same rule: a registration that supplies no token must not erase + // one, and one that does replaces it wholesale. + if agent_token.is_some() { + existing.agent_token = agent_token.clone(); + } existing.clone() }); if let Some(existing) = edited { @@ -2076,7 +2143,7 @@ impl ProxyState { return Ok(existing); } info!("ip {} is invalid, removing", existing.ip); - self.state.allocated_addresses.remove(&existing.ip); + self.release_ip(existing.ip, id); previous = Some(existing); } let ip = self @@ -2115,6 +2182,7 @@ impl ProxyState { ready: None, health: health_check.unwrap_or(false).into(), connections: Default::default(), + agent_token, }, }; self.add_instance(host_info.clone()); @@ -2539,7 +2607,7 @@ impl ProxyState { } pub(crate) fn select_top_n_hosts(&mut self, id: &str) -> Result { - if self.config.debug.insecure_localhost_backend && id == "localhost" { + if self.config.proxy.insecure_localhost_backend && id == "localhost" { return Ok(smallvec![AddressInfo { ip: Ipv4Addr::new(127, 0, 0, 1), counter: Default::default(), @@ -2670,7 +2738,7 @@ impl ProxyState { /// counterpart is [`Self::remove_instance`]. fn forget_instance(&mut self, id: &str) -> Option { let info = self.state.instances.remove(id)?; - self.state.allocated_addresses.remove(&info.ip); + self.release_ip(info.ip, id); self.state.top_n.remove(&info.app_id); if let Some(app_instances) = self.state.apps.get_mut(&info.app_id) { app_instances.remove(id); @@ -2724,6 +2792,46 @@ impl ProxyState { } } +/// Peer gateway addresses this node could hand out to a CVM. +/// +/// Every node must keep its pool clear of the other nodes' addresses, but each +/// node's config validation only sees its own. The replicated node info carries +/// a peer's address and nothing else of its config, so this is the part of the +/// overlap that can be detected here. +fn peer_addresses_in_pool( + wg: &WgConfig, + my_id: NodeId, + nodes: &BTreeMap, +) -> BTreeSet<(NodeId, Ipv4Addr)> { + nodes + .iter() + .filter(|(id, _)| **id != my_id) + .filter_map(|(id, node)| { + let ip = match node.wg_ip.parse::() { + Ok(net) => net.addr(), + Err(_) => node.wg_ip.parse().ok()?, + }; + wg.is_valid_client_ip(ip).then_some((*id, ip)) + }) + .collect() +} + +/// Warn once for each peer address that newly overlaps this node's pool. +fn warn_peer_addresses_in_pool(proxy: &Proxy, warned: &mut BTreeSet<(NodeId, Ipv4Addr)>) { + let overlaps = peer_addresses_in_pool( + &proxy.config.wg, + proxy.config.sync.node_id, + &proxy.kv_store.load_all_nodes(), + ); + for (node_id, ip) in overlaps.difference(warned) { + warn!( + "gateway node {node_id} has address {ip}, which this node may allocate to a CVM; \ + exclude it from client_ip_range or add it to reserved_net" + ); + } + *warned = overlaps; +} + fn gateway_nodes(kv_store: &KvStore, exclude_down: bool) -> Vec { let node_statuses = if exclude_down { kv_store.load_all_node_statuses() @@ -2749,7 +2857,70 @@ fn gateway_nodes(kv_store: &KvStore, exclude_down: bool) -> Vec .collect() } +/// Longest `agent_token` a registration may carry. +/// +/// The token is a short Ed25519 JWT -- a few hundred bytes. The field is +/// self-declared, persisted, synced to every peer and sent back out as a +/// request header, so it is bounded here rather than trusted. +const MAX_AGENT_TOKEN_BYTES: usize = 4096; + +/// The `agent_token` a registration may store, or `None`. +/// +/// Absent and empty both mean "this CVM has no token", which is what a CVM +/// that predates the field or could not mint one reports. A value past +/// [`MAX_AGENT_TOKEN_BYTES`] is not a token at all: it is dropped with a +/// warning rather than stored, so one CVM cannot inflate every record. +fn validated_agent_token(instance_id: &str, token: Option) -> Option { + match token { + Some(token) if token.len() > MAX_AGENT_TOKEN_BYTES => { + warn!( + "[{instance_id}] ignoring an agent token of {} bytes (limit {MAX_AGENT_TOKEN_BYTES})", + token.len() + ); + None + } + Some(token) if token.is_empty() => None, + token => token, + } +} + +/// Apply the key proof policy (`require`) to a registration's `wg_key_proof`. +/// +/// Checked only on the node the CVM registers with: the proof is made for this +/// node's key, and peers already trust what a registering node replicates. +fn ensure_wg_key_proof( + require: bool, + gateway_private_key: &str, + request: &RegisterCvmRequest, + app_info: &AppInfo, + instance_id: &str, +) -> Result<()> { + let Some(proof) = &request.wg_key_proof else { + if require { + bail!("WireGuard key proof is required but the CVM sent none"); + } + debug!("[{instance_id}] registering without a WireGuard key proof"); + return Ok(()); + }; + let verified = wg_key_proof::verify( + proof, + gateway_private_key, + &request.client_public_key, + &app_info.app_id, + &app_info.instance_id, + ); + match verified { + Ok(()) => Ok(()), + Err(err) if require => Err(err.context("invalid WireGuard key proof")), + Err(err) => { + warn!("[{instance_id}] accepting an invalid WireGuard key proof: {err:#}"); + Ok(()) + } + } +} + pub struct RpcHandler { + remote_endpoint: Option, remote_app_id: Option>, remote_app_info: Option, attestation: Option, @@ -2780,48 +2951,81 @@ impl GatewayRpc for RpcHandler { .context("failed to decode app-info from attestation")? } }; - self.state - .auth_client - .ensure_app_authorized(&app_info) - .await - .context("App authorization failed")?; let app_id = hex::encode(&app_info.app_id); let instance_id = hex::encode(&app_info.instance_id); - let compose_hash = hex::encode(&app_info.compose_hash); - let port_policy = request - .port_policy - .map(|policy| -> Result { - let ports = policy - .ports - .into_iter() - .map(|attr| { - let port = u16::try_from(attr.port) - .with_context(|| format!("port {} out of u16 range", attr.port))?; - if port == 0 { - bail!("port must be between 1 and 65535"); - } - Ok((port, crate::kv::PortFlags { pp: attr.pp })) + let result = async { + self.state + .auth_client + .ensure_app_authorized(&app_info) + .await + .context("App authorization failed")?; + ensure_wg_key_proof( + self.state.require_wg_key_proof(), + &self.state.config.wg.private_key, + &request, + &app_info, + &instance_id, + )?; + let compose_hash = hex::encode(&app_info.compose_hash); + let port_policy = request + .port_policy + .map(|policy| -> Result { + let ports = policy + .ports + .into_iter() + .map(|attr| { + let port = u16::try_from(attr.port) + .with_context(|| format!("port {} out of u16 range", attr.port))?; + if port == 0 { + bail!("port must be between 1 and 65535"); + } + Ok((port, crate::kv::PortFlags { pp: attr.pp })) + }) + .collect::>()?; + Ok(PortPolicy { + ports, + restrict_mode: policy.restrict_mode, }) - .collect::>()?; - Ok(PortPolicy { - ports, - restrict_mode: policy.restrict_mode, }) - }) - .transpose()?; - self.state - .register_cvm_async( - app_id, - instance_id, - request.client_public_key, - compose_hash, - ReportedCapabilities { - port_policy, - // A real CVM always states its intent, either way. - health_check: Some(request.health_check), - }, - ) - .await + .transpose()?; + let agent_token = validated_agent_token(&instance_id, request.agent_token); + self.state + .register_cvm_async( + app_id.clone(), + instance_id.clone(), + request.client_public_key, + compose_hash, + ReportedCapabilities { + port_policy, + // A real CVM always states its intent, either way. + health_check: Some(request.health_check), + agent_token, + }, + ) + .await + } + .await; + match &result { + Ok(response) => info!( + target: "dstack_gateway::audit", + operation = "register_cvm", + app_id = %app_id, + instance_id = %instance_id, + client_ip = response.wg.as_ref().map_or("", |wg| wg.client_ip.as_str()), + remote = ?self.remote_endpoint, + "cvm registered" + ), + Err(err) => warn!( + target: "dstack_gateway::audit", + operation = "register_cvm", + app_id = %app_id, + instance_id = %instance_id, + remote = ?self.remote_endpoint, + error = %ra_rpc::log_text(&format_args!("{err:#}")), + "cvm registration refused" + ), + } + result } async fn acme_info(self) -> Result { @@ -2836,6 +3040,7 @@ impl GatewayRpc for RpcHandler { external_port: port.into(), app_address_ns_prefix: state.config.proxy.app_address_ns_prefix.clone(), version: env!("CARGO_PKG_VERSION").to_string(), + wg_public_key: state.config.wg.public_key.clone(), }) } @@ -2866,6 +3071,7 @@ impl RpcCall for RpcHandler { fn construct(context: CallContext<'_, Proxy>) -> Result { Ok(RpcHandler { + remote_endpoint: context.remote_endpoint, remote_app_id: context.remote_app_id, remote_app_info: context.remote_app_info, attestation: context.attestation, diff --git a/dstack/gateway/src/main_service/snapshots/dstack_gateway__main_service__tests__config-2.snap b/dstack/gateway/src/main_service/snapshots/dstack_gateway__main_service__tests__config-2.snap index f126f03ee8..eebb0353e5 100644 --- a/dstack/gateway/src/main_service/snapshots/dstack_gateway__main_service__tests__config-2.snap +++ b/dstack/gateway/src/main_service/snapshots/dstack_gateway__main_service__tests__config-2.snap @@ -1,6 +1,6 @@ --- source: gateway/src/main_service/tests.rs -assertion_line: 71 +assertion_line: 86 expression: info1 --- InstanceInfo { @@ -20,5 +20,6 @@ InstanceInfo { gated: false, state: Ungated, }, + agent_token: None, connections: 0, } diff --git a/dstack/gateway/src/main_service/snapshots/dstack_gateway__main_service__tests__config.snap b/dstack/gateway/src/main_service/snapshots/dstack_gateway__main_service__tests__config.snap index 221032272e..9aaa3dcd4e 100644 --- a/dstack/gateway/src/main_service/snapshots/dstack_gateway__main_service__tests__config.snap +++ b/dstack/gateway/src/main_service/snapshots/dstack_gateway__main_service__tests__config.snap @@ -20,5 +20,6 @@ InstanceInfo { gated: false, state: Ungated, }, + agent_token: None, connections: 0, } diff --git a/dstack/gateway/src/main_service/tests.rs b/dstack/gateway/src/main_service/tests.rs index d2f6efc5e8..71d3ab1dc3 100644 --- a/dstack/gateway/src/main_service/tests.rs +++ b/dstack/gateway/src/main_service/tests.rs @@ -4,7 +4,7 @@ use super::*; use crate::config::{load_config_figment, Config, MutualConfig}; -use crate::kv::PortFlags; +use crate::kv::{GlobalWgKeyProofConfig, PortFlags}; use crate::models::HealthState; use crate::proxy::port_policy::is_port_allowed; use crate::time::encode_ts; @@ -167,6 +167,37 @@ async fn test_wireguard_public_key_cannot_be_reused_by_another_instance() { assert!(!state.lock().state.instances.contains_key("instance-2")); } +/// Every node refuses a record carrying a gateway node's key on import, so the +/// node taking the registration must refuse it too, or it alone routes it. +#[tokio::test] +async fn a_gateway_nodes_public_key_does_not_register() { + let state = create_test_state_with(|config| { + config.wg.public_key = test_pubkey("own-gateway"); + }) + .await; + let peer_gateway = test_pubkey("peer-gateway"); + state + .kv_store + .sync_node( + 7, + &crate::kv::NodeData { + uuid: b"gw7-uuid".to_vec(), + url: "https://gw7.example.com:9202".to_string(), + wg_public_key: peer_gateway.clone(), + wg_endpoint: String::new(), + wg_ip: String::new(), + }, + ) + .unwrap(); + let own = state.config.wg.public_key.clone(); + + for (id, key) in [("steals-peer-key", &peer_gateway), ("steals-own-key", &own)] { + let result = state.do_register_cvm("app", id, key, "compose", Default::default()); + assert!(result.is_err(), "{id} registered"); + assert!(!state.lock().state.instances.contains_key(id)); + } +} + #[tokio::test] async fn test_port_policy_restrict_mode_allows_listed_only() { let state = create_test_state().await; @@ -535,6 +566,7 @@ fn register_instances(proxy: &mut ProxyState, app: &str, count: usize, health_ch ReportedCapabilities { port_policy: Some(policy(false, &[])), health_check: Some(health_check), + agent_token: None, }, ) .unwrap(); @@ -556,6 +588,7 @@ fn observe(proxy: &mut ProxyState, instance_id: &str, state: HealthState) { id: info.id, ip: info.ip, public_key: info.public_key, + agent_token: info.agent_token, }, state, ); @@ -827,6 +860,7 @@ async fn a_published_record_carries_the_declaration_and_not_the_gate() { ReportedCapabilities { port_policy: Some(policy(false, &[])), health_check: Some(true), + agent_token: None, }, ) .unwrap(); @@ -1051,6 +1085,7 @@ async fn both_operator_overrides_survive_the_ip_rebuild_path() { ReportedCapabilities { port_policy: Some(policy(false, &[])), health_check: Some(false), + agent_token: None, }, ) .unwrap(); @@ -1189,6 +1224,7 @@ async fn a_capability_change_arriving_through_kv_invalidates_the_cached_selectio port_policy: existing.port_policy.clone(), port_policy_hash: existing.port_policy_hash.clone(), health_check: Some(true), + agent_token: None, } }; state @@ -1529,6 +1565,7 @@ fn re_register( ReportedCapabilities { port_policy: Some(policy(false, &[])), health_check: Some(health_check), + agent_token: None, }, ) .unwrap(); @@ -1715,6 +1752,7 @@ async fn a_reboot_arriving_through_kv_resets_health_on_this_node_too() { port_policy: existing.port_policy.clone(), port_policy_hash: existing.port_policy_hash.clone(), health_check: Some(true), + agent_token: None, } }; state @@ -1761,6 +1799,7 @@ async fn a_record_written_without_the_capability_field_does_not_clear_it() { port_policy_hash: existing.port_policy_hash.clone(), // The older build does not know the field exists. health_check: None, + agent_token: None, } }; state @@ -1852,6 +1891,7 @@ async fn a_verdict_polled_before_a_reboot_is_not_applied_after_it() { id: "race-app-0".to_string(), ip: proxy.state.instances["race-app-0"].ip, public_key: proxy.state.instances["race-app-0"].public_key.clone(), + agent_token: None, }; // The CVM reboots and re-registers mid-round. @@ -1884,6 +1924,7 @@ async fn a_verdict_polled_from_a_stale_address_is_not_applied() { id: "addr-app-0".to_string(), ip: "10.99.99.99".parse().unwrap(), public_key: proxy.state.instances["addr-app-0"].public_key.clone(), + agent_token: None, }; observe_from(&mut proxy, &polled, HealthState::Healthy); @@ -1913,6 +1954,7 @@ async fn a_registration_that_reports_no_capability_leaves_it_alone() { ReportedCapabilities { port_policy: Some(policy(false, &[])), health_check: None, + agent_token: None, }, ) .unwrap(); @@ -1979,6 +2021,7 @@ async fn disabling_polling_keeps_both_old_and_new_instances_eligible() { ReportedCapabilities { port_policy: Some(policy(false, &[])), health_check: Some(has_endpoint), + agent_token: None, }, ) .unwrap(); @@ -2135,11 +2178,51 @@ fn sync_from_peer_at( port_policy: None, port_policy_hash: String::new(), health_check: Some(false), + agent_token: None, }, ) .unwrap(); } +/// A local registration that loses an IP conflict to an older peer record is +/// kept through its grace period, so two live instances share the address for +/// a while. Dropping the loser must not free the address the winner still uses. +#[tokio::test] +async fn forgetting_a_conflict_loser_keeps_the_winners_ip_allocated() { + let state = create_test_state().await; + let ip = state + .lock() + .new_client_by_id( + "local", + "local-app", + &test_pubkey("local-key"), + "", + Default::default(), + ) + .unwrap() + .ip; + sync_from_peer_at(&state, "peer", &ip.to_string(), &test_pubkey("peer-key"), 1); + reload_instances_from_kv_store(&state.proxy, &state.kv_store).unwrap(); + { + let proxy = state.lock(); + assert_eq!(proxy.state.instances["peer"].ip, ip); + assert_eq!(proxy.state.instances["local"].ip, ip); + } + state.proxy.remove_cvm("local").unwrap(); + + let next = state + .lock() + .new_client_by_id( + "next", + "next-app", + &test_pubkey("next-key"), + "", + Default::default(), + ) + .unwrap(); + assert_ne!(next.ip, ip, "handed out an IP a live instance still holds"); +} + #[tokio::test] async fn a_poisoned_peer_record_costs_only_its_own_instance() { let state = create_test_state().await; @@ -2825,3 +2908,179 @@ async fn refreshing_state_leaves_the_routing_lock_free_while_it_writes_to_the_kv "the routing lock is held while the refresh waits on the KV store" ); } + +#[tokio::test] +async fn a_peer_gateway_address_inside_this_nodes_pool_is_detected() { + let state = create_test_state().await; + let wg = &state.config.wg; + let node = |wg_ip: &str| crate::kv::NodeData { + uuid: Vec::new(), + url: String::new(), + wg_public_key: String::new(), + wg_endpoint: String::new(), + wg_ip: wg_ip.to_string(), + }; + let in_pool = wg + .client_ip_range + .hosts() + .find(|ip| wg.is_valid_client_ip(*ip)) + .unwrap(); + let my_id = state.config.sync.node_id; + let nodes = BTreeMap::from([ + // This node's own address never counts. + (my_id, node(&format!("{in_pool}/24"))), + (my_id + 1, node(&format!("{in_pool}/24"))), + // A bare address, as well as the `Ipv4Net` form this node writes. + (my_id + 2, node(&in_pool.to_string())), + (my_id + 3, node("192.0.2.1/24")), + (my_id + 4, node("not an address")), + ]); + assert_eq!( + peer_addresses_in_pool(wg, my_id, &nodes), + BTreeSet::from([(my_id + 1, in_pool), (my_id + 2, in_pool)]) + ); +} + +mod wg_key_proof_policy { + use super::*; + + const CLIENT_SK: &str = "WCwzH5ldiytV13648mAYDqvo3TJ7oVO0uk6a+PQRaFM="; + const CLIENT_PK: &str = "un2Su94T3QglHE4DiL4ZrZ2iCIDhZlF2cS71h1pXUlo="; + const GATEWAY_SK: &str = "aP33GjsVN0Pz8E4gsggEIjf7Z3f+g2Pn6/+5QMnG0GI="; + const GATEWAY_PK: &str = "yZccXHB08kzYxfvKq/OXUiGSOwpSTrvZuQ05XmxA5wI="; + + fn app_info() -> AppInfo { + AppInfo { + app_id: vec![1; 20], + compose_hash: vec![], + instance_id: vec![2; 20], + device_id: vec![], + mr_system: [0; 32], + mr_aggregated: [0; 32], + os_image_hash: vec![], + key_provider_info: vec![], + init_script_hashes: None, + } + } + + fn request(proof: Option) -> RegisterCvmRequest { + RegisterCvmRequest { + client_public_key: CLIENT_PK.to_string(), + wg_key_proof: proof, + ..Default::default() + } + } + + fn proof_for(app_info: &AppInfo) -> dstack_gateway_rpc::WgKeyProof { + wg_key_proof::compute( + CLIENT_SK, + GATEWAY_PK, + &app_info.app_id, + &app_info.instance_id, + ) + .unwrap() + } + + fn check(require: bool, proof: Option) -> Result<()> { + ensure_wg_key_proof(require, GATEWAY_SK, &request(proof), &app_info(), "test") + } + + #[test] + fn accepts_valid_proof() { + check(false, Some(proof_for(&app_info()))).unwrap(); + check(true, Some(proof_for(&app_info()))).unwrap(); + } + + #[test] + fn accepts_missing_or_invalid_proof_when_not_required() { + check(false, None).unwrap(); + let other_instance = AppInfo { + instance_id: vec![3; 20], + ..app_info() + }; + check(false, Some(proof_for(&other_instance))).unwrap(); + } + + #[test] + fn rejects_missing_proof_when_required() { + let err = check(true, None).unwrap_err(); + assert!(format!("{err:#}").contains("sent none"), "{err:#}"); + } + + #[test] + fn rejects_invalid_proof_when_required() { + let other_instance = AppInfo { + instance_id: vec![3; 20], + ..app_info() + }; + assert!(check(true, Some(proof_for(&other_instance))).is_err()); + + let mut forged = proof_for(&app_info()); + forged.mac[0] ^= 1; + assert!(check(true, Some(forged)).is_err()); + + // A proof made for another gateway node is refused, not misverified. + let mut elsewhere = proof_for(&app_info()); + elsewhere.gateway_public_key = CLIENT_PK.to_string(); + let err = check(true, Some(elsewhere)).unwrap_err(); + assert!( + format!("{err:#}").contains("targets gateway key"), + "{err:#}" + ); + } + + #[tokio::test] + async fn the_stored_policy_decides_and_a_corrupt_one_requires_proofs() { + let state = create_test_state().await; + assert!(!state.require_wg_key_proof(), "absent means not required"); + for require_key_proof in [true, false] { + state + .kv_store + .set_wg_key_proof_config(&GlobalWgKeyProofConfig { require_key_proof }) + .unwrap(); + assert_eq!(state.require_wg_key_proof(), require_key_proof); + } + state + .kv_store + .persistent() + .write() + .put( + crate::kv::keys::GLOBAL_WG_KEY_PROOF_CONFIG.to_string(), + b"not-messagepack".to_vec(), + ) + .unwrap(); + assert!(state.require_wg_key_proof()); + } + + #[tokio::test] + async fn admin_set_and_get_round_trip() { + use crate::admin_service::AdminRpcHandler; + use dstack_gateway_rpc::{admin_server::AdminRpc, WgKeyProofConfig}; + + let state = create_test_state().await; + let admin = || { + AdminRpcHandler::construct(CallContext::builder().state(&state.proxy).build()).unwrap() + }; + assert!( + !admin() + .get_wg_key_proof_config() + .await + .unwrap() + .require_key_proof + ); + admin() + .set_wg_key_proof_config(WgKeyProofConfig { + require_key_proof: true, + }) + .await + .unwrap(); + assert!( + admin() + .get_wg_key_proof_config() + .await + .unwrap() + .require_key_proof + ); + assert!(state.require_wg_key_proof()); + } +} diff --git a/dstack/gateway/src/models.rs b/dstack/gateway/src/models.rs index b41a7ba93a..6ee4e11d48 100644 --- a/dstack/gateway/src/models.rs +++ b/dstack/gateway/src/models.rs @@ -72,6 +72,10 @@ pub struct InstanceInfo { /// [`Health`]'s own state is not, so there is no way to build one whose /// declaration and verdict disagree. pub(crate) health: Health, + /// Bearer token for the instance's guest agent external listener, minted + /// by the CVM at registration. Absent for a legacy CVM, whose listener + /// needs none. + pub agent_token: Option, pub connections: Arc, } @@ -93,6 +97,11 @@ pub struct ReportedCapabilities { /// instance already declared in place. `Some(false)` is an app that did not /// opt in, or an image that predates the field; the gateway polls neither. pub health_check: Option, + /// Bearer token for the agent's external listener. `None` leaves whatever + /// the instance already carried in place, so a registration without one + /// (a legacy CVM, or one that could not mint one yet) does not erase a + /// token a previous registration supplied. + pub agent_token: Option, } impl From> for ReportedCapabilities { @@ -102,6 +111,7 @@ impl From> for ReportedCapabilities { Self { port_policy, health_check: None, + agent_token: None, } } } diff --git a/dstack/gateway/src/pp.rs b/dstack/gateway/src/pp.rs index ab9de28293..48a1351b9e 100644 --- a/dstack/gateway/src/pp.rs +++ b/dstack/gateway/src/pp.rs @@ -4,27 +4,13 @@ use std::net::SocketAddr; -use anyhow::{bail, Context, Result}; +use anyhow::Result; use proxy_protocol::{version1 as v1, version2 as v2, ProxyHeader}; -use tokio::{ - io::{AsyncRead, AsyncReadExt}, - net::TcpStream, -}; +use rocket_proxy_listener::read_proxy_header; +use tokio::net::TcpStream; use crate::config::ProxyConfig; -const V1_PROTOCOL_PREFIX: &str = "PROXY"; -const V1_PREFIX_LEN: usize = 5; -const V1_MAX_LENGTH: usize = 107; -const V1_TERMINATOR: &[u8] = b"\r\n"; - -const V2_PROTOCOL_PREFIX: &[u8] = b"\r\n\r\n\0\r\nQUIT\n"; -const V2_PREFIX_LEN: usize = 12; -const V2_MINIMUM_LEN: usize = 16; -const V2_LENGTH_INDEX: usize = 14; -const READ_BUFFER_LEN: usize = 512; -const V2_MAX_LENGTH: usize = 2048; - /// Read or synthesize the inbound proxy protocol header. /// /// When `inbound_pp_enabled` is true, reads a PP header from the stream (e.g. from an upstream @@ -95,238 +81,10 @@ fn create_inbound_pp_header(inbound: &TcpStream) -> ProxyHeader { } } -/// Read a PROXY protocol header and parse it. -/// -/// The amount of data handed to `proxy_protocol::parse` is load-bearing. -/// `version2::parse` checks `buf.remaining()` against the *fixed* size of the -/// address family and then does `buf.advance(length - that)` using the -/// attacker-declared `length` -- an unchecked advance that panics inside -/// `bytes`, which with `panic = "abort"` would be the whole gateway. Handing it -/// a 228-byte AF_UNIX header declaring `length = 65535` produces -/// `advance out of bounds: the len is 0 but advancing by 65319`. -/// -/// Both v2 paths call `read_exact` for the complete declared body before -/// parsing. The fixed-buffer path therefore has at least `full_length` bytes -/// available, and the oversize path allocates exactly `full_length` bytes. -/// Keep that full-body read if this is changed to parse incrementally: calling -/// `parse` with fewer than the declared number of bytes can reach the unchecked -/// advance. `representative_v2_header_lengths_do_not_abort` covers the boundary -/// lengths on both sides of the fixed-buffer cutoff. -async fn read_proxy_header(mut stream: I) -> Result<(I, ProxyHeader)> -where - I: AsyncRead + Unpin, -{ - let mut buffer = [0; READ_BUFFER_LEN]; - let mut dynamic_buffer = None; - - stream.read_exact(&mut buffer[..V1_PREFIX_LEN]).await?; - - if &buffer[..V1_PREFIX_LEN] == V1_PROTOCOL_PREFIX.as_bytes() { - read_v1_header(&mut stream, &mut buffer).await?; - } else { - stream - .read_exact(&mut buffer[V1_PREFIX_LEN..V2_MINIMUM_LEN]) - .await?; - if &buffer[..V2_PREFIX_LEN] == V2_PROTOCOL_PREFIX { - dynamic_buffer = read_v2_header(&mut stream, &mut buffer).await?; - } else { - bail!("no valid proxy protocol header detected"); - } - } - - let mut buffer = dynamic_buffer.as_deref().unwrap_or(&buffer[..]); - - let header = - proxy_protocol::parse(&mut buffer).context("failed to parse proxy protocol header")?; - Ok((stream, header)) -} - -async fn read_v2_header( - mut stream: I, - buffer: &mut [u8; READ_BUFFER_LEN], -) -> Result>> -where - I: AsyncRead + Unpin, -{ - let length = - u16::from_be_bytes([buffer[V2_LENGTH_INDEX], buffer[V2_LENGTH_INDEX + 1]]) as usize; - let full_length = V2_MINIMUM_LEN + length; - - if full_length > V2_MAX_LENGTH { - bail!("v2 proxy protocol header is too long"); - } - - if full_length > READ_BUFFER_LEN { - let mut dynamic_buffer = Vec::with_capacity(full_length); - dynamic_buffer.extend_from_slice(&buffer[..V2_MINIMUM_LEN]); - dynamic_buffer.resize(full_length, 0); - stream - .read_exact(&mut dynamic_buffer[V2_MINIMUM_LEN..full_length]) - .await?; - - Ok(Some(dynamic_buffer)) - } else { - stream - .read_exact(&mut buffer[V2_MINIMUM_LEN..full_length]) - .await?; - - Ok(None) - } -} - -async fn read_v1_header(mut stream: I, buffer: &mut [u8; READ_BUFFER_LEN]) -> Result<()> -where - I: AsyncRead + Unpin, -{ - let mut end_found = false; - for i in V1_PREFIX_LEN..V1_MAX_LENGTH { - buffer[i] = stream.read_u8().await?; - - if [buffer[i - 1], buffer[i]] == V1_TERMINATOR { - end_found = true; - break; - } - } - if !end_found { - bail!("no valid proxy protocol header detected (v1 terminator not found)"); - } - - Ok(()) -} - #[cfg(test)] mod tests { use super::*; - use proxy_protocol::{version1 as v1, version2 as v2, ProxyHeader}; - - fn extract_v4(header: ProxyHeader) -> (std::net::SocketAddrV4, std::net::SocketAddrV4) { - match header { - ProxyHeader::Version1 { - addresses: - v1::ProxyAddresses::Ipv4 { - source, - destination, - }, - .. - } => (source, destination), - ProxyHeader::Version2 { - addresses: - v2::ProxyAddresses::Ipv4 { - source, - destination, - }, - .. - } => (source, destination), - other => panic!("expected ipv4 header, got {other:?}"), - } - } - - /// Representative and boundary v2 lengths against every address family, - /// with the body absent, truncated and complete. The reader must return -- - /// `Ok` or `Err` -- and never reach the unchecked `advance` in - /// `version2::parse`. - #[tokio::test] - async fn representative_v2_header_lengths_do_not_abort() { - for family_proto in [0x00u8, 0x11, 0x21, 0x31, 0x12, 0x99] { - for length in [ - 0u16, 1, 12, 15, 16, 36, 215, 216, 217, 495, 496, 497, 2032, 2047, 65535, - ] { - for supplied in [0usize, 8, 216, usize::from(length)] { - let mut header = V2_PROTOCOL_PREFIX.to_vec(); - header.extend_from_slice(&[0x21, family_proto]); - header.extend_from_slice(&length.to_be_bytes()); - header.extend(std::iter::repeat_n(0x41u8, supplied)); - // Returning at all is the property under test. - let _ = read_proxy_header(&header[..]).await; - } - } - } - } - - /// The v1 reader stops at the first CRLF, and the parser is then handed the - /// whole zero-padded array rather than the bytes actually read -- which is - /// what keeps `version1::parse`'s two unguarded `get_u8` calls at the end of - /// the header in bounds. - #[tokio::test] - async fn a_v1_header_ending_on_a_bare_cr_does_not_abort() { - for tail in ["", " ", " 1", " 1 ", " 1 65535"] { - let header = format!("PROXY TCP4 1.2.3.4 5.6.7.8{tail}\r\n"); - let _ = read_proxy_header(header.as_bytes()).await; - } - } - - #[tokio::test] - async fn parses_v1_ipv4() { - // v1 is ASCII: "PROXY TCP4 \r\n" - let header = b"PROXY TCP4 1.2.3.4 5.6.7.8 11111 22222\r\n"; - let (_stream, parsed) = read_proxy_header(&header[..]).await.expect("v1 parse"); - let (src, dst) = extract_v4(parsed); - assert_eq!(src.ip().octets(), [1, 2, 3, 4]); - assert_eq!(src.port(), 11111); - assert_eq!(dst.ip().octets(), [5, 6, 7, 8]); - assert_eq!(dst.port(), 22222); - } - - #[tokio::test] - async fn parses_v2_ipv4() { - // v2 magic + ver/cmd 0x21 + family/proto 0x11 (TCP/IPv4) + len 12 - let mut header = Vec::new(); - header.extend_from_slice(V2_PROTOCOL_PREFIX); - header.extend_from_slice(&[0x21, 0x11, 0x00, 0x0c]); - header.extend_from_slice(&[1, 2, 3, 4]); // src ip - header.extend_from_slice(&[5, 6, 7, 8]); // dst ip - header.extend_from_slice(&11111u16.to_be_bytes()); // src port - header.extend_from_slice(&22222u16.to_be_bytes()); // dst port - - let (_stream, parsed) = read_proxy_header(&header[..]).await.expect("v2 parse"); - let (src, dst) = extract_v4(parsed); - assert_eq!(src.ip().octets(), [1, 2, 3, 4]); - assert_eq!(src.port(), 11111); - assert_eq!(dst.ip().octets(), [5, 6, 7, 8]); - assert_eq!(dst.port(), 22222); - } - - #[tokio::test] - async fn rejects_no_prefix() { - // Looks neither like v1 ("PROXY") nor v2 magic. - let bytes = b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"; - let err = read_proxy_header(&bytes[..]).await.unwrap_err(); - assert!( - format!("{err:#}").contains("no valid proxy protocol header"), - "unexpected error: {err:#}" - ); - } - - #[tokio::test] - async fn rejects_v1_without_terminator() { - // PROXY prefix matched but no \r\n terminator within V1_MAX_LENGTH bytes. - let bytes = vec![b'P'; V1_MAX_LENGTH + 8]; // all 'P' — never closes - let mut head = b"PROXY".to_vec(); - head.extend(std::iter::repeat_n(b'A', V1_MAX_LENGTH)); - let err = read_proxy_header(&head[..]).await.unwrap_err(); - let msg = format!("{err:#}"); - assert!( - msg.contains("v1 terminator not found") || msg.contains("no valid proxy"), - "unexpected error: {msg}" - ); - // Sanity: the longer no-terminator buffer would also fail (read past) - let _ = bytes; - } - - #[tokio::test] - async fn rejects_v2_oversize_length() { - // v2 prefix with a length field exceeding V2_MAX_LENGTH. - let mut header = Vec::new(); - header.extend_from_slice(V2_PROTOCOL_PREFIX); - header.extend_from_slice(&[0x21, 0x11]); - // length = V2_MAX_LENGTH bytes -> total = MIN + that, blows the cap - header.extend_from_slice(&(V2_MAX_LENGTH as u16).to_be_bytes()); - let err = read_proxy_header(&header[..]).await.unwrap_err(); - assert!( - format!("{err:#}").contains("too long"), - "unexpected error: {err:#}" - ); - } + use proxy_protocol::version2 as v2; #[test] fn synthesizes_unspec_when_no_addrs() { diff --git a/dstack/gateway/src/proxy.rs b/dstack/gateway/src/proxy.rs index cffb49850a..d4d72838ed 100644 --- a/dstack/gateway/src/proxy.rs +++ b/dstack/gateway/src/proxy.rs @@ -23,7 +23,7 @@ use tokio::{ runtime::Runtime, time::timeout, }; -use tracing::{debug, debug_span, error, info, warn, Instrument}; +use tracing::{debug, error, info, info_span, warn, Instrument}; use crate::{ config::ProxyConfig, @@ -31,6 +31,7 @@ use crate::{ models::EnteredCounter, pp::{get_inbound_pp_header, DisplayAddr}, }; +use access_log::AccessLog; #[derive(Debug, Clone)] pub(crate) struct AddressInfo { @@ -43,6 +44,7 @@ pub(crate) struct AddressInfo { pub(crate) type AddressGroup = smallvec::SmallVec<[AddressInfo; 4]>; +mod access_log; mod adaptive_ktls; mod balance; /// Largest response the gateway will read from a guest agent. @@ -135,6 +137,15 @@ struct DstInfo { is_h2: bool, } +// Require one decimal spelling for each destination port. Port 0 is reserved, +// so reject it along with leading zeros and signs in both SNI and TXT records. +fn parse_canonical_port(port_str: &str) -> Result { + if port_str.starts_with('0') || !port_str.bytes().all(|byte| byte.is_ascii_digit()) { + bail!("invalid port"); + } + port_str.parse::().context("invalid port") +} + fn parse_dst_info(subdomain: &str) -> Result { let mut parts = subdomain.split('-'); let app_id = parts.next().context("no app id found")?.to_owned(); @@ -169,7 +180,7 @@ fn parse_dst_info(subdomain: &str) -> Result { port = if port_str.is_empty() { None } else { - Some(port_str.parse::().context("invalid port")?) + Some(parse_canonical_port(port_str)?) }; } }; @@ -187,7 +198,7 @@ fn parse_dst_info(subdomain: &str) -> Result { pub static NUM_CONNECTIONS: AtomicU64 = AtomicU64::new(0); -async fn handle_connection(inbound: TcpStream, state: Proxy) -> Result<()> { +async fn handle_connection(inbound: TcpStream, state: Proxy, log: &mut AccessLog) -> Result<()> { let timeouts = &state.config.proxy.timeouts; let pp_fut = get_inbound_pp_header(inbound, &state.config.proxy); @@ -196,6 +207,7 @@ async fn handle_connection(inbound: TcpStream, state: Proxy) -> Result<()> { .context("proxy protocol header timeout")? .context("failed to read proxy protocol header")?; debug!("client address: {}", DisplayAddr(&pp_header)); + log.client(&pp_header); let (sni, buffer) = timeout(timeouts.handshake, take_sni(&mut inbound)) .await @@ -204,21 +216,29 @@ async fn handle_connection(inbound: TcpStream, state: Proxy) -> Result<()> { let Some(sni) = sni else { bail!("no sni found"); }; + log.sni(&sni); let (subdomain, base_domain) = sni.split_once('.').context("invalid sni")?; if state.cert_resolver.get().contains_wildcard(base_domain) { let dst = parse_dst_info(subdomain)?; debug!("dst: {dst:?}"); + log.dst(&dst); if dst.is_tls { - tls_passthough::proxy_to_app(state, inbound, pp_header, buffer, &dst.app_id, dst.port) - .await + tls_passthough::proxy_to_app( + state, + inbound, + pp_header, + buffer, + &dst.app_id, + dst.port, + log, + ) + .await } else { - state - .proxy(inbound, pp_header, buffer, &dst.app_id, dst.port, dst.is_h2) - .await + state.proxy(inbound, pp_header, buffer, &dst, log).await } } else { - tls_passthough::proxy_with_sni(state, inbound, pp_header, buffer, &sni).await + tls_passthough::proxy_with_sni(state, inbound, pp_header, buffer, &sni, log).await } } @@ -295,19 +315,26 @@ fn conn_task( proxy: Proxy, slot: Option, ) -> impl std::future::Future + Send + 'static { - let span = debug_span!("conn", id = next_connection_id()); + let span = info_span!("conn", id = next_connection_id()); let conn_entered = EnteredCounter::new(&NUM_CONNECTIONS); async move { let _conn_entered = conn_entered; let _slot = slot; debug!(%from, "new connection"); + let mut log = AccessLog::new(&inbound); let timeouts = &proxy.config.proxy.timeouts; - match timeout(timeouts.total, handle_connection(inbound, proxy)).await { + let result = timeout(timeouts.total, handle_connection(inbound, proxy, &mut log)).await; + match &result { Ok(Ok(_)) => debug!("connection closed"), - Ok(Err(e)) if is_peer_disconnect(&e) => debug!("peer disconnected: {e:#}"), + Ok(Err(e)) if is_peer_disconnect(e) => debug!("peer disconnected: {e:#}"), Ok(Err(e)) => error!("connection error: {e:#}"), Err(_) => error!("connection kept too long, force closing"), } + log.finish(from, || match &result { + Ok(Ok(_)) => "closed".into(), + Ok(Err(e)) => format!("{e:#}"), + Err(_) => "timed out".into(), + }); } .instrument(span) } @@ -725,6 +752,16 @@ mod tests { assert_eq!(sniffed.unwrap().0.as_deref(), Some(host)); } + #[test] + fn test_parse_canonical_port() { + for port in ["1", "80", "65535"] { + assert_eq!(parse_canonical_port(port).unwrap().to_string(), port); + } + for port in ["", "0", "08090", "+8090", "65536", "80", "80s"] { + assert!(parse_canonical_port(port).is_err(), "{port}"); + } + } + #[test] fn test_parse_destination() { // Test basic app_id only @@ -762,5 +799,13 @@ mod tests { assert_eq!(result.app_id, "myapp"); assert_eq!(result.port, 443); assert!(result.is_tls); + + // Test app_id with custom port and HTTP/2 + let result = parse_dst_info("myapp-8090g").unwrap(); + assert_eq!(result.port, 8090); + assert!(result.is_h2); + + // Test non-canonical port + assert!(parse_dst_info("myapp-08090s").is_err()); } } diff --git a/dstack/gateway/src/proxy/access_log.rs b/dstack/gateway/src/proxy/access_log.rs new file mode 100644 index 0000000000..94524f5b2d --- /dev/null +++ b/dstack/gateway/src/proxy/access_log.rs @@ -0,0 +1,140 @@ +// SPDX-FileCopyrightText: © 2024-2025 Phala Network +// +// SPDX-License-Identifier: Apache-2.0 + +//! One `info` line per proxied connection, under the `dstack_gateway::access` +//! target, written when the connection ends. +//! +//! On by default; `RUST_LOG=info,dstack_gateway::access=off` turns it off, and +//! then nothing is collected beyond one level check per connection. It replaces +//! turning on the per-connection debug logs to see who connected to what: those +//! are about six lines and a span entered on every poll, which cost 17% of the +//! new-connection rate on a 4-core gateway against 2.5% for this line. + +use std::os::fd::{AsFd, AsRawFd, OwnedFd}; +use std::time::Instant; + +use proxy_protocol::ProxyHeader; +use tokio::net::TcpStream; +use tracing::info; + +use super::DstInfo; +use crate::pp::DisplayAddr; + +const TARGET: &str = "dstack_gateway::access"; + +pub(crate) struct AccessLog { + /// A duplicate of the inbound socket, held so its counters can still be + /// read once the relay has dropped the original. `None` when the log is off. + socket: Option, + started: Instant, + client: Option, + sni: String, + app_id: String, + port: u16, + route: &'static str, + instance: String, +} + +impl AccessLog { + pub(crate) fn new(inbound: &TcpStream) -> Self { + let enabled = tracing::enabled!(target: TARGET, tracing::Level::INFO); + Self { + socket: enabled + .then(|| inbound.as_fd().try_clone_to_owned().ok()) + .flatten(), + started: Instant::now(), + client: None, + sni: String::new(), + app_id: String::new(), + port: 0, + route: "", + instance: String::new(), + } + } + + fn enabled(&self) -> bool { + self.socket.is_some() + } + + pub(crate) fn client(&mut self, header: &ProxyHeader) { + if self.enabled() { + self.client = Some(header.clone()); + } + } + + pub(crate) fn sni(&mut self, sni: &str) { + if self.enabled() { + self.sni = sni.to_string(); + self.route = "sni"; + } + } + + pub(crate) fn dst(&mut self, dst: &DstInfo) { + if self.enabled() { + self.route = if dst.is_tls { + "passthrough" + } else { + "terminate" + }; + self.app(&dst.app_id, dst.port); + } + } + + pub(crate) fn app(&mut self, app_id: &str, port: u16) { + if self.enabled() { + self.app_id = app_id.to_string(); + self.port = port; + } + } + + pub(crate) fn instance(&mut self, instance_id: &str) { + if self.enabled() { + self.instance = instance_id.to_string(); + } + } + + pub(crate) fn finish(self, from: std::net::SocketAddr, outcome: impl FnOnce() -> String) { + let Some(socket) = self.socket else { + return; + }; + let (bytes_in, bytes_out) = tcp_bytes(&socket).unwrap_or_default(); + let client = self.client.as_ref().map(|h| DisplayAddr(h).to_string()); + info!( + target: TARGET, + client = client.as_deref().unwrap_or("-"), + peer = %from, + sni = self.sni, + route = self.route, + app_id = self.app_id, + port = self.port, + instance = self.instance, + bytes_in, + bytes_out, + us = self.started.elapsed().as_micros() as u64, + outcome = outcome(), + ); + } +} + +/// Bytes received from and acknowledged by the client on this socket, as the +/// kernel counts them. Read here rather than in the relays because spliced and +/// kTLS payloads never pass through this process; for terminated connections it +/// is TLS bytes on the wire. +fn tcp_bytes(socket: &OwnedFd) -> Option<(u64, u64)> { + // SAFETY: `tcp_info` is plain integers, so all-zero is a valid value. + let mut info: libc::tcp_info = unsafe { std::mem::zeroed() }; + let mut len = std::mem::size_of::() as libc::socklen_t; + // SAFETY: `info` is writable for `len` bytes and the kernel writes at most + // that many. + let rc = unsafe { + libc::getsockopt( + socket.as_raw_fd(), + libc::IPPROTO_TCP, + libc::TCP_INFO, + (&mut info as *mut libc::tcp_info).cast(), + &mut len, + ) + }; + (rc == 0).then_some((info.tcpi_bytes_received, info.tcpi_bytes_acked)) +} diff --git a/dstack/gateway/src/proxy/health_check.rs b/dstack/gateway/src/proxy/health_check.rs index c0ea83c7b3..754e3c50f8 100644 --- a/dstack/gateway/src/proxy/health_check.rs +++ b/dstack/gateway/src/proxy/health_check.rs @@ -95,6 +95,10 @@ pub(crate) struct Target { pub id: String, pub ip: Ipv4Addr, pub public_key: String, + /// The token the CVM supplied at registration. `None` for a CVM that + /// predates the field; the poll then carries no credentials and gets + /// whatever the host left anonymous. + pub agent_token: Option, } /// Start the polling loop. Called once at startup. @@ -161,7 +165,7 @@ async fn poll_round( let timeout = config.timeout; let mut polls = futures::stream::iter(targets) .map(|target| async move { - let result = poll_instance(target.ip, agent_port, timeout).await; + let result = poll_instance(&target, agent_port, timeout).await; (target, result) }) .buffer_unordered(config.concurrency.max(1)); @@ -243,6 +247,7 @@ pub(crate) fn select_targets(state: &Proxy) -> Vec { id: instance.id.clone(), ip: instance.ip, public_key: instance.public_key.clone(), + agent_token: instance.agent_token.clone(), }) .collect() } @@ -300,8 +305,8 @@ fn apply_hysteresis( /// A failure to get an answer comes back as [`PollResult::Unreachable`] rather /// than as a verdict; [`apply_hysteresis`] decides when enough of them in a row /// amount to one. -async fn poll_instance(ip: Ipv4Addr, agent_port: u16, timeout: Duration) -> PollResult { - let client = WorkerV1Client::new(prober_transport(ip, agent_port)); +async fn poll_instance(target: &Target, agent_port: u16, timeout: Duration) -> PollResult { + let client = WorkerV1Client::new(prober_transport(target, agent_port)); let response = match tokio::time::timeout(timeout, client.health(Default::default())).await { Err(_) => { return PollResult::unreachable(format!("health poll timed out after {timeout:?}")) @@ -331,7 +336,7 @@ async fn poll_instance(ip: Ipv4Addr, agent_port: u16, timeout: Duration) -> Poll /// one. A probe riding a pooled connection would report healthy for an instance /// no real request can reach. Only the connection is unshared; the client /// itself is process-wide. See `http_client::ConnectionReuse`. -fn prober_transport(ip: Ipv4Addr, agent_port: u16) -> http_client::prpc::PrpcClient { +fn prober_transport(target: &Target, agent_port: u16) -> http_client::prpc::PrpcClient { // `/prpc/v1`, not `/prpc`: `Health` is a v1 `Worker` method. // // No released agent is affected. `Health` never shipped in a release, and a @@ -345,8 +350,12 @@ fn prober_transport(ip: Ipv4Addr, agent_port: u16) -> http_client::prpc::PrpcCli // Instance-id routing keeps working and a restart on a current build fixes // it. Not worth a compatibility probe on every poll for a build nobody was // asked to run. - let url = format!("http://{ip}:{agent_port}/prpc/v1"); - super::guest_agent_client(url, ConnectionReuse::Fresh) + let url = format!("http://{}:{agent_port}/prpc/v1", target.ip); + let client = super::guest_agent_client(url, ConnectionReuse::Fresh); + match &target.agent_token { + Some(token) => client.with_bearer_token(token), + None => client, + } } /// Longest reason kept from an agent's answer. @@ -512,7 +521,7 @@ mod tests { let (tx, rx) = tokio::sync::oneshot::channel(); let port = fake_agent_capturing(Some(br#"{"healthy":true}"#.to_vec()), Some(tx)).await; - let _ = poll_instance(Ipv4Addr::LOCALHOST, port, Duration::from_secs(5)).await; + let _ = poll_instance(&local_target(), port, Duration::from_secs(5)).await; let request_line = rx.await.expect("the poller sent no request"); assert!( @@ -523,7 +532,7 @@ mod tests { async fn poll_fake(answer: Option>) -> PollResult { let port = fake_agent(answer).await; - poll_instance(Ipv4Addr::LOCALHOST, port, Duration::from_secs(5)).await + poll_instance(&local_target(), port, Duration::from_secs(5)).await } #[tokio::test] @@ -553,7 +562,7 @@ mod tests { #[tokio::test] async fn an_agent_that_accepts_and_then_says_nothing_times_out() { let port = fake_agent(None).await; - let result = poll_instance(Ipv4Addr::LOCALHOST, port, Duration::from_millis(100)).await; + let result = poll_instance(&local_target(), port, Duration::from_millis(100)).await; let PollResult::Unreachable(reason) = result else { panic!("a silent agent must not produce a verdict, got {result:?}"); }; @@ -569,7 +578,7 @@ mod tests { .expect("bind"); listener.local_addr().expect("addr").port() }; - let result = poll_instance(Ipv4Addr::LOCALHOST, port, Duration::from_secs(5)).await; + let result = poll_instance(&local_target(), port, Duration::from_secs(5)).await; assert!( matches!(result, PollResult::Unreachable(_)), "a refused connection must not read as an agent saying no, got {result:?}" @@ -635,7 +644,7 @@ mod tests { #[test] fn the_probe_does_not_ride_a_connection_someone_else_opened() { assert_eq!( - prober_transport(Ipv4Addr::new(10, 0, 0, 2), 8090).connection_reuse(), + prober_transport(&target(), 8090).connection_reuse(), ConnectionReuse::Fresh, "a probe over a pooled connection cannot see an agent that refuses new ones" ); @@ -656,6 +665,14 @@ mod tests { id: "inst-1".to_string(), ip: Ipv4Addr::new(10, 0, 0, 2), public_key: "key-1".to_string(), + agent_token: None, + } + } + + fn local_target() -> Target { + Target { + ip: Ipv4Addr::LOCALHOST, + ..target() } } diff --git a/dstack/gateway/src/proxy/sni.rs b/dstack/gateway/src/proxy/sni.rs index 4774b338cc..c3cff30a7f 100644 --- a/dstack/gateway/src/proxy/sni.rs +++ b/dstack/gateway/src/proxy/sni.rs @@ -10,7 +10,7 @@ use parcelona::u8::*; use tracing::trace; pub fn extract_sni(b: &[u8]) -> Option<&[u8]> { - extract_sni_inner(b).ok().map(|r| r.1) + extract_sni_inner(b).ok() } /// Read a `u8`-length-prefixed record. @@ -30,14 +30,26 @@ fn take_record_u8_len(b: &[u8]) -> Result<(&[u8], &[u8]), PErr<'_, u8>> { take_record(b, len) } -fn extract_sni_inner(b: &[u8]) -> Result<(usize, &[u8]), PErr<'_, u8>> { +/// Split off a block of declared length `len`, or as much of it as has +/// arrived, so a partial buffer still parses as far as it goes but nothing is +/// read past the declared end. +fn take_declared(b: &[u8], len: usize) -> (&[u8], &[u8]) { + let (block, rest) = b.split_at(len.min(b.len())); + (rest, block) +} + +/// Bytes left in a block of declared length `len` once parsing reached `rest`. +fn room(len: usize, block: &[u8], rest: &[u8]) -> usize { + len - (block.len() - rest.len()) +} + +fn extract_sni_inner(b: &[u8]) -> Result<&[u8], PErr<'_, u8>> { const CONTENT_TYPE_HANDSHAKE: u8 = 0x16; const HANDSHAKE_TYPE_CLIENT_HELLO: usize = 1; const EXTENSION_TYPE_SNI: usize = 0; const NAME_TYPE_HOST_NAME: usize = 0; - let origin_len = b.len(); - if origin_len < 10 { + if b.len() < 10 { return Err(PErr::new(b)); } @@ -45,7 +57,9 @@ fn extract_sni_inner(b: &[u8]) -> Result<(usize, &[u8]), PErr<'_, u8>> { let err = PErr::new(b).user_msg_push(Msg::Str("not a handshake record")); return Err(err); } - let b = &b[5..]; + // Record length; a handshake fragmented over records is parsed only within the first. + let (b, c) = take_len_be_u16(&b[3..])?; + let (_, b) = take_declared(b, c); // Handshake message type. let (b, c) = take_len_be_u8(b)?; if c != HANDSHAKE_TYPE_CLIENT_HELLO { @@ -54,37 +68,51 @@ fn extract_sni_inner(b: &[u8]) -> Result<(usize, &[u8]), PErr<'_, u8>> { } // Handshake message length. - let (b, c) = take_len_be_u24(b)?; - trace!("1. message len {:?}", c); + let (b, hello_len) = take_len_be_u24(b)?; + trace!("1. message len {:?}", hello_len); + let (_, hello) = take_declared(b, hello_len); // ProtocolVersion (2 bytes) & random (32 bytes). - let (b, _) = take_record(b, 34)?; + let (b, _) = take_record(hello, 34)?; // Session ID (u8-length vec), cipher suites (u16-length vec), compression methods (u8-length vec). let (b, _) = take_record_u8_len(b)?; let (b, _) = take_record_be_u16(b)?; let (b, _) = take_record_u8_len(b)?; - // Extensions length. - let (mut b, mut c) = take_len_be_u16(b)?; + // Extensions length; extensions are the last field of a ClientHello. + let (b, exts_len) = take_len_be_u16(b)?; + trace!("3. Extensions length {:?}", exts_len); + if exts_len != room(hello_len, hello, b) { + let err = PErr::new(b).user_msg_push(Msg::Str("extensions length mismatch")); + return Err(err); + } + let (_, exts) = take_declared(b, exts_len); + let mut b = exts; let mut ext_type: usize; let mut ext_leng: usize; - trace!("3. Extensions length {:?}", c); + let mut ext: &[u8]; loop { // Extension type & length. (b, ext_type) = take_len_be_u16(b)?; (b, ext_leng) = take_len_be_u16(b)?; trace!("4. Ext type (0) {:?} len {:?}", ext_type, ext_leng); + if ext_leng > room(exts_len, exts, b) { + let err = PErr::new(b).user_msg_push(Msg::Str("extension length overflow")); + return Err(err); + } + (b, ext) = take_declared(b, ext_leng); if ext_type != EXTENSION_TYPE_SNI { - if ext_leng > 0 { - (b, _) = take_record(b, ext_leng)?; - } continue; } - // ServerNameList length. - (b, c) = take_len_be_u16(b)?; + // ServerNameList length; the list is the whole extension. + let (mut b, c) = take_len_be_u16(ext)?; trace!("5. ServerNameListmessag len {:?}", c); + if c != room(ext_leng, ext, b) { + let err = PErr::new(b).user_msg_push(Msg::Str("server name list length mismatch")); + return Err(err); + } // ServerNameList. let mut sni: &[u8]; let mut name_type: usize; @@ -97,13 +125,8 @@ fn extract_sni_inner(b: &[u8]) -> Result<(usize, &[u8]), PErr<'_, u8>> { if name_type != NAME_TYPE_HOST_NAME { continue; } - let sni_point: usize = origin_len - b.len(); - trace!( - "[sni] {:?} sni {:?}", - sni_point, - String::from_utf8_lossy(sni) - ); - return Ok((sni_point, sni)); + trace!("[sni] {:?}", String::from_utf8_lossy(sni)); + return Ok(sni); } } } @@ -149,6 +172,38 @@ mod tests { assert_eq!(extract_sni(&hello), Some(&b"app.example.com"[..])); } + /// Offset of the extensions length in `client_hello`: 5 record header, + /// 4 handshake header, 34 version/random, 1 session id, 4 cipher suites, + /// 2 compression methods. + const EXTENSIONS_LEN_OFFSET: usize = 50; + + #[test] + fn a_name_outside_the_declared_extensions_block_is_not_returned() { + let mut hello = client_hello(b"app.example.com"); + hello[EXTENSIONS_LEN_OFFSET..][..2].fill(0); + assert_eq!(extract_sni(&hello), None); + } + + #[test] + fn a_name_past_the_declared_record_is_not_returned() { + let mut hello = client_hello(b"app.example.com"); + // Declare every enclosing block as ending before the extensions. + let trailing = hello.len() - EXTENSIONS_LEN_OFFSET - 2; + let record_len = u16::from_be_bytes([hello[3], hello[4]]) as usize - trailing; + hello[3..5].copy_from_slice(&(record_len as u16).to_be_bytes()); + hello[6..9].copy_from_slice(&((record_len - 4) as u32).to_be_bytes()[1..]); + hello[EXTENSIONS_LEN_OFFSET..][..2].fill(0); + assert_eq!(extract_sni(&hello), None); + } + + #[test] + fn a_name_outside_the_declared_server_name_list_is_not_returned() { + let mut hello = client_hello(b"app.example.com"); + // ServerNameList length follows the extension type and length. + hello[EXTENSIONS_LEN_OFFSET + 6..][..2].fill(0); + assert_eq!(extract_sni(&hello), None); + } + #[test] fn a_record_that_is_not_a_handshake_has_no_sni() { let mut hello = client_hello(b"app.example.com"); diff --git a/dstack/gateway/src/proxy/tls_passthough.rs b/dstack/gateway/src/proxy/tls_passthough.rs index 575b469ec8..c10cce0cfc 100644 --- a/dstack/gateway/src/proxy/tls_passthough.rs +++ b/dstack/gateway/src/proxy/tls_passthough.rs @@ -24,7 +24,9 @@ use crate::{ }; use super::{ + access_log::AccessLog, io_bridge::bridge_tcp, + parse_canonical_port, port_policy::{filter_allowed_addresses, should_send_pp}, AddressGroup, AddressInfo, }; @@ -45,7 +47,7 @@ impl AppAddress { let (app_id, port) = data.split_once(':').context("invalid app address")?; Ok(Self { app_id: app_id.to_string(), - port: port.parse().context("invalid port")?, + port: parse_canonical_port(port)?, }) } } @@ -177,6 +179,7 @@ pub(crate) async fn proxy_with_sni( pp_header: ProxyHeader, buffer: Vec, sni: &str, + log: &mut AccessLog, ) -> Result<()> { let dns_timeout = state.config.proxy.timeouts.dns_resolve; let addr = timeout(dns_timeout, state.app_address_resolver.resolve(sni)) @@ -184,7 +187,17 @@ pub(crate) async fn proxy_with_sni( .with_context(|| format!("DNS TXT resolve timeout for {sni}"))? .with_context(|| format!("failed to resolve app address for {sni}"))?; debug!("target address is {}:{}", addr.app_id, addr.port); - proxy_to_app(state, inbound, pp_header, buffer, &addr.app_id, addr.port).await + log.app(&addr.app_id, addr.port); + proxy_to_app( + state, + inbound, + pp_header, + buffer, + &addr.app_id, + addr.port, + log, + ) + .await } /// Count a connection on `counter` if the app is under its limit. The check and @@ -296,6 +309,7 @@ pub(crate) async fn proxy_to_app( buffer: Vec, app_id: &str, port: u16, + log: &mut AccessLog, ) -> Result<()> { let addresses = state.lock().select_top_n_hosts(app_id)?; let addresses = filter_allowed_addresses(&state, addresses, app_id, port)?; @@ -307,6 +321,7 @@ pub(crate) async fn proxy_to_app( .await .with_context(|| format!("connecting timeout to app {app_id}: {addresses:?}:{port}"))? .with_context(|| format!("failed to connect to app {app_id}: {addresses:?}:{port}"))?; + log.instance(&instance_id); if should_send_pp(&state, &instance_id, port) { let pp_header_bin = proxy_protocol::encode(pp_header).context("failed to encode pp header")?; @@ -348,6 +363,14 @@ pub(crate) async fn proxy_to_app( mod tests { use super::*; + #[test] + fn test_app_address_parse() { + let address = AppAddress::parse(b"myapp:8090").unwrap(); + assert_eq!(address.app_id, "myapp"); + assert_eq!(address.port, 8090); + assert!(AppAddress::parse(b"myapp:08090").is_err()); + } + #[test] fn the_connection_limit_check_takes_the_slot() { let counter = Arc::new(AtomicU64::new(0)); diff --git a/dstack/gateway/src/proxy/tls_terminate.rs b/dstack/gateway/src/proxy/tls_terminate.rs index 0c284865ab..92feee26b2 100644 --- a/dstack/gateway/src/proxy/tls_terminate.rs +++ b/dstack/gateway/src/proxy/tls_terminate.rs @@ -29,9 +29,11 @@ use crate::cert_store::CertResolver; use crate::config::{CryptoProvider, ProxyConfig, TlsVersion}; use crate::main_service::Proxy; +use super::access_log::AccessLog; use super::io_bridge::bridge; use super::port_policy::{filter_allowed_addresses, should_send_pp}; use super::tls_passthough::connect_multiple_hosts; +use super::DstInfo; #[pin_project::pin_project] struct IgnoreUnexpectedEofStream { @@ -355,10 +357,10 @@ impl Proxy { inbound: TcpStream, pp_header: ProxyHeader, buffer: Vec, - app_id: &str, - port: u16, - h2: bool, + dst: &DstInfo, + log: &mut AccessLog, ) -> Result<()> { + let (app_id, port, h2) = (dst.app_id.as_str(), dst.port, dst.is_h2); if app_id == "health" { return self.handle_health_check(inbound, buffer, port, h2).await; } @@ -380,7 +382,7 @@ impl Proxy { // itself worth the offload, then hand it to the kernel. let tls_stream = self.tls_accept_corked(inbound, buffer, h2).await?; let (mut outbound, _counter, instance_id) = - self.connect_upstream(addresses, port, app_id).await?; + self.connect_upstream(addresses, port, app_id, log).await?; self.send_pp_header(&mut outbound, &instance_id, port, pp_header) .await?; return super::adaptive_ktls::relay_with_adaptive_offload( @@ -398,7 +400,7 @@ impl Proxy { // of view, so the payload can be relayed with splice and never // enters this process at all. let (mut outbound, _counter, instance_id) = - self.connect_upstream(addresses, port, app_id).await?; + self.connect_upstream(addresses, port, app_id, log).await?; self.send_pp_header(&mut outbound, &instance_id, port, pp_header) .await?; let (drained, stream) = tls_stream.into_raw(); @@ -440,11 +442,11 @@ impl Proxy { .await .context("ktls splice error"); } - self.relay_to_app(tls_stream, addresses, port, app_id, pp_header) + self.relay_to_app(tls_stream, addresses, port, app_id, pp_header, log) .await } else { let tls_stream = self.tls_accept(inbound, buffer, h2).await?; - self.relay_to_app(tls_stream, addresses, port, app_id, pp_header) + self.relay_to_app(tls_stream, addresses, port, app_id, pp_header, log) .await } } @@ -459,15 +461,18 @@ impl Proxy { addresses: super::AddressGroup, port: u16, app_id: &str, + log: &mut AccessLog, ) -> Result<(TcpStream, crate::models::EnteredCounter, String)> { let max_connections = self.config.proxy.max_connections_per_app; - timeout( + let upstream = timeout( self.config.proxy.timeouts.connect, connect_multiple_hosts(addresses, port, max_connections, app_id), ) .await .map_err(|_| anyhow!("connecting timeout"))? - .context("failed to connect to app") + .context("failed to connect to app")?; + log.instance(&upstream.2); + Ok(upstream) } /// Forward the client's address to the app when its port policy asks for it. @@ -493,12 +498,13 @@ impl Proxy { port: u16, app_id: &str, pp_header: ProxyHeader, + log: &mut AccessLog, ) -> Result<()> where S: AsyncRead + AsyncWrite + Unpin, { let (mut outbound, _counter, instance_id) = - self.connect_upstream(addresses, port, app_id).await?; + self.connect_upstream(addresses, port, app_id, log).await?; self.send_pp_header(&mut outbound, &instance_id, port, pp_header) .await?; bridge( diff --git a/dstack/gateway/test-run/cluster/lib.sh b/dstack/gateway/test-run/cluster/lib.sh index e636fed011..0f7808762f 100644 --- a/dstack/gateway/test-run/cluster/lib.sh +++ b/dstack/gateway/test-run/cluster/lib.sh @@ -69,14 +69,17 @@ generate_config() { local dir="$CONFIG_DIR/${CURRENT_TEST:-suite}/node${node_id}" mkdir -p "$dir" cat >"$dir/gateway.toml" < String { /// /// Regenerate a digest only when you have confirmed against /// `git show v0.5.11:guest-agent/rpc/proto/agent_rpc.proto` that the change is -/// comment-only or a `reserved` addition. +/// comment-only or a `reserved` addition. The one exception is the `GetKey` +/// epoch selectors, which `agent_rpc.proto` explains. #[test] fn the_frozen_services_match_their_pinned_shape() { let set = descriptor_set(); @@ -124,7 +125,7 @@ fn the_frozen_services_match_their_pinned_shape() { let expected = [ ( "DstackGuest", - "aa6b5814627a26284b12c180acb0eb13f91c3e57ce00952734fb358a729762f3", + "6c4ebf6644784f690ec91611f1dc97d103d10963478ba5d513e4cb64fe502ba6", ), ( "Worker", @@ -132,7 +133,7 @@ fn the_frozen_services_match_their_pinned_shape() { ), ( "Tappd", - "65c2e3b49f0ffbdcda4712f4b87b2ca4be386205e57e7956ddc56bec7616cffd", + "804fb5337d51896e094eb5af0cdaba29f0cd102a574c8fd1a1d49f2654096592", ), ]; for (name, want) in expected { diff --git a/dstack/guest-agent/src/access_log.rs b/dstack/guest-agent/src/access_log.rs new file mode 100644 index 0000000000..0397dc5434 --- /dev/null +++ b/dstack/guest-agent/src/access_log.rs @@ -0,0 +1,186 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// +// SPDX-License-Identifier: Apache-2.0 + +//! One line per request on every listener, written to stdout and so to the +//! serial console the host can read. +//! +//! Only what identifies the call is logged: the listener, the peer, the method, +//! the path, the status and the latency. Headers (bearer tokens among them) and +//! bodies stay out. So does the query string, except on listeners that opt in +//! with [`AccessLog::with_query`]: a prpc GET takes its arguments from the +//! query, and on the internal sockets those arguments may be secrets. + +use std::time::Instant; + +use ra_rpc::RemoteEndpoint; +use rocket::{ + fairing::{Fairing, Info, Kind}, + Data, Request, Response, +}; + +/// What the systemd watchdog polls on the external listener. Logging it would +/// put a line on the console every few seconds for the life of the CVM. +pub const WATCHDOG_PROBE_PATH: &str = "/prpc/Worker.Version"; + +const MAX_URI_LEN: usize = 512; + +pub struct AccessLog { + listener: &'static str, + log_query: bool, +} + +impl AccessLog { + pub fn new(listener: &'static str) -> Self { + Self { + listener, + log_query: false, + } + } + + /// Also log the query string, for a listener whose callers never put + /// secrets in it. + pub fn with_query(listener: &'static str) -> Self { + Self { + listener, + log_query: true, + } + } +} + +/// Captured before any other fairing can rewrite the URI, so a request +/// `ScopeFairing` turned away is logged under the path the caller asked for. +struct Started { + at: Instant, + path: String, + query: Option, +} + +#[rocket::async_trait] +impl Fairing for AccessLog { + fn info(&self) -> Info { + Info { + name: "access log", + kind: Kind::Request | Kind::Response, + } + } + + async fn on_request(&self, req: &mut Request<'_>, _: &mut Data<'_>) { + req.local_cache(|| Started::now(req, self.log_query)); + } + + async fn on_response<'r>(&self, req: &'r Request<'_>, res: &mut Response<'r>) { + let started = req.local_cache(|| Started::now(req, self.log_query)); + let path = started.path.as_str(); + let peer = req.remote().cloned().map(RemoteEndpoint::from); + if path == WATCHDOG_PROBE_PATH + && matches!(&peer, Some(RemoteEndpoint::Tcp(addr)) if addr.ip().is_loopback()) + { + return; + } + let uri = match &started.query { + Some(query) => format!("{path}?{query}"), + None => path.to_string(), + }; + tracing::info!( + "{} {} \"{} {}\" {} {:?}", + self.listener, + peer.as_ref().map_or_else(|| "-".into(), describe), + req.method(), + dstack_types::sanitize_for_log(&uri, MAX_URI_LEN), + res.status().code, + started.at.elapsed(), + ); + } +} + +impl Started { + fn now(req: &Request<'_>, log_query: bool) -> Self { + let uri = req.uri(); + Self { + at: Instant::now(), + path: uri.path().to_string(), + query: uri.query().filter(|_| log_query).map(|q| q.to_string()), + } + } +} + +fn describe(peer: &RemoteEndpoint) -> String { + match peer { + RemoteEndpoint::Tcp(addr) | RemoteEndpoint::Quic(addr) => addr.to_string(), + RemoteEndpoint::Unix { + peer: Some(cred), .. + } => format!("pid={},uid={}", cred.pid, cred.uid), + RemoteEndpoint::Unix { peer: None, .. } => "unix".into(), + RemoteEndpoint::Vsock { cid, port } => format!("vsock:{cid}:{port}"), + RemoteEndpoint::Other(address) => dstack_types::sanitize_for_log(address, MAX_URI_LEN), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use rocket::{http::Header, local::asynchronous::Client}; + use std::sync::{Arc, Mutex}; + + #[derive(Clone, Default)] + struct Captured(Arc>>); + + impl std::io::Write for Captured { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + #[rocket::get("/secret")] + fn secret() -> &'static str { + "ok" + } + + async fn log_of(access_log: AccessLog) -> String { + let captured = Captured::default(); + let writer = captured.clone(); + let subscriber = tracing_subscriber::fmt() + .with_ansi(false) + .with_env_filter("dstack_guest_agent::access_log=info") + .with_writer(move || writer.clone()) + .finish(); + let _guard = tracing::subscriber::set_default(subscriber); + + let client = Client::untracked( + rocket::build() + .mount("/", rocket::routes![secret]) + .attach(access_log), + ) + .await + .unwrap(); + client + .get("/secret?path=hunter2") + .header(Header::new("Authorization", "Bearer hunter3")) + .dispatch() + .await; + let log = captured.0.lock().unwrap().clone(); + String::from_utf8(log).unwrap() + } + + #[tokio::test] + async fn neither_the_query_nor_the_token_reaches_the_log() { + let log = log_of(AccessLog::new("test")).await; + assert!(log.contains(r#"test - "GET /secret" 200"#), "{log}"); + assert!(!log.contains("hunter"), "{log}"); + } + + #[tokio::test] + async fn an_opted_in_listener_logs_the_query_but_not_the_token() { + let log = log_of(AccessLog::with_query("test")).await; + assert!( + log.contains(r#"test - "GET /secret?path=hunter2" 200"#), + "{log}" + ); + assert!(!log.contains("hunter3"), "{log}"); + } +} diff --git a/dstack/guest-agent/src/api_auth.rs b/dstack/guest-agent/src/api_auth.rs new file mode 100644 index 0000000000..f247a5a229 --- /dev/null +++ b/dstack/guest-agent/src/api_auth.rs @@ -0,0 +1,367 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// +// SPDX-License-Identifier: Apache-2.0 + +//! Access control for the guest agent's external listener. +//! +//! Every request that reaches `[external]` names a scope, and the caller has +//! to be granted it: either by an Ed25519 JWT, or -- when the host configured +//! it -- by being anonymous. Nothing is granted without one or the other. +//! +//! This is deliberately not a trust boundary. The measured `public_*` switches +//! in app-compose still decide whether confidential data (logs, sysinfo, TCB +//! info) may leave the TEE at all; a scope can only narrow that, never widen +//! it. What scopes decide is who may *ask* -- which the host configures, and +//! which therefore cannot be part of the measurement. + +use std::time::{SystemTime, UNIX_EPOCH}; + +use anyhow::{Context, Result}; +use dstack_api_auth::jwt::{self, Decoded, IssuerKeys, ScopeSet, Verifier}; +use dstack_types::GuestAgentApiConfig; +use ed25519_dalek::VerifyingKey; +use rocket::{ + fairing::{Fairing, Info, Kind}, + http::uri::Origin, + request::{FromRequest, Outcome}, + Data, Request, +}; +use tracing::warn; + +use crate::rpc_service::AppState; + +/// What a caller may do on the external listener. +#[derive(Clone)] +pub struct GuestApiAuth { + verifier: Verifier, + anonymous: ScopeSet, +} + +impl GuestApiAuth { + /// Build from sys-config's `guest_agent_api` block and the app root key. + /// + /// `anonymous_scopes` is validated eagerly so a typo is a boot error rather + /// than a permission that silently never matches. + pub fn new(config: Option<&GuestAgentApiConfig>, app_root_key: &[u8]) -> Result { + let config = config.cloned().unwrap_or_default(); + if let Some(name) = config + .anonymous_scopes + .iter() + .find(|name| !jwt::scope::is_known(name)) + { + anyhow::bail!("guest_agent_api: unknown anonymous scope {name:?}"); + } + let anonymous = ScopeSet::from_names(config.anonymous_scopes); + + let secret = ra_tls::api_v1::derive_app_key( + app_root_key, + jwt::INTERNAL_ISSUER_DOMAIN, + ra_tls::api_v1::KeyAlgorithm::Ed25519, + ) + .context("failed to derive the internal issuer key")?; + let internal = ed25519_dalek::SigningKey::from_bytes(&secret).verifying_key(); + + let external = config + .external_issuers + .into_iter() + .map(|issuer| { + let keys = issuer + .public_keys + .iter() + .map(|encoded| parse_public_key(encoded)) + .collect::>>() + .with_context(|| format!("issuer {:?}", issuer.name))?; + if keys.is_empty() { + warn!("issuer {:?} has no public keys", issuer.name); + } + Ok(IssuerKeys { + name: issuer.name, + keys, + }) + }) + .collect::>()?; + + Ok(Self { + verifier: Verifier::new(internal, external), + anonymous, + }) + } + + /// The scopes a request carries, or `Err` when it presented a token that + /// did not verify. + /// + /// A rejected token never falls back to anonymous: a caller that meant to + /// authenticate and got it wrong should see a refusal, not whatever the + /// host happened to leave open. `app_id` is `None` while the app identity + /// is unavailable, in which case no token can be checked. + fn resolve(&self, token: Option<&Decoded>, app_id: Option<&str>) -> Result { + let Some(token) = token else { + return Ok(self.anonymous.clone()); + }; + let app_id = app_id.context("no token can be accepted until the app identity is known")?; + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + let granted = self + .verifier + .verify_decoded(token, app_id, now) + .context("rejected bearer token")?; + Ok(self.anonymous.union(&granted)) + } +} + +fn parse_public_key(encoded: &str) -> Result { + let bytes: [u8; 32] = hex::decode(encoded) + .context("public key is not hex")? + .try_into() + .ok() + .context("public key must be 32 bytes")?; + VerifyingKey::from_bytes(&bytes).context("public key is not a valid Ed25519 key") +} + +/// The scopes in force for one request, published by [`ScopeFairing`]. +/// +/// A request guard because the dashboard renders parts of itself by scope: it +/// needs the set, not a yes/no. +pub struct EffectiveScopes(pub ScopeSet); + +impl EffectiveScopes { + pub fn allows(&self, scope: &str) -> bool { + self.0.contains(scope) + } +} + +#[rocket::async_trait] +impl<'r> FromRequest<'r> for EffectiveScopes { + type Error = (); + + async fn from_request(request: &'r Request<'_>) -> Outcome { + match request.local_cache(|| None::) { + Some(scopes) => Outcome::Success(EffectiveScopes(scopes.clone())), + // Unreachable: `ScopeFairing` either publishes a set or rewrites + // the request to the 401 route. Kept as a 401 rather than a 403 so + // a request that somehow got past the fairing still looks like + // every other refusal. + None => Outcome::Error((rocket::http::Status::Unauthorized, ())), + } + } +} + +/// The scope a request to the external listener needs, or `None` for a path +/// that names no known route. `None` is refused: the check fails closed, so a +/// spelling this function does not recognise can never reach a handler. +/// +/// Segments come from Rocket's own parser, because that is what the router +/// matches on: it percent-decodes and drops empty segments, so `/%70rpc/Info` +/// and `/prpc//Info` reach the same handler as `/prpc/Info`. +/// +/// The frozen mounts (`/prpc`, `/prpc/v0`) strip one `Worker.` prefix before +/// dispatch, exactly as here; `/prpc/v1` strips nothing. +pub fn required_scope(path: &str) -> Option<&'static str> { + let origin = Origin::parse(path).ok()?; + let segments: Vec<&str> = origin.path().segments().filter(|s| !s.is_empty()).collect(); + let method = match segments.as_slice() { + [] => return Some(jwt::scope::DASHBOARD), + ["metrics"] => return Some(jwt::scope::METRICS), + ["logs", _] => return Some(jwt::scope::LOGS), + ["prpc", "v1", method] => *method, + ["prpc", "v0", method] | ["prpc", method] => { + method.strip_prefix("Worker.").unwrap_or(method) + } + _ => return None, + }; + match method { + "Version" => Some(jwt::scope::VERSION), + "Health" => Some(jwt::scope::HEALTH), + "Info" => Some(jwt::scope::INFO), + "GetAttestationForAppKey" => Some(jwt::scope::ATTEST_APP_KEY), + _ => None, + } +} + +/// Refuses a request whose caller lacks the scope its route needs. +pub struct ScopeFairing { + state: AppState, +} + +impl ScopeFairing { + pub fn new(state: AppState) -> Self { + Self { state } + } +} + +/// The token from an `Authorization: Bearer` header. The scheme is +/// case-insensitive (RFC 9110 §11.1); any other scheme is no token at all. +fn bearer_token<'r>(req: &'r Request<'_>) -> Option<&'r str> { + let (scheme, token) = req.headers().get_one("Authorization")?.split_once(' ')?; + scheme + .eq_ignore_ascii_case("bearer") + .then_some(token.trim()) +} + +#[rocket::async_trait] +impl Fairing for ScopeFairing { + fn info(&self) -> Info { + Info { + name: "guest API scope enforcement", + kind: Kind::Request, + } + } + + async fn on_request(&self, req: &mut Request<'_>, _: &mut Data<'_>) { + // Read the token's shape first. It is the only cheap step, and it is + // the one an unauthenticated caller can drive; the app id lookup below + // can cost a boot attestation, so nothing that arrives here gets that + // far unless it is at least a well-formed Ed25519 token. + let token = match bearer_token(req).map(jwt::decode).transpose() { + Ok(token) => token, + Err(err) => { + tracing::debug!("{err:#}"); + return deny(req); + } + }; + // Only a token needs the app id. Going through `identity()` rather + // than a value bound at startup is what lets a boot whose first decode + // failed recover: the retry is driven by the callers that need it. + let app_id = match token { + Some(_) => self + .state + .identity() + .await + .ok() + .map(|identity| hex::encode(&identity.app_id)), + None => None, + }; + let scopes = match self + .state + .api_auth() + .resolve(token.as_ref(), app_id.as_deref()) + { + Ok(scopes) => scopes, + Err(err) => { + // Every caller on the internet reaches this. A warning per + // attempt is a log the public gets to size. + tracing::debug!("{err:#}"); + return deny(req); + } + }; + match required_scope(req.uri().path().as_str()) { + Some(scope) if scopes.contains(scope) => { + req.local_cache(|| Some(scopes)); + } + _ => deny(req), + } + } +} + +fn deny(req: &mut Request<'_>) { + // `Bearer`, not the shared-token `Basic` default: the way in is a token. + req.local_cache(|| dstack_api_auth::Challenge::Bearer); + if let Ok(uri) = Origin::parse_owned(dstack_api_auth::UNAUTHORIZED_PATH.to_owned()) { + req.set_uri(uri); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_spelling_of_a_route_needs_the_same_scope() { + for path in [ + "/prpc/Info", + "/prpc/v0/Info", + "/prpc/Worker.Info", + "/prpc/v0/Worker.Info", + ] { + assert_eq!(required_scope(path), Some(jwt::scope::INFO), "{path}"); + } + // The frozen surface has no `Health`, but requiring the scope for that + // spelling too is what keeps the check keyed on the method name rather + // than on which mount happened to answer. + for path in ["/prpc/v1/Health", "/prpc/Health", "/prpc/Worker.Health"] { + assert_eq!(required_scope(path), Some(jwt::scope::HEALTH), "{path}"); + } + assert_eq!(required_scope("/"), Some(jwt::scope::DASHBOARD)); + assert_eq!(required_scope("/metrics"), Some(jwt::scope::METRICS)); + assert_eq!(required_scope("/logs/app-1"), Some(jwt::scope::LOGS)); + assert_eq!( + required_scope("/prpc/GetAttestationForAppKey"), + Some(jwt::scope::ATTEST_APP_KEY) + ); + // Fails closed: anything not named here is refused, including a + // second service prefix the dispatcher would not strip. + for path in [ + "/nope", + "/prpc/Worker.Worker.Info", + "/prpc/v0/Worker.Worker.Info", + "/prpc/v1/Worker.Health", + "/prpc/GetQuote", + ] { + assert_eq!(required_scope(path), None, "{path}"); + } + + // The router matches on decoded, non-empty segments, so these reach + // the same handler and must not be able to slip past the check. + for path in ["/%70rpc/Info", "/prpc//Info", "/prpc/v0//Worker.Info"] { + assert_eq!(required_scope(path), Some(jwt::scope::INFO), "{path}"); + } + assert_eq!(required_scope("/%6detrics"), Some(jwt::scope::METRICS)); + } + + fn auth(anonymous: &[&str]) -> GuestApiAuth { + GuestApiAuth::new( + Some(&GuestAgentApiConfig { + anonymous_scopes: anonymous.iter().map(|s| s.to_string()).collect(), + external_issuers: vec![], + }), + &[7u8; 32], + ) + .unwrap() + } + + /// Stands in for a token that is well-formed but not signed by anything + /// this agent trusts. + fn decoded(claims: jwt::Claims) -> Decoded { + let token = jwt::sign(&[1u8; 32], &claims).unwrap(); + jwt::decode(&token).unwrap() + } + + #[test] + fn anonymous_grants_only_what_was_configured() { + assert!(auth(&[]).resolve(None, None).unwrap().is_empty()); + let scopes = auth(&["guest:version"]).resolve(None, None).unwrap(); + assert!(scopes.contains(jwt::scope::VERSION)); + assert!(!scopes.contains(jwt::scope::INFO)); + } + + #[test] + fn a_bad_token_is_refused_rather_than_downgraded_to_anonymous() { + let claims = jwt::Claims { + iss: jwt::internal_issuer("00"), + aud: "00".into(), + iat: 0, + exp: u64::MAX / 2, + scope: jwt::scope::DASHBOARD.into(), + }; + // Signed by the wrong key, so it decodes and fails to verify. + assert!(auth(&["guest:dashboard"]) + .resolve(Some(&decoded(claims)), Some("00")) + .is_err()); + } + + #[test] + fn an_unknown_anonymous_scope_fails_at_startup() { + let err = GuestApiAuth::new( + Some(&GuestAgentApiConfig { + anonymous_scopes: vec!["guest:everything".into()], + external_issuers: vec![], + }), + &[7u8; 32], + ) + .err() + .expect("should reject"); + assert!(err.to_string().contains("guest:everything"), "{err}"); + } +} diff --git a/dstack/guest-agent/src/backend.rs b/dstack/guest-agent/src/backend.rs index fcdf471bb2..c671a34328 100644 --- a/dstack/guest-agent/src/backend.rs +++ b/dstack/guest-agent/src/backend.rs @@ -3,11 +3,39 @@ // SPDX-License-Identifier: Apache-2.0 use anyhow::{Context, Result}; +use cc_eventlog::TdxEvent; use dstack_guest_agent_rpc::v0::GetQuoteResponse; use ra_tls::attestation::Attestation; -use ra_tls::attestation::{QuoteContentType, VersionedAttestation}; +use ra_tls::attestation::{ + AttestationV1, QuoteContentType, TdxAttestationExt, VersionedAttestation, +}; +use tdx_attest::TdxMeasurements; + +/// The TDX measurements and event log legacy `Info` reports. +pub struct TcbInfo { + pub measurements: Option, + pub event_log: Vec, +} + +impl From for TcbInfo { + fn from(attestation: AttestationV1) -> Self { + Self { + measurements: attestation.td10_report().map(|report| TdxMeasurements { + mrtd: report.mr_td, + rtmrs: [report.rt_mr0, report.rt_mr1, report.rt_mr2, report.rt_mr3], + }), + event_log: attestation.tdx_event_log().unwrap_or_default().to_vec(), + } + } +} pub trait PlatformBackend: Send + Sync { + /// Read the TCB info without a quote, or `None` to fall back to + /// [`Self::attestation_for_info`]. + fn local_tcb_info(&self) -> Result> { + Ok(None) + } + fn attestation_for_info(&self) -> Result; fn certificate_attestation(&self, pubkey: &[u8]) -> Result; fn quote_response(&self, report_data: [u8; 64], vm_config: &str) -> Result; @@ -20,6 +48,21 @@ pub trait PlatformBackend: Send + Sync { pub struct RealPlatform; impl PlatformBackend for RealPlatform { + fn local_tcb_info(&self) -> Result> { + let Some(measurements) = + tdx_attest::read_measurements().context("failed to read TDX measurements")? + else { + return Ok(None); + }; + let mut event_log = + cc_eventlog::tdx::read_event_log().context("failed to read event log")?; + cc_eventlog::tdx::fill_v2_preimages(&mut event_log); + Ok(Some(TcbInfo { + measurements: Some(measurements), + event_log, + })) + } + fn attestation_for_info(&self) -> Result { Ok(Attestation::local() .context("Failed to get local attestation")? diff --git a/dstack/guest-agent/src/http_routes.rs b/dstack/guest-agent/src/http_routes.rs index af08338438..587ce3b0dc 100644 --- a/dstack/guest-agent/src/http_routes.rs +++ b/dstack/guest-agent/src/http_routes.rs @@ -4,11 +4,13 @@ use std::time::Duration; +use crate::api_auth::EffectiveScopes; use crate::config::Config; use crate::guest_api_service::{list_containers, GuestApiHandler}; use crate::rpc_service::{AppState, ExternalRpcHandler}; use anyhow::Result; use docker_logs::parse_duration; +use dstack_api_auth::jwt; use dstack_guest_agent_rpc::v0::{worker_server::WorkerRpc, AppInfo}; use guest_api::guest_api_server::GuestApiRpc; use ra_rpc::{CallContext, RpcCall}; @@ -28,14 +30,32 @@ pub fn external_routes(config: &Config) -> Vec { routes } +/// The dashboard, filtered by what this caller was granted. +/// +/// Access to the page is `guest:dashboard` (enforced by the fairing); what it +/// *shows* is narrowed block by block. Two independent gates: the app's +/// measured `public_*` switches decide whether confidential data may leave the +/// TEE at all, and the caller's scopes decide whether this caller may see it. +/// A scope can only hide a block, never reveal one the app kept private. #[get("/")] -async fn index(state: &State) -> Result, String> { +async fn index( + state: &State, + scopes: EffectiveScopes, +) -> Result, String> { let public_logs = state.config().app_compose.public_logs; let public_sysinfo = state.config().app_compose.public_sysinfo; let public_tcbinfo = state.config().app_compose.public_tcbinfo; + let show_identity = scopes.allows(jwt::scope::INFO); + let show_sysinfo = public_sysinfo && scopes.allows(jwt::scope::METRICS); + let show_containers = scopes.allows(jwt::scope::CONTAINERS); + let show_logs = public_logs && scopes.allows(jwt::scope::LOGS); + let show_tcb = public_tcbinfo && show_identity; let context = CallContext::builder().state(&**state).build(); - let handler = ExternalRpcHandler::construct(context.clone()) - .map_err(|e| format!("Failed to construct RPC handler: {}", e))?; + // `Info` costs a boot attestation (and may start a demo-cert request), so + // it is only asked for when the identity block -- and with it the TCB + // block, which requires `guest:info` too -- will be rendered. + // `guest:dashboard` is the one scope an anonymous visitor is most likely + // to be given, and on its own it renders every block hidden. let AppInfo { app_name, app_id, @@ -50,15 +70,21 @@ async fn index(state: &State) -> Result, String> { vm_config: _, cloud_vendor, cloud_product, - } = handler - .info() - .await - .map_err(|e| format!("Failed to get worker info: {}", e))?; + } = if show_identity || show_tcb { + let handler = ExternalRpcHandler::construct(context.clone()) + .map_err(|e| format!("Failed to construct RPC handler: {}", e))?; + handler + .info() + .await + .map_err(|e| format!("Failed to get worker info: {}", e))? + } else { + Default::default() + }; // Only collected when the page will actually render it. Collecting // otherwise would scan every process and disk, and spawn a GPU collector, // on guests that keep their sysinfo private. - let (system_info, gpu_info) = if public_sysinfo { + let (system_info, gpu_info) = if show_sysinfo { let handler = GuestApiHandler::construct(context) .map_err(|e| format!("Failed to construct RPC handler: {}", e))?; ( @@ -69,7 +95,13 @@ async fn index(state: &State) -> Result, String> { Default::default() }; - let containers = list_containers().await.unwrap_or_default().containers; + // Skipped, not merely hidden: the listing walks every container on a + // page an anonymous caller may be allowed to reach. + let containers = if show_containers { + list_containers().await.unwrap_or_default().containers + } else { + Vec::new() + }; let model = crate::models::Dashboard { app_name, app_id, @@ -79,9 +111,11 @@ async fn index(state: &State) -> Result, String> { tcb_info, containers, system_info, - public_sysinfo, - public_logs, - public_tcbinfo, + show_identity, + show_sysinfo, + show_containers, + show_logs, + show_tcb, cloud_vendor, cloud_product, gpu_info, @@ -218,9 +252,9 @@ mod docker_logs { let seconds = match unit { "s" => value, - "m" => value * 60, - "h" => value * 3600, - "d" => value * 24 * 3600, + "m" => value.saturating_mul(60), + "h" => value.saturating_mul(3600), + "d" => value.saturating_mul(24 * 3600), _ => { anyhow::bail!("Invalid time unit. Use s, m, h, or d"); } @@ -231,10 +265,22 @@ mod docker_logs { Ok(now.as_secs().saturating_sub(seconds) as i64) } + fn validate_container_name(name: &str) -> Result<()> { + let mut chars = name.chars(); + let valid = chars.next().is_some_and(|c| c.is_ascii_alphanumeric()) + && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-')); + if !valid { + anyhow::bail!("invalid container name"); + } + Ok(()) + } + pub fn get_logs( container_name: &str, config: LogConfig, ) -> Result>> { + // bollard interpolates the name into the request path without escaping it + validate_container_name(container_name)?; let LogConfig { since, until, @@ -295,6 +341,33 @@ mod docker_logs { use super::*; use std::time::{SystemTime, UNIX_EPOCH}; + #[test] + fn test_validate_container_name() { + for name in [ + "test/json?", + "test/json#", + "../info?", + "test%2Fjson%3F", + "/test", + ".", + "..", + "test\\name", + "test name", + "tést", + "", + ] { + assert!(validate_container_name(name).is_err(), "{name}"); + } + for name in [ + "test", + "dstack-gateway-1", + "Test_1.local", + "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", + ] { + assert!(validate_container_name(name).is_ok(), "{name}"); + } + } + #[test] fn test_parse_duration_empty() { assert_eq!(parse_duration("").unwrap(), 0); @@ -334,6 +407,19 @@ mod docker_logs { ); } + #[test] + fn an_oversized_duration_reaches_back_to_the_epoch() { + let now = SystemTime::now(); + for unit in ["s", "m", "h", "d"] { + let duration = format!("{}{unit}", u64::MAX); + assert_eq!( + parse_duration_inner(&duration, now).unwrap(), + 0, + "{duration}" + ); + } + } + #[test] fn test_parse_duration_errors() { // Invalid unit diff --git a/dstack/guest-agent/src/lib.rs b/dstack/guest-agent/src/lib.rs index 7c70e192a3..b11b0fbf7d 100644 --- a/dstack/guest-agent/src/lib.rs +++ b/dstack/guest-agent/src/lib.rs @@ -5,6 +5,8 @@ pub const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION"); pub const GIT_REV: &str = dstack_build_info::git_revision!(); +mod access_log; +mod api_auth; pub mod backend; pub mod config; mod container_health; diff --git a/dstack/guest-agent/src/models.rs b/dstack/guest-agent/src/models.rs index c8719105b2..7b86f599c7 100644 --- a/dstack/guest-agent/src/models.rs +++ b/dstack/guest-agent/src/models.rs @@ -116,12 +116,26 @@ pub struct Dashboard { pub tcb_info: String, pub containers: Vec, pub system_info: SystemInfo, - pub public_sysinfo: bool, - pub public_logs: bool, - pub public_tcbinfo: bool, + /// The host's sysinfo and GPU collection may be shown: published by the + /// app (`public_sysinfo`) *and* granted to this caller. + pub show_sysinfo: bool, + /// The TCB document may be shown: published by the app + /// (`public_tcbinfo`) *and* granted to this caller. + pub show_tcb: bool, pub cloud_vendor: String, pub cloud_product: String, pub gpu_info: GpuInfoResponse, + /// Whether the caller may see the identity block at all. The page itself + /// already needs `guest:dashboard`; this narrows what it shows, block by + /// block, so a token for one kind of data does not carry the rest. + pub show_identity: bool, + /// Whether the container table is shown. Also decides whether the + /// container list is collected: a scope that hides a block should not pay + /// for producing it. + pub show_containers: bool, + /// Whether the logs column is shown. Requires `public_logs` as well -- a + /// scope cannot unlock logs the app did not publish. + pub show_logs: bool, } #[derive(Template)] @@ -253,11 +267,13 @@ mod tests { tcb_info: String::new(), containers: vec![], system_info: Default::default(), - public_sysinfo: true, - public_logs: false, - public_tcbinfo: false, + show_sysinfo: true, + show_tcb: false, cloud_vendor: String::new(), cloud_product: String::new(), + show_identity: true, + show_containers: true, + show_logs: true, gpu_info: GpuInfoResponse { gpus: vec![GpuDevice { power_usage_mw: Some(70_123), @@ -394,6 +410,59 @@ mod tests { assert!(body.contains("system_load_average_1m 0.40"), "{body}"); } + /// A caller granted only `guest:dashboard` gets the page and nothing on + /// it. Each block is guarded independently, so a missing guard shows up as + /// data in an otherwise empty document rather than as a stray heading. + #[test] + fn a_dashboard_granted_no_block_renders_none_of_them() { + let (app_id, instance_id, device_id) = ([0xd3u8; 32], [0xe5u8; 32], [0xf7u8; 32]); + let html = Dashboard { + app_name: "secret-app".into(), + app_id: app_id.to_vec(), + instance_id: instance_id.to_vec(), + device_id: device_id.to_vec(), + key_provider_info: "secret-kms".into(), + tcb_info: "secret-tcb".into(), + containers: vec![Container { + names: vec!["secret-container".into()], + status: "running".into(), + ..Default::default() + }], + system_info: SystemInfo { + os_name: "secret-os".into(), + cpu_model: "secret-cpu".into(), + ..Default::default() + }, + show_identity: false, + show_sysinfo: false, + show_containers: false, + show_logs: false, + show_tcb: false, + cloud_vendor: "secret-vendor".into(), + cloud_product: "secret-product".into(), + gpu_info: Default::default(), + } + .render() + .expect("render"); + for hidden in [ + "secret-app".to_owned(), + hex::encode(app_id), + hex::encode(instance_id), + hex::encode(device_id), + "secret-kms".into(), + "secret-tcb".into(), + "secret-container".into(), + "secret-os".into(), + "secret-cpu".into(), + "secret-vendor".into(), + "Deployed Containers".into(), + "TCB Info".into(), + "Node Information".into(), + ] { + assert!(!html.contains(&hidden), "{hidden} leaked into {html}"); + } + } + fn dashboard_with(gpu_info: GpuInfoResponse) -> String { Dashboard { app_name: String::new(), @@ -404,11 +473,13 @@ mod tests { tcb_info: String::new(), containers: vec![], system_info: Default::default(), - public_sysinfo: true, - public_logs: false, - public_tcbinfo: false, + show_sysinfo: true, + show_tcb: false, cloud_vendor: String::new(), cloud_product: String::new(), + show_identity: true, + show_containers: true, + show_logs: true, gpu_info, } .render() diff --git a/dstack/guest-agent/src/rpc_service.rs b/dstack/guest-agent/src/rpc_service.rs index 6ae1a8aa7a..2ba67bc460 100644 --- a/dstack/guest-agent/src/rpc_service.rs +++ b/dstack/guest-agent/src/rpc_service.rs @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: Apache-2.0 +use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; @@ -24,12 +25,10 @@ use ed25519_dalek::{Signer as Ed25519Signer, SigningKey as Ed25519SigningKey, Ve use fs_err as fs; use k256::ecdsa::SigningKey; use or_panic::ResultOrPanic; -use ra_rpc::{CallContext, RpcCall}; +use ra_rpc::{CallContext, ResultExt as _, RpcCall}; use ra_tls::{ api_v1::sign_recoverable_keccak256, - attestation::{ - QuoteContentType, TdxAttestationExt, VersionedAttestation, DEFAULT_HASH_ALGORITHM, - }, + attestation::{QuoteContentType, VersionedAttestation, DEFAULT_HASH_ALGORITHM}, cert::{CertConfigV2, CertSigningRequestV2, Csr}, kdf::{derive_key, derive_p256_key_pair_from_bytes}, }; @@ -40,7 +39,7 @@ use serde_json::json; use tracing::error; use crate::{ - backend::{PlatformBackend, RealPlatform}, + backend::{PlatformBackend, RealPlatform, TcbInfo}, config::Config, }; @@ -61,6 +60,13 @@ const IDENTITY_RETRY_INTERVAL: Duration = Duration::from_secs(30); /// every `Info` may start: a quote plus an RA-TLS round trip to the KMS. const DEMO_CERT_RETRY_INTERVAL: Duration = Duration::from_secs(30); +/// How long a caller may wait for the attestation queue. +/// +/// Callers keep running after their client disconnects, so without a bound a +/// slow platform lets abandoned requests take every quote slot from live ones. +/// A timeout counts as a failure for the identity and demo-cert throttles. +const ATTEST_QUEUE_TIMEOUT: Duration = Duration::from_secs(10); + /// Decode the immutable identity fields out of a boot attestation. /// /// Costs a quote and an event-log replay, which is why its result is cached for @@ -92,11 +98,40 @@ pub struct AppState { inner: Arc, } +/// The app root key of one KMS root epoch, with its KMS signature. +#[derive(Clone)] +pub(crate) struct AppRoot { + pub epoch: u32, + pub app_epoch: u32, + pub k256_key: Vec, + pub signing_key: SigningKey, + pub kms_signature: Vec, +} + +impl AppRoot { + fn new(epoch: u32, app_epoch: u32, k256_key: Vec, kms_signature: Vec) -> Result { + let signing_key = SigningKey::from_slice(&k256_key) + .context("the app root k256 key is not a valid secp256k1 scalar")?; + Ok(Self { + epoch, + app_epoch, + k256_key, + signing_key, + kms_signature, + }) + } +} + struct AppStateInner { config: Config, keys: AppKeys, vm_config: String, cert_client: CertRequestClient, + /// Successfully fetched roots of earlier epochs. The lock is not held + /// while fetching, so concurrent first requests for one epoch may each ask + /// the KMS; the first result is kept. Failures are not cached, so a refused + /// epoch is asked for again on every call. + historical_roots: tokio::sync::Mutex>, demo_cert: tokio::sync::OnceCell, /// When the last demo-cert request failed; held while one is running. demo_cert_last_failure: tokio::sync::Mutex>, @@ -123,6 +158,8 @@ struct AppStateInner { /// VM is running. cloud_vendor: String, cloud_product: String, + /// Access control for the external listener. See `api_auth`. + api_auth: crate::api_auth::GuestApiAuth, } /// The identity fields v1 `Info` reports, decoded once. @@ -151,13 +188,18 @@ impl AppStateInner { /// running one on the executor stalls every connection the agent serves, /// including the systemd watchdog heartbeat. Callers queue here rather than /// on `dstack-attest`'s quote lock, so a flood of requests holds no threads. - /// The guard moves into the task, so a cancelled caller cannot let the - /// next call in while its own is still running. + /// The wait is bounded by [`ATTEST_QUEUE_TIMEOUT`]. The guard moves into + /// the task, so a cancelled caller cannot let the next call in while its + /// own is still running. async fn attest( &self, work: impl FnOnce(&dyn PlatformBackend) -> Result + Send + 'static, ) -> Result { - let guard = self.attest_lock.clone().lock_owned().await; + let guard = + tokio::time::timeout(ATTEST_QUEUE_TIMEOUT, self.attest_lock.clone().lock_owned()) + .await + .context("the attestation queue is busy, retry later") + .with_code(503)?; let platform = self.platform.clone(); tokio::task::spawn_blocking(move || { let _guard = guard; @@ -167,6 +209,23 @@ impl AppStateInner { .context("the attestation task panicked")? } + /// The TCB info for legacy `Info`, read without a quote where the platform + /// allows, so `Info` does not queue behind quote callers. + async fn tcb_info(&self) -> Result { + let platform = self.platform.clone(); + let local = tokio::task::spawn_blocking(move || platform.local_tcb_info()) + .await + .context("the TCB info task panicked")??; + match local { + Some(tcb) => Ok(tcb), + None => Ok(self + .attest(|platform| platform.attestation_for_info()) + .await? + .into_v1() + .into()), + } + } + async fn issue_cert( &self, key: &KeyPair, @@ -258,11 +317,11 @@ impl AppState { .context("Failed to parse VM config")?; let collateral_urls = sys_config.collateral_urls(); let gpu_attestor = crate::gpu_attest::GpuAttestor::new(); - let vm_config = sys_config.vm_config; + let vm_config = sys_config.vm_config.clone(); // Same trust anchor decision as dstack-util: never host-supplied, and // development roots only when this guest published them itself. let verifier = Arc::new(default_verifier(&collateral_urls)?); - let cert_client = CertRequestClient::create(&keys, verifier, vm_config.clone()) + let cert_client = CertRequestClient::create(&keys, verifier, &sys_config) .await .context("Failed to create cert signer")?; // Only run the refresh loop when the app asked the gateway to gate on @@ -279,6 +338,11 @@ impl AppState { config.app_compose.runner.clone(), ) }); + // A bad `guest_agent_api` block is a boot error: an unknown scope name + // would otherwise silently grant nothing. + let api_auth = + crate::api_auth::GuestApiAuth::new(sys_config.guest_agent_api.as_ref(), &keys.k256_key) + .context("failed to set up guest API access control")?; // Parsed once, and non-fatally: an unusable app root key is reported by // the RPCs that need one, not by refusing to start. let app_root_signing_key = match SigningKey::from_slice(&keys.k256_key) { @@ -293,6 +357,7 @@ impl AppState { config, keys, cert_client, + historical_roots: Default::default(), demo_cert: Default::default(), demo_cert_last_failure: Default::default(), vm_config, @@ -305,6 +370,7 @@ impl AppState { attest_lock: Arc::default(), cloud_vendor: read_dmi_file("sys_vendor"), cloud_product: read_dmi_file("product_name"), + api_auth, }), }; // Decode identity now so no request has to. Non-fatal: a platform that @@ -327,6 +393,11 @@ impl AppState { &self.inner.config } + /// Access control for the external listener. + pub(crate) fn api_auth(&self) -> &crate::api_auth::GuestApiAuth { + &self.inner.api_auth + } + pub(crate) fn health(&self) -> Option<&crate::health::HealthMonitor> { self.inner.health.as_deref() } @@ -364,6 +435,81 @@ impl AppState { Ok(key) } + /// KMS root epoch of the app keys this agent serves. + pub(crate) fn root_epoch(&self) -> u32 { + self.inner.keys.root_epoch() + } + + /// The app root key and its KMS signature of `root_epoch`; the current + /// ones when unset. An older epoch is requested from the KMS once and kept + /// in memory. + pub(crate) async fn app_root( + &self, + root_epoch: Option, + app_epoch: Option, + ) -> Result { + let current = self.root_epoch(); + let epoch = root_epoch.unwrap_or(current); + let current_app = self.inner.keys.app_epoch(); + let app_epoch = app_epoch.unwrap_or(current_app); + if app_epoch > current_app { + anyhow::bail!("app epoch {app_epoch} is newer than current {current_app}"); + } + if epoch == current && app_epoch == current_app { + return Ok(AppRoot { + epoch, + app_epoch, + k256_key: self.app_root_k256_key().to_vec(), + signing_key: self.app_root_signing_key()?.clone(), + kms_signature: self.kms_k256_signature().to_vec(), + }); + } + if epoch > current { + anyhow::bail!("root epoch {epoch} is newer than the current one, {current}"); + } + self.historical_root(epoch, app_epoch).await + } + + pub(crate) async fn historical_root(&self, epoch: u32, app_epoch: u32) -> Result { + if let Some(root) = self + .inner + .historical_roots + .lock() + .await + .get(&(epoch, app_epoch)) + .cloned() + { + return Ok(root); + } + let keys = self + .inner + .cert_client + .get_app_key(Some(epoch), Some(app_epoch)) + .await + .with_context(|| format!("failed to fetch the app keys of root epoch {epoch}"))?; + let root = AppRoot::new(epoch, app_epoch, keys.k256_key, keys.k256_signature)?; + let mut roots = self.inner.historical_roots.lock().await; + Ok(roots + .entry((epoch, app_epoch)) + .or_insert_with(|| root.clone()) + .clone()) + } + + #[cfg(test)] + pub(crate) async fn insert_historical_root( + &self, + epoch: u32, + k256_key: Vec, + kms_signature: Vec, + ) { + let root = AppRoot::new(epoch, 0, k256_key, kms_signature).unwrap(); + self.inner + .historical_roots + .lock() + .await + .insert((epoch, 0), root); + } + /// The KMS root key's signature over the app root public key: the second /// link of every signature chain, produced outside this agent and passed /// through byte-for-byte on both API surfaces. @@ -548,32 +694,19 @@ pub async fn get_info(state: &AppState, external: bool) -> Result { let (tcb_info, vm_config) = if hide_tcb_info { Default::default() } else { - let attestation = state - .inner - .attest(|platform| platform.attestation_for_info()) - .await? - .into_v1(); - let td_report = match attestation.td10_report() { - Some(report) => json!({ - "mrtd": hex::encode(report.mr_td), - "rtmr0": hex::encode(report.rt_mr0), - "rtmr1": hex::encode(report.rt_mr1), - "rtmr2": hex::encode(report.rt_mr2), - "rtmr3": hex::encode(report.rt_mr3), - }), - None => json!({}), - }; + let tcb = state.inner.tcb_info().await?; + let mr = tcb.measurements.as_ref(); let tcb_info = serde_json::to_string_pretty(&json!({ - "mrtd": td_report["mrtd"], - "rtmr0": td_report["rtmr0"], - "rtmr1": td_report["rtmr1"], - "rtmr2": td_report["rtmr2"], - "rtmr3": td_report["rtmr3"], + "mrtd": mr.map(|m| hex::encode(m.mrtd)), + "rtmr0": mr.map(|m| hex::encode(m.rtmrs[0])), + "rtmr1": mr.map(|m| hex::encode(m.rtmrs[1])), + "rtmr2": mr.map(|m| hex::encode(m.rtmrs[2])), + "rtmr3": mr.map(|m| hex::encode(m.rtmrs[3])), "mr_aggregated": hex::encode(&identity.mr_aggregated), "os_image_hash": hex::encode(&identity.os_image_hash), "compose_hash": hex::encode(&identity.compose_hash), "device_id": hex::encode(&identity.device_id), - "event_log": attestation.tdx_event_log().unwrap_or_default(), + "event_log": tcb.event_log, "app_compose": state.config().app_compose.raw, })) .unwrap_or_default(); @@ -643,7 +776,11 @@ impl DstackGuestRpc for InternalRpcHandler { } async fn get_key(self, request: GetKeyArgs) -> Result { - let k256_app_key = &self.state.inner.keys.k256_key; + let root = self + .state + .app_root(request.root_epoch, request.app_epoch) + .await?; + let k256_app_key = &root.k256_key; let algorithm = normalize_algorithm(&request.algorithm); let (key, pubkey_hex) = match algorithm { @@ -672,16 +809,16 @@ impl DstackGuestRpc for InternalRpcHandler { }; let msg_to_sign = format!("{}:{}", request.purpose, pubkey_hex); - let app_signing_key = - SigningKey::from_slice(k256_app_key).context("Failed to parse app k256 key")?; // The shared 65-byte `r || s || v` envelope. Byte-identical to the copy // this replaced -- `get_key_pins_the_frozen_chain_link` is the vector // that says so, and it exists for exactly this de-duplication. - let signature = sign_recoverable_keccak256(&app_signing_key, msg_to_sign.as_bytes())?; + let signature = sign_recoverable_keccak256(&root.signing_key, msg_to_sign.as_bytes())?; Ok(GetKeyResponse { key, - signature_chain: vec![signature, self.state.inner.keys.k256_signature.clone()], + signature_chain: vec![signature, root.kms_signature], + root_epoch: root.epoch, + app_epoch: root.app_epoch, }) } @@ -716,6 +853,7 @@ impl DstackGuestRpc for InternalRpcHandler { path: "vms".to_string(), purpose: "signing".to_string(), algorithm: key_algorithm.to_string(), + ..Default::default() }) .await?; let (signature, public_key) = match algorithm { @@ -1031,6 +1169,7 @@ impl ExternalRpcHandler { path: "vms".to_string(), purpose: "signing".to_string(), algorithm: key_algorithm.to_string(), + ..Default::default() }) .await?; @@ -1096,13 +1235,21 @@ pub(crate) mod tests { Signature as Ed25519Signature, Verifier, VerifyingKey as Ed25519VerifyingKey, }; use k256::ecdsa::{Signature as K256Signature, VerifyingKey}; - use ra_tls::attestation::{AttestationV1, PlatformEvidence, VersionedAttestation}; + use ra_tls::attestation::{ + AttestationV1, PlatformEvidence, TdxAttestationExt, VersionedAttestation, + }; use sha2::{Digest as _, Sha256}; use std::collections::HashSet; use std::convert::TryFrom; use std::io::Write; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + pub(crate) const DUMMY_K256_KEY: [u8; 32] = [ + 0x1A, 0x2B, 0x3C, 0x4D, 0x5E, 0x6F, 0x7A, 0x8B, 0x9C, 0x0D, 0x1E, 0x2F, 0x3A, 0x4B, 0x5C, + 0x6D, 0x7E, 0x8F, 0x9A, 0x0B, 0x1C, 0x2D, 0x3E, 0x4F, 0x5A, 0x6B, 0x7C, 0x8D, 0x9E, 0x0F, + 0x1A, 0x2B, + ]; + fn extract_pubkey_from_report_data(report_data: &[u8], prefix: &str) -> Result> { let end = report_data .iter() @@ -1133,10 +1280,45 @@ pub(crate) mod tests { .expect("certificate carries an attestation") } + pub(crate) const HISTORICAL_K256_KEY: [u8; 32] = [0x11; 32]; + pub(crate) async fn setup_test_state() -> (AppState, tempfile::NamedTempFile) { setup_test_state_with_platform(None).await } + #[tokio::test] + async fn app_root_selectors_and_cache_keep_epochs_independent() { + let (mut state, _guard) = setup_test_state().await; + Arc::get_mut(&mut state.inner).unwrap().keys.key_provider = KeyProvider::Kms { + url: "https://unused.invalid".into(), + pubkey: vec![], + root_epoch: 2, + app_epoch: 2, + }; + for (root, app, byte) in [(2, 0, 0x11), (0, 2, 0x22), (0, 0, 0x33)] { + state.inner.historical_roots.lock().await.insert( + (root, app), + AppRoot::new(root, app, vec![byte; 32], vec![]).unwrap(), + ); + } + let current = state.app_root(None, None).await.unwrap(); + assert_eq!((current.epoch, current.app_epoch), (2, 2)); + for (root, app, byte) in [ + (None, Some(0), 0x11), + (Some(0), None, 0x22), + (Some(0), Some(0), 0x33), + ] { + let key = state.app_root(root, app).await.unwrap(); + assert_eq!( + (key.epoch, key.app_epoch), + (root.unwrap_or(2), app.unwrap_or(2)) + ); + assert_eq!(key.k256_key, vec![byte; 32]); + } + assert!(state.app_root(Some(3), None).await.is_err()); + assert!(state.app_root(None, Some(3)).await.is_err()); + } + /// How many times the fixture platform was asked to attest for `Info`, and /// whether it should refuse. Counting the calls is the only way to see the /// identity throttle work: what it changes is how often the platform is @@ -1329,15 +1511,10 @@ pNs85uhOZE8z2jr8Pg== -----END CERTIFICATE----- "#; - const DUMMY_K256_KEY: [u8; 32] = [ - 0x1A, 0x2B, 0x3C, 0x4D, 0x5E, 0x6F, 0x7A, 0x8B, 0x9C, 0x0D, 0x1E, 0x2F, 0x3A, 0x4B, - 0x5C, 0x6D, 0x7E, 0x8F, 0x9A, 0x0B, 0x1C, 0x2D, 0x3E, 0x4F, 0x5A, 0x6B, 0x7C, 0x8D, - 0x9E, 0x0F, 0x1A, 0x2B, - ]; - let dummy_keys = AppKeys { disk_crypt_key: Vec::new(), env_crypt_key: Vec::new(), + sealed_env_key: Vec::new(), k256_key: DUMMY_K256_KEY.to_vec(), k256_signature: Vec::new(), gateway_app_id: String::new(), @@ -1348,7 +1525,8 @@ pNs85uhOZE8z2jr8Pg== }; let verifier = Arc::new(AttestationVerifier::new_prod(None).unwrap()); - let dummy_cert_client = CertRequestClient::create(&dummy_keys, verifier, String::new()) + let sys_config = serde_json::from_value(serde_json::json!({ "vm_config": "" })).unwrap(); + let dummy_cert_client = CertRequestClient::create(&dummy_keys, verifier, &sys_config) .await .expect("Failed to create CertRequestClient"); @@ -1365,6 +1543,14 @@ pNs85uhOZE8z2jr8Pg== } impl PlatformBackend for TestSimulatorPlatform { + fn local_tcb_info(&self) -> Result> { + let attestation = self.attestation.clone().into_v1(); + if !matches!(attestation.platform, PlatformEvidence::Tdx { .. }) { + return Ok(None); + } + Ok(Some(attestation.into())) + } + fn attestation_for_info(&self) -> Result { self.probe.calls.fetch_add(1, Ordering::Relaxed); if self.probe.failing.load(Ordering::Relaxed) { @@ -1429,6 +1615,7 @@ pNs85uhOZE8z2jr8Pg== keys: dummy_keys, vm_config: String::new(), cert_client: dummy_cert_client, + historical_roots: Default::default(), demo_cert: Default::default(), demo_cert_last_failure: Default::default(), platform: Arc::new(TestSimulatorPlatform { @@ -1463,6 +1650,7 @@ pNs85uhOZE8z2jr8Pg== // against v0 `get_info` compares like with like. cloud_vendor: read_dmi_file("sys_vendor"), cloud_product: read_dmi_file("product_name"), + api_auth: crate::api_auth::GuestApiAuth::new(None, &DUMMY_K256_KEY).unwrap(), }; ( @@ -1729,6 +1917,7 @@ pNs85uhOZE8z2jr8Pg== path: "test".to_string(), purpose: "signing".to_string(), algorithm: "secp256k1".to_string(), + ..Default::default() }) .await .unwrap(); @@ -1738,6 +1927,28 @@ pNs85uhOZE8z2jr8Pg== ); } + #[tokio::test] + async fn get_key_selects_the_epochs() { + let (state, _guard) = setup_test_state().await; + let get_key = |root_epoch, app_epoch| { + InternalRpcHandler::new(state.clone()).get_key(GetKeyArgs { + path: "test".to_string(), + purpose: "signing".to_string(), + root_epoch, + app_epoch, + ..Default::default() + }) + }; + + let current = get_key(None, None).await.unwrap(); + assert_eq!((current.root_epoch, current.app_epoch), (0, 0)); + let selected = get_key(Some(0), Some(0)).await.unwrap(); + assert_eq!(selected.key, current.key); + assert_eq!(selected.signature_chain, current.signature_chain); + assert!(get_key(Some(1), None).await.is_err()); + assert!(get_key(None, Some(1)).await.is_err()); + } + #[test] fn test_normalize_algorithm() { assert_eq!(normalize_algorithm("k256"), "secp256k1"); @@ -1761,11 +1972,13 @@ pNs85uhOZE8z2jr8Pg== path: "test".to_string(), purpose: "signing".to_string(), algorithm: "k256".to_string(), + ..Default::default() }; let req_secp = GetKeyArgs { path: "test".to_string(), purpose: "signing".to_string(), algorithm: "secp256k1".to_string(), + ..Default::default() }; let resp_k256 = handler_k256.get_key(req_k256).await.unwrap(); @@ -1784,6 +1997,7 @@ pNs85uhOZE8z2jr8Pg== path: "test".to_string(), purpose: "signing".to_string(), algorithm: "secp256k1_prehashed".to_string(), + ..Default::default() }; let result = handler.get_key(request).await; @@ -1800,6 +2014,7 @@ pNs85uhOZE8z2jr8Pg== path: "test".to_string(), purpose: "signing".to_string(), algorithm: "ed25519".to_string(), + ..Default::default() }; let response = handler.get_key(request).await.unwrap(); @@ -1821,11 +2036,13 @@ pNs85uhOZE8z2jr8Pg== path: "test".to_string(), purpose: "signing".to_string(), algorithm: "".to_string(), + ..Default::default() }; let req_secp = GetKeyArgs { path: "test".to_string(), purpose: "signing".to_string(), algorithm: "secp256k1".to_string(), + ..Default::default() }; let resp_default = handler_default.get_key(req_default).await.unwrap(); @@ -1862,6 +2079,7 @@ pNs85uhOZE8z2jr8Pg== path: "test".to_string(), purpose: "signing".to_string(), algorithm: "rsa".to_string(), + ..Default::default() }; let result = handler.get_key(request).await; @@ -2080,6 +2298,84 @@ pNs85uhOZE8z2jr8Pg== quote.await.unwrap().unwrap(); } + /// Legacy `Info` reads the TCB info without a quote, so it answers while a + /// quote holds the queue, with the same document the quote would give. + #[tokio::test] + async fn legacy_info_does_not_queue_behind_a_quote() { + let probe = Arc::new(InfoAttestationProbe::default()); + let (state, _guard) = setup_test_state_with_probe(probe.clone()).await; + let identity = state.identity().await.unwrap(); + state.inner.demo_cert.set(String::new()).unwrap(); + let (entered_rx, release_tx) = probe.arm_gate(); + let quote = tokio::spawn({ + let state = state.clone(); + async move { state.quote_response([0; 64]).await } + }); + entered_rx.await.unwrap(); + + let info = tokio::time::timeout(Duration::from_secs(2), get_info(&state, false)) + .await + .expect("Info answers while the quote is held") + .unwrap(); + let attestation = state + .inner + .platform + .attestation_for_info() + .unwrap() + .into_v1(); + let report = attestation.td10_report().unwrap(); + let expected = json!({ + "mrtd": hex::encode(report.mr_td), + "rtmr0": hex::encode(report.rt_mr0), + "rtmr1": hex::encode(report.rt_mr1), + "rtmr2": hex::encode(report.rt_mr2), + "rtmr3": hex::encode(report.rt_mr3), + "mr_aggregated": hex::encode(&identity.mr_aggregated), + "os_image_hash": hex::encode(&identity.os_image_hash), + "compose_hash": hex::encode(&identity.compose_hash), + "device_id": hex::encode(&identity.device_id), + "event_log": attestation.tdx_event_log().unwrap(), + "app_compose": state.config().app_compose.raw, + }); + assert_eq!( + info.tcb_info, + serde_json::to_string_pretty(&expected).unwrap() + ); + + release_tx.send(()).unwrap(); + quote.await.unwrap().unwrap(); + } + + #[tokio::test(start_paused = true)] + async fn a_platform_call_gives_up_on_a_held_queue_with_503() { + let (state, _guard) = setup_test_state_with_probe(Arc::default()).await; + let held = state.inner.attest_lock.lock().await; + + let err = state + .quote_response([0; 64]) + .await + .expect_err("the queue is held"); + assert_eq!(ra_rpc::code_of(&err), Some(503)); + + drop(held); + state.quote_response([0; 64]).await.unwrap(); + } + + #[tokio::test(start_paused = true)] + async fn identity_callers_wait_at_most_one_queue_timeout() { + let probe = Arc::new(InfoAttestationProbe::default()); + let (state, _guard) = setup_test_state_with_probe(probe.clone()).await; + let _held = state.inner.attest_lock.lock().await; + + let start = tokio::time::Instant::now(); + let (first, second) = tokio::join!(state.identity(), state.identity()); + assert_eq!(start.elapsed(), ATTEST_QUEUE_TIMEOUT); + assert_eq!(ra_rpc::code_of(&first.unwrap_err()), Some(503)); + let throttled = second.unwrap_err().to_string(); + assert!(throttled.contains("next attempt"), "{throttled}"); + assert_eq!(probe.calls(), 0); + } + /// A failed decode must be as cheap to repeat as a cached success is. /// `identity()` is reached from the anonymous `/prpc/v1/Info`, and each /// attempt is a hardware quote plus an RTMR replay under the global quote diff --git a/dstack/guest-agent/src/rpc_service_v1.rs b/dstack/guest-agent/src/rpc_service_v1.rs index 354e94618a..48deb3a3dd 100644 --- a/dstack/guest-agent/src/rpc_service_v1.rs +++ b/dstack/guest-agent/src/rpc_service_v1.rs @@ -159,16 +159,20 @@ impl V1RpcHandler { Self { state } } - /// Derive the key named by `(domain, algorithm)` together with its - /// signature chain. - fn derive(&self, domain: &str, algorithm: &str) -> Result<(AppKey, Vec>)> { + /// Derive the key named by `(domain, algorithm)` under the app root of + /// `root_epoch`, together with its signature chain and that epoch. + async fn derive( + &self, + domain: &str, + algorithm: &str, + root_epoch: Option, + app_epoch: Option, + ) -> Result<(AppKey, Vec>, u32, u32)> { let algorithm = Algorithm::parse(algorithm)?; - let key = AppKey::derive(self.state.app_root_k256_key(), domain, algorithm)?; - let chain = vec![ - key.claim_signature(self.state.app_root_signing_key()?)?, - self.state.kms_k256_signature().to_vec(), - ]; - Ok((key, chain)) + let root = self.state.app_root(root_epoch, app_epoch).await?; + let key = AppKey::derive(&root.k256_key, domain, algorithm)?; + let chain = vec![key.claim_signature(&root.signing_key)?, root.kms_signature]; + Ok((key, chain, root.epoch, root.app_epoch)) } } @@ -196,11 +200,20 @@ impl DstackGuestRpc for V1RpcHandler { } async fn get_key(self, request: GetKeyRequest) -> Result { - let (key, signature_chain) = self.derive(&request.domain, &request.algorithm)?; + let (key, signature_chain, root_epoch, app_epoch) = self + .derive( + &request.domain, + &request.algorithm, + request.root_epoch, + request.app_epoch, + ) + .await?; Ok(GetKeyResponse { key: key.secret(), public_key: key.public_key(), signature_chain, + root_epoch, + app_epoch, }) } @@ -342,9 +355,54 @@ mod tests { GetKeyRequest { domain: domain.to_string(), algorithm: algorithm.to_string(), + root_epoch: None, + app_epoch: None, } } + #[tokio::test] + async fn get_key_selects_the_root_epoch() { + let (state, _guard) = state().await; + let handler = || V1RpcHandler::new(state.clone()); + let request = |root_epoch| GetKeyRequest { + root_epoch, + ..get_key_request("storage-encryption", "secp256k1") + }; + + let current = handler().get_key(request(None)).await.unwrap(); + assert_eq!(current.root_epoch, 0); + assert_eq!(current.app_epoch, 0); + assert!(handler() + .get_key(GetKeyRequest { + app_epoch: Some(1), + ..request(None) + }) + .await + .is_err()); + assert_eq!( + handler().get_key(request(Some(0))).await.unwrap().key, + current.key + ); + assert!(handler().get_key(request(Some(1))).await.is_err()); + } + + /// Older epochs come from the KMS once and are then served from memory; + /// the fixture has no KMS, so the cache is filled directly. + #[tokio::test] + async fn an_older_root_is_fetched_once_and_cached() { + let (state, _guard) = state().await; + let key = crate::rpc_service::tests::HISTORICAL_K256_KEY.to_vec(); + state + .insert_historical_root(1, key.clone(), vec![0xab; 65]) + .await; + let root = state.historical_root(1, 0).await.unwrap(); + assert_eq!(root.k256_key, key); + assert_eq!(root.kms_signature, [0xab; 65]); + // An uncached epoch needs the KMS, which a local key provider lacks. + assert!(state.historical_root(2, 0).await.is_err()); + assert!(state.historical_root(1, 1).await.is_err()); + } + /// The fixture's app root key is what `keys::tests` committed its vectors /// against. If the two drift, the vectors stop describing what this /// handler serves and every assertion built on them goes quiet. @@ -458,6 +516,7 @@ mod tests { path: "storage-encryption".to_string(), purpose: "signing".to_string(), algorithm: "secp256k1".to_string(), + ..Default::default() }) .await .unwrap(); @@ -482,6 +541,7 @@ mod tests { path: "test".to_string(), purpose: "signing".to_string(), algorithm: String::new(), + ..Default::default() }) .await .unwrap(); diff --git a/dstack/guest-agent/src/server.rs b/dstack/guest-agent/src/server.rs index 0021f4f9be..126aef4b06 100644 --- a/dstack/guest-agent/src/server.rs +++ b/dstack/guest-agent/src/server.rs @@ -4,6 +4,8 @@ use std::{future::pending, os::unix::net::UnixListener as StdUnixListener, time::Duration}; +use crate::access_log::{AccessLog, WATCHDOG_PROBE_PATH}; +use crate::api_auth::ScopeFairing; use crate::config::BindAddr; use crate::guest_api_service::GuestApiHandler; use crate::http_routes; @@ -38,6 +40,7 @@ async fn run_internal_v0( "/prpc/", ra_rpc::prpc_routes!(AppState, InternalRpcHandlerV0, trim: "Tappd."), ) + .attach(AccessLog::new("tappd.sock")) .manage(state); let ignite = rocket .ignite() @@ -132,7 +135,9 @@ async fn run_internal( activated_socket: Option, sock_ready_tx: oneshot::Sender<()>, ) -> Result<()> { - let rocket = mount_internal(rocket::custom(figment)).manage(state); + let rocket = mount_internal(rocket::custom(figment)) + .attach(AccessLog::new("dstack.sock")) + .manage(state); let ignite = rocket .ignite() .await @@ -179,6 +184,13 @@ async fn run_internal( async fn run_external(state: AppState, figment: Figment) -> Result<()> { let rocket = mount_external(rocket::custom(figment)) .mount("/", http_routes::external_routes(state.config())) + // Where `ScopeFairing` rewrites a denied request. + .mount("/", dstack_api_auth::routes()) + // Before `ScopeFairing`, so a refused request is logged under the path + // it asked for rather than the 401 route it was rewritten to. The + // query is kept: tokens travel in the header, never in the query. + .attach(AccessLog::with_query("external")) + .attach(ScopeFairing::new(state.clone())) .attach(AdHoc::on_response("Add app version header", |_req, res| { Box::pin(async move { res.set_raw_header("X-App-Version", app_version()); @@ -195,6 +207,7 @@ async fn run_external(state: AppState, figment: Figment) -> Result<()> { async fn run_guest_api(state: AppState, figment: Figment) -> Result<()> { let rocket = rocket::custom(figment) .mount("/api", ra_rpc::prpc_routes!(AppState, GuestApiHandler)) + .attach(AccessLog::with_query("guest-api")) .manage(state); let ignite = rocket @@ -237,13 +250,31 @@ async fn run_watchdog(port: u16) { info!("Watchdog enabled, interval={watchdog_usec}us, heartbeat={heatbeat_interval:?}"); let mut interval = tokio::time::interval(heatbeat_interval); - let probe_url = format!("http://localhost:{port}/prpc/Worker.Version"); + let probe_url = format!("http://localhost:{port}{WATCHDOG_PROBE_PATH}"); + // Built once: the loop runs every few seconds for the process's lifetime, + // and a fresh client per tick leaks a connection pool each time. + // Idle connections are not pooled: the server drops a keep-alive + // connection after 15s without a request, which races the heartbeat and + // fails the probe with a connection reset. + let client = match reqwest::Client::builder().pool_max_idle_per_host(0).build() { + Ok(client) => client, + Err(err) => { + error!("failed to build health-check client: {err}"); + return pending::<()>().await; + } + }; loop { interval.tick().await; - let client = reqwest::Client::new(); match client.get(&probe_url).send().await { - Ok(response) if response.status().is_success() => { + // 401 is the listener answering a caller with no scope, which is + // what happens when the host removes `guest:version` from + // `anonymous_scopes`; it proves the listener is up as well as a + // 200 does. + Ok(response) + if response.status().is_success() + || response.status() == reqwest::StatusCode::UNAUTHORIZED => + { if let Err(err) = sd_notify(false, &[NotifyState::Watchdog]) { error!("Failed to notify systemd: {err}"); } @@ -425,4 +456,73 @@ mod tests { let (status, _) = get(&pre_v1, "/EmitEvent").await; assert_eq!(status, 400); } + + /// With nothing anonymous, no spelling of a route reaches a handler + /// without a token. + #[tokio::test] + async fn the_external_listener_refuses_every_spelling_without_a_token() { + let (state, _guard) = setup_test_state().await; + let client = Client::tracked( + mount_external(rocket::build()) + .mount("/", dstack_api_auth::routes()) + .attach(ScopeFairing::new(state.clone())) + .manage(state), + ) + .await + .expect("rocket failed to ignite"); + for path in [ + "/prpc/Info", + "/prpc/Worker.Worker.Info", + "/prpc/v0/Worker.Worker.GetAttestationForAppKey", + "/%70rpc/Version", + "/prpc/v1/Health", + "/nope", + ] { + let (status, _) = get(&client, path).await; + assert_eq!(status, 401, "{path}"); + } + } + + /// A token from the app's own issuer opens exactly its scopes. + #[tokio::test] + async fn an_internal_token_grants_only_its_own_scopes() { + use dstack_api_auth::jwt; + + let (state, _guard) = setup_test_state().await; + let app_id = hex::encode(&state.identity().await.unwrap().app_id); + let secret = ra_tls::api_v1::derive_app_key( + &crate::rpc_service::tests::DUMMY_K256_KEY, + jwt::INTERNAL_ISSUER_DOMAIN, + ra_tls::api_v1::KeyAlgorithm::Ed25519, + ) + .unwrap(); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs(); + let token = jwt::sign( + &secret, + &jwt::Claims { + iss: jwt::internal_issuer(&app_id), + aud: app_id, + iat: now, + exp: now + 60, + scope: jwt::scope::INFO.into(), + }, + ) + .unwrap(); + let client = Client::tracked( + mount_external(rocket::build()) + .mount("/", dstack_api_auth::routes()) + .attach(ScopeFairing::new(state.clone())) + .manage(state), + ) + .await + .expect("rocket failed to ignite"); + let auth = rocket::http::Header::new("Authorization", format!("bearer {token}")); + for (path, expected) in [("/prpc/Info", 200), ("/prpc/Version", 401)] { + let response = client.get(path).header(auth.clone()).dispatch().await; + assert_eq!(response.status().code, expected, "{path}"); + } + } } diff --git a/dstack/guest-agent/templates/dashboard.html b/dstack/guest-agent/templates/dashboard.html index ee973bb909..29e19d94e1 100644 --- a/dstack/guest-agent/templates/dashboard.html +++ b/dstack/guest-agent/templates/dashboard.html @@ -158,9 +158,11 @@ + {% if show_identity || show_sysinfo %}

Node Information

+ {% if show_identity %}
App Name
{{app_name}}
@@ -187,7 +189,8 @@

Node Information

{{cloud_vendor}} ({{cloud_product}})
{% endif %} - {% if public_sysinfo %} + {% endif %} + {% if show_sysinfo %}
Operating System
{{system_info.os_name}} {{system_info.os_version}}
@@ -225,8 +228,9 @@

Node Information

{% endif %}
+ {% endif %} - {% if public_sysinfo %} + {% if show_sysinfo %}

GPUs

{% if !gpu_info.error.is_empty() %}
{{ gpu_info.error }}
@@ -333,6 +337,7 @@

GPUs

{% endif %} {% endif %} + {% if show_containers %}

Deployed Containers

@@ -340,7 +345,7 @@

Deployed Containers

- {% if public_logs %} + {% if show_logs %} {% endif %} @@ -351,7 +356,7 @@

Deployed Containers

- {% if public_logs %} + {% if show_logs %}
Name StatusLogs
{{name|cname}} {{container.status}} View Logs @@ -362,12 +367,11 @@

Deployed Containers

+ {% endif %} + {% if show_tcb %}

TCB Info

- {% if public_tcbinfo %} - {% else %} -

TCB info is not public

{% endif %} diff --git a/dstack/host-api/proto/host_api.proto b/dstack/host-api/proto/host_api.proto index f8864f516d..85106ed6ee 100644 --- a/dstack/host-api/proto/host_api.proto +++ b/dstack/host-api/proto/host_api.proto @@ -27,8 +27,19 @@ message GetSealingKeyResponse { bytes provider_quote = 2; } +// The env the guest re-encrypted to the current KMS root epoch at boot; empty +// when it needed no change. +message SealedEnv { + bytes sealed_env = 1; +} + service HostApi { rpc Info(google.protobuf.Empty) returns (HostInfo); rpc Notify(Notification) returns (google.protobuf.Empty); rpc GetSealingKey(GetSealingKeyRequest) returns (GetSealingKeyResponse); + // Close this boot's env update window, replacing the VM's stored encrypted + // env if it is still the one the VM booted with. Accepted once per boot; any + // answer means the window is closed, and the guest starts application code + // only after one. + rpc UpdateSealedEnv(SealedEnv) returns (google.protobuf.Empty); } diff --git a/dstack/host-api/src/client.rs b/dstack/host-api/src/client.rs index 5a06060099..aa6f214ff4 100644 --- a/dstack/host-api/src/client.rs +++ b/dstack/host-api/src/client.rs @@ -4,6 +4,7 @@ use crate::host_api_client::HostApiClient; use http_client::prpc::PrpcClient; +pub use http_client::prpc::StatusError; pub type DefaultClient = HostApiClient; diff --git a/dstack/http-client/src/prpc.rs b/dstack/http-client/src/prpc.rs index 5971a12245..8ad81fbaae 100644 --- a/dstack/http-client/src/prpc.rs +++ b/dstack/http-client/src/prpc.rs @@ -87,6 +87,34 @@ impl PrpcClient { } } +/// A pRPC server answered with a status other than 200. +/// +/// Carried in the returned `anyhow::Error`, so callers can tell, say, a method +/// the server does not implement from other failures without parsing text. +#[derive(Debug)] +pub struct StatusError { + pub path: String, + pub status: u16, + /// The reason the server gave, if it gave one. + pub message: Option, +} + +impl std::fmt::Display for StatusError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let Self { + path, + status, + message, + } = self; + match message { + Some(message) => write!(f, "{path} failed with status {status}: {message}"), + None => write!(f, "Invalid status code: {status}, path={path}"), + } + } +} + +impl std::error::Error for StatusError {} + /// The reason a pRPC server gave for failing a JSON request, if it gave one. /// /// Servers built on `ra-rpc` answer a failed call with `{"error": "..."}`. @@ -142,10 +170,12 @@ impl RequestClient for PrpcClient { None => request.await?, }; if status != 200 { - match server_error_message(&body) { - Some(error) => anyhow::bail!("{path} failed with status {status}: {error}"), - None => anyhow::bail!("Invalid status code: {status}, path={path}"), + return Err(StatusError { + path, + status, + message: server_error_message(&body), } + .into()); } let response = serde_json::from_slice(normalize_json_response_body(&body)) .context("Failed to deserialize response")?; diff --git a/dstack/kms/Cargo.toml b/dstack/kms/Cargo.toml index 5c616d7a4e..5c421a67fd 100644 --- a/dstack/kms/Cargo.toml +++ b/dstack/kms/Cargo.toml @@ -13,10 +13,12 @@ license.workspace = true anyhow.workspace = true clap.workspace = true fs-err.workspace = true +futures.workspace = true dstack-build-info.workspace = true hex.workspace = true hex_fmt.workspace = true rocket.workspace = true +rocket-proxy-listener.workspace = true serde.workspace = true tracing.workspace = true tracing-subscriber.workspace = true @@ -32,6 +34,7 @@ reqwest = { workspace = true, features = ["json"] } sha2.workspace = true sha3.workspace = true k256.workspace = true +p256.workspace = true rand.workspace = true dstack-guest-agent-rpc.workspace = true http-client = { workspace = true, features = ["prpc"] } @@ -52,6 +55,7 @@ moka = { workspace = true, features = ["future"] } [dev-dependencies] cc-eventlog.workspace = true +mock-attestation = { path = "../crates/mock-attestation" } [features] default = [] diff --git a/dstack/kms/README.md b/dstack/kms/README.md index f837488d98..5f76e53598 100644 --- a/dstack/kms/README.md +++ b/dstack/kms/README.md @@ -28,39 +28,67 @@ CVMs running in dstack support three boot modes: - Supports application upgrades - Requires control contract configuration - `key-provider` in RTMR: `{"type": "kms", "id": ""}` -- `app-id` is equal to the address of the deployed App Smart Contract. +- With on-chain app policy, `app-id` is the address of the deployed app contract. + In [delegated mode](auth-eth/README.md#delegated-app-authorization), the delegate + owns app identity policy and auth-eth does not require an app contract. + +## Listeners + +The KMS serves on up to four listeners, each configured in its own +`[listeners.]` section of `kms.toml` with `address` and `port`: + +| Listener | For | Serves | On | +|---|---|---|---| +| `[listeners.guest]` | CVMs | All KMS RPCs, including those that release keys | Always | +| `[listeners.admin]` | Operators, other KMS nodes | Admin RPCs and the key handover, behind its admin credential | `enabled = true` (default) | +| `[listeners.public]` | Deployers, verifiers | Only the read-only RPCs | `enabled = true` | +| `[listeners.onboard]` | Operators | The setup page, before the KMS has keys | `[core.onboard] enabled = true` | + +`[listeners.default]` holds what they share, which a listener's own section +overrides: `tls`, `proxy_protocol` (see below) and Rocket settings such as +`workers`. The onboard listener serves plain HTTP and does not inherit the +default `tls`, nor support `proxy_protocol`. + +KMS 0.6.4 and earlier read these settings from `[rpc]` (now `guest`), +`[core.admin]` (now `admin`, credentials included), `[core.onboard]` +(`address`, `port`, `tls`), and Rocket settings at the top level of the file +(now in `[listeners.default]`). The KMS refuses to +start on a config that still sets any of them, naming where each moved, so +update the config together with the KMS image. ## Admin API authentication The KMS public RPCs authenticate callers by RA-TLS attestation. Operator-facing admin RPCs are instead served on a **separate admin -listener** (`[core.admin]` in `kms.toml`) behind the same shared HTTP +listener** (`[listeners.admin]`) behind the same shared HTTP authenticator used by the VMM and gateway, configured identically to the gateway admin API, so the credential travels in the `Authorization: Bearer ` or `X-Admin-Token: ` header: ```toml -[core.admin] +[listeners.admin] enabled = true address = "127.0.0.1" port = 8001 +# TLS from [listeners.default.tls], unless set in [listeners.admin.tls]. # generate with: openssl rand -hex 32 auth_token = "" # htpasswd_file = "/etc/kms/admin.htpasswd" # bcrypt (htpasswd -B), optional insecure_no_auth = false - -[core.admin.tls] -key = "/etc/kms/certs/rpc.key" -certs = "/etc/kms/certs/rpc.crt" ``` The token can also be supplied via the `DSTACK_KMS_ADMIN_TOKEN` or -`ADMIN_API_TOKEN` environment variables instead of the config file. The admin +`ADMIN_API_TOKEN` environment variables instead of the config file, or as its +hex SHA-256 in `auth_token_hash` (`printf '%s' "$TOKEN" | sha256sum`) for a +config that is not secret, such as a KMS app compose. The hash is then public, +so the token must be high-entropy random, such as `openssl rand -hex 32`: a +weak token can be brute-forced offline from its hash. The admin listener fails closed: enabled with neither `auth_token` nor `htpasswd_file` -(and `insecure_no_auth = false`) refuses to start. Call it with, for example: +(and `insecure_no_auth = false`) refuses to start. With TLS the +listener serves HTTPS (use `http://` without it). Call it with, for example: ```bash -curl -X POST "http://127.0.0.1:8001/prpc/Admin.ClearImageCache?json" \ +curl -k -X POST "https://127.0.0.1:8001/prpc/Admin.ClearImageCache?json" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"image_hash": "", "config_hash": ""}' @@ -70,10 +98,70 @@ This admin authentication is separate from the on-chain / webhook authorization below, which decides whether a CVM may boot and receive keys. KMS-to-KMS onboarding calls `Admin.GetKmsKey` with a self-issued RA-TLS client -certificate plus the source's admin bearer token; other admin RPCs need no client -certificate. `core.onboard.public_key_handover = true` (the default) keeps -`KMS.GetKmsKey` on the public listener for older clients. +certificate plus the source's admin bearer token, so it requires +TLS on the admin listener and an admin address the new KMS can reach; other admin RPCs +need no client certificate. `core.onboard.public_key_handover` is off by default; set it to +`true` only to also serve `KMS.GetKmsKey` on the public listener for older +clients. + +A KMS refuses to start serving without a handover path, so that other nodes can +always onboard from it: unless `public_key_handover = true`, it requires +`[listeners.admin] enabled = true` with a TLS `key` and `certs`, and +the error names the missing setting. The check runs at startup, before +onboarding or bootstrap, so a misconfigured node fails before it gets or +generates root keys. There is no opt-out, `auth_api = "dev"` included. The default `kms.toml` +enables the admin listener with TLS on the RPC key and certificate, so it +starts only once an admin token is set (`auth_token`, +`DSTACK_KMS_ADMIN_TOKEN` or `auth_token_hash`). The `dstack-app` composes and +`dstackup` set `auth_token_hash` from a token they generate. + +Three settings relax authorization, each over a different scope: + +| Setting | Effect | +|---------|--------| +| `core.enforce_self_authorization = false` | Skips only this KMS's self check. Root epochs are still checked against the registry (`servable_epoch`), and every app and caller is still authorized. | +| `core.auth_api.type = "dev"` | Allows everything: no backend is consulted for self, app or KMS checks. Development only. | +| `core.onboard.public_key_handover = true` | Only bypasses the admin listener for key handover: `KMS.GetKmsKey` stays on the public listener, still subject to the self, caller and key-release checks. | + +The self check caches this KMS's own boot info for an hour, so a change to its +TCB status takes effect up to an hour later, and caches the backend's decision +for a second. + +`GetAppEnvEncryptPubKey` and `GetSealedEnvPubKey` need no client certificate and +read the app epoch from the auth backend (`/app/:appId`). The KMS caches each +app's epoch for a second (up to 10,000 apps; failures are not cached), so +repeated requests for one app reach the backend once. Requests for random app +IDs still pass through and can trigger chain RPC calls or delegate lookups; +rate limit them per source in the reverse proxy or gateway in front of the KMS. + +## Public listener + +The guest listener serves the key-releasing RPCs (`GetAppKey`, `SignCert`, +`GetTempCaCert`, `GetKmsKey`) next to the read-only ones. To restrict it to +the CVMs, enable `[listeners.public]`: a second listener serving only +`GetMeta`, `GetAppEnvEncryptPubKey` and `GetSealedEnvPubKey`, at the same +`/prpc/` paths, so deployers, verifiers and `vmm-cli.py` can point at +it unchanged. The guest listener keeps serving all of them. + +```toml +[listeners.public] +enabled = true +address = "0.0.0.0" +port = 8002 +``` +## PROXY protocol + +A proxy in front of the KMS must pass TLS through, since the KMS verifies the +client's RA-TLS certificate itself, so the KMS sees the proxy's address rather +than the client's. Set `proxy_protocol = true` in `[listeners.default]`, or in +one listener's section, to read the client address from a PROXY protocol (v1 +or v2) header instead. The request logs then carry it as `remote`. A listener with +`proxy_protocol = true` drops connections that send no header within five +seconds, so only enable it behind a proxy that sends one, such as HAProxy with +`send-proxy-v2` (and `check-send-proxy` for health checks). The header is +trusted as sent: make the listener reachable only through the proxy, or any +client can choose the `remote` that the logs and the key release audit record. ## KMS Implementation @@ -81,16 +169,16 @@ certificate. `core.onboard.public_key_handover = true` (the default) keeps 1. **dstack-kms** - Main RPC service for app key requests - Quote verification and boot info validation - - Asks `dstack-kms-auth-eth` for permission + - Asks the auth webhook ([`auth-eth`](auth-eth/)) for permission - Builtin Replicator for root keys -2. **dstack-kms-auth-eth** +2. **[auth-eth](auth-eth/) webhook server** - Chain interface for permission checks - Two-step validation: 1. KMS control contract check - 2. App control contract check + 2. App control contract check, or an external app-authorization service when `APP_AUTH_URL` is set ([delegated app authorization](auth-eth/README.md#delegated-app-authorization)) -3. **Authorization Contracts** +3. **Authorization Contracts** ([`auth-eth`](auth-eth/)) - `DstackKms.sol` - Maintains a registry for all Applications - Maintains the allowed KMS Instance MRs @@ -103,7 +191,7 @@ certificate. `core.onboard.public_key_handover = true` (the default) keeps ### Deployment The first two components are deployed as an dstack app on dstack in Local-Key-Provider mode. -The docker compose file would look like [this](dstack-app/docker-compose.yaml). +See [`compose-dev.yaml`](dstack-app/compose-dev.yaml) for the compose file and [`deploy-to-vmm.sh`](dstack-app/deploy-to-vmm.sh) for how to deploy it. The solidity contracts are deployed on an ethereum compatible chain. @@ -162,7 +250,7 @@ Once onboarded, the KMS node begins listening for app key provisioning requests. When a KMS node receives a key provisioning request, it: 1. Validates the TDX quote of the requesting App -2. Queries the DstackKms contract for provisioning allowance +2. Asks the configured authorization backend whether the app may receive keys 3. If allowed, generates and sends the keys to the App ### Attestation @@ -209,7 +297,7 @@ Let's explain each one: The `GetAppKey` RPC is used by the dstack app to request an app key. In this RPC, the KMS node will: - Verify the TDX quote and extract the app ID and MRs from it -- Query the smart contract to check if the app is authorized to request the app key +- Ask the configured authorization backend whether the app may receive the key - If authorized, derive the app keys from the root key and app ID - Sign the app keys with the root key - Return the app keys to the app @@ -240,5 +328,221 @@ The `SignCert` RPC is used by the dstack app to sign a TLS certificate. In this - Verify the TDX quote and extract the Certificate Signing Request (CSR) - Verify the CSR signature -- Query the smart contract to check if the app is authorized +- Ask the configured authorization backend whether the app may receive a certificate - If authorized, sign the CSR with the CA root key and return the certificate chain to the app + + +## Authorization protocol + +Authorization uses two explicit endpoints: + +- `POST /authorizeKms` for KMS self-authorization and root-key handover. +- `POST /authorizeApp` for application keys and certificates. + +By default, the Ethereum backends call the matching `DstackKms` method. Both +methods accept `AuthorizationRequest` and return `AuthorizationResult`; no +caller-kind flag is sent. The KMS method checks the KMS policy; the app method +applies registered app policy. When auth-eth runs with `APP_AUTH_URL`, it first calls +`DstackKms.checkKmsAppPolicy` at the pinned policy block to check the app +operation, root epoch, OS image allowlist for the selected epoch, and TEE +variant policy. Only if those checks pass does it ask the delegate for the +app identity decision and current app epoch (see +[delegated app authorization](auth-eth/README.md#delegated-app-authorization)). +KMS callers do not fetch contract metadata to decide which policy to use. + +Before authorizing an SEV-SNP attestation, the KMS reads +`GET /sevSnpTcbRequirements`, reusing the answer for a second. `requirements` is +the JSON list of minimum TCBs it judges the TCB status against; the list +`core.attestation.sev_snp_tcb_requirements_file` names decides for a CPU the +published one does not cover. The KMS refuses the request when it cannot read the published list or +neither has an entry for the report's CPU. See +[AMD SEV-SNP](../../docs/amd-sev-snp.md). + +`requestedAppEpoch` selects the application's own key epoch, independently of KMS +root epochs. Omission uses `currentAppEpoch`; explicit zero selects app epoch zero. +Solidity uses `OptionalUint256 { isSet, value }` for both selectors. Future epochs +are denied; historical epochs remain subject to current authorization policy. +Policy denials still carry the chain root fields. A delegate transport error, +timeout, non-2xx response, or invalid answer instead produces HTTP 503 without +an `AuthorizationResult`. See [application key epochs](../../docs/app-key-epochs.md) +for rotation and migration. + +`requestedRootEpoch` is optional in the JSON request. Omit it to use the epoch in +this authorization result; an explicit `0` selects epoch 0. Solidity represents +it as `OptionalUint256 { isSet, value }` alongside `AppInfo` in the request. The +contract rejects future root epochs for application requests; historical epochs +remain available subject to the selected policy row. No serving epoch or serving +hash is sent. KMS-to-KMS handover explicitly selects the highest exported root +epoch, including a registered pending epoch. Approval in that row authorizes the +complete keyring, including older roots. KMS self-authorization omits the selector +and checks the current root epoch. The recipient separately authorizes the +source to `kms_export_keys` at the highest received epoch before importing it. + +Every request includes a required `operation` describing what the attested +subject is authorized to do. JSON uses `snake_case`; the contract receives +`keccak256(bytes(operation))` as `bytes32`. Rust uses the shared serde-derived +`AuthorizationOperation` enum. Unknown operations and operations on the wrong +endpoint are rejected. The supported operations currently share the existing +material policy, leaving room for independent policies later: + +| Endpoint | Operation | Subject | +| --- | --- | --- | +| `authorizeKms` | `kms_bootstrap` | KMS generating its first roots | +| `authorizeKms` | `kms_serve` | KMS serving app keys, public keys or certificates | +| `authorizeKms` | `kms_export_keys` | Source KMS handing over its keyring | +| `authorizeKms` | `kms_import_keys` | Recipient KMS receiving a keyring | +| `authorizeApp` | `app_get_key` | App receiving derived keys | +| `authorizeApp` | `app_get_cert` | App requesting a certificate | + +The KMS chooses the operation from its code path, not an untrusted RPC field. +Self-authorization caches are keyed by operation. Legacy authorization endpoints +retain their existing semantics for old KMS binaries; fine-grained operation +policies cannot protect calls still served by those old binaries. + +### Launch tickets + +A launch ticket stops a party without it from launching an app, or onboarding a +KMS instance, even on an allowed OS image and device. The KMS sends +`sha256("dstack-launch-ticket/v1:" || ticket)` as `launchTicketHash`, zero when +none was presented. `authorizeApp` checks it for `app_get_key` and +`app_get_cert`; `authorizeKms` checks it for `kms_import_keys`, which the source +KMS authorizes for the joining instance. Only that import hands a KMS the root +keys, so the other KMS operations take no ticket. With delegated app +authorization, the delegate receives `launchTicketHash` and is responsible for +app launch ticket policy. + +An app CVM reads its ticket from `launch_ticket` in its sys-config, which the +VMM writes from `--launch-ticket-file`, and sends it in `GetAppKey` and +`SignCert`. A joining KMS does not read its sys-config: it takes the ticket in +the `Onboard` request and sends it in `GetKmsKey`, so deploy a KMS CVM without +`--launch-ticket-file`. The ticket never enters `vm_config`, which attestations +embed, and the VMM returns only its hash. A ticket must be 32 to 1024 bytes +without surrounding whitespace, since its hash is public; the CLI and web UIs +trim it. + +`DstackApp.setRequireLaunchTicket` and `DstackKms.setRequireKmsLaunchTicket` +turn the check on; `addLaunchTicket` and `addKmsLaunchTicket` allow a hash, +listed by `launchTickets()` and `kmsLaunchTickets()`, with a public label only +logged in the added event. The allowlists cover every app and root epoch. + +Tickets need the VMM, the KMS and the auth backend at 0.6.5 or later, and a +guest OS at 0.6.5 or later, or 0.5.15 or later on 0.5.x: an older one drops +the ticket, and the request fails as `Invalid launch ticket`. A required ticket +refuses the legacy `isAppAllowed` and `isKmsAllowed`, whose callers cannot +present one. Older KMS instances authorize serving through `isKmsAllowed`, so +upgrade every KMS instance before turning on `requireKmsLaunchTicket`, or they +stop serving every app. + +The ticket is a bearer secret: the host launching the CVM holds it. Use a fresh +random ticket per deployment, and remove its hash, shown by `vmm-cli info`, once +the host stops serving it; a KMS ticket is needed only while onboarding, so +remove it once the instance has joined. A guest sends its ticket before it has +authenticated the KMS, so its secrecy also rests on the network path between +the CVM and the KMS. + +App keys are deterministic, so a release before the requirement is set cannot +be taken back. Deploy the app contract without a compose hash +(`INITIAL_COMPOSE_HASH` unset), call `setRequireLaunchTicket(true)` and +`addLaunchTicket`, and only then add the compose hash. Turning the requirement +on for a running app leaves its CVMs running, but their certificate requests +fail until they restart with a ticket. + +### Onboarding source pin + +Before a joining KMS sends its launch ticket or admin token, it requires the +source's RPC certificate, at the TLS handshake, to be a `kms:rpc` leaf signed by +the current root CA. It reads that CA from `rootCaPubkey` in the auth API's +`GET /` response: the P-256 SubjectPublicKeyInfo DER of the current root epoch's +CA, hex, optionally `0x`-prefixed. Onboarding therefore needs an auth backend +reporting it, and an `https://` source URL; upgrade the auth backend before the +KMS. The `dev` auth API registers no roots and pins nothing. + +The response is an `AuthorizationResult`: + +```json +{ + "authorized": true, + "rejectionReason": "", + "gatewayAppId": "0x...", + "currentRootEpoch": 0, + "currentAppEpoch": 0, + "currentRootEpochHash": "0x...", + "latestRootEpoch": 0, + "latestRootEpochHash": "0x..." +} +``` + +With on-chain authorization, the decision, app epoch, and root fields come +from one contract call; the simple backend reads them from one `dstack-auth` +configuration snapshot. With delegated app authorization, auth-eth trusts the +delegate for the app identity decision and `currentAppEpoch`, but reads +`gatewayAppId` and the current and latest root epoch fields from `DstackKms` +at the pinned policy block. This split applies to a valid delegate denial too. + +`latestRootEpoch` and `latestRootEpochHash` report the latest registered epoch, +which may be pending activation. Onboarding refuses a source holding epochs +beyond it and, when the source holds it, requires its chain hash to match. +Except for `kms_bootstrap`, with no registered epoch the result is +`authorized: false`, `rejectionReason: "Root epoch not registered"`, epochs 0 +and zero hashes. A zero hash never authorizes key release or requests an epoch +switch. + +The KMS holds no serving-epoch snapshot. It verifies the returned current epoch +and chain hash against its keyring, then derives keys from `requestedRootEpoch` when +specified or the returned current epoch otherwise. Missing or mismatched roots +fail closed. Self-authorization retains its one-second cache of complete results. + +The TLS listener has a separate lifetime: when an authorized current CA differs +from the running RPC certificate's issuer, the KMS requests a restart to refresh +that certificate and the caller must retry. The RPC CA does not select key +epochs. Application key responses and signed certificate chains report the +selected epoch's CA. CA certificates +are reloaded after renewal at startup. + +Upgrade the contract and auth backend and register epoch 0 before using this +protocol for key release. Runtime authorization never falls back to the legacy +API if the new endpoint or contract method is unavailable. The old contract +methods and `/bootAuth/app` and `/bootAuth/kms` endpoints remain available for +older clients. Bootstrap uses the `kms_bootstrap` operation, which checks KMS policy at epoch zero +even before roots are registered. Other operations require registered roots. +Onboarding checks its source through `authorizeKms`, without a legacy fallback. For +`dstack-auth`, set `kmsContractAddr` to the attested KMS app ID and configure +`rootEpochs`. For development without a backend, use `[core.auth_api] type = "dev"`, +which allows everything. + + +## Direct attested key retrieval + +`GetTempCaCert`, its original response fields, and the `temp_ca_key` handover +field remain available for existing OS images and legacy KMS onboarding. The +compatibility CA is stored in `tmp-ca.key`/`tmp-ca.crt`, independent of all root +epochs; existing files are reused and missing files are recreated. Its public +private key authenticates nobody. Client identity still requires attestation. +The returned `ca_cert` is the currently served root CA. + +Upgrade contracts and auth backends, register the original roots as epoch 0, +then upgrade KMS nodes before guests. Keep root and app epochs at zero during +the mixed-version phase; rotate only after guests support key migration. + +Guests and `dstack-util get-keys` generate their self-issued RA-TLS certificate +locally, then call `GetAppKey` directly. They verify the response connection's +attestation and `kms:rpc` usage, and verify that the returned root CA signed that +connection's certificate. Skipping CA-chain validation during this first request +still verifies the TLS handshake signature, so replaying an attested certificate +without its private key cannot impersonate the server. There is no `GetMeta` preflight or first unauthenticated +connection. The optional provider pin and the key-provider launch measurement +still bind the root identity; a valid quote alone is not a KMS policy decision. +`--root-ca` additionally pins the CLI connection before sending the request. + +Onboarding with an admin token uses a self-issued client certificate. Tokenless +onboarding, which needs a source with `core.onboard.public_key_handover = true`, +obtains the source temp CA first so pre-0.6 sources remain usable. +Both paths check the source attestation captured from the key-carrying connection +against local KMS policy before importing anything. Retries and reconnects repeat +verification on the response connection; no assumption relies on one TCP session +lasting forever. All subsequent key requests pin the KMS CA established at startup, regardless +of whether the epoch selector is omitted or explicit. A supplied `trusted_ca` +always wins over the response CA. The selected epoch's CA never replaces this +lifetime pin; a TLS CA change requires a fresh boot/trust establishment rather +than silently trusting another KMS. Without a supplied pin, the response CA +must sign the actual RPC certificate, even when an epoch is explicitly selected. diff --git a/dstack/kms/auth-eth-bun/.oxlintrc.json b/dstack/kms/auth-eth-bun/.oxlintrc.json deleted file mode 100644 index f7d7b8e35e..0000000000 --- a/dstack/kms/auth-eth-bun/.oxlintrc.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "$schema": "https://raw.githubusercontent.com/oxc-project/oxc/main/crates/oxc_linter/src/config/schema.json", - "rules": { - "typescript": "warn", - "unicorn": "warn", - "react": "off", - "jsx-a11y": "off", - "nextjs": "off" - }, - "env": { - "node": true, - "es2022": true - }, - "globals": { - "globalThis": "readonly", - "console": "readonly" - }, - "ignore_patterns": [ - "node_modules/**", - "dist/**", - "build/**", - "coverage/**", - "*.min.js", - "*.d.ts", - "*.test.ts" - ] -} diff --git a/dstack/kms/auth-eth-bun/README.md b/dstack/kms/auth-eth-bun/README.md deleted file mode 100644 index 9fc755b6c7..0000000000 --- a/dstack/kms/auth-eth-bun/README.md +++ /dev/null @@ -1,129 +0,0 @@ -# dstack KMS auth-eth-bun - -a single-file implementation of the dstack KMS ethereum backend using bun + hono + zod. - -## features - -- 🚀 fast and lightweight with bun runtime -- 🔧 modern web framework with hono.js -- ✅ type-safe validation with zod.js -- 📦 single file implementation -- 🔐 ethereum smart contract integration with viem - -## installation - -```bash -# install dependencies -bun install -``` - -## usage - -### development -```bash -# run with hot reload -bun run dev -``` - -### production -```bash -# run directly -bun run start - -# or build first -bun run build -``` - -### testing -```bash -# run tests (watch mode) -bun run test - -# run tests once -bun run test:run -``` - -### code quality -```bash -# run linter -bun run lint - -# run linter and fix issues -bun run lint:fix - -# format code -bun run format - -# run full check (lint + tests) -bun run check -``` - -## environment variables - -- `ETH_RPC_URL` - ethereum RPC endpoint (default: http://localhost:8545) -- `KMS_CONTRACT_ADDR` - KMS contract address (default: 0x0000000000000000000000000000000000000000) -- `PORT` - server port (default: 3000) -- `ETH_CHAIN_ID` - reject every decision if the RPC reports a different chain ID (default: unset, no check) -- `ETH_FINALITY_CONFIRMATIONS` - read policy this many blocks behind the RPC head (default: 0, the head) - -## API endpoints - -### GET / -health check and system information - -### POST /bootAuth/app -application boot authentication - -### POST /bootAuth/kms -KMS boot authentication - -## request format - -```json -{ - "tcbStatus": "string", - "advisoryIds": ["string"], - "mrAggregated": "string", - "mrSystem": "string", - "osImageHash": "string", - "appId": "string", - "composeHash": "string", - "instanceId": "string", - "deviceId": "string" -} -``` - -## response format - -```json -{ - "isAllowed": boolean, - "reason": "string", - "gatewayAppId": "string" -} -``` - -## API compatibility - -this implementation is fully compatible with the original fastify + ethers version: - -- **request/response schemas**: identical to original API -- **OpenAPI specification**: available in `openapi.json` -- **comprehensive testing**: vitest test suite validates compatibility -- **backward compatibility**: supports both minimal and full BootInfo formats - -### OpenAPI specification - -the complete API specification is available in `openapi.json` and includes: -- detailed schema definitions -- request/response examples -- compatibility notes - -### compatibility testing - -the test suite (`index.test.ts`) validates: -- ✅ request/response format compatibility -- ✅ schema validation using OpenAPI spec -- ✅ error handling behavior -- ✅ hex encoding/decoding compatibility -- ✅ optional field handling diff --git a/dstack/kms/auth-eth-bun/bun.lock b/dstack/kms/auth-eth-bun/bun.lock deleted file mode 100644 index a471f6bc8d..0000000000 --- a/dstack/kms/auth-eth-bun/bun.lock +++ /dev/null @@ -1,314 +0,0 @@ -{ - "lockfileVersion": 1, - "workspaces": { - "": { - "name": "auth-eth-bun", - "dependencies": { - "@hono/zod-validator": "0.2.2", - "hono": "4.13.5", - "viem": "2.31.7", - "zod": "3.25.76", - }, - "devDependencies": { - "@types/bun": "1.2.18", - "@types/node": "^24.0.14", - "@vitest/ui": "1.6.1", - "openapi-types": "12.1.3", - "oxlint": "0.9.10", - "typescript": "5.8.3", - "vitest": "4.1.11", - }, - }, - }, - "packages": { - "@adraffy/ens-normalize": ["@adraffy/ens-normalize@1.11.0", "", {}, "sha512-/3DDPKHqqIqxUULp8yP4zODUY1i+2xvVWsv8A79xGWdCAG+8sb0hRh0Rk2QyOJUnnbyPUAZYcpBuRe3nS2OIUg=="], - - "@hono/zod-validator": ["@hono/zod-validator@0.2.2", "", { "peerDependencies": { "hono": ">=3.9.0", "zod": "^3.19.1" } }, "sha512-dSDxaPV70Py8wuIU2QNpoVEIOSzSXZ/6/B/h4xA7eOMz7+AarKTSGV8E6QwrdcCbBLkpqfJ4Q2TmBO0eP1tCBQ=="], - - "@jest/schemas": ["@jest/schemas@29.6.3", "", { "dependencies": { "@sinclair/typebox": "^0.27.8" } }, "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA=="], - - "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.6.0", "", {}, "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw=="], - - "@noble/ciphers": ["@noble/ciphers@1.3.0", "", {}, "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw=="], - - "@noble/curves": ["@noble/curves@1.9.2", "", { "dependencies": { "@noble/hashes": "1.8.0" } }, "sha512-HxngEd2XUcg9xi20JkwlLCtYwfoFw4JGkuZpT+WlsPD4gB/cxkvTD8fSsoAnphGZhFdZYKeQIPCuFlWPm1uE0g=="], - - "@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], - - "@nodelib/fs.scandir": ["@nodelib/fs.scandir@2.1.5", "", { "dependencies": { "@nodelib/fs.stat": "2.0.5", "run-parallel": "^1.1.9" } }, "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g=="], - - "@nodelib/fs.stat": ["@nodelib/fs.stat@2.0.5", "", {}, "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A=="], - - "@nodelib/fs.walk": ["@nodelib/fs.walk@1.2.8", "", { "dependencies": { "@nodelib/fs.scandir": "2.1.5", "fastq": "^1.6.0" } }, "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg=="], - - "@oxc-project/types": ["@oxc-project/types@0.150.0", "", {}, "sha512-rDS5/31E9HfPl/CIzGrn0DOlvBbXFseQ5URJ9sYMfstbKLD/c6Gm9vmRzRGDdAXyOIL4zmO37lc9RIwYqVruZw=="], - - "@oxlint/darwin-arm64": ["@oxlint/darwin-arm64@0.9.10", "", { "os": "darwin", "cpu": "arm64" }, "sha512-eOXKZYq5bnCSgDefgM5bzAg+4Fc//Rc4yjgKN8iDWUARweCaChiQXb6TXX8MfEfs6qayEMy6yVj0pqoFz0B1aw=="], - - "@oxlint/darwin-x64": ["@oxlint/darwin-x64@0.9.10", "", { "os": "darwin", "cpu": "x64" }, "sha512-UeYICDvLUaUOcY+0ugZUEmBMRLP+x8iTgL7TeY6BlpGw2ahbtUOTbyIIRWtr/0O++TnjZ+v8TzhJ9crw6Ij6dg=="], - - "@oxlint/linux-arm64-gnu": ["@oxlint/linux-arm64-gnu@0.9.10", "", { "os": "linux", "cpu": "arm64" }, "sha512-0Zn+vqHhrZyufFBfq9WOgiIool0gCR14BLsdS+0Dwd9o+kNxPGA5q7erQFkiC4rpkxtfBHeD3iIKMMt7d29Kyw=="], - - "@oxlint/linux-arm64-musl": ["@oxlint/linux-arm64-musl@0.9.10", "", { "os": "linux", "cpu": "arm64" }, "sha512-tkQcWpYwF42bA/uRaV2iMFePHkBjTTgomOgeEaiw6XOSJX4nBEqGIIboqqLBWT4JnKCf/L+IG3y/e1MflhKByw=="], - - "@oxlint/linux-x64-gnu": ["@oxlint/linux-x64-gnu@0.9.10", "", { "os": "linux", "cpu": "x64" }, "sha512-JHbkMUnibqaSMBvLHyqTL5cWxcGW+jw+Ppt2baLISpvo34a6fBR+PI7v/A92sEDWe0W1rPhypzCwA8mKpkQ3DA=="], - - "@oxlint/linux-x64-musl": ["@oxlint/linux-x64-musl@0.9.10", "", { "os": "linux", "cpu": "x64" }, "sha512-aBBwN7bQzidwHwEXr7BAdVvMTLWstCy5gikerjLnGDeCSXX9r+o6+yUzTOqZvOo66E+XBgOJaVbY8rsL1MLE0g=="], - - "@oxlint/win32-arm64": ["@oxlint/win32-arm64@0.9.10", "", { "os": "win32", "cpu": "arm64" }, "sha512-LXDnk7vKHT3IY6G1jq0O7+XMhtcHOYuxLGIx4KP+4xS6vKgBY+Bsq4xV3AtmtKlvnXkP5FxHpfLmcEtm5AWysA=="], - - "@oxlint/win32-x64": ["@oxlint/win32-x64@0.9.10", "", { "os": "win32", "cpu": "x64" }, "sha512-w5XRAV4bhgwenjjpGYZGglqzG9Wv/sI+cjQWJBQsvfDXsr2w4vOBXzt1j3/Z3EcSqf4KtkCa/IIuAhQyeShUbA=="], - - "@polka/url": ["@polka/url@1.0.0-next.29", "", {}, "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww=="], - - "@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.9", "", { "os": "android", "cpu": "arm" }, "sha512-tNISae1QEf/vkb3xkRcjV5SEdzPE97We5IVaa2Z8jSszQPZ8U60B/YCYpw4QI7VidYsBtKavczXf+DyDs9WGxw=="], - - "@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.2.9", "", { "os": "android", "cpu": "arm64" }, "sha512-YC8YsI30o606GTZi0VyzYlsDKFP8W61i/QzayHDkLbNEz/IShqAmTa+hsJRj13xTHA0H+6fk4b2UmGn+Q/cMlg=="], - - "@rolldown/binding-darwin-arm64": ["@rolldown/binding-darwin-arm64@1.2.9", "", { "os": "darwin", "cpu": "arm64" }, "sha512-IwhlH3qK5urrY8hZiEgGkHKEFN901p/p2bjxCxJlr4GyNnF7wYpUvK+Y43uaRYuC4hpfjzbR3SJC3arX1jGvmw=="], - - "@rolldown/binding-darwin-x64": ["@rolldown/binding-darwin-x64@1.2.9", "", { "os": "darwin", "cpu": "x64" }, "sha512-XxpJfVzFh+jilRxIXUqcfYAYcunIc/XEzIizsOL1fcJee5Sf7H3mH8WlLmfHfluz5amqR88QQo9izKtmMlavAw=="], - - "@rolldown/binding-freebsd-x64": ["@rolldown/binding-freebsd-x64@1.2.9", "", { "os": "freebsd", "cpu": "x64" }, "sha512-kSfvhmgeWyfkbT3p/1s5vSgboogoah2zkm9fX2zjg2hHxSV7T4KhMWRUUaRk4OXNqoD3QAUeRqLcs1aZOK4U1g=="], - - "@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/binding-linux-arm-gnueabihf@1.2.9", "", { "os": "linux", "cpu": "arm" }, "sha512-1RVzG17pxqbTfYLC352JlLt6kKLG+6Hr30n8DlIJqsnV5luUDd2Qdx9Ayw1Cabfyb1K9k0jXEZ7evxkRoT+uiw=="], - - "@rolldown/binding-linux-arm64-gnu": ["@rolldown/binding-linux-arm64-gnu@1.2.9", "", { "os": "linux", "cpu": "arm64" }, "sha512-BXqPvZ2drqVD+/Z8UpKwcs4Mp7grM+eGFku4CAEKrEtcbAsUpzREphK1sogCRZGreVPiMkiiBtw0n3TPteuqvw=="], - - "@rolldown/binding-linux-arm64-musl": ["@rolldown/binding-linux-arm64-musl@1.2.9", "", { "os": "linux", "cpu": "arm64" }, "sha512-11vWvo8YDwLzukt27J3aYDWU+gg2P7J+ZOmiJ0hkF5BXZDW7pVya7r40MXDy6ya0i9KamoENSVKIugvJNgFXIA=="], - - "@rolldown/binding-linux-ppc64-gnu": ["@rolldown/binding-linux-ppc64-gnu@1.2.9", "", { "os": "linux", "cpu": "ppc64" }, "sha512-a1tijMkdwsIARtc0F39ApURROkf3NwqinI6TOiSSWCTR7dT96dffNvMUtDHnq64wKNTIZOIlzKrFvvFUznJiyw=="], - - "@rolldown/binding-linux-s390x-gnu": ["@rolldown/binding-linux-s390x-gnu@1.2.9", "", { "os": "linux", "cpu": "s390x" }, "sha512-x6SQNdAvv4c3hWqTMaWuawzMX9myaCs/yEmlGsxJzkdClnHW7FbrjQuSiRDhuSYzEYoEMhsaJy9qHG/XNemJPQ=="], - - "@rolldown/binding-linux-x64-gnu": ["@rolldown/binding-linux-x64-gnu@1.2.9", "", { "os": "linux", "cpu": "x64" }, "sha512-9s0AZ8BFK5/n7B/TBoa2yJE3gI3KURrbXcPBlsAsvjU4VeJKgE90y1YtNxyEUIcHPQkg6/yfF3qihUrcM/Kf0Q=="], - - "@rolldown/binding-linux-x64-musl": ["@rolldown/binding-linux-x64-musl@1.2.9", "", { "os": "linux", "cpu": "x64" }, "sha512-P7VWAmV+WdJluH7ovnRGoiv2i8To7GAZ+kGzfGup635cyL7SyYl3lSUaA3Gp5THf0n/Co5EyEqb2zbqq+nMOHQ=="], - - "@rolldown/binding-openharmony-arm64": ["@rolldown/binding-openharmony-arm64@1.2.9", "", { "os": "none", "cpu": "arm64" }, "sha512-1qixtsE4BK8h+yS3BfmZ09UhA7O/N4IACva6YBr7EBvCJraByTuRcgOTaiA62Tm0vey3UcKXLOaoGHtYmNGEVg=="], - - "@rolldown/binding-win32-arm64-msvc": ["@rolldown/binding-win32-arm64-msvc@1.2.9", "", { "os": "win32", "cpu": "arm64" }, "sha512-ok8IQjcEPs1AKZfuEUznVBrJw+gK4soq+bx8b1X2XoMqVClarc1q5JDmVtWXY1xfr6ZuHTAsPXHTgTrqKTZeww=="], - - "@rolldown/binding-win32-x64-msvc": ["@rolldown/binding-win32-x64-msvc@1.2.9", "", { "os": "win32", "cpu": "x64" }, "sha512-Ip2mXoU0hM0boq3Rf+ekuT653OROSo6aSYcPT1VHE4q52KvyxgFkQgrgb/IEsxOuvQ2fZZbs8khJAyCEPM24/g=="], - - "@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.1", "", {}, "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw=="], - - "@scure/base": ["@scure/base@1.2.6", "", {}, "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg=="], - - "@scure/bip32": ["@scure/bip32@1.7.0", "", { "dependencies": { "@noble/curves": "~1.9.0", "@noble/hashes": "~1.8.0", "@scure/base": "~1.2.5" } }, "sha512-E4FFX/N3f4B80AKWp5dP6ow+flD1LQZo/w8UnLGYZO674jS6YnYeepycOOksv+vLPSpgN35wgKgy+ybfTb2SMw=="], - - "@scure/bip39": ["@scure/bip39@1.6.0", "", { "dependencies": { "@noble/hashes": "~1.8.0", "@scure/base": "~1.2.5" } }, "sha512-+lF0BbLiJNwVlev4eKelw1WWLaiKXw7sSl8T6FvBlWkdX+94aGJ4o8XjUdlyhTCjd8c+B3KT3JfS8P0bLRNU6A=="], - - "@sinclair/typebox": ["@sinclair/typebox@0.27.8", "", {}, "sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA=="], - - "@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], - - "@types/bun": ["@types/bun@1.2.18", "", { "dependencies": { "bun-types": "1.2.18" } }, "sha512-Xf6RaWVheyemaThV0kUfaAUvCNokFr+bH8Jxp+tTZfx7dAPA8z9ePnP9S9+Vspzuxxx9JRAXhnyccRj3GyCMdQ=="], - - "@types/chai": ["@types/chai@5.2.3", "", { "dependencies": { "@types/deep-eql": "*", "assertion-error": "^2.0.1" } }, "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="], - - "@types/deep-eql": ["@types/deep-eql@4.0.2", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="], - - "@types/estree": ["@types/estree@1.0.8", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="], - - "@types/node": ["@types/node@24.0.14", "", { "dependencies": { "undici-types": "~7.8.0" } }, "sha512-4zXMWD91vBLGRtHK3YbIoFMia+1nqEz72coM42C5ETjnNCa/heoj7NT1G67iAfOqMmcfhuCZ4uNpyz8EjlAejw=="], - - "@types/react": ["@types/react@19.1.8", "", { "dependencies": { "csstype": "^3.0.2" } }, "sha512-AwAfQ2Wa5bCx9WP8nZL2uMZWod7J7/JSplxbTmBQ5ms6QpqNYm672H0Vu9ZVKVngQ+ii4R/byguVEUZQyeg44g=="], - - "@vitest/expect": ["@vitest/expect@4.1.11", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "@types/chai": "^5.2.2", "@vitest/spy": "4.1.11", "@vitest/utils": "4.1.11", "chai": "^6.2.2", "tinyrainbow": "^3.1.0" } }, "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw=="], - - "@vitest/mocker": ["@vitest/mocker@4.1.11", "", { "dependencies": { "@vitest/spy": "4.1.11", "estree-walker": "^3.0.3", "magic-string": "^0.30.21" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["msw", "vite"] }, "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ=="], - - "@vitest/pretty-format": ["@vitest/pretty-format@4.1.11", "", { "dependencies": { "tinyrainbow": "^3.1.0" } }, "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw=="], - - "@vitest/runner": ["@vitest/runner@4.1.11", "", { "dependencies": { "@vitest/utils": "4.1.11", "pathe": "^2.0.3" } }, "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw=="], - - "@vitest/snapshot": ["@vitest/snapshot@4.1.11", "", { "dependencies": { "@vitest/pretty-format": "4.1.11", "@vitest/utils": "4.1.11", "magic-string": "^0.30.21", "pathe": "^2.0.3" } }, "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog=="], - - "@vitest/spy": ["@vitest/spy@4.1.11", "", {}, "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA=="], - - "@vitest/ui": ["@vitest/ui@1.6.1", "", { "dependencies": { "@vitest/utils": "1.6.1", "fast-glob": "^3.3.2", "fflate": "^0.8.1", "flatted": "^3.2.9", "pathe": "^1.1.1", "picocolors": "^1.0.0", "sirv": "^2.0.4" }, "peerDependencies": { "vitest": "1.6.1" } }, "sha512-xa57bCPGuzEFqGjPs3vVLyqareG8DX0uMkr5U/v5vLv5/ZUrBrPL7gzxzTJedEyZxFMfsozwTIbbYfEQVo3kgg=="], - - "@vitest/utils": ["@vitest/utils@1.6.1", "", { "dependencies": { "diff-sequences": "^29.6.3", "estree-walker": "^3.0.3", "loupe": "^2.3.7", "pretty-format": "^29.7.0" } }, "sha512-jOrrUvXM4Av9ZWiG1EajNto0u96kWAhJ1LmPmJhXXQx/32MecEKd10pOLYgS2BQx1TgkGhloPU1ArDW2vvaY6g=="], - - "abitype": ["abitype@1.0.8", "", { "peerDependencies": { "typescript": ">=5.0.4", "zod": "^3 >=3.22.0" }, "optionalPeers": ["typescript", "zod"] }, "sha512-ZeiI6h3GnW06uYDLx0etQtX/p8E24UaHHBj57RSjK7YBFe7iuVn07EDpOeP451D06sF27VOz9JJPlIKJmXgkEg=="], - - "ansi-styles": ["ansi-styles@5.2.0", "", {}, "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA=="], - - "assertion-error": ["assertion-error@2.0.1", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="], - - "braces": ["braces@3.0.3", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="], - - "bun-types": ["bun-types@1.2.18", "", { "dependencies": { "@types/node": "*" }, "peerDependencies": { "@types/react": "^19" } }, "sha512-04+Eha5NP7Z0A9YgDAzMk5PHR16ZuLVa83b26kH5+cp1qZW4F6FmAURngE7INf4tKOvCE69vYvDEwoNl1tGiWw=="], - - "chai": ["chai@6.2.2", "", {}, "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg=="], - - "convert-source-map": ["convert-source-map@2.0.0", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="], - - "csstype": ["csstype@3.1.3", "", {}, "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw=="], - - "detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], - - "diff-sequences": ["diff-sequences@29.6.3", "", {}, "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q=="], - - "es-module-lexer": ["es-module-lexer@2.3.2", "", {}, "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw=="], - - "estree-walker": ["estree-walker@3.0.3", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="], - - "eventemitter3": ["eventemitter3@5.0.1", "", {}, "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA=="], - - "expect-type": ["expect-type@1.4.0", "", {}, "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA=="], - - "fast-glob": ["fast-glob@3.3.3", "", { "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", "glob-parent": "^5.1.2", "merge2": "^1.3.0", "micromatch": "^4.0.8" } }, "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg=="], - - "fastq": ["fastq@1.19.1", "", { "dependencies": { "reusify": "^1.0.4" } }, "sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ=="], - - "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], - - "fflate": ["fflate@0.8.2", "", {}, "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A=="], - - "fill-range": ["fill-range@7.1.1", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="], - - "flatted": ["flatted@3.3.3", "", {}, "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg=="], - - "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], - - "get-func-name": ["get-func-name@2.0.2", "", {}, "sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ=="], - - "glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="], - - "hono": ["hono@4.13.5", "", {}, "sha512-O6+/eCYRkzzzy0rPWwKLiGBR1nFuUPZynnwjxN1MBA62NNqbT0wQEzQyK2gSO5yDIDB336sXQleAhOHrzlYyKw=="], - - "is-extglob": ["is-extglob@2.1.1", "", {}, "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ=="], - - "is-glob": ["is-glob@4.0.3", "", { "dependencies": { "is-extglob": "^2.1.1" } }, "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg=="], - - "is-number": ["is-number@7.0.0", "", {}, "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng=="], - - "isows": ["isows@1.0.7", "", { "peerDependencies": { "ws": "*" } }, "sha512-I1fSfDCZL5P0v33sVqeTDSpcstAg/N+wF5HS033mogOVIp4B+oHC7oOCsA3axAbBSGTJ8QubbNmnIRN/h8U7hg=="], - - "lightningcss": ["lightningcss@1.33.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.33.0", "lightningcss-darwin-arm64": "1.33.0", "lightningcss-darwin-x64": "1.33.0", "lightningcss-freebsd-x64": "1.33.0", "lightningcss-linux-arm-gnueabihf": "1.33.0", "lightningcss-linux-arm64-gnu": "1.33.0", "lightningcss-linux-arm64-musl": "1.33.0", "lightningcss-linux-x64-gnu": "1.33.0", "lightningcss-linux-x64-musl": "1.33.0", "lightningcss-win32-arm64-msvc": "1.33.0", "lightningcss-win32-x64-msvc": "1.33.0" } }, "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA=="], - - "lightningcss-android-arm64": ["lightningcss-android-arm64@1.33.0", "", { "os": "android", "cpu": "arm64" }, "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg=="], - - "lightningcss-darwin-arm64": ["lightningcss-darwin-arm64@1.33.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg=="], - - "lightningcss-darwin-x64": ["lightningcss-darwin-x64@1.33.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ=="], - - "lightningcss-freebsd-x64": ["lightningcss-freebsd-x64@1.33.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg=="], - - "lightningcss-linux-arm-gnueabihf": ["lightningcss-linux-arm-gnueabihf@1.33.0", "", { "os": "linux", "cpu": "arm" }, "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ=="], - - "lightningcss-linux-arm64-gnu": ["lightningcss-linux-arm64-gnu@1.33.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg=="], - - "lightningcss-linux-arm64-musl": ["lightningcss-linux-arm64-musl@1.33.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ=="], - - "lightningcss-linux-x64-gnu": ["lightningcss-linux-x64-gnu@1.33.0", "", { "os": "linux", "cpu": "x64" }, "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg=="], - - "lightningcss-linux-x64-musl": ["lightningcss-linux-x64-musl@1.33.0", "", { "os": "linux", "cpu": "x64" }, "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw=="], - - "lightningcss-win32-arm64-msvc": ["lightningcss-win32-arm64-msvc@1.33.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA=="], - - "lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.33.0", "", { "os": "win32", "cpu": "x64" }, "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA=="], - - "loupe": ["loupe@2.3.7", "", { "dependencies": { "get-func-name": "^2.0.1" } }, "sha512-zSMINGVYkdpYSOBmLi0D1Uo7JU9nVdQKrHxC8eYlV+9YKK9WePqAlL7lSlorG/U2Fw1w0hTBmaa/jrQ3UbPHtA=="], - - "magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], - - "merge2": ["merge2@1.4.1", "", {}, "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg=="], - - "micromatch": ["micromatch@4.0.8", "", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="], - - "mrmime": ["mrmime@2.0.1", "", {}, "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ=="], - - "nanoid": ["nanoid@3.3.19", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug=="], - - "obug": ["obug@2.2.1", "", {}, "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q=="], - - "openapi-types": ["openapi-types@12.1.3", "", {}, "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw=="], - - "ox": ["ox@0.8.1", "", { "dependencies": { "@adraffy/ens-normalize": "^1.11.0", "@noble/ciphers": "^1.3.0", "@noble/curves": "^1.9.1", "@noble/hashes": "^1.8.0", "@scure/bip32": "^1.7.0", "@scure/bip39": "^1.6.0", "abitype": "^1.0.8", "eventemitter3": "5.0.1" }, "peerDependencies": { "typescript": ">=5.4.0" }, "optionalPeers": ["typescript"] }, "sha512-e+z5epnzV+Zuz91YYujecW8cF01mzmrUtWotJ0oEPym/G82uccs7q0WDHTYL3eiONbTUEvcZrptAKLgTBD3u2A=="], - - "oxlint": ["oxlint@0.9.10", "", { "optionalDependencies": { "@oxlint/darwin-arm64": "0.9.10", "@oxlint/darwin-x64": "0.9.10", "@oxlint/linux-arm64-gnu": "0.9.10", "@oxlint/linux-arm64-musl": "0.9.10", "@oxlint/linux-x64-gnu": "0.9.10", "@oxlint/linux-x64-musl": "0.9.10", "@oxlint/win32-arm64": "0.9.10", "@oxlint/win32-x64": "0.9.10" }, "bin": { "oxlint": "bin/oxlint", "oxc_language_server": "bin/oxc_language_server" } }, "sha512-bKiiFN7Hnoaist/rditTRBXz+GXKYuLd53/NB7Q6zHB/bifELJarSoRLkAUGElIJKl4PSr3lTh1g6zehh+rX0g=="], - - "pathe": ["pathe@1.1.2", "", {}, "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ=="], - - "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], - - "picomatch": ["picomatch@4.0.5", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="], - - "postcss": ["postcss@8.5.28", "", { "dependencies": { "nanoid": "^3.3.18", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A=="], - - "pretty-format": ["pretty-format@29.7.0", "", { "dependencies": { "@jest/schemas": "^29.6.3", "ansi-styles": "^5.0.0", "react-is": "^18.0.0" } }, "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ=="], - - "queue-microtask": ["queue-microtask@1.2.3", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="], - - "react-is": ["react-is@18.3.1", "", {}, "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg=="], - - "reusify": ["reusify@1.1.0", "", {}, "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw=="], - - "rolldown": ["rolldown@1.2.9", "", { "dependencies": { "@oxc-project/types": "=0.150.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm-eabi": "1.2.9", "@rolldown/binding-android-arm64": "1.2.9", "@rolldown/binding-darwin-arm64": "1.2.9", "@rolldown/binding-darwin-x64": "1.2.9", "@rolldown/binding-freebsd-x64": "1.2.9", "@rolldown/binding-linux-arm-gnueabihf": "1.2.9", "@rolldown/binding-linux-arm64-gnu": "1.2.9", "@rolldown/binding-linux-arm64-musl": "1.2.9", "@rolldown/binding-linux-ppc64-gnu": "1.2.9", "@rolldown/binding-linux-s390x-gnu": "1.2.9", "@rolldown/binding-linux-x64-gnu": "1.2.9", "@rolldown/binding-linux-x64-musl": "1.2.9", "@rolldown/binding-openharmony-arm64": "1.2.9", "@rolldown/binding-win32-arm64-msvc": "1.2.9", "@rolldown/binding-win32-x64-msvc": "1.2.9" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-hx/Pv0N1haXRb11qkfnK5MXB/iqr7i0yjWQqmO9uHqZpBgQSqzc8UsSnEpalsh+j1I8qQ2CkXAkJC8Br3dKSlg=="], - - "run-parallel": ["run-parallel@1.2.0", "", { "dependencies": { "queue-microtask": "^1.2.2" } }, "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA=="], - - "siginfo": ["siginfo@2.0.0", "", {}, "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g=="], - - "sirv": ["sirv@2.0.4", "", { "dependencies": { "@polka/url": "^1.0.0-next.24", "mrmime": "^2.0.0", "totalist": "^3.0.0" } }, "sha512-94Bdh3cC2PKrbgSOUqTiGPWVZeSiXfKOVZNJniWoqrWrRkB1CJzBU3NEbiTsPcYy1lDsANA/THzS+9WBiy5nfQ=="], - - "source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="], - - "stackback": ["stackback@0.0.2", "", {}, "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw=="], - - "std-env": ["std-env@4.2.0", "", {}, "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw=="], - - "tinybench": ["tinybench@2.9.0", "", {}, "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg=="], - - "tinyexec": ["tinyexec@1.3.1", "", {}, "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA=="], - - "tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="], - - "tinyrainbow": ["tinyrainbow@3.1.1", "", {}, "sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw=="], - - "to-regex-range": ["to-regex-range@5.0.1", "", { "dependencies": { "is-number": "^7.0.0" } }, "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ=="], - - "totalist": ["totalist@3.0.1", "", {}, "sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ=="], - - "typescript": ["typescript@5.8.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ=="], - - "undici-types": ["undici-types@7.8.0", "", {}, "sha512-9UJ2xGDvQ43tYyVMpuHlsgApydB8ZKfVYTsLDhXkFL/6gfkp+U8xTGdh8pMJv1SpZna0zxG1DwsKZsreLbXBxw=="], - - "viem": ["viem@2.31.7", "", { "dependencies": { "@noble/curves": "1.9.2", "@noble/hashes": "1.8.0", "@scure/bip32": "1.7.0", "@scure/bip39": "1.6.0", "abitype": "1.0.8", "isows": "1.0.7", "ox": "0.8.1", "ws": "8.18.2" }, "peerDependencies": { "typescript": ">=5.0.4" }, "optionalPeers": ["typescript"] }, "sha512-mpB8Hp6xK77E/b/yJmpAIQcxcOfpbrwWNItjnXaIA8lxZYt4JS433Pge2gg6Hp3PwyFtaUMh01j5L8EXnLTjQQ=="], - - "vite": ["vite@8.3.0", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", "postcss": "^8.5.28", "rolldown": "~1.2.6", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.7.1", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-lhZBVvEHefgE+HQZC9O7EBJgCU/nVzFNl7vkS4RE0APtWLP02/8QVIkQtzBxPquh7lq5/78NHipTj7ODQ6XuyQ=="], - - "vitest": ["vitest@4.1.11", "", { "dependencies": { "@vitest/expect": "4.1.11", "@vitest/mocker": "4.1.11", "@vitest/pretty-format": "4.1.11", "@vitest/runner": "4.1.11", "@vitest/snapshot": "4.1.11", "@vitest/spy": "4.1.11", "@vitest/utils": "4.1.11", "es-module-lexer": "^2.0.0", "expect-type": "^1.3.0", "magic-string": "^0.30.21", "obug": "^2.1.1", "pathe": "^2.0.3", "picomatch": "^4.0.3", "std-env": "^4.0.0-rc.1", "tinybench": "^2.9.0", "tinyexec": "^1.0.2", "tinyglobby": "^0.2.15", "tinyrainbow": "^3.1.0", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", "@vitest/browser-playwright": "4.1.11", "@vitest/browser-preview": "4.1.11", "@vitest/browser-webdriverio": "4.1.11", "@vitest/coverage-istanbul": "4.1.11", "@vitest/coverage-v8": "4.1.11", "@vitest/ui": "4.1.11", "happy-dom": "*", "jsdom": "*" }, "optionalPeers": ["@edge-runtime/vm", "@opentelemetry/api", "@types/node", "@vitest/browser-playwright", "@vitest/browser-preview", "@vitest/browser-webdriverio", "@vitest/coverage-istanbul", "@vitest/coverage-v8", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "./vitest.mjs" } }, "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw=="], - - "why-is-node-running": ["why-is-node-running@2.3.0", "", { "dependencies": { "siginfo": "^2.0.0", "stackback": "0.0.2" }, "bin": { "why-is-node-running": "cli.js" } }, "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w=="], - - "ws": ["ws@8.18.2", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-DMricUmwGZUVr++AEAe2uiVM7UoO9MAVZMDu05UQOaUII0lp+zOzLLU4Xqh/JvTqklB1T4uELaaPBKyjE1r4fQ=="], - - "zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="], - - "@vitest/expect/@vitest/utils": ["@vitest/utils@4.1.11", "", { "dependencies": { "@vitest/pretty-format": "4.1.11", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" } }, "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ=="], - - "@vitest/runner/@vitest/utils": ["@vitest/utils@4.1.11", "", { "dependencies": { "@vitest/pretty-format": "4.1.11", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" } }, "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ=="], - - "@vitest/runner/pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], - - "@vitest/snapshot/@vitest/utils": ["@vitest/utils@4.1.11", "", { "dependencies": { "@vitest/pretty-format": "4.1.11", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" } }, "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ=="], - - "@vitest/snapshot/pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], - - "bun-types/@types/node": ["@types/node@22.7.5", "", { "dependencies": { "undici-types": "~6.19.2" } }, "sha512-jML7s2NAzMWc//QSJ1a3prpk78cOPchGvXJsC3C6R6PSMoooztvRVQEz89gmBTBY1SPMaqo5teB4uNHPdetShQ=="], - - "micromatch/picomatch": ["picomatch@2.3.1", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="], - - "vite/picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="], - - "vitest/@vitest/utils": ["@vitest/utils@4.1.11", "", { "dependencies": { "@vitest/pretty-format": "4.1.11", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" } }, "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ=="], - - "vitest/pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], - - "bun-types/@types/node/undici-types": ["undici-types@6.19.8", "", {}, "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw=="], - } -} diff --git a/dstack/kms/auth-eth-bun/index.test.ts b/dstack/kms/auth-eth-bun/index.test.ts deleted file mode 100644 index fd97ffdb63..0000000000 --- a/dstack/kms/auth-eth-bun/index.test.ts +++ /dev/null @@ -1,567 +0,0 @@ -// SPDX-FileCopyrightText: © 2025 Phala Network -// -// SPDX-License-Identifier: Apache-2.0 - -import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest'; -import openApiSpec from './openapi.json'; - -// Mock viem -const mockReadContract = vi.fn(); -const mockGetChainId = vi.fn(); -const mockGetBlockNumber = vi.fn(); - -vi.mock('viem', () => ({ - createPublicClient: vi.fn(() => ({ - readContract: mockReadContract, - getChainId: mockGetChainId, - getBlockNumber: mockGetBlockNumber, - })), - http: vi.fn(), - getContract: vi.fn(), -})); - -// Dynamic import after mocking -let appFetch: any; - -beforeAll(async () => { - // Set environment variables for testing - process.env.ETH_RPC_URL = 'http://localhost:8545'; - process.env.KMS_CONTRACT_ADDR = '0x1234567890123456789012345678901234567890'; - process.env.PORT = '3001'; - process.env.ETH_CHAIN_ID = '1337'; - process.env.ETH_FINALITY_CONFIRMATIONS = '2'; - - // Import the app after mocking - const indexModule = await import('./index.ts'); - appFetch = indexModule.default.fetch; -}); - -beforeEach(() => { - // Reset mocks before each test - vi.clearAllMocks(); - mockGetChainId.mockResolvedValue(1337); - mockGetBlockNumber.mockResolvedValue(100n); -}); - -describe('API Compatibility Tests', () => { - describe('GET /', () => { - it('should return system info matching OpenAPI spec', async () => { - // Mock contract calls - mockReadContract.mockImplementation((params) => { - if (params.functionName === 'gatewayAppId') { - return '0xabcdefabcdefabcdefabcdefabcdefabcdefabcd'; - } - if (params.functionName === 'appImplementation') { - return '0x9876543210987654321098765432109876543210'; - } - }); - mockGetChainId.mockResolvedValue(1337); - - const response = await appFetch(new Request('http://localhost:3001/')); - const data = await response.json(); - - expect(response.status).toBe(200); - expect(data).toMatchObject({ - status: 'ok', - kmsContractAddr: '0x1234567890123456789012345678901234567890', - ethRpcUrl: 'http://localhost:8545', - gatewayAppId: expect.any(String), - chainId: expect.any(Number), - appAuthImplementation: expect.any(String), - appImplementation: expect.any(String), - }); - - // Verify response structure matches OpenAPI spec - const systemInfoSchema = openApiSpec.components.schemas.SystemInfo; - const requiredFields = systemInfoSchema.required; - - requiredFields.forEach(field => { - expect(data).toHaveProperty(field); - }); - }); - - it('should handle errors gracefully', async () => { - // Mock contract calls to throw error - mockReadContract.mockRejectedValue(new Error('contract error')); - mockGetChainId.mockRejectedValue(new Error('network error')); - - const response = await appFetch(new Request('http://localhost:3001/')); - const data = await response.json(); - - expect(response.status).toBe(500); - expect(data).toMatchObject({ - status: 'error', - message: 'authorization backend unavailable', - }); - }); - }); - - describe('POST /bootAuth/app', () => { - const validBootInfo = { - mrAggregated: '0x1234567890123456789012345678901234567890123456789012345678901234', - osImageHash: '0xabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcd', - appId: '0x1111111111111111111111111111111111111111', - composeHash: '0x2222222222222222222222222222222222222222222222222222222222222222', - instanceId: '0x3333333333333333333333333333333333333333', - deviceId: '0x4444444444444444444444444444444444444444444444444444444444444444', - }; - - it('should validate app boot with required fields only', async () => { - // Mock successful contract response - mockReadContract.mockImplementation((params) => { - if (params.functionName === 'isAppAllowed') { - return [true, 'success']; - } - if (params.functionName === 'gatewayAppId') { - return '0xgateway123456789012345678901234567890'; - } - }); - - const response = await appFetch(new Request('http://localhost:3001/bootAuth/app', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(validBootInfo), - })); - - const data = await response.json(); - - expect(response.status).toBe(200); - expect(data).toMatchObject({ - isAllowed: true, - reason: 'success', - gatewayAppId: expect.any(String), - }); - - // Verify response matches OpenAPI spec - const bootResponseSchema = openApiSpec.components.schemas.BootResponse; - const requiredFields = bootResponseSchema.required; - - requiredFields.forEach(field => { - expect(data).toHaveProperty(field); - }); - }); - - it('should handle full BootInfo with optional fields', async () => { - const fullBootInfo = { - ...validBootInfo, - tcbStatus: 'OK', - advisoryIds: ['INTEL-SA-00123'], - mrSystem: '0x5555555555555555555555555555555555555555555555555555555555555555', - }; - - mockReadContract.mockImplementation((params) => { - if (params.functionName === 'isAppAllowed') { - return [true, 'success with full info']; - } - if (params.functionName === 'gatewayAppId') { - return '0xgateway123456789012345678901234567890'; - } - }); - - const response = await appFetch(new Request('http://localhost:3001/bootAuth/app', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(fullBootInfo), - })); - - const data = await response.json(); - - expect(response.status).toBe(200); - expect(data.isAllowed).toBe(true); - expect(data.reason).toBe('success with full info'); - }); - - it('should handle contract errors', async () => { - mockReadContract.mockRejectedValue(new Error('contract call failed')); - - const response = await appFetch(new Request('http://localhost:3001/bootAuth/app', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(validBootInfo), - })); - - const data = await response.json(); - - expect(response.status).toBe(200); - expect(data).toMatchObject({ - isAllowed: false, - gatewayAppId: '', - reason: 'authorization backend unavailable', - }); - }); - - it('should reject invalid request body', async () => { - const invalidBootInfo = { - mrAggregated: '0x1234', // missing required fields - }; - - const response = await appFetch(new Request('http://localhost:3001/bootAuth/app', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(invalidBootInfo), - })); - - expect(response.status).toBe(400); - }); - - - it('should reject oversized and non-hex measurements before backend use', async () => { - for (const mrAggregated of ['0x' + 'ab'.repeat(33), 'not-hex']) { - const response = await appFetch(new Request('http://localhost:3001/bootAuth/app', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ ...validBootInfo, mrAggregated }), - })); - - expect(response.status).toBe(400); - expect(await response.json()).toEqual({ isAllowed: false, reason: 'invalid authorization request', gatewayAppId: '' }); - } - expect(mockReadContract).not.toHaveBeenCalled(); - }); -}); - - describe('POST /bootAuth/kms', () => { - const validBootInfo = { - mrAggregated: '0x1234567890123456789012345678901234567890123456789012345678901234', - osImageHash: '0xabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcd', - appId: '0x1111111111111111111111111111111111111111', - composeHash: '0x2222222222222222222222222222222222222222222222222222222222222222', - instanceId: '0x3333333333333333333333333333333333333333', - deviceId: '0x4444444444444444444444444444444444444444444444444444444444444444', - }; - - it('should validate KMS boot successfully', async () => { - // Mock successful contract response - mockReadContract.mockImplementation((params) => { - if (params.functionName === 'isKmsAllowed') { - return [true, 'KMS allowed']; - } - if (params.functionName === 'gatewayAppId') { - return '0xgateway123456789012345678901234567890'; - } - }); - - const response = await appFetch(new Request('http://localhost:3001/bootAuth/kms', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(validBootInfo), - })); - - const data = await response.json(); - - expect(response.status).toBe(200); - expect(data).toMatchObject({ - isAllowed: true, - reason: 'KMS allowed', - gatewayAppId: expect.any(String), - }); - }); - - it('should handle KMS rejection', async () => { - mockReadContract.mockImplementation((params) => { - if (params.functionName === 'isKmsAllowed') { - return [false, 'KMS not authorized']; - } - if (params.functionName === 'gatewayAppId') { - return '0xgateway123456789012345678901234567890'; - } - }); - - const response = await appFetch(new Request('http://localhost:3001/bootAuth/kms', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(validBootInfo), - })); - - const data = await response.json(); - - expect(response.status).toBe(200); - expect(data).toMatchObject({ - isAllowed: false, - reason: 'KMS not authorized', - gatewayAppId: expect.any(String), - }); - }); - - it('should not log "Test backend error" messages', async () => { - const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); - - mockReadContract.mockRejectedValue(new Error('Test backend error')); - - const response = await appFetch(new Request('http://localhost:3001/bootAuth/kms', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(validBootInfo), - })); - - const data = await response.json(); - - expect(response.status).toBe(200); - expect(data.isAllowed).toBe(false); - expect(data.reason).toBe('authorization backend unavailable'); - - // Verify that console.error was not called for test errors - expect(consoleSpy).not.toHaveBeenCalled(); - - consoleSpy.mockRestore(); - }); - - it('should log other error messages', async () => { - const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); - - mockReadContract.mockRejectedValue(new Error('real error')); - - const response = await appFetch(new Request('http://localhost:3001/bootAuth/kms', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(validBootInfo), - })); - - const data = await response.json(); - - expect(response.status).toBe(200); - expect(data.isAllowed).toBe(false); - expect(data.reason).toBe('authorization backend unavailable'); - - // Diagnostics identify the failing boundary without retaining backend details. - expect(consoleSpy).toHaveBeenCalledWith('KMS authorization backend failed'); - expect(JSON.stringify(consoleSpy.mock.calls)).not.toContain('real error'); - - consoleSpy.mockRestore(); - }); - }); -}); - -describe('API Schema Compatibility', () => { - it('should match BootInfo schema requirements', () => { - const bootInfoSchema = openApiSpec.components.schemas.BootInfo; - - // Required fields should match original fastify schema - expect(bootInfoSchema.required).toEqual([ - 'mrAggregated', - 'osImageHash', - 'appId', - 'composeHash', - 'instanceId', - 'deviceId' - ]); - - // Optional fields should be present for full compatibility - expect(bootInfoSchema.properties).toHaveProperty('tcbStatus'); - expect(bootInfoSchema.properties).toHaveProperty('advisoryIds'); - expect(bootInfoSchema.properties).toHaveProperty('mrSystem'); - }); - - it('should match BootResponse schema requirements', () => { - const bootResponseSchema = openApiSpec.components.schemas.BootResponse; - - expect(bootResponseSchema.required).toEqual([ - 'isAllowed', - 'reason', - 'gatewayAppId' - ]); - }); - - it('should match SystemInfo schema requirements', () => { - const systemInfoSchema = openApiSpec.components.schemas.SystemInfo; - - expect(systemInfoSchema.required).toEqual([ - 'status', - 'kmsContractAddr', - 'ethRpcUrl', - 'gatewayAppId', - 'chainId', - 'appAuthImplementation', - 'appImplementation' - ]); - }); -}); - -describe('Hex Decoding Compatibility', () => { - it('should handle hex values with and without 0x prefix', async () => { - const bootInfoWithoutPrefix = { - mrAggregated: '1234567890123456789012345678901234567890123456789012345678901234', - osImageHash: 'abcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcd', - appId: '1111111111111111111111111111111111111111', - composeHash: '2222222222222222222222222222222222222222222222222222222222222222', - instanceId: '3333333333333333333333333333333333333333', - deviceId: '4444444444444444444444444444444444444444444444444444444444444444', - }; - - mockReadContract.mockImplementation((params) => { - if (params.functionName === 'isAppAllowed') { - // Verify that hex values are properly formatted - const [bootInfoStruct] = params.args; - expect(bootInfoStruct.mrAggregated).toMatch(/^0x[0-9a-f]{64}$/i); - expect(bootInfoStruct.appId).toMatch(/^0x[0-9a-f]{40}$/i); - return [true, 'success']; - } - if (params.functionName === 'gatewayAppId') { - return '0xgateway123456789012345678901234567890'; - } - }); - - const response = await appFetch(new Request('http://localhost:3001/bootAuth/app', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(bootInfoWithoutPrefix), - })); - - expect(response.status).toBe(200); - }); -}); - -describe('Authorization freshness and domain binding', () => { - const requestBody = { - mrAggregated: '0x' + '11'.repeat(32), - osImageHash: '0x' + '22'.repeat(32), - appId: '0x' + '33'.repeat(20), - composeHash: '0x' + '44'.repeat(32), - instanceId: '0x' + '55'.repeat(20), - deviceId: '0x' + '66'.repeat(32), - }; - - const postApp = (body = requestBody) => appFetch(new Request( - 'http://localhost:3001/bootAuth/app', - { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(body), - }, - )); - - it('re-evaluates replayed payloads instead of caching an earlier allow', async () => { - let decisions = 0; - mockReadContract.mockImplementation((params) => { - expect(params.address).toBe('0x1234567890123456789012345678901234567890'); - if (params.functionName === 'isAppAllowed') { - decisions += 1; - return decisions === 1 ? [true, 'initial allow'] : [false, 'policy changed']; - } - if (params.functionName === 'gatewayAppId') return 'gateway-app'; - throw new Error(`unexpected function ${params.functionName}`); - }); - - const first = await postApp(); - const replay = await postApp(); - - expect(await first.json()).toMatchObject({ isAllowed: true, reason: 'initial allow' }); - expect(await replay.json()).toMatchObject({ isAllowed: false, reason: 'policy changed' }); - expect(decisions).toBe(2); - }); - - it('binds changed measurements and identities into distinct contract arguments', async () => { - const calls: unknown[] = []; - mockReadContract.mockImplementation((params) => { - if (params.functionName === 'isAppAllowed') { - calls.push(params.args[0]); - return [true, 'allowed']; - } - if (params.functionName === 'gatewayAppId') return 'gateway-app'; - throw new Error(`unexpected function ${params.functionName}`); - }); - - await postApp(); - await postApp({ ...requestBody, composeHash: '0x' + '77'.repeat(32) }); - await postApp({ ...requestBody, appId: '0x' + '88'.repeat(20) }); - - expect(calls).toHaveLength(3); - expect(calls[0]).not.toEqual(calls[1]); - expect(calls[0]).not.toEqual(calls[2]); - }); - - it('fails closed during backend interruption and succeeds after recovery', async () => { - mockReadContract.mockRejectedValueOnce(new Error('backend unavailable')); - const interrupted = await postApp(); - expect(await interrupted.json()).toEqual({ - isAllowed: false, - gatewayAppId: '', - reason: 'authorization backend unavailable', - }); - - mockReadContract.mockImplementation((params) => { - if (params.functionName === 'isAppAllowed') return [true, 'recovered']; - if (params.functionName === 'gatewayAppId') return 'gateway-app'; - throw new Error(`unexpected function ${params.functionName}`); - }); - const recovered = await postApp(); - expect(await recovered.json()).toMatchObject({ isAllowed: true, reason: 'recovered' }); - }); -}); - - -describe('Ethereum finalized snapshot authorization', () => { - const requestBody = { - mrAggregated: '0x' + '11'.repeat(32), - osImageHash: '0x' + '22'.repeat(32), - appId: '0x' + '33'.repeat(20), - composeHash: '0x' + '44'.repeat(32), - instanceId: '0x' + '55'.repeat(20), - deviceId: '0x' + '66'.repeat(32), - }; - - const authorize = () => appFetch(new Request('http://localhost:3001/bootAuth/app', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(requestBody), - })); - - it('reads the decision and gateway identity from one confirmation-depth snapshot', async () => { - mockGetBlockNumber.mockResolvedValue(100n); - mockReadContract.mockImplementation((params) => { - expect(params.blockNumber).toBe(98n); - if (params.functionName === 'isAppAllowed') return [true, 'finalized allow']; - if (params.functionName === 'gatewayAppId') return 'gateway-app'; - throw new Error(`unexpected function ${params.functionName}`); - }); - - const response = await authorize(); - expect(await response.json()).toMatchObject({ isAllowed: true, reason: 'finalized allow' }); - expect(mockGetBlockNumber).toHaveBeenCalledTimes(1); - }); - - it('re-evaluates the canonical finalized snapshot after a short reorg', async () => { - mockGetBlockNumber.mockResolvedValueOnce(100n).mockResolvedValueOnce(101n); - let decisions = 0; - const observedBlocks: bigint[] = []; - mockReadContract.mockImplementation((params) => { - if (params.functionName === 'isAppAllowed') { - observedBlocks.push(params.blockNumber); - decisions += 1; - return decisions === 1 ? [true, 'old canonical allow'] : [false, 'new canonical deny']; - } - if (params.functionName === 'gatewayAppId') return 'gateway-app'; - throw new Error(`unexpected function ${params.functionName}`); - }); - - const before = await authorize(); - const after = await authorize(); - expect(await before.json()).toMatchObject({ isAllowed: true }); - expect(await after.json()).toMatchObject({ isAllowed: false, reason: 'new canonical deny' }); - expect(observedBlocks).toEqual([98n, 99n]); - }); - - it.each([ - ['wrong chain', () => mockGetChainId.mockResolvedValue(1)], - ['stale head', () => mockGetBlockNumber.mockResolvedValue(1n)], - ['head timeout', () => mockGetBlockNumber.mockRejectedValue(new Error('timeout'))], - ])('fails closed for %s and recovers without retained decisions', async (_name, inject) => { - inject(); - const failed = await authorize(); - expect(await failed.json()).toEqual({ - isAllowed: false, - gatewayAppId: '', - reason: 'authorization backend unavailable', - }); - - mockGetChainId.mockResolvedValue(1337); - mockGetBlockNumber.mockResolvedValue(102n); - mockReadContract.mockImplementation((params) => { - if (params.functionName === 'isAppAllowed') return [true, 'recovered']; - if (params.functionName === 'gatewayAppId') return 'gateway-app'; - throw new Error(`unexpected function ${params.functionName}`); - }); - const recovered = await authorize(); - expect(await recovered.json()).toMatchObject({ isAllowed: true, reason: 'recovered' }); - }); -}); diff --git a/dstack/kms/auth-eth-bun/index.ts b/dstack/kms/auth-eth-bun/index.ts deleted file mode 100644 index 3ea279327c..0000000000 --- a/dstack/kms/auth-eth-bun/index.ts +++ /dev/null @@ -1,339 +0,0 @@ -// SPDX-FileCopyrightText: © 2025 Phala Network -// -// SPDX-License-Identifier: Apache-2.0 - -import { Hono } from 'hono'; -import { zValidator } from '@hono/zod-validator'; -import { z } from 'zod'; -import { createPublicClient, http, type Address, type Hex } from 'viem'; - -// zod schemas for validation - compatible with original fastify implementation -const boundedHex = (bytes: number, description: string) => - z.string() - .regex(/^(?:0x)?[0-9a-fA-F]*$/, `${description} must be hexadecimal`) - .refine( - (value) => value.replace(/^0x/, '').length <= bytes * 2, - `${description} exceeds ${bytes} bytes`, - ); - -const BootInfoSchema = z.object({ - // Short hexadecimal values remain compatible with the original backend, - // which left-pads them before making the contract call. - mrAggregated: boundedHex(32, 'aggregated MR measurement'), - osImageHash: boundedHex(32, 'OS Image hash'), - appId: boundedHex(20, 'application ID'), - composeHash: boundedHex(32, 'compose hash'), - instanceId: boundedHex(20, 'instance ID'), - deviceId: boundedHex(32, 'device ID'), - tcbStatus: z.string().max(128).optional().default(''), - advisoryIds: z.array(z.string().max(256)).max(128).optional().default([]), - mrSystem: boundedHex(32, 'system MR measurement').optional().default('') -}); - -const BootResponseSchema = z.object({ - isAllowed: z.boolean(), - reason: z.string(), - gatewayAppId: z.string() -}); - -type BootInfo = z.infer; -type BootResponse = z.infer; - -// DstackKms contract ABI (minimal required functions) -const DSTACK_KMS_ABI = [ - { - name: 'isKmsAllowed', - type: 'function', - stateMutability: 'view', - inputs: [ - { - name: 'bootInfo', - type: 'tuple', - components: [ - { name: 'appId', type: 'address' }, - { name: 'composeHash', type: 'bytes32' }, - { name: 'instanceId', type: 'address' }, - { name: 'deviceId', type: 'bytes32' }, - { name: 'mrAggregated', type: 'bytes32' }, - { name: 'mrSystem', type: 'bytes32' }, - { name: 'osImageHash', type: 'bytes32' }, - { name: 'tcbStatus', type: 'string' }, - { name: 'advisoryIds', type: 'string[]' } - ] - } - ], - outputs: [ - { name: 'isAllowed', type: 'bool' }, - { name: 'reason', type: 'string' } - ] - }, - { - name: 'isAppAllowed', - type: 'function', - stateMutability: 'view', - inputs: [ - { - name: 'bootInfo', - type: 'tuple', - components: [ - { name: 'appId', type: 'address' }, - { name: 'composeHash', type: 'bytes32' }, - { name: 'instanceId', type: 'address' }, - { name: 'deviceId', type: 'bytes32' }, - { name: 'mrAggregated', type: 'bytes32' }, - { name: 'mrSystem', type: 'bytes32' }, - { name: 'osImageHash', type: 'bytes32' }, - { name: 'tcbStatus', type: 'string' }, - { name: 'advisoryIds', type: 'string[]' } - ] - } - ], - outputs: [ - { name: 'isAllowed', type: 'bool' }, - { name: 'reason', type: 'string' } - ] - }, - { - name: 'gatewayAppId', - type: 'function', - stateMutability: 'view', - inputs: [], - outputs: [{ name: '', type: 'string' }] - }, - { - name: 'appImplementation', - type: 'function', - stateMutability: 'view', - inputs: [], - outputs: [{ name: '', type: 'address' }] - } -] as const; - -// ethereum backend class -class EthereumBackend { - private client: ReturnType; - private kmsContractAddr: Address; - private expectedChainId?: number; - private finalityConfirmations: bigint; - - constructor( - client: ReturnType, - kmsContractAddr: string, - expectedChainId: number | undefined, - finalityConfirmations: bigint, - ) { - this.client = client; - this.kmsContractAddr = kmsContractAddr as Address; - this.expectedChainId = expectedChainId; - this.finalityConfirmations = finalityConfirmations; - } - - private async finalizedBlockNumber(): Promise { - const chainId = await this.client.getChainId(); - if (this.expectedChainId !== undefined && chainId !== this.expectedChainId) { - throw new Error('authorization backend chain ID mismatch'); - } - const head = await this.client.getBlockNumber(); - if (head < this.finalityConfirmations) { - throw new Error('authorization backend has not reached configured finality'); - } - return head - this.finalityConfirmations; - } - - private decodeHex(hex: string, sz: number = 32): Hex { - // remove '0x' prefix if present - hex = hex.startsWith('0x') ? hex.slice(2) : hex; - // pad hex string to specified size - hex = hex.padStart(sz * 2, '0'); - // add '0x' prefix back - return `0x${hex}` as Hex; - } - - async checkBoot(bootInfo: BootInfo, isKms: boolean): Promise { - // create boot info struct for contract call - const bootInfoStruct = { - appId: this.decodeHex(bootInfo.appId, 20) as Address, - composeHash: this.decodeHex(bootInfo.composeHash, 32), - instanceId: this.decodeHex(bootInfo.instanceId, 20) as Address, - deviceId: this.decodeHex(bootInfo.deviceId, 32), - mrAggregated: this.decodeHex(bootInfo.mrAggregated, 32), - mrSystem: this.decodeHex(bootInfo.mrSystem || '', 32), - osImageHash: this.decodeHex(bootInfo.osImageHash, 32), - tcbStatus: bootInfo.tcbStatus || '', - advisoryIds: bootInfo.advisoryIds || [] - }; - - const blockNumber = await this.finalizedBlockNumber(); - let response; - if (isKms) { - response = await this.client.readContract({ - address: this.kmsContractAddr, - abi: DSTACK_KMS_ABI, - functionName: 'isKmsAllowed', - args: [bootInfoStruct], - blockNumber - }); - } else { - response = await this.client.readContract({ - address: this.kmsContractAddr, - abi: DSTACK_KMS_ABI, - functionName: 'isAppAllowed', - args: [bootInfoStruct], - blockNumber - }); - } - - const [isAllowed, reason] = response; - const gatewayAppId = await this.client.readContract({ - address: this.kmsContractAddr, - abi: DSTACK_KMS_ABI, - functionName: 'gatewayAppId', - blockNumber - }); - - return { - isAllowed, - reason, - gatewayAppId: gatewayAppId as string, - }; - } - - async getGatewayAppId(): Promise { - const result = await this.client.readContract({ - address: this.kmsContractAddr, - abi: DSTACK_KMS_ABI, - functionName: 'gatewayAppId' - }); - return result as string; - } - - async getChainId(): Promise { - const chainId = await this.client.getChainId(); - return Number(chainId); - } - - async getAppImplementation(): Promise { - const result = await this.client.readContract({ - address: this.kmsContractAddr, - abi: DSTACK_KMS_ABI, - functionName: 'appImplementation' - }); - return result as string; - } -} - -// initialize app -const app = new Hono(); - -// initialize ethereum backend -const rpcUrl = process.env.ETH_RPC_URL || 'http://localhost:8545'; -const kmsContractAddr = process.env.KMS_CONTRACT_ADDR || '0x0000000000000000000000000000000000000000'; -const parseNonNegativeInteger = (name: string, value: string | undefined): number | undefined => { - if (value === undefined || value === '') return undefined; - if (!/^(?:0|[1-9][0-9]*)$/.test(value)) throw new Error(`${name} must be a non-negative integer`); - const parsed = Number(value); - if (!Number.isSafeInteger(parsed)) throw new Error(`${name} exceeds the safe integer range`); - return parsed; -}; -const expectedChainId = parseNonNegativeInteger('ETH_CHAIN_ID', process.env.ETH_CHAIN_ID); -const finalityConfirmations = BigInt( - parseNonNegativeInteger('ETH_FINALITY_CONFIRMATIONS', process.env.ETH_FINALITY_CONFIRMATIONS) ?? 0, -); -const client = createPublicClient({ - transport: http(rpcUrl) -}); -const ethereum = new EthereumBackend(client, kmsContractAddr, expectedChainId, finalityConfirmations); - -const publicRpcEndpoint = (value: string): string => { - try { - const endpoint = new URL(value); - return `${endpoint.protocol}//${endpoint.host}`; - } catch { - return 'configured'; - } -}; - -const backendUnavailable = 'authorization backend unavailable'; -const invalidRequest = { isAllowed: false, reason: 'invalid authorization request', gatewayAppId: '' }; - -// health check and info endpoint -app.get('/', async (c) => { - try { - const batch = await Promise.all([ - ethereum.getGatewayAppId(), - ethereum.getChainId(), - ethereum.getAppImplementation(), - ]); - console.log('batch', batch); - - return c.json({ - status: 'ok', - kmsContractAddr: kmsContractAddr, - ethRpcUrl: publicRpcEndpoint(rpcUrl), - gatewayAppId: batch[0], - chainId: batch[1], - appAuthImplementation: batch[2], // NOTE: for backward compatibility - appImplementation: batch[2], - }); - } catch (error) { - console.error('authorization backend health check failed'); - return c.json({ - status: 'error', - message: backendUnavailable - }, 500); - } -}); - -// app boot authentication -app.post('/bootAuth/app', - zValidator('json', BootInfoSchema, (result, c) => { - if (!result.success) return c.json(invalidRequest, 400); - }), - async (c) => { - try { - const bootInfo = c.req.valid('json'); - const result = await ethereum.checkBoot(bootInfo, false); - return c.json(result); - } catch (error) { - console.error('application authorization backend failed'); - return c.json({ - isAllowed: false, - gatewayAppId: '', - reason: backendUnavailable - }); - } - } -); - -// KMS boot authentication -app.post('/bootAuth/kms', - zValidator('json', BootInfoSchema, (result, c) => { - if (!result.success) return c.json(invalidRequest, 400); - }), - async (c) => { - try { - const bootInfo = c.req.valid('json'); - const result = await ethereum.checkBoot(bootInfo, true); - return c.json(result); - } catch (error) { - // don't log test backend errors - if (!(error instanceof Error && "Test backend error" === error.message)) { - console.error('KMS authorization backend failed'); - } - return c.json({ - isAllowed: false, - gatewayAppId: '', - reason: backendUnavailable - }); - } - } -); - -// start server -const port = parseInt(process.env.PORT || '3000'); -console.log(`starting server on port ${port}`); - -export default { - port, - fetch: app.fetch, -}; diff --git a/dstack/kms/auth-eth-bun/openapi.json b/dstack/kms/auth-eth-bun/openapi.json deleted file mode 100644 index e87c036116..0000000000 --- a/dstack/kms/auth-eth-bun/openapi.json +++ /dev/null @@ -1,241 +0,0 @@ -{ - "openapi": "3.0.0", - "info": { - "title": "dstack KMS Ethereum Backend API", - "description": "API for dstack KMS Ethereum backend authentication and system information", - "version": "1.0.0" - }, - "servers": [ - { - "url": "http://localhost:3000", - "description": "Development server" - } - ], - "paths": { - "/": { - "get": { - "summary": "Health check and system information", - "description": "Returns system status and configuration information", - "operationId": "getSystemInfo", - "responses": { - "200": { - "description": "System information", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/SystemInfo" - } - } - } - }, - "500": { - "description": "Internal server error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } - } - } - } - }, - "/bootAuth/app": { - "post": { - "summary": "Application boot authentication", - "description": "Validates application boot information against smart contract", - "operationId": "authenticateAppBoot", - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/BootInfo" - } - } - } - }, - "responses": { - "200": { - "description": "Authentication result", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/BootResponse" - } - } - } - } - } - } - }, - "/bootAuth/kms": { - "post": { - "summary": "KMS boot authentication", - "description": "Validates KMS boot information against smart contract", - "operationId": "authenticateKmsBoot", - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/BootInfo" - } - } - } - }, - "responses": { - "200": { - "description": "Authentication result", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/BootResponse" - } - } - } - } - } - } - } - }, - "components": { - "schemas": { - "BootInfo": { - "type": "object", - "required": [ - "mrAggregated", - "osImageHash", - "appId", - "composeHash", - "instanceId", - "deviceId" - ], - "properties": { - "mrAggregated": { - "type": "string", - "description": "Aggregated MR measurement" - }, - "osImageHash": { - "type": "string", - "description": "OS Image hash" - }, - "appId": { - "type": "string", - "description": "Application ID" - }, - "composeHash": { - "type": "string", - "description": "Compose hash" - }, - "instanceId": { - "type": "string", - "description": "Instance ID" - }, - "deviceId": { - "type": "string", - "description": "Device ID" - }, - "tcbStatus": { - "type": "string", - "description": "TCB status (optional for compatibility)" - }, - "advisoryIds": { - "type": "array", - "items": { - "type": "string" - }, - "description": "Advisory IDs (optional for compatibility)" - }, - "mrSystem": { - "type": "string", - "description": "MR System measurement (optional for compatibility)" - } - } - }, - "BootResponse": { - "type": "object", - "required": [ - "isAllowed", - "reason", - "gatewayAppId" - ], - "properties": { - "isAllowed": { - "type": "boolean", - "description": "Whether the boot is allowed" - }, - "reason": { - "type": "string", - "description": "Reason for the decision" - }, - "gatewayAppId": { - "type": "string", - "description": "Gateway application ID" - } - } - }, - "SystemInfo": { - "type": "object", - "required": [ - "status", - "kmsContractAddr", - "ethRpcUrl", - "gatewayAppId", - "chainId", - "appAuthImplementation", - "appImplementation" - ], - "properties": { - "status": { - "type": "string", - "enum": ["ok"], - "description": "System status" - }, - "kmsContractAddr": { - "type": "string", - "description": "KMS contract address" - }, - "ethRpcUrl": { - "type": "string", - "description": "Ethereum RPC URL" - }, - "gatewayAppId": { - "type": "string", - "description": "Gateway application ID" - }, - "chainId": { - "type": "number", - "description": "Blockchain chain ID" - }, - "appAuthImplementation": { - "type": "string", - "description": "App auth implementation address (deprecated, use appImplementation)" - }, - "appImplementation": { - "type": "string", - "description": "App implementation address" - } - } - }, - "Error": { - "type": "object", - "required": [ - "status", - "message" - ], - "properties": { - "status": { - "type": "string", - "enum": ["error"] - }, - "message": { - "type": "string", - "description": "Error message" - } - } - } - } - } -} diff --git a/dstack/kms/auth-eth-bun/package.json b/dstack/kms/auth-eth-bun/package.json deleted file mode 100644 index 1957b4a1d6..0000000000 --- a/dstack/kms/auth-eth-bun/package.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "auth-eth-bun", - "version": "1.0.0", - "description": "dstack KMS ethereum backend with bun + hono + zod", - "main": "index.ts", - "scripts": { - "dev": "bun run --watch index.ts", - "start": "bun run index.ts", - "build": "bun build index.ts --outdir ./dist --target bun", - "test": "vitest", - "test:run": "vitest run", - "lint": "oxlint .", - "lint:fix": "oxlint --fix .", - "fmt": "oxlint --fix .", - "check": "bun run lint && bun run test:run" - }, - "dependencies": { - "hono": "4.13.5", - "@hono/zod-validator": "0.2.2", - "zod": "3.25.76", - "viem": "2.31.7" - }, - "devDependencies": { - "@types/bun": "1.2.18", - "@types/node": "^24.0.14", - "@vitest/ui": "1.6.1", - "openapi-types": "12.1.3", - "oxlint": "0.9.10", - "typescript": "5.8.3", - "vitest": "4.1.11" - }, - "type": "module" -} diff --git a/dstack/kms/auth-eth-bun/vitest.config.ts b/dstack/kms/auth-eth-bun/vitest.config.ts deleted file mode 100644 index 17597daca3..0000000000 --- a/dstack/kms/auth-eth-bun/vitest.config.ts +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-FileCopyrightText: © 2025 Phala Network -// -// SPDX-License-Identifier: Apache-2.0 - -import { defineConfig } from 'vitest/config'; - -export default defineConfig({ - test: { - globals: true, - environment: 'node', - }, -}); diff --git a/dstack/kms/auth-eth/.dockerignore b/dstack/kms/auth-eth/.dockerignore new file mode 100644 index 0000000000..a2451cfe00 --- /dev/null +++ b/dstack/kms/auth-eth/.dockerignore @@ -0,0 +1,10 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +# This directory also holds the Foundry project (contracts/, lib/, test/, +# script/, ...). The image only needs the server source and its lockfile. +* +!package.json +!bun.lock +!index.ts diff --git a/dstack/kms/auth-eth/.env.example b/dstack/kms/auth-eth/.env.example deleted file mode 100644 index a1e967f46c..0000000000 --- a/dstack/kms/auth-eth/.env.example +++ /dev/null @@ -1,21 +0,0 @@ -# SPDX-FileCopyrightText: © 2025 Phala Network -# -# SPDX-License-Identifier: Apache-2.0 - -# Example environment configuration for local testing - -# Server configuration -PORT=8000 -HOST=127.0.0.1 - -# Ethereum configuration -ETH_RPC_URL=http://127.0.0.1:8545 -KMS_CONTRACT_ADDR=0x0000000000000000000000000000000000000000 - -# For testing with local Anvil node (Foundry): -# ETH_RPC_URL=http://127.0.0.1:8545 -# KMS_CONTRACT_ADDR= - -# For testing with testnet: -# ETH_RPC_URL=https://rpc.sepolia.org -# KMS_CONTRACT_ADDR= diff --git a/dstack/kms/auth-eth/.gitignore b/dstack/kms/auth-eth/.gitignore index 0993643fe3..10450c1b1b 100644 --- a/dstack/kms/auth-eth/.gitignore +++ b/dstack/kms/auth-eth/.gitignore @@ -1,13 +1,10 @@ -/artifacts +# Foundry /broadcast /cache -/coverage -/dist /out -# Test logs -anvil-test.log -anvil.log -deploy.log -server-test.log -.env.test +# Bun server +/node_modules +/dist +/coverage +.env diff --git a/dstack/kms/auth-eth/.oxlintrc.json b/dstack/kms/auth-eth/.oxlintrc.json new file mode 100644 index 0000000000..2dcc5d26d9 --- /dev/null +++ b/dstack/kms/auth-eth/.oxlintrc.json @@ -0,0 +1,21 @@ +{ + "$schema": "./node_modules/oxlint/configuration_schema.json", + "plugins": ["typescript", "unicorn"], + "env": { + "node": true, + "es2022": true + }, + "ignorePatterns": [ + "node_modules/**", + "lib/**", + "out/**", + "cache/**", + "broadcast/**", + "dist/**", + "build/**", + "coverage/**", + "*.min.js", + "*.d.ts", + "*.test.ts" + ] +} diff --git a/dstack/kms/auth-eth/Dockerfile b/dstack/kms/auth-eth/Dockerfile new file mode 100644 index 0000000000..07a538bfc6 --- /dev/null +++ b/dstack/kms/auth-eth/Dockerfile @@ -0,0 +1,23 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +# Built from this directory, so the image carries exactly the checked-out +# source and lockfile rather than a clone fetched at build time. +FROM oven/bun:1.4.4-alpine@sha256:4cf82f5686b196504fe119db3fcd9185b191f82ece82c40680e597228ec6070a AS deps +WORKDIR /app +COPY --chmod=0644 package.json bun.lock ./ +RUN bun install --frozen-lockfile --production --ignore-scripts + +FROM oven/bun:1.4.4-alpine@sha256:4cf82f5686b196504fe119db3fcd9185b191f82ece82c40680e597228ec6070a +WORKDIR /app +COPY --from=deps /app/node_modules ./node_modules +COPY --chmod=0644 package.json index.ts ./ +ARG GIT_REV=unknown +LABEL org.opencontainers.image.revision="${GIT_REV}" +ENV NODE_ENV=production +# The KMS webhook default (`kms.toml`) is http://auth-api:8000. +ENV PORT=8000 +EXPOSE 8000 +USER bun +CMD ["bun", "index.ts"] diff --git a/dstack/kms/auth-eth/README.md b/dstack/kms/auth-eth/README.md index 3d3b88f367..eaccf8941f 100644 --- a/dstack/kms/auth-eth/README.md +++ b/dstack/kms/auth-eth/README.md @@ -1,66 +1,418 @@ -# dstack KMS Auth-ETH +# dstack KMS auth-eth -A Foundry-based smart contract project for dstack's Key Management System (KMS) authentication on Ethereum. +On-chain authorization for the dstack KMS. This directory holds both halves: -## Overview +- **Contracts** (`contracts/`, `test/`, `script/`): the upgradeable `DstackKms` + and `DstackApp` contracts, built and tested with Foundry. + - **DstackKms**: Key Management System contract with app registration and validation + - **DstackApp**: Application-specific authentication contract with device and compose hash management +- **Webhook server** (`index.ts`): a single-file Bun + Hono + zod + viem server + that reads those contracts and serves the KMS auth webhook (`/bootAuth/*`, + `/authorizeKms`, `/authorizeApp`). -This project contains upgradeable smart contracts for: -- **DstackKms**: Key Management System contract with app registration and validation -- **DstackApp**: Application-specific authentication contract with device and compose hash management +## Upgrade order -## Prerequisites +Upgrade the `DstackKms` contract before deploying the new auth backend or KMS. +Before enabling `APP_AUTH_URL`, make sure the pinned policy block includes the +upgrade that adds `DstackKms.checkKmsAppPolicy`; delegated authorization returns +503 if that method is unavailable at the pinned block. An empty root epoch +registry is supported on the upgraded contract; there is no fallback for legacy +contracts. Old KMS instances that omit the root epoch can +receive app authorization only while no epoch is registered or epoch 0 is current, +subject to the existing authorization policy. -- [Foundry](https://book.getfoundry.sh/getting-started/installation) - For smart contract development and testing -- Node.js - For the bootAuth server and TypeScript development +## Webhook server + +### Prerequisites + +- [Bun](https://bun.sh) -## Setup +### Development -1. Install dependencies: ```bash -# Install Foundry dependencies -forge install +bun install --frozen-lockfile + +# run with hot reload +bun run dev + +# run once +bun run start + +# tests (watch mode / once) +bun run test +bun run test:run -# Install Node.js dependencies for server -npm install +# lint, lint with fixes, lint + tests +bun run lint +bun run lint:fix +bun run check ``` -2. Build contracts and server: +The Bun server sets `idleTimeout` to 255s (Bun's maximum). Bun's default of 10s closes the socket while a slow `eth_call` is still in flight, which surfaces on the KMS side as `connection closed before message completed`. + +### Environment variables + +- `ETH_RPC_URL` - ethereum RPC endpoint (required unless `ETH_RPC_URLS` is set) +- `ETH_RPC_URLS` - several RPC endpoints separated by whitespace, in place of `ETH_RPC_URL`. see [multiple RPC providers](#multiple-rpc-providers) +- `ETH_RPC_QUORUM` - `n/m`: every read must be answered alike by n of the m endpoints in `ETH_RPC_URLS`; m must be their count and n more than half of it (required with `ETH_RPC_URLS`) +- `KMS_CONTRACT_ADDR` - KMS contract address (default: 0x0000000000000000000000000000000000000000) +- `PORT` - server port (default: 3000) +- `ETH_CHAIN_ID` - reject every decision if the RPC reports a different chain ID (default: unset, no check) +- `ETH_BLOCK_TAG` - block policy is read at: `latest`, `safe` or `finalized` (default: `finalized`). each request resolves the tag to one block and reads all state there, except `GET /app/:appId` when `APP_AUTH_URL` is unset, which serves only the env public key RPCs and reads the app epoch at `latest`, or `ETH_FINALITY_CONFIRMATIONS` blocks behind it (at least one) when the providers do not agree on the newest block. the server resolves the tag and reads at that block's hash once at startup, and refuses to start if the RPC cannot serve either. a later tag delays every policy change, including emergency revocations, until that block is reached (about 13 minutes for `finalized` on Ethereum mainnet). use `finalized` on L1. set `latest` explicitly for an OP-stack chain read through the Helios light client, which tracks only the sequencer-signed unsafe head and serves neither `safe` nor `finalized`, and for local development chains such as Anvil, which finalizes 64 blocks behind its head. see [reorgs and the block tag](#reorgs-and-the-block-tag) before using `latest` or `safe` +- `ETH_FINALITY_CONFIRMATIONS` - read this many blocks further behind the block `ETH_BLOCK_TAG` resolves to (default: 0) +- `ETH_MAX_BLOCK_AGE` - reject every decision if the block read is older than this many seconds by the server clock (default: unset, no check; required with more than one RPC endpoint). it bounds how far providers that withhold new blocks can hold policy back; leave room for `ETH_BLOCK_TAG`, as `finalized` on Ethereum mainnet is already about 13 minutes old +- `APP_AUTH_URL` - optional absolute http(s) URL of an app-authorization service (default: unset). when unset, `/authorizeApp` and `GET /app/:appId` are read from `DstackKms`. when set, `GET /app/:appId` is forwarded to this URL at the same path, as is `/authorizeApp` after the on-chain KMS policy check passes. use an absolute URL without credentials; any query or fragment is ignored. external delegates require HTTPS. a blank value is unset. see [delegated app authorization](#delegated-app-authorization) + +### Multiple RPC providers + +With one endpoint, whoever runs it decides what the KMS reads. `ETH_RPC_URLS` +and `ETH_RPC_QUORUM=n/m` make n providers have to agree instead: + +```yaml +environment: + ETH_RPC_URLS: | + https://eth-mainnet.g.alchemy.com/v2/${ALCHEMY_KEY} + https://mainnet.infura.io/v3/${INFURA_KEY} + https://ethereum-rpc.publicnode.com + ETH_RPC_QUORUM: 2/3 + ETH_MAX_BLOCK_AGE: 1800 +``` + +Each request resolves `ETH_BLOCK_TAG` to the highest block n providers have +reached, less `ETH_FINALITY_CONFIRMATIONS`, and takes that block's hash from n +providers that agree on it. Every contract read is then pinned to the hash and +answered only with a result n providers return alike. A provider that fails, +times out or reverts casts no vote, and without n votes the request fails +closed. `ETH_RPC_URL` alone is the same path with `1/1`. + +- **Choosing n/m.** Forging a read takes n colluding providers and stopping + the server takes m-n+1, so `2/3` or `3/5` tolerates one or two outages while + `n/n` stops on the first. n must be more than half of m, as otherwise two + groups of providers could each return a different answer. With `latest`, set `ETH_FINALITY_CONFIRMATIONS` to + 1 or 2 so that providers a block apart still agree. +- **Stale blocks.** The same m-n+1 providers, by lagging or by reporting an + old block, make the server read an earlier state of the chain, in which a + revoked policy is still in force. Only `ETH_MAX_BLOCK_AGE` bounds this, so + the server refuses to start with several endpoints and no such limit. The + bounds are proved in `formal/DstackFormal/Kms/RpcQuorum.lean`. +- **Choosing providers.** Use endpoints whose origin serves one chain and + nothing a customer controls. A provider that selects a chain or a + user-defined fork by path or by key lets whoever supplies the key decide what + that endpoint answers. Origins must be distinct, but two that resell the same + upstream are still one provider. +- **API keys.** The endpoint list and the quorum belong in the measured + compose file; the keys do not. `m` is stated apart from the list so that a + key cannot add an endpoint, and a key must not be able to leave its place in + the URL: in a dstack CVM, give it an `allowed_envs` spec such as + `ALCHEMY_KEY: /[A-Za-z0-9_-]{1,128}/` and deliver it through `.user-config`, + as `dstack-app/deploy-to-vmm.sh` does from the specs in its `rpc.json`. Only + the origin of an endpoint is ever logged or served by `GET /`. Redirects are + refused. +- **Cost.** Every request costs m times the RPC calls, and a provider that + hangs holds each request up for the 10-second RPC timeout. + +### Reorgs and the block tag + +Only `finalized` protects policy from reorgs. With `latest` or `safe`, a reorg +can revert any policy transaction the server has already acted on, in both +directions: + +- **Revocations roll back.** A removed OS image, compose hash or device, or a + revoked KMS measurement, is authorized again until the revocation is + re-included and the read block reaches it. +- **Activations roll back.** A root epoch activation or an app epoch increase + can disappear. Neither this server nor the KMS keeps a high-water mark: the + KMS only checks the reported epoch against its keyring's chain hash, so after + a root epoch rollback it restarts once and serves the previous epoch as + current, and apps again receive keys of their previous app epoch. + +Keys released in that window stay released. `ETH_FINALITY_CONFIRMATIONS=N` +reads N blocks behind the tagged block, so a reorg shallower than N blocks is +never observed, at the cost of delaying every policy change, revocations +included, by N more blocks. A reorg deeper than N still rolls back, so this +narrows the risk with `latest` or `safe` but does not remove it. Through Helios +on an OP-stack chain, `latest` is the sequencer's unsafe head: choose N from +how deep a reorg of that head you are willing to accept, and send emergency +revocations with that delay in mind. + +### Container image + +Tagged releases are published by the `KMS auth-eth` workflow +(`.github/workflows/kms-auth-eth.yml`): pushing the tag +`kms-auth-eth-v` builds this directory and publishes +`ghcr.io/dstack-tee/dstack-kms-auth-eth:` with a build provenance +attestation. Pull requests that touch this directory run the audit, lint and +tests and build the image without pushing it. + +The image listens on port 8000, which matches the KMS webhook default +`http://auth-api:8000`. Deploy it by digest: + +```yaml +auth-api: + image: ghcr.io/dstack-tee/dstack-kms-auth-eth:@sha256: + environment: + - ETH_RPC_URL=https://... + - KMS_CONTRACT_ADDR=0x... + - ETH_CHAIN_ID=8453 +``` + +To build it locally (the `.dockerignore` keeps the Foundry +project out of the build context): + ```bash -# Build smart contracts -forge build +docker build -t dstack-kms-auth-eth . +``` + +#### Reproducing a release image + +Use a clean checkout of the release tag and BuildKit 0.20.2, matching the +workflow. COPY permissions are fixed independently of the checkout umask. +Export with the commit timestamp and timestamp rewriting; a plain +`docker build` does not reproduce the release digest. + +```bash +docker buildx create --name auth-repro --driver docker-container \ + --driver-opt image=moby/buildkit:v0.20.2@sha256:c457984bd29f04d6acc90c8d9e717afe3922ae14665f3187e0096976fe37b1c8 + +git_revision=$(git rev-parse HEAD) +source_date_epoch=$(git show -s --format=%ct HEAD) +docker buildx build --builder auth-repro --platform linux/amd64 \ + --provenance=false \ + --build-arg "GIT_REV=$git_revision" \ + --build-arg "SOURCE_DATE_EPOCH=$source_date_epoch" \ + --label org.opencontainers.image.source=https://github.com/Dstack-TEE/dstack \ + --label "org.opencontainers.image.revision=$git_revision" \ + --label 'org.opencontainers.image.description=dstack KMS auth webhook backed by the DstackKms contract' \ + --tag ghcr.io/dstack-tee/dstack-kms-auth-eth:VERSION \ + --output type=oci,rewrite-timestamp=true,dest=/tmp/auth-eth.oci.tar . +``` + +Replace `VERSION` with the release version. These settings apply to releases +that include timestamp normalization; earlier tags used a different workflow. + +Releases before the rename were published as +`ghcr.io/dstack-tee/dstack-kms-auth-eth-bun` from `kms-auth-eth-bun-v*` tags; +those images remain available. + +### API endpoints + +#### GET / +health check and system information + +`authApiInfo` is a JSON-encoded object the KMS forwards verbatim through its +unauthenticated `GetMeta` RPC, so it carries public data only: +`kmsContractAddr`, `chainId`, `appImplementation`, `ethRpcUrl` (the origins of +the endpoints, joined by commas), `ethRpcUrls` (the same origins as an array), +`rpcQuorum` (`ETH_RPC_QUORUM`), `blockTag` +(`ETH_BLOCK_TAG`), `finalityConfirmations` (`ETH_FINALITY_CONFIRMATIONS`), +`maxBlockAge` (`ETH_MAX_BLOCK_AGE`, when set) and `policyBlockNumber` (the +block the policy was read at). + +#### POST /bootAuth/app +application boot authentication + +#### POST /bootAuth/kms +KMS boot authentication + +### Request format + +```json +{ + "tcbStatus": "string", + "advisoryIds": ["string"], + "mrAggregated": "string", + "mrSystem": "string", + "osImageHash": "string", + "appId": "string", + "composeHash": "string", + "instanceId": "string", + "deviceId": "string" +} +``` + +### Response format -# Build TypeScript server -npm run build +```json +{ + "isAllowed": boolean, + "reason": "string", + "gatewayAppId": "string" +} ``` -## Testing +### API compatibility + +this implementation keeps the API of the removed fastify + ethers server that used to live in this directory: + +- **request/response schemas**: identical to original API +- **OpenAPI specification**: available in `openapi.json` +- **comprehensive testing**: vitest test suite validates compatibility +- **backward compatibility**: supports both minimal and full BootInfo formats + +#### dstack-kms 0.6 + +dstack-kms 0.6 posts `dstack_verifier::PolicyBootInfo`: bytes as unprefixed +hex, plus `teeVariant` and `keyProviderInfo`. the legacy `/bootAuth/*` routes +drop both; `/authorizeKms` and `/authorizeApp` require `teeVariant` and pass it +to the contract unchanged, and drop `keyProviderInfo` — except that with +`APP_AUTH_URL` set, `/authorizeApp` forwards the request body unchanged to the +delegate, `keyProviderInfo` included. the KMS checks +`appId`, `composeHash` and `instanceId` widths itself before calling the webhook. the `dstack-kms 0.6 bootAuth payload` +tests pin this contract. + +#### OpenAPI specification + +the complete API specification is available in `openapi.json` and includes: +- detailed schema definitions +- request/response examples +- compatibility notes + +#### compatibility testing + +The test suite (`index.test.ts`) validates: +- ✅ request/response format compatibility +- ✅ schema validation using OpenAPI spec +- ✅ error handling behavior +- ✅ hex encoding/decoding compatibility +- ✅ optional field handling + +#### Authorization endpoints + +`POST /authorizeKms` and `POST /authorizeApp` return HTTP 200 with an `AuthorizationResult` +for policy decisions, including `authorized`, +`rejectionReason`, `gatewayAppId`, `currentRootEpoch`, `currentRootEpochHash`, `currentAppEpoch`, +`latestRootEpoch`, and `latestRootEpochHash` (the latest registered epoch, which may be pending activation). +The selected endpoint determines the policy; the backend checks that the verified +`appId` matches that scope. Optional `requestedAppEpoch` selects the app epoch; +omission uses the current app epoch, explicit zero selects epoch zero, and future +values are denied. The optional +`requestedRootEpoch` selects historical keys; omission uses the returned current +epoch, and an explicit `0` selects epoch 0. The optional `launchTicketHash` is the +hash of the launch ticket the CVM presented and is passed to the contract as +`bytes32`, zero when absent. See the +[KMS authorization protocol](../README.md#authorization-protocol) for registration, +bootstrap, and compatibility requirements. The legacy `/bootAuth/*` endpoints +remain available. + +#### Authorization operations + +`/authorizeKms` and `/authorizeApp` require an `operation` string. See the +[KMS authorization protocol](../README.md#authorization-protocol) for the names +and subject semantics. Bootstrap alone may authorize before root registration; +unknown operations are rejected. Legacy `/bootAuth/*` routes are unchanged. + +#### Delegated app authorization + +Set `APP_AUTH_URL` to keep KMS policy on `DstackKms` and let another service +decide app identity policy (registration, compose hash, app epoch). This is +for app identities that are not `DstackApp` contracts. The KMS-owned app +policy stays on chain: before forwarding `POST /authorizeApp`, this server +calls `DstackKms.checkKmsAppPolicy` at the request's pinned block and denies +on a non-empty answer. Leave `APP_AUTH_URL` unset to keep the chain path. + +Only configure a delegate you trust to make app authorization decisions. +External delegates require HTTPS. Use HTTP only inside the KMS CVM: on +loopback (`localhost`, IPv4 `127.0.0.0/8`, or IPv6 `::1`) or with a +single-label hostname that resolves to a service in the same Compose project, +for example `APP_AUTH_URL=http://app-auth:3000`. + +When it is set: + +- `POST /authorizeApp` forwards the request body byte for byte, including + fields this server does not interpret. `launchTicketHash` passes through, and + so does a future top-level `userConfigHash` (lowercase hex, no `0x` prefix, + app operations only). The delegate returns `authorized`, `rejectionReason`, + and `currentAppEpoch`. This server overwrites `gatewayAppId`, + `currentRootEpoch`, `currentRootEpochHash`, `latestRootEpoch`, and + `latestRootEpochHash` with values read from `DstackKms` at the request's + pinned block, using the same block-selection policy as `GET /`. +- The delegate must authorize the gateway app too, because the gateway CVM's `/authorizeApp` requests are delegated. +- A `checkKmsAppPolicy` rejection is denied without calling the delegate: a + KMS operation posted to `/authorizeApp` (`Invalid authorization operation`), + no registered root epoch (`Root epoch not registered`), a + `requestedRootEpoch` newer than the current one (`Requested root epoch is + not active`), an OS image outside the allowlist of the selected epoch + (`OS image is not allowed`), or a disallowed TEE variant + (`TEE variant not allowed`). +- A chain policy rejection or a valid delegate denial is HTTP 200 with + `authorized: false` and the chain root fields. +- A delegate transport error, timeout (20s for the delegate call), non-2xx + response, or invalid answer is HTTP 503. The response includes neither the + chain root fields nor the delegate's error body. The KMS's 60s webhook + budget also covers the preceding chain reads. If the chain cannot be read, + the route returns 503 without calling the delegate. +- `GET /app/:appId` is forwarded to the same path. The app id is checked before + it is placed in the URL. A delegate failure is 503; this server does not + invent epoch 0. The chain's `latest` read for this route applies only when + `APP_AUTH_URL` is unset. +- `POST /authorizeKms`, `GET /`, and `GET /sevSnpTcbRequirements` stay on chain. + +`POST /bootAuth/app` also stays on chain. Only KMS builds before 0.6.4 call it +in production, and its response has no root-epoch fields to reconcile with a +delegate. A delegated deployment must be used with a KMS that calls +`/authorizeApp`. Do not point an older KMS at `APP_AUTH_URL`: its app boots +would still be judged by `DstackKms`. + +This server does not follow delegate redirects. + +## Contracts + +### Prerequisites + +- [Foundry](https://book.getfoundry.sh/getting-started/installation) - For smart contract development and testing +- Node.js/npx - Only for `@openzeppelin/upgrades-core`, which the upgrade-safety tests run through `npx` with `--ffi` + +### Setup -### Smart contract tests (Foundry) ```bash -forge test --ffi +# Fetch the Foundry dependencies (git submodules under lib/) +git submodule update --init --recursive lib/forge-std \ + lib/openzeppelin-contracts-upgradeable lib/openzeppelin-foundry-upgrades + +# Fetch the OpenZeppelin upgrade-safety validator that `forge test --ffi` runs +# through npx. Do not `npm install` it here: package.json belongs to the Bun +# webhook server. +npx --yes @openzeppelin/upgrades-core@^1.37.0 --help > /dev/null + +# Build the contracts +forge build ``` -### BootAuth server tests (Jest) +### Testing + ```bash -npm test +# Run `forge clean` first: stale build-info files make the upgrade validator +# report the same contract twice. +forge clean +forge test --ffi ``` -### Local integration testing +### Local chain + +To try the contracts together with the webhook server, deploy them to a local +Anvil node and point the webhook server at the proxy: + ```bash -# Quick test workflow — spins up Anvil, deploys, runs Jest + Foundry against the live chain -npm run test:all +# Terminal 1: local node +anvil + +# Terminal 2: deploy with Anvil's first prefunded account; the output prints +# "DstackKms proxy deployed to: 0x..." +PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 \ + forge script script/Deploy.s.sol:DeployScript --broadcast --rpc-url http://127.0.0.1:8545 -# Step-by-step workflow -npm run test:setup # Start Anvil and deploy contracts -npm run test:run # Run tests against deployed contracts -npm run test:cleanup # Stop all test processes +# Terminal 3: webhook server. Anvil finalizes 64 blocks behind its head, so read +# at the latest block. +bun install +ETH_RPC_URL=http://127.0.0.1:8545 ETH_BLOCK_TAG=latest KMS_CONTRACT_ADDR=0x... PORT=8000 \ + bun index.ts ``` -## Contract Management +### Contract Management Use Foundry scripts for all contract operations instead of Cast commands: -### Deployment +#### Deployment ```bash # Deploy both contracts forge script script/Deploy.s.sol:DeployScript --broadcast --rpc-url http://localhost:8545 @@ -69,7 +421,7 @@ forge script script/Deploy.s.sol:DeployScript --broadcast --rpc-url http://local forge script script/Deploy.s.sol:DeployScript --broadcast --rpc-url --private-key ``` -### Management Operations +#### Management Operations ```bash # Add KMS aggregated MR KMS_CONTRACT_ADDR=0x... MR_AGGREGATED=0x1234... \ @@ -80,7 +432,7 @@ KMS_CONTRACT_ADDR=0x... APP_OWNER=0x... \ forge script script/Manage.s.sol:DeployApp --broadcast --rpc-url $RPC_URL ``` -### Query Operations +#### Query Operations ```bash # Get KMS settings KMS_CONTRACT_ADDR=0x... \ @@ -91,7 +443,7 @@ APP_CONTRACT_ADDR=0x... DEVICE_ID=0x1234... \ forge script script/Query.s.sol:CheckAppDevice --rpc-url $RPC_URL ``` -### Safe Upgrades +#### Safe Upgrades ```bash # Upgrade KMS to V2 KMS_CONTRACT_ADDR=0x... \ @@ -100,55 +452,46 @@ forge script script/Upgrade.s.sol:UpgradeKmsToV2 --broadcast --rpc-url $RPC_URL See `script/README.md` for complete documentation of all available scripts. -## BootAuth Server - -The project includes a Fastify-based HTTP server for TEE boot validation: - -### Endpoints -- **`GET /`** - Health check and contract information -- **`POST /bootAuth/app`** - Validate application boot information -- **`POST /bootAuth/kms`** - Validate KMS boot information - -### Configuration -Set these environment variables: -- **`ETH_RPC_URL`** - Ethereum RPC endpoint (default: `http://localhost:8545`) -- **`KMS_CONTRACT_ADDR`** - Deployed DstackKms contract address -- **`PORT`** - Server port (default: `8000`) -- **`HOST`** - Server host (default: `127.0.0.1`) +#### Epoch-scoped material approvals -### Running the Server -```bash -# Development mode -npm run dev - -# Production mode -npm run build && npm start +Material approvals use exact root/app epoch rows; neither older nor newer rows +are implicitly authorized. Material setters name their rows: `*AtEpochs` a +range, and in `DstackApp` `*AtEpoch` one row; `DstackApp` reports them as +`IAppEpochManagement`. +The management scripts take `ROOT_EPOCH`/`APP_EPOCH`, or +`FROM_ROOT_EPOCH`/`TO_ROOT_EPOCH` and `FROM_APP_EPOCH`/`TO_APP_EPOCH`, and use +the epoch-less setters of app policies predating app epochs. Original bool mappings and events remain epoch-zero views after +upgrading; epoch-specific getters/events describe the new rows. KMS keyring +handover separately checks its highest exported root epoch, which authorizes the +whole keyring. See [epoch-scoped allowlists](../../../docs/app-key-epochs.md#epoch-scoped-allowlists) +for migration, upgrade order and compatibility. -# Test the server -npm test -``` +### Static Analysis & Symbolic Verification -## Static Analysis & Symbolic Verification (local only) - -We run [Slither](https://github.com/crytic/slither) and -[Halmos](https://github.com/a16z/halmos) locally during development. They -are intentionally not part of CI — symbolic proofs are slow, sensitive to -solver versions, and most valuable as an interactive design check rather -than a gate. +We run [Slither](https://github.com/crytic/slither) locally during +development. [Halmos](https://github.com/a16z/halmos) also runs in CI +(`.github/workflows/halmos.yml`, pinned Halmos and Forge versions) whenever +this directory changes. ```bash pipx install slither-analyzer halmos slither . halmos --contract DstackAppSymbolicTest +halmos --contract DstackAppEpochSymbolicTest halmos --contract DstackKmsSymbolicTest +halmos --contract DstackKmsEpochSymbolicTest ``` +Forge 1.8 enables `dynamic_test_linking` by default, which compiles `new` in +tests to `vm.deployCode`, a cheat code Halmos 0.3.3 does not support. Disable +it for Halmos runs with `FOUNDRY_DYNAMIC_TEST_LINKING=false`. + Configuration lives in `slither.config.json` and `foundry.toml`. See `docs/formal-verification.md` for the verification roadmap, what each symbolic property proves, and the deeper-verification plan for a future audit-firm engagement. -## Additional Commands +### Additional Commands ```bash # Format code diff --git a/dstack/kms/auth-eth/TESTING.md b/dstack/kms/auth-eth/TESTING.md deleted file mode 100644 index 40398cef5c..0000000000 --- a/dstack/kms/auth-eth/TESTING.md +++ /dev/null @@ -1,47 +0,0 @@ -# Testing Guide - -## Smart Contract Testing - -```bash -forge test --ffi -``` - -## API Server Testing - -### Unit Tests -```bash -npm test # Jest, mocked Ethereum backend -``` - -### Integration Tests -```bash -npm run test:all # Complete: Anvil + Deploy + API tests + Cleanup -``` - -This automatically: -1. Starts Anvil node -2. Deploys contracts -3. Starts API server -4. Tests all endpoints -5. Cleans up - -## Manual Testing - -### Start Services -```bash -npm run test:setup # Start Anvil and deploy contracts -npm run dev # Start API server in development mode -``` - -### Test Endpoints -```bash -curl http://127.0.0.1:8000/ # Health check -curl -X POST http://127.0.0.1:8000/bootAuth/app \ - -H "Content-Type: application/json" \ - -d '{"tcbStatus":"UpToDate","advisoryIds":[],"mrAggregated":"0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef","osImageHash":"0xabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcd"}' -``` - -### Cleanup -```bash -npm run test:cleanup # Stop all test processes -``` diff --git a/dstack/kms/auth-eth/bun.lock b/dstack/kms/auth-eth/bun.lock new file mode 100644 index 0000000000..736936e3c0 --- /dev/null +++ b/dstack/kms/auth-eth/bun.lock @@ -0,0 +1,233 @@ +{ + "lockfileVersion": 1, + "configVersion": 0, + "workspaces": { + "": { + "name": "auth-eth", + "dependencies": { + "@hono/zod-validator": "0.9.1", + "hono": "4.13.16", + "viem": "2.57.5", + "zod": "4.6.7", + }, + "devDependencies": { + "@types/bun": "1.4.2", + "@types/node": "24.19.2", + "oxlint": "1.88.0", + "typescript": "5.9.3", + "vite": "8.3.3", + "vitest": "5.0.4", + }, + }, + }, + "overrides": { + "source-map-js": "1.2.2", + }, + "packages": { + "@adraffy/ens-normalize": ["@adraffy/ens-normalize@1.11.0", "", {}, "sha512-/3DDPKHqqIqxUULp8yP4zODUY1i+2xvVWsv8A79xGWdCAG+8sb0hRh0Rk2QyOJUnnbyPUAZYcpBuRe3nS2OIUg=="], + + "@hono/zod-validator": ["@hono/zod-validator@0.9.1", "", { "peerDependencies": { "hono": ">=4.11.2", "zod": "^3.25.0 || ^4.0.0" } }, "sha512-iiv6w0qrIc0arfvCtUqBWsvl4fXjzaTcQcCJTTtCnkawF9HHGE+KjEl0ox3gQJ6rKZEgE3mLExlQCF72M+mNuw=="], + + "@jridgewell/resolve-uri": ["@jridgewell/resolve-uri@3.1.2", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="], + + "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.6.0", "", {}, "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw=="], + + "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="], + + "@noble/ciphers": ["@noble/ciphers@1.3.0", "", {}, "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw=="], + + "@noble/curves": ["@noble/curves@1.9.1", "", { "dependencies": { "@noble/hashes": "1.8.0" } }, "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA=="], + + "@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], + + "@oxc-project/types": ["@oxc-project/types@0.155.0", "", {}, "sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q=="], + + "@oxlint/binding-android-arm-eabi": ["@oxlint/binding-android-arm-eabi@1.88.0", "", { "os": "android", "cpu": "arm" }, "sha512-k6Fgkf86ubfeH4GvqYsRolfuVAp0pfYVZvifSlXNHPdMaWUOfxUrmLEeDD7hF6U2oJuhsVxhSWq86/xCJ+9MmA=="], + + "@oxlint/binding-android-arm64": ["@oxlint/binding-android-arm64@1.88.0", "", { "os": "android", "cpu": "arm64" }, "sha512-AsIyhl9o1ejwtac7NMbhKpMdSml6NWR0ljKjZERxC8OHYDAW8o/Om9n1QHVLi4VCEUo42Zte2/Op9kyoGpJZMg=="], + + "@oxlint/binding-darwin-arm64": ["@oxlint/binding-darwin-arm64@1.88.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-qgBjB7eEKcCB4RqjXGuoSZq74g0wD09fWFJ+HWcCJcKaga8TeUHtb+BY0SsxdleSLBgx4RZ7qmgo0EzqEq7JoQ=="], + + "@oxlint/binding-darwin-x64": ["@oxlint/binding-darwin-x64@1.88.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-sCz3X5Mw/xdzEzn4fsCt1Iq8NKJnGNfhR+b9B5k+4DysYAHsmIhYoocnBPiQ9kvY3+pUun2A0Z8Vtun/Nv6YoQ=="], + + "@oxlint/binding-freebsd-x64": ["@oxlint/binding-freebsd-x64@1.88.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-xTOdYOIqCufgIj0knvxu86FBfovP6QBiD7ngNva01gb8xPQCD5gXkE5APGczH35zStim1O3zqvFbLQmY85xXRg=="], + + "@oxlint/binding-linux-arm-gnueabihf": ["@oxlint/binding-linux-arm-gnueabihf@1.88.0", "", { "os": "linux", "cpu": "arm" }, "sha512-BLadtw88NdYJBrAtC1dYzrPfSP2d5zgx6iuZycdD0YmZBJ2Nqbit9Z4PSaIb6gxK25dweArGMPbOmq/0ugwUPg=="], + + "@oxlint/binding-linux-arm-musleabihf": ["@oxlint/binding-linux-arm-musleabihf@1.88.0", "", { "os": "linux", "cpu": "arm" }, "sha512-wILSczl/DaZsCcf7j7tvNbssp8hxEHIJxrv4j7+JjI3TAL1U/JTWbeUtoJJC/vo8+2hkTmHLYoKJjmiNbijdXw=="], + + "@oxlint/binding-linux-arm64-gnu": ["@oxlint/binding-linux-arm64-gnu@1.88.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-jutT2Hy8JCuZuMwIFHo2HtyxfOfBJHyQxlBHBK1SL9W2f8n/WhjAP0FnDMz9d/mjhv9+QA0mx5AdQ9fDjsrFFg=="], + + "@oxlint/binding-linux-arm64-musl": ["@oxlint/binding-linux-arm64-musl@1.88.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-8N8iGV9hh4Lkeuq7QsEkjoXNRRflqR1G2qyoGYXcA0k5qllrdqmfylKEXyHIVERxqNDyMO4StqDQ0uLxXcBQAg=="], + + "@oxlint/binding-linux-ppc64-gnu": ["@oxlint/binding-linux-ppc64-gnu@1.88.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-5ydcQt3znNQ/rGEWYRvpS2cK9+T18P2VYgnyJ+eloEAwi9YUmsXy5VGrRqNWIK6qzWwHGnEE3ojVqqQNo+f0hA=="], + + "@oxlint/binding-linux-riscv64-gnu": ["@oxlint/binding-linux-riscv64-gnu@1.88.0", "", { "os": "linux", "cpu": "none" }, "sha512-iGx0uvFT54b/5DPJdEBCxYIrVB3v0uTy+JhRh3CyEp8/22BXDkG8rffkFwREdLsdj9mOrPbJYVOZw8ipcBuzjw=="], + + "@oxlint/binding-linux-riscv64-musl": ["@oxlint/binding-linux-riscv64-musl@1.88.0", "", { "os": "linux", "cpu": "none" }, "sha512-Wt47mKMWelVjRjuR7BCFxXkB0m79K1sTEbqMHRWciKUgo5iv7sWsF4RXSOyFYHD9zerNrkRZblnN273rhwOA1Q=="], + + "@oxlint/binding-linux-s390x-gnu": ["@oxlint/binding-linux-s390x-gnu@1.88.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-g3L12KCS4+1gtUt3RbJ4F+Yxx4LNmmZLEPfhd8rAHEJjJk2lAgNfnjGoP/phJyhG5WS6VbNYbJtadJelNfvTMA=="], + + "@oxlint/binding-linux-x64-gnu": ["@oxlint/binding-linux-x64-gnu@1.88.0", "", { "os": "linux", "cpu": "x64" }, "sha512-og/XHVDOD9ZJgRiZkT9DgzQd4sr+JZW7e4l17Q/jVMZiIbeEd4uIu9iAoUbTF1gIvVZoRc4QDOxyVUvQGp4WHg=="], + + "@oxlint/binding-linux-x64-musl": ["@oxlint/binding-linux-x64-musl@1.88.0", "", { "os": "linux", "cpu": "x64" }, "sha512-EmhBsp+xuKb6YbZNEMLBo80Xw71AZOIm18do8ni/GLX/Lw1XzNhVYpbxO1KasYtoAvrGtCOdCPULRlIE0bPbTQ=="], + + "@oxlint/binding-openharmony-arm64": ["@oxlint/binding-openharmony-arm64@1.88.0", "", { "os": "none", "cpu": "arm64" }, "sha512-DBUcx/KwYdg1DAz+G01P/GFv512J04EsZadbHptx2FTpWT/MWRg21ZToNHt9pnsfQRBQ3et/g+vqzbvrdAVbuA=="], + + "@oxlint/binding-win32-arm64-msvc": ["@oxlint/binding-win32-arm64-msvc@1.88.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-xeVd0n4XG5HvynxfYvXi6uB+JvZbVZataowPS8cYpMbYg9mwE4sSyElFQd4LVJFifq8bRLDSR18XgEildmcXAg=="], + + "@oxlint/binding-win32-ia32-msvc": ["@oxlint/binding-win32-ia32-msvc@1.88.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-MA6iOw//amleaz2mVMsZrA7NHlEexjTrhIxSMFCXQi6IUuQO+3Od00GZhr2iCYw6RFzMW36jkKK/WHBXMsoQAw=="], + + "@oxlint/binding-win32-x64-msvc": ["@oxlint/binding-win32-x64-msvc@1.88.0", "", { "os": "win32", "cpu": "x64" }, "sha512-3Sz6rVWe8Dy+ufsXurFN1GX2dX43F/lQMSLelK9gFjiba7nHvLlqlhR5cHlWVnCpSqUY1hN9pyCX9XToe6ve6g=="], + + "@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.15", "", { "os": "android", "cpu": "arm" }, "sha512-aLcgK9gIJ3YRvrrtfSBbRa27F5WrpiTaPulnFpsHPxpUHgFlSgnU4854MHwoRGEBhfRJDWCS2WQ7lIjskE9Olw=="], + + "@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.2.15", "", { "os": "android", "cpu": "arm64" }, "sha512-xD7DdZCrbThKuxNg7ooQmvp07ys4J/pnSEMTG3/OdOWl6daC67m/Q4fL78sRHMxTH/N4fGUbYhcPM0MF5WFHkg=="], + + "@rolldown/binding-darwin-arm64": ["@rolldown/binding-darwin-arm64@1.2.15", "", { "os": "darwin", "cpu": "arm64" }, "sha512-m2WuQ6r0B4OTYxyPpNLtXaMRbRDUbG8YQV2Q3KTdSSK8Th6KHCnC8jVCJt8bvYeSB5WivkkNbc85mKadaSdOxA=="], + + "@rolldown/binding-darwin-x64": ["@rolldown/binding-darwin-x64@1.2.15", "", { "os": "darwin", "cpu": "x64" }, "sha512-5RtnsHM36nodM9WbMy+zip0LGS/G+y5wro5RHrpOlr4ac24+1zSi9kiV2MP1myZeZ/ifEHfulQcWjnAXzc2C2A=="], + + "@rolldown/binding-freebsd-x64": ["@rolldown/binding-freebsd-x64@1.2.15", "", { "os": "freebsd", "cpu": "x64" }, "sha512-g3l09pyFqhu+135JKkbkwiKGQmwU5hUMUPJ4VdBADvuqR8d33L6H578rh8m7rtxbdp+VmX/+nzI7nvhSZlzpUQ=="], + + "@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/binding-linux-arm-gnueabihf@1.2.15", "", { "os": "linux", "cpu": "arm" }, "sha512-nIe3VugI97nGQtspPxDqA4sXMUpeiocKIP/CqpY/u/vgbT+alX+cVxu1C/oVBPKg4feNTmYovE91v4DgXvXNwQ=="], + + "@rolldown/binding-linux-arm64-gnu": ["@rolldown/binding-linux-arm64-gnu@1.2.15", "", { "os": "linux", "cpu": "arm64" }, "sha512-iTBjXx+B5QSvgI89lJfmqh4wTh8NabR1YZIIN3hNx4zSG0EVfVqkOvLulNpG4251pbd6/IAmZ/LefVk1Y4rPhw=="], + + "@rolldown/binding-linux-arm64-musl": ["@rolldown/binding-linux-arm64-musl@1.2.15", "", { "os": "linux", "cpu": "arm64" }, "sha512-uN26XOnVR7rqQupG3V9oAG2EGGatWjcJHOeDOHUFCh4TBWmP2tHTFoVN13aYbwfm0aHqJAEmcwhAu6sooIjfqQ=="], + + "@rolldown/binding-linux-ppc64-gnu": ["@rolldown/binding-linux-ppc64-gnu@1.2.15", "", { "os": "linux", "cpu": "ppc64" }, "sha512-9nWkcdd+H+XhaA3fQIwpHnKIrfx/PQ6rO0pivr78Og07tXlUlctBBJoEYLPfhTmCR/QxEVdn6uPjHV5SymPhdw=="], + + "@rolldown/binding-linux-s390x-gnu": ["@rolldown/binding-linux-s390x-gnu@1.2.15", "", { "os": "linux", "cpu": "s390x" }, "sha512-Ggh0ciFjLwIusLSLz7LZYEaGdxOAUJXI+Qu5JCbhPJJHEt8vP+IjRATTJheiJsdzzTYgUiHUiw3X1Ea3ZpMBdA=="], + + "@rolldown/binding-linux-x64-gnu": ["@rolldown/binding-linux-x64-gnu@1.2.15", "", { "os": "linux", "cpu": "x64" }, "sha512-FHg60rS6DBePAYZ9X9F67x+JObFdmgn6tupA1C/a3B+CufFmTD4mX+e8M75tCiAO3foR/6xwVBI0KQiI7sn/rw=="], + + "@rolldown/binding-linux-x64-musl": ["@rolldown/binding-linux-x64-musl@1.2.15", "", { "os": "linux", "cpu": "x64" }, "sha512-/cvV/7v5VGz/moiz0XKRj2dE8DzsKyhIu1KpOvJGPjRywg3yscON889UGvAe8zfiJLHup7VLjBduoGWi3HusWQ=="], + + "@rolldown/binding-openharmony-arm64": ["@rolldown/binding-openharmony-arm64@1.2.15", "", { "os": "none", "cpu": "arm64" }, "sha512-MyzC5Hrv/sm+Z7TSGKP/j8001RO2xQm1zOpCNVL4j0cY/VhBZviludA2YFQ7i4lH6ZAXxQm0lcMdBzM+99mE7w=="], + + "@rolldown/binding-win32-arm64-msvc": ["@rolldown/binding-win32-arm64-msvc@1.2.15", "", { "os": "win32", "cpu": "arm64" }, "sha512-+PgYiS+AH5omy6L45ZLxybasauJaj3M8buoT83D+nzPmCayXlxUV9hydhciCKVyIg0B/v0BtXPDE1uGqNwCPpg=="], + + "@rolldown/binding-win32-x64-msvc": ["@rolldown/binding-win32-x64-msvc@1.2.15", "", { "os": "win32", "cpu": "x64" }, "sha512-HFZd2QNQYn1JbIi+Hpd7H+r/lkWxcfIu28nirZ6eCn2LafuvmExMlb/P96Sfx5tf7pPArw39IdhmCF8vmV+NhQ=="], + + "@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.1", "", {}, "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw=="], + + "@scure/base": ["@scure/base@1.2.6", "", {}, "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg=="], + + "@scure/bip32": ["@scure/bip32@1.7.0", "", { "dependencies": { "@noble/curves": "~1.9.0", "@noble/hashes": "~1.8.0", "@scure/base": "~1.2.5" } }, "sha512-E4FFX/N3f4B80AKWp5dP6ow+flD1LQZo/w8UnLGYZO674jS6YnYeepycOOksv+vLPSpgN35wgKgy+ybfTb2SMw=="], + + "@scure/bip39": ["@scure/bip39@1.6.0", "", { "dependencies": { "@noble/hashes": "~1.8.0", "@scure/base": "~1.2.5" } }, "sha512-+lF0BbLiJNwVlev4eKelw1WWLaiKXw7sSl8T6FvBlWkdX+94aGJ4o8XjUdlyhTCjd8c+B3KT3JfS8P0bLRNU6A=="], + + "@types/bun": ["@types/bun@1.4.2", "", { "dependencies": { "bun-types": "1.4.2" } }, "sha512-GimotNn7+ZV0uVArItBbriZsR1oNf0+WTzPkdcFrzShI7k2norL0uzEaJT8T33dWr7O/c9ZDuAFQrctKCi72oQ=="], + + "@types/chai": ["@types/chai@5.2.3", "", { "dependencies": { "@types/deep-eql": "*", "assertion-error": "^2.0.1" } }, "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="], + + "@types/deep-eql": ["@types/deep-eql@4.0.2", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="], + + "@types/estree": ["@types/estree@1.0.8", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="], + + "@types/node": ["@types/node@24.19.2", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ=="], + + "@vitest/mocker": ["@vitest/mocker@5.0.4", "", { "dependencies": { "@jridgewell/trace-mapping": "0.3.31", "@vitest/spy": "5.0.4", "estree-walker": "^3.0.3", "magic-string": "^1.4.3" }, "peerDependencies": { "msw": "^2.4.9 || ^3.0.0", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["msw", "vite"] }, "sha512-tqAlrYWce4iUxhr3ncNohejtCTOcHeE8XWrSNZY3OhPoDn01yeGv+gnaBy64ATp7o6pb03eIbBAjzmibpc9vIQ=="], + + "@vitest/spy": ["@vitest/spy@5.0.4", "", {}, "sha512-MZKk/gSkm2q+ICobMxCpH1mA+cCAWm8WV7UhxlqGjq/sJ3AGc1BqFOs5CRVXxH78wQtme9q/NAAgBquj4AcyMw=="], + + "abitype": ["abitype@1.2.3", "", { "peerDependencies": { "typescript": ">=5.0.4", "zod": "^3.22.0 || ^4.0.0" }, "optionalPeers": ["typescript", "zod"] }, "sha512-Ofer5QUnuUdTFsBRwARMoWKOH1ND5ehwYhJ3OJ/BQO+StkwQjHw0XyVh4vDttzHB7QOFhPHa/o413PJ82gU/Tg=="], + + "assertion-error": ["assertion-error@2.0.1", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="], + + "bun-types": ["bun-types@1.4.2", "", { "dependencies": { "@types/node": "*" } }, "sha512-bxV1FgK7yBIzjRe5zBozIM4Bem11ZJcCXSrjWRG3YWLt8yFDePu4cLjpebO8OvPeIE9trbyPF4fuj3Cia4Fj3w=="], + + "chai": ["chai@6.3.0", "", {}, "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg=="], + + "detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], + + "es-module-lexer": ["es-module-lexer@2.3.2", "", {}, "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw=="], + + "estree-walker": ["estree-walker@3.0.3", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="], + + "eventemitter3": ["eventemitter3@5.0.1", "", {}, "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA=="], + + "expect-type": ["expect-type@1.4.0", "", {}, "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA=="], + + "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], + + "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], + + "hono": ["hono@4.13.16", "", {}, "sha512-AOLOEhvrV+iH92xXCnFr/5+3KjPKcI3xP63XJtX5spAnkznPdHijlIsUTpi7/9EhWqrTCekw5c5zh1K+YsVw7A=="], + + "isows": ["isows@1.0.7", "", { "peerDependencies": { "ws": "*" } }, "sha512-I1fSfDCZL5P0v33sVqeTDSpcstAg/N+wF5HS033mogOVIp4B+oHC7oOCsA3axAbBSGTJ8QubbNmnIRN/h8U7hg=="], + + "lightningcss": ["lightningcss@1.33.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.33.0", "lightningcss-darwin-arm64": "1.33.0", "lightningcss-darwin-x64": "1.33.0", "lightningcss-freebsd-x64": "1.33.0", "lightningcss-linux-arm-gnueabihf": "1.33.0", "lightningcss-linux-arm64-gnu": "1.33.0", "lightningcss-linux-arm64-musl": "1.33.0", "lightningcss-linux-x64-gnu": "1.33.0", "lightningcss-linux-x64-musl": "1.33.0", "lightningcss-win32-arm64-msvc": "1.33.0", "lightningcss-win32-x64-msvc": "1.33.0" } }, "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA=="], + + "lightningcss-android-arm64": ["lightningcss-android-arm64@1.33.0", "", { "os": "android", "cpu": "arm64" }, "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg=="], + + "lightningcss-darwin-arm64": ["lightningcss-darwin-arm64@1.33.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg=="], + + "lightningcss-darwin-x64": ["lightningcss-darwin-x64@1.33.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ=="], + + "lightningcss-freebsd-x64": ["lightningcss-freebsd-x64@1.33.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg=="], + + "lightningcss-linux-arm-gnueabihf": ["lightningcss-linux-arm-gnueabihf@1.33.0", "", { "os": "linux", "cpu": "arm" }, "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ=="], + + "lightningcss-linux-arm64-gnu": ["lightningcss-linux-arm64-gnu@1.33.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg=="], + + "lightningcss-linux-arm64-musl": ["lightningcss-linux-arm64-musl@1.33.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ=="], + + "lightningcss-linux-x64-gnu": ["lightningcss-linux-x64-gnu@1.33.0", "", { "os": "linux", "cpu": "x64" }, "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg=="], + + "lightningcss-linux-x64-musl": ["lightningcss-linux-x64-musl@1.33.0", "", { "os": "linux", "cpu": "x64" }, "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw=="], + + "lightningcss-win32-arm64-msvc": ["lightningcss-win32-arm64-msvc@1.33.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA=="], + + "lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.33.0", "", { "os": "win32", "cpu": "x64" }, "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA=="], + + "magic-string": ["magic-string@1.4.3", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0" } }, "sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ=="], + + "nanoid": ["nanoid@3.3.19", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug=="], + + "obug": ["obug@3.0.0", "", {}, "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw=="], + + "ox": ["ox@0.14.56", "", { "dependencies": { "@adraffy/ens-normalize": "^1.11.0", "@noble/ciphers": "^1.3.0", "@noble/curves": "1.9.1", "@noble/hashes": "^1.8.0", "@scure/bip32": "^1.7.0", "@scure/bip39": "^1.6.0", "abitype": "^1.2.3", "eventemitter3": "5.0.1" }, "peerDependencies": { "typescript": ">=5.4.0" }, "optionalPeers": ["typescript"] }, "sha512-Feinlj+deWEam6RIwurRE+eHZ2N3hoUb3AAjQ10BmxRCYIymfqNkv0eZ+4ln4GkgDmSGLD2rGtTMqsFYSVDC6w=="], + + "oxlint": ["oxlint@1.88.0", "", { "optionalDependencies": { "@oxlint/binding-android-arm-eabi": "1.88.0", "@oxlint/binding-android-arm64": "1.88.0", "@oxlint/binding-darwin-arm64": "1.88.0", "@oxlint/binding-darwin-x64": "1.88.0", "@oxlint/binding-freebsd-x64": "1.88.0", "@oxlint/binding-linux-arm-gnueabihf": "1.88.0", "@oxlint/binding-linux-arm-musleabihf": "1.88.0", "@oxlint/binding-linux-arm64-gnu": "1.88.0", "@oxlint/binding-linux-arm64-musl": "1.88.0", "@oxlint/binding-linux-ppc64-gnu": "1.88.0", "@oxlint/binding-linux-riscv64-gnu": "1.88.0", "@oxlint/binding-linux-riscv64-musl": "1.88.0", "@oxlint/binding-linux-s390x-gnu": "1.88.0", "@oxlint/binding-linux-x64-gnu": "1.88.0", "@oxlint/binding-linux-x64-musl": "1.88.0", "@oxlint/binding-openharmony-arm64": "1.88.0", "@oxlint/binding-win32-arm64-msvc": "1.88.0", "@oxlint/binding-win32-ia32-msvc": "1.88.0", "@oxlint/binding-win32-x64-msvc": "1.88.0" }, "peerDependencies": { "oxlint-tsgolint": ">=7.0.2003", "vite-plus": "*" }, "optionalPeers": ["oxlint-tsgolint", "vite-plus"], "bin": { "oxlint": "bin/oxlint" } }, "sha512-uIcFgw8BmqvFRGzH5+r7d2zJMEexwNSrEmM6WQNnGh3VkO0XYTEFoyxyNE6tjKMUib9Cue4XJA2DoWruO5D6aw=="], + + "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], + + "picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="], + + "postcss": ["postcss@8.5.28", "", { "dependencies": { "nanoid": "^3.3.18", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A=="], + + "rolldown": ["rolldown@1.2.15", "", { "dependencies": { "@oxc-project/types": "=0.155.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm-eabi": "1.2.15", "@rolldown/binding-android-arm64": "1.2.15", "@rolldown/binding-darwin-arm64": "1.2.15", "@rolldown/binding-darwin-x64": "1.2.15", "@rolldown/binding-freebsd-x64": "1.2.15", "@rolldown/binding-linux-arm-gnueabihf": "1.2.15", "@rolldown/binding-linux-arm64-gnu": "1.2.15", "@rolldown/binding-linux-arm64-musl": "1.2.15", "@rolldown/binding-linux-ppc64-gnu": "1.2.15", "@rolldown/binding-linux-s390x-gnu": "1.2.15", "@rolldown/binding-linux-x64-gnu": "1.2.15", "@rolldown/binding-linux-x64-musl": "1.2.15", "@rolldown/binding-openharmony-arm64": "1.2.15", "@rolldown/binding-win32-arm64-msvc": "1.2.15", "@rolldown/binding-win32-x64-msvc": "1.2.15" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-6odND+fel5zVw3I4Yc2e69gvguDnX0CAAGiNDZSq4ik5WUcaLrkD2GLuog0XcODbor31hZ5ayEMgVDno+KPV5g=="], + + "source-map-js": ["source-map-js@1.2.2", "", {}, "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw=="], + + "std-env": ["std-env@4.3.0", "", {}, "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag=="], + + "tinybench": ["tinybench@6.2.2", "", {}, "sha512-nIZ2N2dFpjBsg2hgitKu7mA+FvsIJuGJOwysRngmVRRmWgR/UyPjwJj8c/fT/dhm8EkHnF5EOogRf+0Z2qrimA=="], + + "tinyexec": ["tinyexec@1.3.1", "", {}, "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA=="], + + "tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="], + + "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], + + "undici-types": ["undici-types@7.24.6", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="], + + "viem": ["viem@2.57.5", "", { "dependencies": { "@noble/curves": "1.9.1", "@noble/hashes": "1.8.0", "@scure/bip32": "1.7.0", "@scure/bip39": "1.6.0", "abitype": "1.2.3", "isows": "1.0.7", "ox": "0.14.56", "ws": "8.21.0" }, "peerDependencies": { "typescript": ">=5.0.4" }, "optionalPeers": ["typescript"] }, "sha512-BaUdS5lJJTxr6hJX17K0AjHbgUhsolsqH8CCbTq1WMunW/I/Siwc9VrTwccCcNPppgqa/gY4TqK8Zl8LLmlTlw=="], + + "vite": ["vite@8.3.3", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", "postcss": "^8.5.28", "rolldown": "~1.2.11", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.7.1", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-cTAldKPImjg6c+gk48U19POPn3GCBzZwpdsN8ZMEEcbpes+6/wvfqUd0C2y3qYY4wsj8PwgFwrZ/1jBPVttMSg=="], + + "vitest": ["vitest@5.0.4", "", { "dependencies": { "@types/chai": "^5.2.2", "@vitest/mocker": "5.0.4", "chai": "^6.3.0", "es-module-lexer": "^2.3.2", "expect-type": "^1.4.0", "magic-string": "^1.4.3", "obug": "^3.0.0", "picomatch": "^4.0.7", "std-env": "^4.3.0", "tinybench": "^6.2.2", "tinyexec": "^1.3.1", "tinyglobby": "^0.2.17", "why-is-node-running": "3.2.1" }, "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^22.0.0 || >=24.0.0", "@vitest/browser-playwright": "5.0.4", "@vitest/browser-preview": "5.0.4", "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", "@vitest/coverage-istanbul": "5.0.4", "@vitest/coverage-v8": "5.0.4", "@vitest/ui": "5.0.4", "happy-dom": "*", "jsdom": "*", "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["@edge-runtime/vm", "@opentelemetry/api", "@types/node", "@vitest/browser-playwright", "@vitest/browser-preview", "@vitest/browser-webdriverio", "@vitest/coverage-istanbul", "@vitest/coverage-v8", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "./vitest.mjs" } }, "sha512-z0WxZRV2Sg48wF0FSgMq3TFG8JS38/Qr96vZVZdX6+Em9raQTvnXQvdTFJe2m3rfyJnEHeHQ/snceIdi8D1pVg=="], + + "why-is-node-running": ["why-is-node-running@3.2.1", "", { "bin": { "why-is-node-running": "cli.js" } }, "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ=="], + + "ws": ["ws@8.21.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g=="], + + "zod": ["zod@4.6.7", "", {}, "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg=="], + + "@scure/bip32/@noble/curves": ["@noble/curves@1.9.2", "", { "dependencies": { "@noble/hashes": "1.8.0" } }, "sha512-HxngEd2XUcg9xi20JkwlLCtYwfoFw4JGkuZpT+WlsPD4gB/cxkvTD8fSsoAnphGZhFdZYKeQIPCuFlWPm1uE0g=="], + + "tinyglobby/picomatch": ["picomatch@4.0.5", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="], + } +} diff --git a/dstack/kms/auth-eth/contracts/AuthorizationOperation.sol b/dstack/kms/auth-eth/contracts/AuthorizationOperation.sol new file mode 100644 index 0000000000..d5f926616f --- /dev/null +++ b/dstack/kms/auth-eth/contracts/AuthorizationOperation.sol @@ -0,0 +1,24 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// +// SPDX-License-Identifier: Apache-2.0 + +pragma solidity ^0.8.24; + +/// The operation is performed by the attested subject, not the policy caller. +library AuthorizationOperation { + bytes32 internal constant KMS_BOOTSTRAP = keccak256("kms_bootstrap"); + bytes32 internal constant KMS_SERVE = keccak256("kms_serve"); + bytes32 internal constant KMS_EXPORT_KEYS = keccak256("kms_export_keys"); + bytes32 internal constant KMS_IMPORT_KEYS = keccak256("kms_import_keys"); + bytes32 internal constant APP_GET_KEY = keccak256("app_get_key"); + bytes32 internal constant APP_GET_CERT = keccak256("app_get_cert"); + + function isKms(bytes32 operation) internal pure returns (bool) { + return operation == KMS_BOOTSTRAP || operation == KMS_SERVE || operation == KMS_EXPORT_KEYS + || operation == KMS_IMPORT_KEYS; + } + + function isApp(bytes32 operation) internal pure returns (bool) { + return operation == APP_GET_KEY || operation == APP_GET_CERT; + } +} diff --git a/dstack/kms/auth-eth/contracts/DstackApp.sol b/dstack/kms/auth-eth/contracts/DstackApp.sol index 7d90f29efd..b484214d00 100644 --- a/dstack/kms/auth-eth/contracts/DstackApp.sol +++ b/dstack/kms/auth-eth/contracts/DstackApp.sol @@ -7,11 +7,16 @@ pragma solidity ^0.8.24; import "./IAppAuth.sol"; -import "./IAppAuthBasicManagement.sol"; +import "./AuthorizationOperation.sol"; +import "./IAppEpochAuth.sol"; +import "./TeeVariantPolicy.sol"; +import "./IAppEpochManagement.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol"; +import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol"; +import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; contract DstackApp is Initializable, @@ -19,27 +24,59 @@ contract DstackApp is UUPSUpgradeable, ERC165Upgradeable, IAppAuth, - IAppAuthBasicManagement + IAppEpochAuth, + IAppEpochManagement { - // Mapping of allowed compose hashes for this app + using EnumerableSet for EnumerableSet.Bytes32Set; + + /// @notice Allowed compose hashes for this app. Epoch 0 only; for other epochs use the *AtEpoch getters and + /// EpochPolicyChanged. mapping(bytes32 => bool) public allowedComposeHashes; // State variable to track if upgrades are disabled bool private _upgradesDisabled; - // Whether allow any device to boot this app or only allow devices + /// @notice Whether any device may boot this app, at every app epoch. bool public allowAnyDevice; - // Mapping of allowed device IDs for this app + /// @notice Allowed device IDs for this app. Epoch 0 only; for other epochs use the *AtEpoch getters and + /// EpochPolicyChanged. mapping(bytes32 => bool) public allowedDeviceIds; // Whether to require TCB status to be UpToDate bool public requireTcbUpToDate; - // Additional events specific to DstackApp + uint256 public override currentAppEpoch; + event AppEpochAdvanced(uint256 indexed epoch); + + // Epoch zero continues to use the original fields above after an upgrade. + mapping(uint256 => mapping(bytes32 => bool)) private _composeHashesByEpoch; + mapping(uint256 => mapping(bytes32 => bool)) private _deviceIdsByEpoch; + + // The TEE platforms this app may run on. + TeeVariantPolicy.Policy private _teeVariants; + + /// @notice Whether a boot must present an allowed launch ticket, at every app epoch. + bool public requireLaunchTicket; + // Allowed launch tickets, by sha256("dstack-launch-ticket/v1:" || ticket), at every app epoch. + EnumerableSet.Bytes32Set private _launchTickets; + + event EpochPolicyChanged(bytes32 indexed policy, bytes32 indexed value, uint256 indexed epoch, bool enabled); + + /// @notice Legacy material events. Epoch 0 only; for other epochs use the *AtEpoch getters and EpochPolicyChanged. + event ComposeHashAdded(bytes32 composeHash); + event ComposeHashRemoved(bytes32 composeHash); + event DeviceAdded(bytes32 deviceId); + event DeviceRemoved(bytes32 deviceId); event UpgradesDisabled(); + /// @notice Covers every app epoch; there is no EpochPolicyChanged counterpart. event AllowAnyDeviceSet(bool allowAny); + event AllowAnyTeeVariantSet(bool allowAny); + event AllowedTeeVariantsSet(string[] teeVariants); event RequireTcbUpToDateSet(bool requireUpToDate); + event RequireLaunchTicketSet(bool required); + event LaunchTicketAdded(bytes32 indexed ticketHash, string label); + event LaunchTicketRemoved(bytes32 indexed ticketHash); /// @notice Additive audit event for reconstructing authorization policy. event PolicyChanged(address indexed actor, bytes32 indexed policy, bytes32 indexed value, bool enabled); @@ -128,8 +165,8 @@ contract DstackApp is override(ERC165Upgradeable, IERC165) returns (bool) { - return interfaceId == 0x1e079198 // IAppAuth - || interfaceId == 0x8fd37527 // IAppAuthBasicManagement + return interfaceId == type(IAppEpochAuth).interfaceId || interfaceId == type(IAppEpochManagement).interfaceId + || interfaceId == 0x1e079198 // IAppAuth || super.supportsInterface(interfaceId); } @@ -143,26 +180,97 @@ contract DstackApp is emit PolicyChanged(msg.sender, keccak256(bytes(policy)), value, enabled); } - // Add a compose hash to allowed list - function addComposeHash(bytes32 composeHash) external onlyOwner { + function allowedComposeHashesAtEpoch(uint256 epoch, bytes32 composeHash) public view returns (bool) { + return epoch == 0 ? allowedComposeHashes[composeHash] : _composeHashesByEpoch[epoch][composeHash]; + } + + function allowedDeviceIdsAtEpoch(uint256 epoch, bytes32 deviceId) public view returns (bool) { + return epoch == 0 ? allowedDeviceIds[deviceId] : _deviceIdsByEpoch[epoch][deviceId]; + } + + // A request may select any app epoch up to the current one and is decided + // on that epoch's row, so revoking a value takes every row that allows it: + // 0 through currentAppEpoch. + function _setAtEpochs( + function(uint256, bytes32, bool) internal setter, + uint256 fromEpoch, + uint256 toEpoch, + bytes32 value, + bool allowed + ) + private + { + require(fromEpoch <= toEpoch, "Invalid app epoch range"); + for (uint256 epoch = fromEpoch; epoch <= toEpoch; ++epoch) { + setter(epoch, value, allowed); + } + } + + function addComposeHashAtEpoch(uint256 epoch, bytes32 composeHash) public onlyOwner { require(composeHash != bytes32(0), "invalid compose hash"); - allowedComposeHashes[composeHash] = true; - emit ComposeHashAdded(composeHash); - _emitPolicy("compose-hash", composeHash, true); + _setComposeHash(epoch, composeHash, true); } - // Remove a compose hash from allowed list - function removeComposeHash(bytes32 composeHash) external onlyOwner { - allowedComposeHashes[composeHash] = false; - emit ComposeHashRemoved(composeHash); - _emitPolicy("compose-hash", composeHash, false); + function addComposeHashAtEpochs(uint256 fromEpoch, uint256 toEpoch, bytes32 composeHash) external onlyOwner { + require(composeHash != bytes32(0), "invalid compose hash"); + _setAtEpochs(_setComposeHash, fromEpoch, toEpoch, composeHash, true); } - // Set whether any device is allowed to boot this app - function setAllowAnyDevice(bool _allowAnyDevice) external onlyOwner { - allowAnyDevice = _allowAnyDevice; - emit AllowAnyDeviceSet(_allowAnyDevice); - _emitPolicy("allow-any-device", bytes32(0), _allowAnyDevice); + function removeComposeHashAtEpoch(uint256 epoch, bytes32 composeHash) public onlyOwner { + _setComposeHash(epoch, composeHash, false); + } + + function removeComposeHashAtEpochs(uint256 fromEpoch, uint256 toEpoch, bytes32 composeHash) external onlyOwner { + _setAtEpochs(_setComposeHash, fromEpoch, toEpoch, composeHash, false); + } + + function _requireWritableEpoch(uint256 epoch) private view { + require(epoch <= currentAppEpoch + 1, "Unknown app epoch"); + } + + function _setComposeHash(uint256 epoch, bytes32 composeHash, bool allowed) private { + _requireWritableEpoch(epoch); + if (epoch == 0) { + allowedComposeHashes[composeHash] = allowed; + if (allowed) emit ComposeHashAdded(composeHash); + else emit ComposeHashRemoved(composeHash); + _emitPolicy("compose-hash", composeHash, allowed); + } else { + _composeHashesByEpoch[epoch][composeHash] = allowed; + } + emit EpochPolicyChanged(keccak256("compose-hash"), composeHash, epoch, allowed); + } + + // Covers every app epoch: restricting devices is a decision about hosts, not + // key generations, and must not leave an older epoch open to any host. + function setAllowAnyDevice(bool allowed) external onlyOwner { + allowAnyDevice = allowed; + emit AllowAnyDeviceSet(allowed); + _emitPolicy("allow-any-device", bytes32(0), allowed); + } + + /// @notice Whether this app may run on any TEE platform, rather than only on + /// {allowedTeeVariants}. Covers every app epoch. + function allowAnyTeeVariant() public view returns (bool) { + return !_teeVariants.restricted; + } + + /// @notice The TEE platforms, named as the KMS reports them, this app may run on + /// unless {allowAnyTeeVariant}. + function allowedTeeVariants() external view returns (string[] memory) { + return TeeVariantPolicy.allowedNames(_teeVariants); + } + + function setAllowAnyTeeVariant(bool allowed) external onlyOwner { + _teeVariants.restricted = !allowed; + emit AllowAnyTeeVariantSet(allowed); + _emitPolicy("allow-any-tee-variant", bytes32(0), allowed); + } + + function setAllowedTeeVariants(string[] calldata teeVariants) external onlyOwner { + uint64 mask = TeeVariantPolicy.setAllowed(_teeVariants, teeVariants); + emit AllowedTeeVariantsSet(teeVariants); + _emitPolicy("allowed-tee-variants", bytes32(uint256(mask)), true); } // Set whether TCB status must be UpToDate to boot this app @@ -172,28 +280,111 @@ contract DstackApp is _emitPolicy("require-tcb-up-to-date", bytes32(0), _requireUpToDate); } - // Add a device ID to allowed list - function addDevice(bytes32 deviceId) external onlyOwner { + function setRequireLaunchTicket(bool required) external onlyOwner { + requireLaunchTicket = required; + emit RequireLaunchTicketSet(required); + _emitPolicy("require-launch-ticket", bytes32(0), required); + } + + /// @notice Allow a launch ticket. The label is public and only logged. + function addLaunchTicket(bytes32 ticketHash, string calldata label) external onlyOwner { + require(ticketHash != bytes32(0), "invalid launch ticket hash"); + _launchTickets.add(ticketHash); + emit LaunchTicketAdded(ticketHash, label); + _emitPolicy("launch-ticket", ticketHash, true); + } + + function removeLaunchTicket(bytes32 ticketHash) external onlyOwner { + _launchTickets.remove(ticketHash); + emit LaunchTicketRemoved(ticketHash); + _emitPolicy("launch-ticket", ticketHash, false); + } + + /// @notice The allowed launch tickets; their labels are in {LaunchTicketAdded}. + function launchTickets() external view returns (bytes32[] memory) { + return _launchTickets.values(); + } + + function addDeviceAtEpoch(uint256 epoch, bytes32 deviceId) public onlyOwner { require(deviceId != bytes32(0), "invalid device ID"); - allowedDeviceIds[deviceId] = true; - emit DeviceAdded(deviceId); - _emitPolicy("device", deviceId, true); + _setDevice(epoch, deviceId, true); } - // Remove a device ID from allowed list - function removeDevice(bytes32 deviceId) external onlyOwner { - allowedDeviceIds[deviceId] = false; - emit DeviceRemoved(deviceId); - _emitPolicy("device", deviceId, false); + function addDeviceAtEpochs(uint256 fromEpoch, uint256 toEpoch, bytes32 deviceId) external onlyOwner { + require(deviceId != bytes32(0), "invalid device ID"); + _setAtEpochs(_setDevice, fromEpoch, toEpoch, deviceId, true); } - // Check if an app is allowed to boot - function isAppAllowed(IAppAuth.AppBootInfo calldata bootInfo) + function removeDeviceAtEpoch(uint256 epoch, bytes32 deviceId) public onlyOwner { + _setDevice(epoch, deviceId, false); + } + + function removeDeviceAtEpochs(uint256 fromEpoch, uint256 toEpoch, bytes32 deviceId) external onlyOwner { + _setAtEpochs(_setDevice, fromEpoch, toEpoch, deviceId, false); + } + + function _setDevice(uint256 epoch, bytes32 deviceId, bool allowed) private { + _requireWritableEpoch(epoch); + if (epoch == 0) { + allowedDeviceIds[deviceId] = allowed; + if (allowed) emit DeviceAdded(deviceId); + else emit DeviceRemoved(deviceId); + _emitPolicy("device", deviceId, allowed); + } else { + _deviceIdsByEpoch[epoch][deviceId] = allowed; + } + emit EpochPolicyChanged(keccak256("device"), deviceId, epoch, allowed); + } + + // Legacy callers derive epoch-zero keys from this bool, so once the app epoch + // advances they are refused rather than handed keys the owner is retiring. + function isAppAllowed(IAppAuth.AppInfo calldata bootInfo) external view override returns (bool isAllowed, string memory reason) { + if (currentAppEpoch != 0) return (false, "App epoch requires epoch-aware authorization"); + // Legacy callers report no platform and no launch ticket, so only a policy + // restricting neither admits them. + return _authorizeApp(bootInfo, allowAnyTeeVariant(), 0, bytes32(0)); + } + + /// Decide the request at the selected app epoch; the KMS fills gateway and root fields. + function authorizeApp(AuthorizationRequest calldata request) + external + view + override + returns (AuthorizationResult memory result) + { + result.currentAppEpoch = currentAppEpoch; + if (!AuthorizationOperation.isApp(request.operation)) { + result.rejectionReason = "Invalid authorization operation"; + return result; + } + uint256 appEpoch = request.requestedAppEpoch.isSet ? request.requestedAppEpoch.value : currentAppEpoch; + (result.authorized, result.rejectionReason) = _authorizeApp( + request.appInfo, + TeeVariantPolicy.admits(_teeVariants, request.teeVariant), + appEpoch, + request.launchTicketHash + ); + } + + function _authorizeApp( + IAppAuth.AppInfo calldata bootInfo, + bool teeVariantAllowed, + uint256 appEpoch, + bytes32 launchTicketHash + ) + private + view + returns (bool, string memory) + { + if (requireLaunchTicket && !_launchTickets.contains(launchTicketHash)) { + return (false, "Invalid launch ticket"); + } + if (appEpoch > currentAppEpoch) return (false, "Requested app epoch is not active"); // Optionally require TCB status to be up to date if ( requireTcbUpToDate @@ -203,18 +394,38 @@ contract DstackApp is } // Check if compose hash is allowed - if (!allowedComposeHashes[bootInfo.composeHash]) { + if (!allowedComposeHashesAtEpoch(appEpoch, bootInfo.composeHash)) { return (false, "Compose hash not allowed"); } // Check if device is allowed (when device restriction is enabled) - if (!allowAnyDevice && !allowedDeviceIds[bootInfo.deviceId]) { + if (!allowAnyDevice && !allowedDeviceIdsAtEpoch(appEpoch, bootInfo.deviceId)) { return (false, "Device not allowed"); } + if (!teeVariantAllowed) { + return (false, "TEE variant not allowed"); + } + return (true, ""); } + /// @notice Deploy an uninitialized proxy of this implementation. {DstackKms} deploys apps through its + /// `appImplementation` and initializes them, so it does not carry the proxy's creation code. Anyone may call + /// it, as anyone may deploy a proxy themselves; it refuses to run through a proxy. + function deployProxy() external notDelegated returns (address) { + return address(new ERC1967Proxy(address(this), "")); + } + + /// Advance only from the epoch the owner intended, rejecting stale transactions. + function advanceAppEpoch(uint256 expectedCurrentEpoch) external onlyOwner { + require(currentAppEpoch == expectedCurrentEpoch, "App epoch changed"); + require(currentAppEpoch < type(uint32).max, "App epoch exhausted"); + currentAppEpoch++; + emit AppEpochAdvanced(currentAppEpoch); + _emitPolicy("app-epoch", bytes32(currentAppEpoch), true); + } + // Function to permanently disable upgrades function disableUpgrades() external onlyOwner { _upgradesDisabled = true; @@ -223,5 +434,5 @@ contract DstackApp is } // Add storage gap for upgradeable contracts - uint256[49] private __gap; + uint256[42] private __gap; } diff --git a/dstack/kms/auth-eth/contracts/DstackKms.sol b/dstack/kms/auth-eth/contracts/DstackKms.sol index f79325b891..ac427e2db3 100644 --- a/dstack/kms/auth-eth/contracts/DstackKms.sol +++ b/dstack/kms/auth-eth/contracts/DstackKms.sol @@ -7,13 +7,20 @@ pragma solidity ^0.8.24; import "./IAppAuth.sol"; +import "./AuthorizationOperation.sol"; +import "./IAppEpochAuth.sol"; +import "./TeeVariantPolicy.sol"; +import "./DstackApp.sol"; +import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol"; -import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol"; +import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; contract DstackKms is Initializable, Ownable2StepUpgradeable, UUPSUpgradeable, ERC165Upgradeable, IAppAuth { + using EnumerableSet for EnumerableSet.Bytes32Set; + // Struct for KMS information struct KmsInfo { bytes k256Pubkey; @@ -22,7 +29,8 @@ contract DstackKms is Initializable, Ownable2StepUpgradeable, UUPSUpgradeable, E bytes eventlog; } - // KMS information + // Retained for proxy storage compatibility and legacy readers. Only root + // epoch registration and activation may update this identity. KmsInfo public kmsInfo; // The dstack-gateway App ID @@ -32,23 +40,99 @@ contract DstackKms is Initializable, Ownable2StepUpgradeable, UUPSUpgradeable, E // Mapping of registered apps mapping(address => bool) public registeredApps; - // Mapping of allowed aggregated MR measurements for running KMS + /// @notice Allowed aggregated MR measurements for running KMS. Epoch 0 only; for other epochs use the *AtEpoch + /// getters and EpochPolicyChanged. mapping(bytes32 => bool) public kmsAllowedAggregatedMrs; - // Mapping of allowed KMS device IDs + /// @notice Allowed KMS device IDs. Epoch 0 only; for other epochs use the *AtEpoch getters and EpochPolicyChanged. mapping(bytes32 => bool) public kmsAllowedDeviceIds; - // Mapping of allowed image measurements + /// @notice Allowed OS image measurements. Epoch 0 only; for other epochs use the *AtEpoch getters and + /// EpochPolicyChanged. mapping(bytes32 => bool) public allowedOsImages; // DstackApp implementation contract address for factory deployment address public appImplementation; + // DER SubjectPublicKeyInfo prefix of a P-256 key with an uncompressed point; + // the 64 bytes of the point follow. + bytes27 private constant P256_SPKI_PREFIX = 0x3059301306072a8648ce3d020106082a8648ce3d03010703420004; + + struct RootEpoch { + bytes caPubkey; + bytes k256Pubkey; + // Where to fetch the generating KMS's attestation. Its report data binds + // both public keys, so the evidence proves itself: anyone can check the + // keys came from an approved KMS in a TEE. + string evidenceUrl; + // Commits to the public keys of this epoch and every earlier one: + // keccak256(previous chainHash || keccak256(caPubkey) || + // keccak256(k256Pubkey)), with a zero previous hash for epoch 0. + bytes32 chainHash; + // Keys this epoch's policy rows; unique to each registration. + uint256 registration; + } + + // Root keys of each KMS root epoch, indexed by epoch; epoch 0 is the + // original roots. A registered epoch's keys and chain hash never change. + // A pending epoch can be popped, and the owner can update evidenceUrl: + // the evidence proves itself, so the URL only says where it is stored. + RootEpoch[] private _rootEpochs; + + // The epoch KMS instances serve. Registering epoch 0 makes it current; + // later epochs take effect only when activated, one at a time. + uint256 private _currentRootEpoch; + + // Number of root epoch registrations, popped ones included. + uint256 private _rootEpochRegistrations; + + // Policy rows of epochs from 1, keyed by the epoch's registration so that a + // popped and re-registered epoch starts empty, even with the same keys. + // Epoch zero continues to use the original fields above after an upgrade. + mapping(uint256 => mapping(bytes32 => bool)) private _kmsAggregatedMrsByRoot; + mapping(uint256 => mapping(bytes32 => bool)) private _kmsDeviceIdsByRoot; + mapping(uint256 => mapping(bytes32 => bool)) private _osImagesByRoot; + + // The TEE platforms KMS instances and apps may run on. + TeeVariantPolicy.Policy private _teeVariants; + + /// @notice Whether a KMS instance must present an allowed launch ticket to + /// receive the root keys, at every root epoch. + bool public requireKmsLaunchTicket; + // Allowed KMS launch tickets, by sha256("dstack-launch-ticket/v1:" || ticket). + EnumerableSet.Bytes32Set private _kmsLaunchTickets; + + /// @notice The minimum TCB each CPU must meet for an SEV-SNP TCB to report "UpToDate", as the JSON list + /// the KMS parses: AMD publishes no TCB status. Covers every root epoch. A KMS judges a CPU + /// it does not list against its own list, and refuses one neither lists. + string public sevSnpTcbRequirements; + + event EpochPolicyChanged(bytes32 indexed policy, bytes32 indexed value, uint256 indexed epoch, bool enabled); + + error InvalidEpochCaPubkey(); + error InvalidEpochK256Pubkey(); + error EmptyEpochEvidenceUrl(); + error Epoch0KeysDifferFromKmsInfo(); + error InvalidRootEpochActivation(); + error RootEpochChainHashMismatch(); + error NotPendingRootEpoch(); + error NoRootEpochRegistered(); + error UnknownRootEpoch(); + error InvalidAppId(); + error InvalidImplementationAddress(); + error AppImplementationNotSet(); + error InvalidOwnerAddress(); + error InvalidRootEpochRange(); + error AppNotRegistered(); + error AppNotDeployed(); + error InvalidLaunchTicketHash(); + // Events // appId is unindexed for backward compatibility with deployed log indexers. // slither-disable-next-line unindexed-event-address event AppRegistered(address appId); event KmsInfoSet(bytes k256Pubkey); + /// @notice Legacy material events. Epoch 0 only; for other epochs use the *AtEpoch getters and EpochPolicyChanged. event KmsAggregatedMrAdded(bytes32 mrAggregated); event KmsAggregatedMrRemoved(bytes32 mrAggregated); event KmsDeviceAdded(bytes32 deviceId); @@ -56,8 +140,20 @@ contract DstackKms is Initializable, Ownable2StepUpgradeable, UUPSUpgradeable, E event OsImageHashAdded(bytes32 osImageHash); event OsImageHashRemoved(bytes32 osImageHash); event GatewayAppIdSet(string gatewayAppId); + event AllowAnyTeeVariantSet(bool allowAny); + event AllowedTeeVariantsSet(string[] teeVariants); + event SevSnpTcbRequirementsSet(string requirements); + event RequireKmsLaunchTicketSet(bool required); + event KmsLaunchTicketAdded(bytes32 indexed ticketHash, string label); + event KmsLaunchTicketRemoved(bytes32 indexed ticketHash); // slither-disable-next-line unindexed-event-address event AppImplementationSet(address implementation); + event RootEpochRegistered( + uint256 indexed epoch, bytes32 chainHash, bytes caPubkey, bytes k256Pubkey, string evidenceUrl + ); + event RootEpochActivated(uint256 indexed epoch); + event RootEpochPopped(uint256 indexed epoch, bytes32 chainHash); + event RootEpochEvidenceUrlSet(uint256 indexed epoch, string evidenceUrl); event AppDeployedViaFactory(address indexed appId, address indexed deployer); /// @notice Additive audit event for reconstructing authorization policy. /// @dev `value` is the affected bytes32 value, address, or hash of dynamic public data. @@ -78,7 +174,7 @@ contract DstackKms is Initializable, Ownable2StepUpgradeable, UUPSUpgradeable, E if (_appImplementation != address(0)) { appImplementation = _appImplementation; emit AppImplementationSet(_appImplementation); - _emitPolicy("app-implementation", bytes32(uint256(uint160(_appImplementation))), true); + _emitPolicy(keccak256("app-implementation"), bytes32(uint256(uint160(_appImplementation))), true); } } @@ -101,35 +197,179 @@ contract DstackKms is Initializable, Ownable2StepUpgradeable, UUPSUpgradeable, E // Function to authorize upgrades (required by UUPSUpgradeable) function _authorizeUpgrade(address newImplementation) internal override onlyOwner { - _emitPolicy("implementation-upgrade", bytes32(uint256(uint160(newImplementation))), true); + _emitPolicy(keccak256("implementation-upgrade"), bytes32(uint256(uint160(newImplementation))), true); + } + + function _emitPolicy(bytes32 policy, bytes32 value, bool enabled) internal { + emit PolicyChanged(msg.sender, policy, value, enabled); + } + + // Register the root public keys of the next KMS root epoch, with where to + // fetch the attestation proving where they were generated. It is not served until + // activated, except epoch 0, which is current from the start and must be + // the kmsInfo keys when those are set. + function registerRootEpoch( + // P-256 DER SubjectPublicKeyInfo, uncompressed (91 bytes) + bytes calldata caPubkey, + // secp256k1 SEC1 compressed (33 bytes) + bytes calldata k256Pubkey, + string calldata evidenceUrl + ) + external + onlyOwner + returns (uint256 epoch) + { + if (caPubkey.length != 91 || bytes27(caPubkey[:27]) != P256_SPKI_PREFIX) revert InvalidEpochCaPubkey(); + if (k256Pubkey.length != 33 || (k256Pubkey[0] != 0x02 && k256Pubkey[0] != 0x03)) { + revert InvalidEpochK256Pubkey(); + } + if (bytes(evidenceUrl).length == 0) revert EmptyEpochEvidenceUrl(); + epoch = _rootEpochs.length; + if (epoch == 0 && kmsInfo.k256Pubkey.length > 0) { + if ( + keccak256(caPubkey) != keccak256(kmsInfo.caPubkey) + || keccak256(k256Pubkey) != keccak256(kmsInfo.k256Pubkey) + ) revert Epoch0KeysDifferFromKmsInfo(); + } + bytes32 previous = epoch == 0 ? bytes32(0) : _rootEpochs[epoch - 1].chainHash; + bytes32 chainHash = keccak256(abi.encodePacked(previous, keccak256(caPubkey), keccak256(k256Pubkey))); + _rootEpochs.push(RootEpoch(caPubkey, k256Pubkey, evidenceUrl, chainHash, _rootEpochRegistrations++)); + emit RootEpochRegistered(epoch, chainHash, caPubkey, k256Pubkey, evidenceUrl); + _emitPolicy(keccak256("root-epoch"), chainHash, true); + if (epoch == 0) { + _useRootEpoch(0); + } + } + + // Make the next registered root epoch the one KMS instances serve. Bind + // activation to its chain hash in case a pending epoch has been replaced. + function activateRootEpoch(uint256 epoch, bytes32 chainHash) external onlyOwner { + if (epoch != _currentRootEpoch + 1 || epoch >= _rootEpochs.length) revert InvalidRootEpochActivation(); + if (_rootEpochs[epoch].chainHash != chainHash) revert RootEpochChainHashMismatch(); + _currentRootEpoch = epoch; + _useRootEpoch(epoch); + _emitPolicy(keccak256("root-epoch-activated"), bytes32(epoch), true); + } + + // Point kmsInfo at the keys of the now current epoch, for readers of the + // legacy KMS identity. Its quote and event log described the previous keys; + // the epoch's evidence is at its evidenceUrl. + function _useRootEpoch(uint256 epoch) private { + RootEpoch storage keys = _rootEpochs[epoch]; + kmsInfo.caPubkey = keys.caPubkey; + kmsInfo.k256Pubkey = keys.k256Pubkey; + delete kmsInfo.quote; + delete kmsInfo.eventlog; + emit KmsInfoSet(keys.k256Pubkey); + emit RootEpochActivated(epoch); + } + + // Point an epoch at a new copy of its evidence, for when the old location + // goes away. The evidence proves itself, so only its location changes. + function setRootEpochEvidenceUrl(uint256 epoch, string calldata evidenceUrl) external onlyOwner { + if (epoch >= _rootEpochs.length) revert UnknownRootEpoch(); + if (bytes(evidenceUrl).length == 0) revert EmptyEpochEvidenceUrl(); + _rootEpochs[epoch].evidenceUrl = evidenceUrl; + emit RootEpochEvidenceUrlSet(epoch, evidenceUrl); + } + + // Drop the last registered epoch while it is still pending, for when the + // nodes holding it are lost before enough others have onboarded it. The + // epoch is named by number and chain hash, so a stale call cannot drop a + // later registration of the same number. Its policy rows go with it: the + // next registration of the number starts with empty rows, whatever its keys, + // which must be prepared again before activation. + function popRootEpoch(uint256 epoch, bytes32 chainHash) external onlyOwner { + if (epoch + 1 != _rootEpochs.length || epoch <= _currentRootEpoch) revert NotPendingRootEpoch(); + if (_rootEpochs[epoch].chainHash != chainHash) revert RootEpochChainHashMismatch(); + _rootEpochs.pop(); + emit RootEpochPopped(epoch, chainHash); + _emitPolicy(keccak256("root-epoch"), chainHash, false); + } + + function rootEpochCount() external view returns (uint256) { + return _rootEpochs.length; + } + + // The root epoch KMS instances serve and its chain hash + function currentRootEpoch() external view returns (uint256 epoch, bytes32 chainHash) { + if (_rootEpochs.length == 0) revert NoRootEpochRegistered(); + epoch = _currentRootEpoch; + chainHash = _rootEpochs[epoch].chainHash; + } + + function rootEpoch(uint256 epoch) + external + view + returns (bytes memory caPubkey, bytes memory k256Pubkey, string memory evidenceUrl, bytes32 chainHash) + { + if (epoch >= _rootEpochs.length) revert UnknownRootEpoch(); + RootEpoch storage keys = _rootEpochs[epoch]; + return (keys.caPubkey, keys.k256Pubkey, keys.evidenceUrl, keys.chainHash); + } + + /// @notice Whether KMS instances and apps may run on any TEE platform, rather than only on + /// {allowedTeeVariants}. Covers every root epoch. + function allowAnyTeeVariant() public view returns (bool) { + return !_teeVariants.restricted; + } + + /// @notice The TEE platforms, named as the KMS reports them, KMS instances and apps may run on + /// unless {allowAnyTeeVariant}. + function allowedTeeVariants() external view returns (string[] memory) { + return TeeVariantPolicy.allowedNames(_teeVariants); + } + + function setAllowAnyTeeVariant(bool allowed) external onlyOwner { + _teeVariants.restricted = !allowed; + emit AllowAnyTeeVariantSet(allowed); + _emitPolicy(keccak256("allow-any-tee-variant"), bytes32(0), allowed); + } + + function setAllowedTeeVariants(string[] calldata teeVariants) external onlyOwner { + uint64 mask = TeeVariantPolicy.setAllowed(_teeVariants, teeVariants); + emit AllowedTeeVariantsSet(teeVariants); + _emitPolicy(keccak256("allowed-tee-variants"), bytes32(uint256(mask)), true); + } + + function setSevSnpTcbRequirements(string calldata requirements) external onlyOwner { + sevSnpTcbRequirements = requirements; + emit SevSnpTcbRequirementsSet(requirements); + _emitPolicy( + keccak256("sev-snp-tcb-requirements"), keccak256(bytes(requirements)), bytes(requirements).length != 0 + ); } - function _emitPolicy(string memory policy, bytes32 value, bool enabled) internal { - emit PolicyChanged(msg.sender, keccak256(bytes(policy)), value, enabled); + function setRequireKmsLaunchTicket(bool required) external onlyOwner { + requireKmsLaunchTicket = required; + emit RequireKmsLaunchTicketSet(required); + _emitPolicy(keccak256("require-kms-launch-ticket"), bytes32(0), required); } - // Function to set KMS information - function setKmsInfo(KmsInfo memory info) external onlyOwner { - kmsInfo = info; - emit KmsInfoSet(info.k256Pubkey); - _emitPolicy("kms-info", keccak256(info.k256Pubkey), true); + /// @notice Allow a KMS launch ticket. The label is public and only logged. + function addKmsLaunchTicket(bytes32 ticketHash, string calldata label) external onlyOwner { + if (ticketHash == bytes32(0)) revert InvalidLaunchTicketHash(); + _kmsLaunchTickets.add(ticketHash); + emit KmsLaunchTicketAdded(ticketHash, label); + _emitPolicy(keccak256("kms-launch-ticket"), ticketHash, true); } - // Function to set KMS quote - function setKmsQuote(bytes memory quote) external onlyOwner { - kmsInfo.quote = quote; + function removeKmsLaunchTicket(bytes32 ticketHash) external onlyOwner { + _kmsLaunchTickets.remove(ticketHash); + emit KmsLaunchTicketRemoved(ticketHash); + _emitPolicy(keccak256("kms-launch-ticket"), ticketHash, false); } - // Function to set KMS eventlog - function setKmsEventlog(bytes memory eventlog) external onlyOwner { - kmsInfo.eventlog = eventlog; + /// @notice The allowed KMS launch tickets; their labels are in {KmsLaunchTicketAdded}. + function kmsLaunchTickets() external view returns (bytes32[] memory) { + return _kmsLaunchTickets.values(); } // Function to set trusted Gateway App ID function setGatewayAppId(string memory appId) external onlyOwner { gatewayAppId = appId; emit GatewayAppIdSet(appId); - _emitPolicy("gateway-app-id", keccak256(bytes(appId)), true); + _emitPolicy(keccak256("gateway-app-id"), keccak256(bytes(appId)), true); } /// @notice Register an app address as known to this KMS. @@ -142,18 +382,18 @@ contract DstackKms is Initializable, Ownable2StepUpgradeable, UUPSUpgradeable, E /// and by the registered app's own {IAppAuth-isAppAllowed}, so /// registration alone confers no privilege. function registerApp(address appId) public { - require(appId != address(0), "Invalid app ID"); + if (appId == address(0)) revert InvalidAppId(); registeredApps[appId] = true; emit AppRegistered(appId); - _emitPolicy("registered-app", bytes32(uint256(uint160(appId))), true); + _emitPolicy(keccak256("registered-app"), bytes32(uint256(uint160(appId))), true); } // Function to set DstackApp implementation contract address function setAppImplementation(address _implementation) external onlyOwner { - require(_implementation != address(0), "Invalid implementation address"); + if (_implementation == address(0)) revert InvalidImplementationAddress(); appImplementation = _implementation; emit AppImplementationSet(_implementation); - _emitPolicy("app-implementation", bytes32(uint256(uint160(_implementation))), true); + _emitPolicy(keccak256("app-implementation"), bytes32(uint256(uint160(_implementation))), true); } // Factory method: Deploy and register DstackApp in single transaction @@ -168,28 +408,24 @@ contract DstackKms is Initializable, Ownable2StepUpgradeable, UUPSUpgradeable, E public returns (address appId) { - require(appImplementation != address(0), "DstackApp implementation not set"); - require(initialOwner != address(0), "Invalid owner address"); - - bytes memory initData = abi.encodeWithSelector( - bytes4(keccak256("initialize(address,bool,bool,bool,bytes32,bytes32)")), - initialOwner, - disableUpgrades, - requireTcbUpToDate, - allowAnyDevice, - initialDeviceId, - initialComposeHash - ); - - // The ERC1967Proxy constructor delegatecalls into `appImplementation`'s - // initializer. The owner sets `appImplementation` via - // setAppImplementation; safety here rests on owner trust, not on a - // structural reentrancy impossibility — a malicious owner could in - // principle install an impl whose `initialize` reenters this contract. - // See docs/specification.md §1 for the owner trust scope and §6.1 for - // the malicious-registered-app threat model. + if (appImplementation == address(0)) revert AppImplementationNotSet(); + if (initialOwner == address(0)) revert InvalidOwnerAddress(); + + // `appImplementation` deploys an uninitialized ERC1967Proxy of itself, + // which this contract initializes in the same transaction. The owner + // sets `appImplementation` via setAppImplementation; safety here rests + // on owner trust, not on a structural reentrancy impossibility — a + // malicious owner could in principle install an impl whose + // `deployProxy` or `initialize` reenters this contract, or whose + // `deployProxy` returns an existing contract. See + // docs/specification.md §1 for the owner trust scope and §6.1 for the + // malicious-registered-app threat model. // slither-disable-next-line reentrancy-benign,reentrancy-events - appId = address(new ERC1967Proxy(appImplementation, initData)); + appId = DstackApp(appImplementation).deployProxy(); + DstackApp(appId) + .initialize( + initialOwner, disableUpgrades, requireTcbUpToDate, allowAnyDevice, initialDeviceId, initialComposeHash + ); registerApp(appId); emit AppDeployedViaFactory(appId, msg.sender); } @@ -210,94 +446,335 @@ contract DstackKms is Initializable, Ownable2StepUpgradeable, UUPSUpgradeable, E ); } - // Function to register an aggregated MR measurement - function addKmsAggregatedMr(bytes32 mrAggregated) external onlyOwner { - kmsAllowedAggregatedMrs[mrAggregated] = true; - emit KmsAggregatedMrAdded(mrAggregated); - _emitPolicy("kms-aggregated-mr", mrAggregated, true); + function kmsAllowedAggregatedMrsAtEpoch(uint256 epoch, bytes32 mrAggregated) public view returns (bool) { + if (epoch == 0) return kmsAllowedAggregatedMrs[mrAggregated]; + return epoch < _rootEpochs.length && _kmsAggregatedMrsByRoot[_rootEpochs[epoch].registration][mrAggregated]; } - // Function to deregister an aggregated MR measurement - function removeKmsAggregatedMr(bytes32 mrAggregated) external onlyOwner { - kmsAllowedAggregatedMrs[mrAggregated] = false; - emit KmsAggregatedMrRemoved(mrAggregated); - _emitPolicy("kms-aggregated-mr", mrAggregated, false); + function addKmsAggregatedMrAtEpochs(uint256 fromEpoch, uint256 toEpoch, bytes32 mrAggregated) external onlyOwner { + _setAtEpochs(_setKmsAggregatedMr, fromEpoch, toEpoch, mrAggregated, true); } - // Function to register a KMS device ID - function addKmsDevice(bytes32 deviceId) external onlyOwner { - kmsAllowedDeviceIds[deviceId] = true; - emit KmsDeviceAdded(deviceId); - _emitPolicy("kms-device", deviceId, true); + function removeKmsAggregatedMrAtEpochs( + uint256 fromEpoch, + uint256 toEpoch, + bytes32 mrAggregated + ) + external + onlyOwner + { + _setAtEpochs(_setKmsAggregatedMr, fromEpoch, toEpoch, mrAggregated, false); + } + + function _setKmsAggregatedMr(uint256 epoch, bytes32 mrAggregated, bool allowed) private { + if (epoch > _latestRootEpoch()) revert UnknownRootEpoch(); + if (epoch == 0) { + kmsAllowedAggregatedMrs[mrAggregated] = allowed; + if (allowed) emit KmsAggregatedMrAdded(mrAggregated); + else emit KmsAggregatedMrRemoved(mrAggregated); + _emitPolicy(keccak256("kms-aggregated-mr"), mrAggregated, allowed); + } else { + _kmsAggregatedMrsByRoot[_rootEpochs[epoch].registration][mrAggregated] = allowed; + } + emit EpochPolicyChanged(keccak256("kms-aggregated-mr"), mrAggregated, epoch, allowed); + } + + function kmsAllowedDeviceIdsAtEpoch(uint256 epoch, bytes32 deviceId) public view returns (bool) { + if (epoch == 0) return kmsAllowedDeviceIds[deviceId]; + return epoch < _rootEpochs.length && _kmsDeviceIdsByRoot[_rootEpochs[epoch].registration][deviceId]; + } + + function addKmsDeviceAtEpochs(uint256 fromEpoch, uint256 toEpoch, bytes32 deviceId) external onlyOwner { + _setAtEpochs(_setKmsDevice, fromEpoch, toEpoch, deviceId, true); + } + + function removeKmsDeviceAtEpochs(uint256 fromEpoch, uint256 toEpoch, bytes32 deviceId) external onlyOwner { + _setAtEpochs(_setKmsDevice, fromEpoch, toEpoch, deviceId, false); + } + + function _setKmsDevice(uint256 epoch, bytes32 deviceId, bool allowed) private { + if (epoch > _latestRootEpoch()) revert UnknownRootEpoch(); + if (epoch == 0) { + kmsAllowedDeviceIds[deviceId] = allowed; + if (allowed) emit KmsDeviceAdded(deviceId); + else emit KmsDeviceRemoved(deviceId); + _emitPolicy(keccak256("kms-device"), deviceId, allowed); + } else { + _kmsDeviceIdsByRoot[_rootEpochs[epoch].registration][deviceId] = allowed; + } + emit EpochPolicyChanged(keccak256("kms-device"), deviceId, epoch, allowed); } - // Function to deregister a KMS device ID - function removeKmsDevice(bytes32 deviceId) external onlyOwner { - kmsAllowedDeviceIds[deviceId] = false; - emit KmsDeviceRemoved(deviceId); - _emitPolicy("kms-device", deviceId, false); + function allowedOsImagesAtEpoch(uint256 epoch, bytes32 osImageHash) public view returns (bool) { + if (epoch == 0) return allowedOsImages[osImageHash]; + return epoch < _rootEpochs.length && _osImagesByRoot[_rootEpochs[epoch].registration][osImageHash]; } - // Function to register an image measurement - function addOsImageHash(bytes32 osImageHash) external onlyOwner { - allowedOsImages[osImageHash] = true; - emit OsImageHashAdded(osImageHash); - _emitPolicy("os-image", osImageHash, true); + function addOsImageHashAtEpochs(uint256 fromEpoch, uint256 toEpoch, bytes32 osImageHash) external onlyOwner { + _setAtEpochs(_setOsImageHash, fromEpoch, toEpoch, osImageHash, true); } - // Function to deregister an image measurement - function removeOsImageHash(bytes32 osImageHash) external onlyOwner { - allowedOsImages[osImageHash] = false; - emit OsImageHashRemoved(osImageHash); - _emitPolicy("os-image", osImageHash, false); + function removeOsImageHashAtEpochs(uint256 fromEpoch, uint256 toEpoch, bytes32 osImageHash) external onlyOwner { + _setAtEpochs(_setOsImageHash, fromEpoch, toEpoch, osImageHash, false); } - // Function to check if KMS is allowed to boot - function isKmsAllowed(AppBootInfo calldata bootInfo) external view returns (bool isAllowed, string memory reason) { + function _setOsImageHash(uint256 epoch, bytes32 osImageHash, bool allowed) private { + if (epoch > _latestRootEpoch()) revert UnknownRootEpoch(); + if (epoch == 0) { + allowedOsImages[osImageHash] = allowed; + if (allowed) emit OsImageHashAdded(osImageHash); + else emit OsImageHashRemoved(osImageHash); + _emitPolicy(keccak256("os-image"), osImageHash, allowed); + } else { + _osImagesByRoot[_rootEpochs[epoch].registration][osImageHash] = allowed; + } + emit EpochPolicyChanged(keccak256("os-image"), osImageHash, epoch, allowed); + } + + // A request may select any epoch up to the current one and is decided on + // that epoch's row, so revoking a value takes every row that allows it: + // 0 through rootEpochCount() - 1. + function _setAtEpochs( + function(uint256, bytes32, bool) internal setter, + uint256 fromEpoch, + uint256 toEpoch, + bytes32 value, + bool allowed + ) + private + { + if (fromEpoch > toEpoch) revert InvalidRootEpochRange(); + for (uint256 epoch = fromEpoch; epoch <= toEpoch; ++epoch) { + setter(epoch, value, allowed); + } + } + + function _latestRootEpoch() private view returns (uint256) { + return _rootEpochs.length == 0 ? 0 : _rootEpochs.length - 1; + } + + /// Reverts for an unregistered or undeployed app rather than reporting epoch + /// zero for it. Legacy policies have epoch zero; an advertised getter must succeed. + function currentAppEpoch(address appId) external view returns (uint256) { + if (!registeredApps[appId]) revert AppNotRegistered(); + if (appId.code.length == 0) revert AppNotDeployed(); + return _appEpoch(appId); + } + + /// Zero for an app authorization rejects anyway, so the decision reports the rejection. + function _appEpoch(address appId) private view returns (uint256) { + if (!registeredApps[appId] || appId.code.length == 0) return 0; + if (!ERC165Checker.supportsInterface(appId, type(IAppEpochAuth).interfaceId)) return 0; + return IAppEpochAuth(appId).currentAppEpoch(); + } + + /// Authorize an attested identity and return the root epoch from the same state. + /// The caller selects KMS or app policy. + function authorizeKms(AuthorizationRequest calldata request) external view returns (AuthorizationResult memory) { + return _checkKmsAuthorization(request); + } + + /// Apply the KMS-owned checks, forward the request unchanged to an epoch-aware + /// policy, then fill the gateway and root epoch fields. + function authorizeApp(AuthorizationRequest calldata request) + external + view + returns (AuthorizationResult memory result) + { + address appId = request.appInfo.appId; + string memory rejection = _checkAppPolicy(request, true); + if (bytes(rejection).length == 0) { + if (ERC165Checker.supportsInterface(appId, type(IAppEpochAuth).interfaceId)) { + // The policy owns the operation scope and the app epoch, so its + // decision and epoch come from one call. + result = IAppEpochAuth(appId).authorizeApp(request); + } else if (request.requestedAppEpoch.isSet && request.requestedAppEpoch.value != 0) { + result.rejectionReason = "Requested app epoch is not active"; + } else { + // Legacy policies only know app epoch zero. + (result.authorized, result.rejectionReason) = IAppAuth(appId).isAppAllowed(request.appInfo); + } + } else { + result.rejectionReason = rejection; + } + _fillRootEpochs(result); + } + + /// The KMS-owned fields of every authorization result, read from the same state. + function _fillRootEpochs(AuthorizationResult memory result) private view { + result.gatewayAppId = gatewayAppId; + if (_rootEpochs.length == 0) return; + result.currentRootEpoch = _currentRootEpoch; + result.currentRootEpochHash = _rootEpochs[_currentRootEpoch].chainHash; + uint256 latest = _latestRootEpoch(); + result.latestRootEpoch = latest; + result.latestRootEpochHash = _rootEpochs[latest].chainHash; + } + + /// The KMS-owned part of an app authorization, without the app identity + /// checks an off-chain delegate owns. Empty means the KMS admits the + /// request at the selected root epoch. A delegated auth-eth calls this at + /// its pinned block so a revoked OS image or a disallowed TEE variant is + /// denied on chain even though registration is judged off chain. + function checkKmsAppPolicy(AuthorizationRequest calldata request) external view returns (string memory) { + return _checkAppPolicy(request, false); + } + + /// The full app-authorization chain when `withAppIdentity` holds; the + /// identity checks slot between the epoch and TEE variant checks so the + /// on-chain precedence is unchanged. + function _checkAppPolicy( + AuthorizationRequest calldata request, + bool withAppIdentity + ) + private + view + returns (string memory) + { + if (!AuthorizationOperation.isApp(request.operation)) return "Invalid authorization operation"; + if (_rootEpochs.length == 0) return "Root epoch not registered"; + if (request.requestedRootEpoch.isSet && request.requestedRootEpoch.value > _currentRootEpoch) { + return "Requested root epoch is not active"; + } + uint256 selectedRootEpoch = + request.requestedRootEpoch.isSet ? request.requestedRootEpoch.value : _currentRootEpoch; + return _checkAppDeployment( + request.appInfo, + TeeVariantPolicy.admits(_teeVariants, request.teeVariant), + selectedRootEpoch, + withAppIdentity + ); + } + + function _checkAppDeployment( + AppInfo calldata bootInfo, + bool teeVariantAllowed, + uint256 selectedRootEpoch, + bool withAppIdentity + ) + private + view + returns (string memory) + { + if (withAppIdentity && !registeredApps[bootInfo.appId]) return "App not registered"; + if (!allowedOsImagesAtEpoch(selectedRootEpoch, bootInfo.osImageHash)) return "OS image is not allowed"; + if (withAppIdentity && !isContract(bootInfo.appId)) return "App not deployed or invalid address"; + if (!teeVariantAllowed) return "TEE variant not allowed"; + return ""; + } + + function _checkKmsAuthorization(AuthorizationRequest calldata request) + private + view + returns (AuthorizationResult memory result) + { + _fillRootEpochs(result); + if (!AuthorizationOperation.isKms(request.operation)) { + result.rejectionReason = "Invalid authorization operation"; + return result; + } + // The source KMS checks the joining instance's ticket before handing it + // the root keys. Only this import hands them out; an instance that + // bootstraps or serves without them holds no registered root. + if ( + request.operation == AuthorizationOperation.KMS_IMPORT_KEYS && requireKmsLaunchTicket + && !_kmsLaunchTickets.contains(request.launchTicketHash) + ) { + result.rejectionReason = "Invalid launch ticket"; + return result; + } + if (_rootEpochs.length == 0 && request.operation != AuthorizationOperation.KMS_BOOTSTRAP) { + result.rejectionReason = "Root epoch not registered"; + return result; + } + if (request.requestedRootEpoch.isSet && request.requestedRootEpoch.value > _latestRootEpoch()) { + result.rejectionReason = "Requested root epoch is not registered"; + return result; + } + // Serving issues keys of the epoch, so only the current one; the key + // handover may move a pending epoch between instances. + if ( + request.operation == AuthorizationOperation.KMS_SERVE && request.requestedRootEpoch.isSet + && request.requestedRootEpoch.value > _currentRootEpoch + ) { + result.rejectionReason = "Requested root epoch is not active"; + return result; + } + if (request.requestedAppEpoch.isSet && request.requestedAppEpoch.value != 0) { + result.rejectionReason = "Requested app epoch is not active"; + return result; + } + uint256 selectedRootEpoch = + request.requestedRootEpoch.isSet ? request.requestedRootEpoch.value : _currentRootEpoch; + (result.authorized, result.rejectionReason) = + _kmsPolicy(request.appInfo, TeeVariantPolicy.admits(_teeVariants, request.teeVariant), selectedRootEpoch); + } + + // Legacy entry point for pre-epoch KMS binaries: reads epoch 0, and refuses + // once a later root epoch is current. + function isKmsAllowed(AppInfo calldata bootInfo) external view returns (bool isAllowed, string memory reason) { + // Legacy callers present no launch ticket and cannot say which operation they authorize. + if (requireKmsLaunchTicket) return (false, "Invalid launch ticket"); + if (_currentRootEpoch != 0) { + return (false, "Root epoch requires epoch-aware authorization"); + } + // Legacy callers report no platform, so only an unrestricted policy admits them. + return _kmsPolicy(bootInfo, allowAnyTeeVariant(), 0); + } + + function _kmsPolicy( + AppInfo memory bootInfo, + bool teeVariantAllowed, + uint256 selectedRootEpoch + ) + private + view + returns (bool, string memory) + { // Check if the TCB status is up to date if (keccak256(abi.encodePacked(bootInfo.tcbStatus)) != keccak256(abi.encodePacked("UpToDate"))) { return (false, "TCB status is not up to date"); } // Check if the OS image is allowed - if (!allowedOsImages[bootInfo.osImageHash]) { + if (!allowedOsImagesAtEpoch(selectedRootEpoch, bootInfo.osImageHash)) { return (false, "OS image is not allowed"); } // Check if the aggregated MR is allowed - if (!kmsAllowedAggregatedMrs[bootInfo.mrAggregated]) { + if (!kmsAllowedAggregatedMrsAtEpoch(selectedRootEpoch, bootInfo.mrAggregated)) { return (false, "Aggregated MR not allowed"); } // Check if the KMS device ID is allowed - if (!kmsAllowedDeviceIds[bootInfo.deviceId]) { + if (!kmsAllowedDeviceIdsAtEpoch(selectedRootEpoch, bootInfo.deviceId)) { return (false, "KMS is not allowed to boot on this device"); } + if (!teeVariantAllowed) { + return (false, "TEE variant not allowed"); + } + return (true, ""); } - // Function to check if an app is allowed to boot - function isAppAllowed(AppBootInfo calldata bootInfo) + // Legacy entry point for pre-epoch KMS binaries: reads epoch 0, and refuses + // once a later root epoch is current. + function isAppAllowed(AppInfo calldata bootInfo) external view override returns (bool isAllowed, string memory reason) { - // Check if app is registered - if (!registeredApps[bootInfo.appId]) { - return (false, "App not registered"); + if (_currentRootEpoch != 0) { + return (false, "Root epoch requires epoch-aware authorization"); } - // Check if the OS image is allowed - if (!allowedOsImages[bootInfo.osImageHash]) { - return (false, "OS image is not allowed"); + if (_appEpoch(bootInfo.appId) != 0) { + return (false, "App epoch requires epoch-aware authorization"); } - - // Check if the contract exists at the appId address - if (!isContract(bootInfo.appId)) { - return (false, "App not deployed or invalid address"); - } - + // Legacy callers report no platform, so only an unrestricted policy admits them. + string memory rejection = _checkAppDeployment(bootInfo, allowAnyTeeVariant(), 0, true); + if (bytes(rejection).length != 0) return (false, rejection); // Call the app's isAppAllowed function. The tuple is forwarded as the // function's return value; the slither detector trips on the named // return + forward pattern but the value is actually used. @@ -306,7 +783,7 @@ contract DstackKms is Initializable, Ownable2StepUpgradeable, UUPSUpgradeable, E } // Add storage gap for upgradeable contracts - uint256[50] private __gap; + uint256[39] private __gap; } function isContract(address addr) view returns (bool) { diff --git a/dstack/kms/auth-eth/contracts/IAppAuth.sol b/dstack/kms/auth-eth/contracts/IAppAuth.sol index 56b7689710..896c609549 100644 --- a/dstack/kms/auth-eth/contracts/IAppAuth.sol +++ b/dstack/kms/auth-eth/contracts/IAppAuth.sol @@ -33,7 +33,7 @@ interface IAppAuth is IERC165 { * @param tcbStatus Trusted Computing Base status * @param advisoryIds Array of security advisory identifiers */ - struct AppBootInfo { + struct AppInfo { address appId; bytes32 composeHash; address instanceId; @@ -52,5 +52,5 @@ interface IAppAuth is IERC165 { * @return isAllowed True if the app is authorized to boot, false otherwise * @return reason Human-readable reason for the decision (empty if allowed) */ - function isAppAllowed(AppBootInfo calldata bootInfo) external view returns (bool isAllowed, string memory reason); + function isAppAllowed(AppInfo calldata bootInfo) external view returns (bool isAllowed, string memory reason); } diff --git a/dstack/kms/auth-eth/contracts/IAppEpochAuth.sol b/dstack/kms/auth-eth/contracts/IAppEpochAuth.sol new file mode 100644 index 0000000000..bc06d48a61 --- /dev/null +++ b/dstack/kms/auth-eth/contracts/IAppEpochAuth.sol @@ -0,0 +1,51 @@ +/* + * SPDX-FileCopyrightText: © 2026 Phala Network + * + * SPDX-License-Identifier: Apache-2.0 + */ + +pragma solidity ^0.8.24; + +import "./IAppAuth.sol"; + +/// An explicitly selected value; `isSet == false` selects the current one. +struct OptionalUint256 { + bool isSet; + uint256 value; +} + +struct AuthorizationRequest { + IAppAuth.AppInfo appInfo; + bytes32 operation; + OptionalUint256 requestedAppEpoch; + OptionalUint256 requestedRootEpoch; + /// The TEE platform the KMS attested, e.g. "dstack-tdx" or "dstack-amd-sev-snp". + /// Measurements, device IDs and TCB status are only meaningful per platform, + /// and one OS image may boot on several. + string teeVariant; + /// The launch ticket the attested subject presented, as + /// sha256("dstack-launch-ticket/v1:" || ticket); zero when it presented none. + bytes32 launchTicketHash; +} + +struct AuthorizationResult { + bool authorized; + string rejectionReason; + string gatewayAppId; + uint256 currentRootEpoch; + bytes32 currentRootEpochHash; + uint256 currentAppEpoch; + // The latest registered root epoch, which may be pending activation. + uint256 latestRootEpoch; + bytes32 latestRootEpochHash; +} + +/// Optional epoch- and operation-aware policy capability. Legacy policies only authorize app epoch zero. +interface IAppEpochAuth { + function currentAppEpoch() external view returns (uint256); + + /// Receives the KMS request unchanged. The policy validates the operation and app + /// epoch and fills `authorized`, `rejectionReason` and `currentAppEpoch`; the KMS + /// owns `gatewayAppId` and the current and latest root epoch fields. + function authorizeApp(AuthorizationRequest calldata request) external view returns (AuthorizationResult memory); +} diff --git a/dstack/kms/auth-eth/contracts/IAppEpochManagement.sol b/dstack/kms/auth-eth/contracts/IAppEpochManagement.sol new file mode 100644 index 0000000000..28ed4e2d71 --- /dev/null +++ b/dstack/kms/auth-eth/contracts/IAppEpochManagement.sol @@ -0,0 +1,27 @@ +/* + * SPDX-FileCopyrightText: © 2026 Phala Network + * + * SPDX-License-Identifier: Apache-2.0 + */ + +pragma solidity ^0.8.24; + +/// Allowlist management. Each allowlist setter names the app epoch rows it +/// writes: one epoch, or `fromEpoch` through `toEpoch`, at most the next epoch. +/// `setAllowAnyDevice`, `setAllowAnyTeeVariant` and `setAllowedTeeVariants` cover +/// every app epoch. +/// Replaces the epoch-less IAppAuthBasicManagement (0x8fd37527), which policies +/// predating app epochs still report; tools tell the two apart by interface ID. +interface IAppEpochManagement { + function addComposeHashAtEpoch(uint256 epoch, bytes32 composeHash) external; + function addComposeHashAtEpochs(uint256 fromEpoch, uint256 toEpoch, bytes32 composeHash) external; + function removeComposeHashAtEpoch(uint256 epoch, bytes32 composeHash) external; + function removeComposeHashAtEpochs(uint256 fromEpoch, uint256 toEpoch, bytes32 composeHash) external; + function addDeviceAtEpoch(uint256 epoch, bytes32 deviceId) external; + function addDeviceAtEpochs(uint256 fromEpoch, uint256 toEpoch, bytes32 deviceId) external; + function removeDeviceAtEpoch(uint256 epoch, bytes32 deviceId) external; + function removeDeviceAtEpochs(uint256 fromEpoch, uint256 toEpoch, bytes32 deviceId) external; + function setAllowAnyDevice(bool allowed) external; + function setAllowAnyTeeVariant(bool allowed) external; + function setAllowedTeeVariants(string[] calldata teeVariants) external; +} diff --git a/dstack/kms/auth-eth/contracts/TeeVariantPolicy.sol b/dstack/kms/auth-eth/contracts/TeeVariantPolicy.sol new file mode 100644 index 0000000000..e1780461d8 --- /dev/null +++ b/dstack/kms/auth-eth/contracts/TeeVariantPolicy.sol @@ -0,0 +1,69 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// +// SPDX-License-Identifier: Apache-2.0 + +pragma solidity ^0.8.24; + +/// The TEE platforms a policy admits, named as the KMS reports them in +/// `AuthorizationRequest.teeVariant`. It covers every epoch: which platforms may hold keys +/// is a trust decision, not a property of a key generation. +library TeeVariantPolicy { + /// Zero-initialized as unrestricted, so proxies upgraded from before platform + /// policies keep their decisions. Bit `n` of `allowed` admits `names()[n]`. + struct Policy { + bool restricted; + uint64 allowed; + } + + uint256 private constant COUNT = 5; + + /// The platforms a policy can list, in the order of dstack's `TeeVariant`. + /// Append new ones (and bump COUNT); a restricted policy refuses names it + /// does not know. + function names() internal pure returns (string[COUNT] memory) { + return ["dstack-tdx", "dstack-gcp-tdx", "dstack-nitro-enclave", "dstack-amd-sev-snp", "dstack-aws-nitro-tpm"]; + } + + function admits(Policy storage policy, string calldata teeVariant) internal view returns (bool) { + if (!policy.restricted) return true; + (bool known, uint8 index) = _indexOf(teeVariant); + return known && (policy.allowed >> index) & 1 == 1; + } + + /// Returns the stored mask, a canonical value for audit events. + function setAllowed(Policy storage policy, string[] calldata teeVariants) internal returns (uint64) { + uint64 allowed = 0; + for (uint256 i = 0; i < teeVariants.length; ++i) { + (bool known, uint8 index) = _indexOf(teeVariants[i]); + require(known, "unknown TEE variant"); + allowed |= uint64(1) << index; + } + policy.allowed = allowed; + return allowed; + } + + function allowedNames(Policy storage policy) internal view returns (string[] memory list) { + string[COUNT] memory all = names(); + uint64 allowed = policy.allowed; + list = new string[](_popcount(allowed)); + uint256 n = 0; + for (uint256 i = 0; i < all.length; ++i) { + if ((allowed >> i) & 1 == 1) list[n++] = all[i]; + } + } + + function _indexOf(string calldata teeVariant) private pure returns (bool, uint8) { + bytes32 key = keccak256(bytes(teeVariant)); + string[COUNT] memory all = names(); + for (uint8 i = 0; i < all.length; ++i) { + if (keccak256(bytes(all[i])) == key) return (true, i); + } + return (false, 0); + } + + function _popcount(uint64 bits) private pure returns (uint256 count) { + for (; bits != 0; bits &= bits - 1) { + ++count; + } + } +} diff --git a/dstack/kms/auth-eth/contracts/test-utils/reference/v0.5.9/DstackAppV059.sol b/dstack/kms/auth-eth/contracts/test-utils/reference/v0.5.9/DstackAppV059.sol new file mode 100644 index 0000000000..7eafcd703f --- /dev/null +++ b/dstack/kms/auth-eth/contracts/test-utils/reference/v0.5.9/DstackAppV059.sol @@ -0,0 +1,200 @@ +/* + * SPDX-FileCopyrightText: © 2025 Phala Network + * + * SPDX-License-Identifier: Apache-2.0 + */ + +pragma solidity ^0.8.22; + +import "./IAppAuth.sol"; +import "./IAppAuthBasicManagement.sol"; +import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; +import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; +import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; +import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol"; + +contract DstackApp is + Initializable, + OwnableUpgradeable, + UUPSUpgradeable, + ERC165Upgradeable, + IAppAuth, + IAppAuthBasicManagement +{ + // Mapping of allowed compose hashes for this app + mapping(bytes32 => bool) public allowedComposeHashes; + + // State variable to track if upgrades are disabled + bool private _upgradesDisabled; + + // Whether allow any device to boot this app or only allow devices + bool public allowAnyDevice; + + // Mapping of allowed device IDs for this app + mapping(bytes32 => bool) public allowedDeviceIds; + + // Whether to require TCB status to be UpToDate + bool public requireTcbUpToDate; + + // Additional events specific to DstackApp + event UpgradesDisabled(); + event AllowAnyDeviceSet(bool allowAny); + event RequireTcbUpToDateSet(bool requireUpToDate); + + /// @custom:oz-upgrades-unsafe-allow constructor + constructor() { + _disableInitializers(); + } + + // Old initialize — preserved for upgrade compatibility + function initialize( + address initialOwner, + bool _disableUpgrades, + bool _allowAnyDevice, + bytes32 initialDeviceId, + bytes32 initialComposeHash + ) public initializer { + _initializeCommon(initialOwner, _disableUpgrades, _allowAnyDevice, initialDeviceId, initialComposeHash); + } + + // New initialize — includes requireTcbUpToDate + function initialize( + address initialOwner, + bool _disableUpgrades, + bool _requireTcbUpToDate, + bool _allowAnyDevice, + bytes32 initialDeviceId, + bytes32 initialComposeHash + ) public initializer { + requireTcbUpToDate = _requireTcbUpToDate; + _initializeCommon(initialOwner, _disableUpgrades, _allowAnyDevice, initialDeviceId, initialComposeHash); + } + + function _initializeCommon( + address initialOwner, + bool _disableUpgrades, + bool _allowAnyDevice, + bytes32 initialDeviceId, + bytes32 initialComposeHash + ) internal { + require(initialOwner != address(0), "invalid owner address"); + + _upgradesDisabled = _disableUpgrades; + allowAnyDevice = _allowAnyDevice; + + // Add initial device if provided + if (initialDeviceId != bytes32(0)) { + allowedDeviceIds[initialDeviceId] = true; + emit DeviceAdded(initialDeviceId); + } + + // Add initial compose hash if provided + if (initialComposeHash != bytes32(0)) { + allowedComposeHashes[initialComposeHash] = true; + emit ComposeHashAdded(initialComposeHash); + } + + __Ownable_init(initialOwner); + __UUPSUpgradeable_init(); + __ERC165_init(); + } + + function version() public pure returns (uint256) { + return 2; + } + + /** + * @dev See {IERC165-supportsInterface}. + * @notice Returns true if this contract implements the interface defined by interfaceId + * @param interfaceId The interface identifier, as specified in ERC-165 + * @return True if the contract implements `interfaceId` + */ + function supportsInterface(bytes4 interfaceId) + public + view + virtual + override(ERC165Upgradeable, IERC165) + returns (bool) + { + return + interfaceId == 0x1e079198 || // IAppAuth + interfaceId == 0x8fd37527 || // IAppAuthBasicManagement + super.supportsInterface(interfaceId); + } + + // Function to authorize upgrades (required by UUPSUpgradeable) + function _authorizeUpgrade(address) internal view override onlyOwner { + require(!_upgradesDisabled, "Upgrades are permanently disabled"); + } + + // Add a compose hash to allowed list + function addComposeHash(bytes32 composeHash) external onlyOwner { + allowedComposeHashes[composeHash] = true; + emit ComposeHashAdded(composeHash); + } + + // Remove a compose hash from allowed list + function removeComposeHash(bytes32 composeHash) external onlyOwner { + allowedComposeHashes[composeHash] = false; + emit ComposeHashRemoved(composeHash); + } + + // Set whether any device is allowed to boot this app + function setAllowAnyDevice(bool _allowAnyDevice) external onlyOwner { + allowAnyDevice = _allowAnyDevice; + emit AllowAnyDeviceSet(_allowAnyDevice); + } + + // Set whether TCB status must be UpToDate to boot this app + function setRequireTcbUpToDate(bool _requireUpToDate) external onlyOwner { + requireTcbUpToDate = _requireUpToDate; + emit RequireTcbUpToDateSet(_requireUpToDate); + } + + // Add a device ID to allowed list + function addDevice(bytes32 deviceId) external onlyOwner { + allowedDeviceIds[deviceId] = true; + emit DeviceAdded(deviceId); + } + + // Remove a device ID from allowed list + function removeDevice(bytes32 deviceId) external onlyOwner { + allowedDeviceIds[deviceId] = false; + emit DeviceRemoved(deviceId); + } + + // Check if an app is allowed to boot + function isAppAllowed( + IAppAuth.AppBootInfo calldata bootInfo + ) external view override returns (bool isAllowed, string memory reason) { + // Optionally require TCB status to be up to date + if ( + requireTcbUpToDate && + keccak256(abi.encodePacked(bootInfo.tcbStatus)) != + keccak256(abi.encodePacked("UpToDate")) + ) { + return (false, "TCB status is not up to date"); + } + + // Check if compose hash is allowed + if (!allowedComposeHashes[bootInfo.composeHash]) { + return (false, "Compose hash not allowed"); + } + + // Check if device is allowed (when device restriction is enabled) + if (!allowAnyDevice && !allowedDeviceIds[bootInfo.deviceId]) { + return (false, "Device not allowed"); + } + + return (true, ""); + } + + // Function to permanently disable upgrades + function disableUpgrades() external onlyOwner { + _upgradesDisabled = true; + emit UpgradesDisabled(); + } + + // Add storage gap for upgradeable contracts + uint256[49] private __gap; +} diff --git a/dstack/kms/auth-eth/contracts/test-utils/reference/v0.5.9/DstackKmsV059.sol b/dstack/kms/auth-eth/contracts/test-utils/reference/v0.5.9/DstackKmsV059.sol new file mode 100644 index 0000000000..64031076cd --- /dev/null +++ b/dstack/kms/auth-eth/contracts/test-utils/reference/v0.5.9/DstackKmsV059.sol @@ -0,0 +1,286 @@ +/* + * SPDX-FileCopyrightText: © 2025 Phala Network + * + * SPDX-License-Identifier: Apache-2.0 + */ + +pragma solidity ^0.8.22; + +import "./IAppAuth.sol"; +import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; +import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; +import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; +import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol"; +import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol"; + +contract DstackKms is + Initializable, + OwnableUpgradeable, + UUPSUpgradeable, + ERC165Upgradeable, + IAppAuth +{ + // Struct for KMS information + struct KmsInfo { + bytes k256Pubkey; + bytes caPubkey; + bytes quote; + bytes eventlog; + } + + // KMS information + KmsInfo public kmsInfo; + + // The dstack-gateway App ID + /// @custom:oz-renamed-from tproxyAppId + string public gatewayAppId; + + // Mapping of registered apps + mapping(address => bool) public registeredApps; + + // Mapping of allowed aggregated MR measurements for running KMS + mapping(bytes32 => bool) public kmsAllowedAggregatedMrs; + + // Mapping of allowed KMS device IDs + mapping(bytes32 => bool) public kmsAllowedDeviceIds; + + // Mapping of allowed image measurements + mapping(bytes32 => bool) public allowedOsImages; + + // DstackApp implementation contract address for factory deployment + address public appImplementation; + + // Events + event AppRegistered(address appId); + event KmsInfoSet(bytes k256Pubkey); + event KmsAggregatedMrAdded(bytes32 mrAggregated); + event KmsAggregatedMrRemoved(bytes32 mrAggregated); + event KmsDeviceAdded(bytes32 deviceId); + event KmsDeviceRemoved(bytes32 deviceId); + event OsImageHashAdded(bytes32 osImageHash); + event OsImageHashRemoved(bytes32 osImageHash); + event GatewayAppIdSet(string gatewayAppId); + event AppImplementationSet(address implementation); + event AppDeployedViaFactory(address indexed appId, address indexed deployer); + + /// @custom:oz-upgrades-unsafe-allow constructor + constructor() { + _disableInitializers(); + } + + // Initialize the contract with the owner wallet address and optionally set DstackApp implementation + function initialize(address initialOwner, address _appImplementation) public initializer { + __Ownable_init(initialOwner); + __UUPSUpgradeable_init(); + __ERC165_init(); + + // Set DstackApp implementation if provided + if (_appImplementation != address(0)) { + appImplementation = _appImplementation; + emit AppImplementationSet(_appImplementation); + } + } + + /** + * @dev See {IERC165-supportsInterface}. + * @notice Returns true if this contract implements the interface defined by interfaceId + * @param interfaceId The interface identifier, as specified in ERC-165 + * @return True if the contract implements `interfaceId` + */ + function supportsInterface(bytes4 interfaceId) + public + view + virtual + override(ERC165Upgradeable, IERC165) + returns (bool) + { + return + interfaceId == 0x1e079198 || // IAppAuth + super.supportsInterface(interfaceId); + } + + // Function to authorize upgrades (required by UUPSUpgradeable) + function _authorizeUpgrade( + address newImplementation + ) internal override onlyOwner {} + + // Function to set KMS information + function setKmsInfo(KmsInfo memory info) external onlyOwner { + kmsInfo = info; + emit KmsInfoSet(info.k256Pubkey); + } + + // Function to set KMS quote + function setKmsQuote(bytes memory quote) external onlyOwner { + kmsInfo.quote = quote; + } + + // Function to set KMS eventlog + function setKmsEventlog(bytes memory eventlog) external onlyOwner { + kmsInfo.eventlog = eventlog; + } + + // Function to set trusted Gateway App ID + function setGatewayAppId(string memory appId) external onlyOwner { + gatewayAppId = appId; + emit GatewayAppIdSet(appId); + } + + // Function to register an app + function registerApp(address appId) public { + require(appId != address(0), "Invalid app ID"); + registeredApps[appId] = true; + emit AppRegistered(appId); + } + + // Function to set DstackApp implementation contract address + function setAppImplementation(address _implementation) external onlyOwner { + require(_implementation != address(0), "Invalid implementation address"); + appImplementation = _implementation; + emit AppImplementationSet(_implementation); + } + + // Factory method: Deploy and register DstackApp in single transaction + function deployAndRegisterApp( + address initialOwner, + bool disableUpgrades, + bool requireTcbUpToDate, + bool allowAnyDevice, + bytes32 initialDeviceId, + bytes32 initialComposeHash + ) public returns (address appId) { + require(appImplementation != address(0), "DstackApp implementation not set"); + require(initialOwner != address(0), "Invalid owner address"); + + bytes memory initData = abi.encodeWithSelector( + bytes4(keccak256("initialize(address,bool,bool,bool,bytes32,bytes32)")), + initialOwner, + disableUpgrades, + requireTcbUpToDate, + allowAnyDevice, + initialDeviceId, + initialComposeHash + ); + + appId = address(new ERC1967Proxy(appImplementation, initData)); + registerApp(appId); + emit AppDeployedViaFactory(appId, msg.sender); + } + + // Backward compatible factory method for old SDK callers (pre TCB flag) + function deployAndRegisterApp( + address initialOwner, + bool disableUpgrades, + bool allowAnyDevice, + bytes32 initialDeviceId, + bytes32 initialComposeHash + ) external returns (address appId) { + return deployAndRegisterApp( + initialOwner, + disableUpgrades, + false, + allowAnyDevice, + initialDeviceId, + initialComposeHash + ); + } + + // Function to register an aggregated MR measurement + function addKmsAggregatedMr(bytes32 mrAggregated) external onlyOwner { + kmsAllowedAggregatedMrs[mrAggregated] = true; + emit KmsAggregatedMrAdded(mrAggregated); + } + + // Function to deregister an aggregated MR measurement + function removeKmsAggregatedMr(bytes32 mrAggregated) external onlyOwner { + kmsAllowedAggregatedMrs[mrAggregated] = false; + emit KmsAggregatedMrRemoved(mrAggregated); + } + + // Function to register a KMS device ID + function addKmsDevice(bytes32 deviceId) external onlyOwner { + kmsAllowedDeviceIds[deviceId] = true; + emit KmsDeviceAdded(deviceId); + } + + // Function to deregister a KMS device ID + function removeKmsDevice(bytes32 deviceId) external onlyOwner { + kmsAllowedDeviceIds[deviceId] = false; + emit KmsDeviceRemoved(deviceId); + } + + // Function to register an image measurement + function addOsImageHash(bytes32 osImageHash) external onlyOwner { + allowedOsImages[osImageHash] = true; + emit OsImageHashAdded(osImageHash); + } + + // Function to deregister an image measurement + function removeOsImageHash(bytes32 osImageHash) external onlyOwner { + allowedOsImages[osImageHash] = false; + emit OsImageHashRemoved(osImageHash); + } + + // Function to check if KMS is allowed to boot + function isKmsAllowed( + AppBootInfo calldata bootInfo + ) external view returns (bool isAllowed, string memory reason) { + // Check if the TCB status is up to date + if ( + keccak256(abi.encodePacked(bootInfo.tcbStatus)) != + keccak256(abi.encodePacked("UpToDate")) + ) { + return (false, "TCB status is not up to date"); + } + + // Check if the OS image is allowed + if (!allowedOsImages[bootInfo.osImageHash]) { + return (false, "OS image is not allowed"); + } + + // Check if the aggregated MR is allowed + if (!kmsAllowedAggregatedMrs[bootInfo.mrAggregated]) { + return (false, "Aggregated MR not allowed"); + } + + // Check if the KMS device ID is allowed + if (!kmsAllowedDeviceIds[bootInfo.deviceId]) { + return (false, "KMS is not allowed to boot on this device"); + } + + return (true, ""); + } + + // Function to check if an app is allowed to boot + function isAppAllowed( + AppBootInfo calldata bootInfo + ) external view override returns (bool isAllowed, string memory reason) { + // Check if app is registered + if (!registeredApps[bootInfo.appId]) { + return (false, "App not registered"); + } + // Check if the OS image is allowed + if (!allowedOsImages[bootInfo.osImageHash]) { + return (false, "OS image is not allowed"); + } + + // Check if the contract exists at the appId address + if (!isContract(bootInfo.appId)) { + return (false, "App not deployed or invalid address"); + } + + // Call the app's isAppAllowed function + return IAppAuth(bootInfo.appId).isAppAllowed(bootInfo); + } + + // Add storage gap for upgradeable contracts + uint256[50] private __gap; +} + +function isContract(address addr) view returns (bool){ + uint32 size; + assembly { + size := extcodesize(addr) + } + return (size > 0); +} diff --git a/dstack/kms/auth-eth/contracts/test-utils/reference/v0.5.9/IAppAuth.sol b/dstack/kms/auth-eth/contracts/test-utils/reference/v0.5.9/IAppAuth.sol new file mode 100644 index 0000000000..29eb6737a8 --- /dev/null +++ b/dstack/kms/auth-eth/contracts/test-utils/reference/v0.5.9/IAppAuth.sol @@ -0,0 +1,58 @@ +/* + * SPDX-FileCopyrightText: © 2025 Phala Network + * + * SPDX-License-Identifier: Apache-2.0 + */ + +pragma solidity ^0.8.0; + +import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; + +/** + * @title IAppAuth + * @notice Core interface for App Authentication contracts + * @dev This interface defines the core function for validating app boot information. + * Any contract implementing this interface should also implement ERC-165 to + * allow interface detection. + * + * Interface ID: 0x1e079198 + * + * This interface can be checked using: + * contract.supportsInterface(0x1e079198) + */ +interface IAppAuth is IERC165 { + /** + * @notice Information required to validate app boot authorization + * @param appId The unique identifier for the application + * @param composeHash Hash of the application composition/configuration + * @param instanceId Unique identifier for this specific app instance + * @param deviceId Unique identifier for the device/hardware + * @param mrAggregated Aggregated measurement register value + * @param mrSystem System measurement register value + * @param osImageHash Hash of the operating system image + * @param tcbStatus Trusted Computing Base status + * @param advisoryIds Array of security advisory identifiers + */ + struct AppBootInfo { + address appId; + bytes32 composeHash; + address instanceId; + bytes32 deviceId; + bytes32 mrAggregated; + bytes32 mrSystem; + bytes32 osImageHash; + string tcbStatus; + string[] advisoryIds; + } + + /** + * @notice Check if an application is allowed to boot with the given parameters + * @dev This is the core authorization function that validates all boot parameters + * @param bootInfo Struct containing all necessary boot validation information + * @return isAllowed True if the app is authorized to boot, false otherwise + * @return reason Human-readable reason for the decision (empty if allowed) + */ + function isAppAllowed( + AppBootInfo calldata bootInfo + ) external view returns (bool isAllowed, string memory reason); +} diff --git a/dstack/kms/auth-eth/contracts/test-utils/reference/v0.5.9/IAppAuthBasicManagement.sol b/dstack/kms/auth-eth/contracts/test-utils/reference/v0.5.9/IAppAuthBasicManagement.sol new file mode 100644 index 0000000000..0396b1d479 --- /dev/null +++ b/dstack/kms/auth-eth/contracts/test-utils/reference/v0.5.9/IAppAuthBasicManagement.sol @@ -0,0 +1,71 @@ +/* + * SPDX-FileCopyrightText: © 2025 Phala Network + * + * SPDX-License-Identifier: Apache-2.0 + */ + +pragma solidity ^0.8.0; + +import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; + +/** + * @title IAppAuthBasicManagement + * @notice Basic management interface for App Authentication contracts + * @dev This interface defines the standard functions that UI tools and other contracts + * can use to interact with App Auth contracts. Any contract implementing this + * interface should also implement ERC-165 to allow interface detection. + * + * Interface ID: 0x8fd37527 + * + * UI tools can check if a contract supports this interface by calling: + * contract.supportsInterface(type(IAppAuthBasicManagement).interfaceId) + */ +interface IAppAuthBasicManagement is IERC165 { + /// @notice Emitted when a new compose hash is added to the allowed list + /// @param composeHash The compose hash that was added + event ComposeHashAdded(bytes32 composeHash); + + /// @notice Emitted when a compose hash is removed from the allowed list + /// @param composeHash The compose hash that was removed + event ComposeHashRemoved(bytes32 composeHash); + + /// @notice Emitted when a new device ID is added to the allowed list + /// @param deviceId The device ID that was added + event DeviceAdded(bytes32 deviceId); + + /// @notice Emitted when a device ID is removed from the allowed list + /// @param deviceId The device ID that was removed + event DeviceRemoved(bytes32 deviceId); + + /** + * @notice Add a compose hash to the allowed list + * @dev MUST emit ComposeHashAdded event on success + * MUST revert if caller is not authorized + * @param composeHash The compose hash to add + */ + function addComposeHash(bytes32 composeHash) external; + + /** + * @notice Remove a compose hash from the allowed list + * @dev MUST emit ComposeHashRemoved event on success + * MUST revert if caller is not authorized + * @param composeHash The compose hash to remove + */ + function removeComposeHash(bytes32 composeHash) external; + + /** + * @notice Add a device ID to the allowed list + * @dev MUST emit DeviceAdded event on success + * MUST revert if caller is not authorized + * @param deviceId The device ID to add + */ + function addDevice(bytes32 deviceId) external; + + /** + * @notice Remove a device ID from the allowed list + * @dev MUST emit DeviceRemoved event on success + * MUST revert if caller is not authorized + * @param deviceId The device ID to remove + */ + function removeDevice(bytes32 deviceId) external; +} \ No newline at end of file diff --git a/dstack/kms/auth-eth/contracts/test-utils/reference/v0.6.0/DstackAppV060.sol b/dstack/kms/auth-eth/contracts/test-utils/reference/v0.6.0/DstackAppV060.sol new file mode 100644 index 0000000000..7d90f29efd --- /dev/null +++ b/dstack/kms/auth-eth/contracts/test-utils/reference/v0.6.0/DstackAppV060.sol @@ -0,0 +1,227 @@ +/* + * SPDX-FileCopyrightText: © 2025 Phala Network + * + * SPDX-License-Identifier: Apache-2.0 + */ + +pragma solidity ^0.8.24; + +import "./IAppAuth.sol"; +import "./IAppAuthBasicManagement.sol"; +import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; +import "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol"; +import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; +import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol"; + +contract DstackApp is + Initializable, + Ownable2StepUpgradeable, + UUPSUpgradeable, + ERC165Upgradeable, + IAppAuth, + IAppAuthBasicManagement +{ + // Mapping of allowed compose hashes for this app + mapping(bytes32 => bool) public allowedComposeHashes; + + // State variable to track if upgrades are disabled + bool private _upgradesDisabled; + + // Whether allow any device to boot this app or only allow devices + bool public allowAnyDevice; + + // Mapping of allowed device IDs for this app + mapping(bytes32 => bool) public allowedDeviceIds; + + // Whether to require TCB status to be UpToDate + bool public requireTcbUpToDate; + + // Additional events specific to DstackApp + event UpgradesDisabled(); + event AllowAnyDeviceSet(bool allowAny); + event RequireTcbUpToDateSet(bool requireUpToDate); + /// @notice Additive audit event for reconstructing authorization policy. + event PolicyChanged(address indexed actor, bytes32 indexed policy, bytes32 indexed value, bool enabled); + + /// @custom:oz-upgrades-unsafe-allow constructor + constructor() { + _disableInitializers(); + } + + // Old initialize — preserved for upgrade compatibility + function initialize( + address initialOwner, + bool _disableUpgrades, + bool _allowAnyDevice, + bytes32 initialDeviceId, + bytes32 initialComposeHash + ) + public + initializer + { + _initializeCommon(initialOwner, _disableUpgrades, _allowAnyDevice, initialDeviceId, initialComposeHash); + } + + // New initialize — includes requireTcbUpToDate + function initialize( + address initialOwner, + bool _disableUpgrades, + bool _requireTcbUpToDate, + bool _allowAnyDevice, + bytes32 initialDeviceId, + bytes32 initialComposeHash + ) + public + initializer + { + requireTcbUpToDate = _requireTcbUpToDate; + _initializeCommon(initialOwner, _disableUpgrades, _allowAnyDevice, initialDeviceId, initialComposeHash); + } + + function _initializeCommon( + address initialOwner, + bool _disableUpgrades, + bool _allowAnyDevice, + bytes32 initialDeviceId, + bytes32 initialComposeHash + ) + internal + { + require(initialOwner != address(0), "invalid owner address"); + + _upgradesDisabled = _disableUpgrades; + allowAnyDevice = _allowAnyDevice; + + // Add initial device if provided + if (initialDeviceId != bytes32(0)) { + allowedDeviceIds[initialDeviceId] = true; + emit DeviceAdded(initialDeviceId); + _emitPolicy("device", initialDeviceId, true); + } + + // Add initial compose hash if provided + if (initialComposeHash != bytes32(0)) { + allowedComposeHashes[initialComposeHash] = true; + emit ComposeHashAdded(initialComposeHash); + _emitPolicy("compose-hash", initialComposeHash, true); + } + + __Ownable_init(initialOwner); + __UUPSUpgradeable_init(); + __ERC165_init(); + } + + function version() public pure returns (uint256) { + return 2; + } + + /** + * @dev See {IERC165-supportsInterface}. + * @notice Returns true if this contract implements the interface defined by interfaceId + * @param interfaceId The interface identifier, as specified in ERC-165 + * @return True if the contract implements `interfaceId` + */ + function supportsInterface(bytes4 interfaceId) + public + view + virtual + override(ERC165Upgradeable, IERC165) + returns (bool) + { + return interfaceId == 0x1e079198 // IAppAuth + || interfaceId == 0x8fd37527 // IAppAuthBasicManagement + || super.supportsInterface(interfaceId); + } + + // Function to authorize upgrades (required by UUPSUpgradeable) + function _authorizeUpgrade(address newImplementation) internal override onlyOwner { + require(!_upgradesDisabled, "Upgrades are permanently disabled"); + _emitPolicy("implementation-upgrade", bytes32(uint256(uint160(newImplementation))), true); + } + + function _emitPolicy(string memory policy, bytes32 value, bool enabled) internal { + emit PolicyChanged(msg.sender, keccak256(bytes(policy)), value, enabled); + } + + // Add a compose hash to allowed list + function addComposeHash(bytes32 composeHash) external onlyOwner { + require(composeHash != bytes32(0), "invalid compose hash"); + allowedComposeHashes[composeHash] = true; + emit ComposeHashAdded(composeHash); + _emitPolicy("compose-hash", composeHash, true); + } + + // Remove a compose hash from allowed list + function removeComposeHash(bytes32 composeHash) external onlyOwner { + allowedComposeHashes[composeHash] = false; + emit ComposeHashRemoved(composeHash); + _emitPolicy("compose-hash", composeHash, false); + } + + // Set whether any device is allowed to boot this app + function setAllowAnyDevice(bool _allowAnyDevice) external onlyOwner { + allowAnyDevice = _allowAnyDevice; + emit AllowAnyDeviceSet(_allowAnyDevice); + _emitPolicy("allow-any-device", bytes32(0), _allowAnyDevice); + } + + // Set whether TCB status must be UpToDate to boot this app + function setRequireTcbUpToDate(bool _requireUpToDate) external onlyOwner { + requireTcbUpToDate = _requireUpToDate; + emit RequireTcbUpToDateSet(_requireUpToDate); + _emitPolicy("require-tcb-up-to-date", bytes32(0), _requireUpToDate); + } + + // Add a device ID to allowed list + function addDevice(bytes32 deviceId) external onlyOwner { + require(deviceId != bytes32(0), "invalid device ID"); + allowedDeviceIds[deviceId] = true; + emit DeviceAdded(deviceId); + _emitPolicy("device", deviceId, true); + } + + // Remove a device ID from allowed list + function removeDevice(bytes32 deviceId) external onlyOwner { + allowedDeviceIds[deviceId] = false; + emit DeviceRemoved(deviceId); + _emitPolicy("device", deviceId, false); + } + + // Check if an app is allowed to boot + function isAppAllowed(IAppAuth.AppBootInfo calldata bootInfo) + external + view + override + returns (bool isAllowed, string memory reason) + { + // Optionally require TCB status to be up to date + if ( + requireTcbUpToDate + && keccak256(abi.encodePacked(bootInfo.tcbStatus)) != keccak256(abi.encodePacked("UpToDate")) + ) { + return (false, "TCB status is not up to date"); + } + + // Check if compose hash is allowed + if (!allowedComposeHashes[bootInfo.composeHash]) { + return (false, "Compose hash not allowed"); + } + + // Check if device is allowed (when device restriction is enabled) + if (!allowAnyDevice && !allowedDeviceIds[bootInfo.deviceId]) { + return (false, "Device not allowed"); + } + + return (true, ""); + } + + // Function to permanently disable upgrades + function disableUpgrades() external onlyOwner { + _upgradesDisabled = true; + emit UpgradesDisabled(); + _emitPolicy("upgrades-disabled", bytes32(0), true); + } + + // Add storage gap for upgradeable contracts + uint256[49] private __gap; +} diff --git a/dstack/kms/auth-eth/contracts/test-utils/reference/v0.6.0/DstackKmsV060.sol b/dstack/kms/auth-eth/contracts/test-utils/reference/v0.6.0/DstackKmsV060.sol new file mode 100644 index 0000000000..f79325b891 --- /dev/null +++ b/dstack/kms/auth-eth/contracts/test-utils/reference/v0.6.0/DstackKmsV060.sol @@ -0,0 +1,318 @@ +/* + * SPDX-FileCopyrightText: © 2025 Phala Network + * + * SPDX-License-Identifier: Apache-2.0 + */ + +pragma solidity ^0.8.24; + +import "./IAppAuth.sol"; +import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; +import "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol"; +import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; +import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol"; +import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol"; + +contract DstackKms is Initializable, Ownable2StepUpgradeable, UUPSUpgradeable, ERC165Upgradeable, IAppAuth { + // Struct for KMS information + struct KmsInfo { + bytes k256Pubkey; + bytes caPubkey; + bytes quote; + bytes eventlog; + } + + // KMS information + KmsInfo public kmsInfo; + + // The dstack-gateway App ID + /// @custom:oz-renamed-from tproxyAppId + string public gatewayAppId; + + // Mapping of registered apps + mapping(address => bool) public registeredApps; + + // Mapping of allowed aggregated MR measurements for running KMS + mapping(bytes32 => bool) public kmsAllowedAggregatedMrs; + + // Mapping of allowed KMS device IDs + mapping(bytes32 => bool) public kmsAllowedDeviceIds; + + // Mapping of allowed image measurements + mapping(bytes32 => bool) public allowedOsImages; + + // DstackApp implementation contract address for factory deployment + address public appImplementation; + + // Events + // appId is unindexed for backward compatibility with deployed log indexers. + // slither-disable-next-line unindexed-event-address + event AppRegistered(address appId); + event KmsInfoSet(bytes k256Pubkey); + event KmsAggregatedMrAdded(bytes32 mrAggregated); + event KmsAggregatedMrRemoved(bytes32 mrAggregated); + event KmsDeviceAdded(bytes32 deviceId); + event KmsDeviceRemoved(bytes32 deviceId); + event OsImageHashAdded(bytes32 osImageHash); + event OsImageHashRemoved(bytes32 osImageHash); + event GatewayAppIdSet(string gatewayAppId); + // slither-disable-next-line unindexed-event-address + event AppImplementationSet(address implementation); + event AppDeployedViaFactory(address indexed appId, address indexed deployer); + /// @notice Additive audit event for reconstructing authorization policy. + /// @dev `value` is the affected bytes32 value, address, or hash of dynamic public data. + event PolicyChanged(address indexed actor, bytes32 indexed policy, bytes32 indexed value, bool enabled); + + /// @custom:oz-upgrades-unsafe-allow constructor + constructor() { + _disableInitializers(); + } + + // Initialize the contract with the owner wallet address and optionally set DstackApp implementation + function initialize(address initialOwner, address _appImplementation) public initializer { + __Ownable_init(initialOwner); + __UUPSUpgradeable_init(); + __ERC165_init(); + + // Set DstackApp implementation if provided + if (_appImplementation != address(0)) { + appImplementation = _appImplementation; + emit AppImplementationSet(_appImplementation); + _emitPolicy("app-implementation", bytes32(uint256(uint160(_appImplementation))), true); + } + } + + /** + * @dev See {IERC165-supportsInterface}. + * @notice Returns true if this contract implements the interface defined by interfaceId + * @param interfaceId The interface identifier, as specified in ERC-165 + * @return True if the contract implements `interfaceId` + */ + function supportsInterface(bytes4 interfaceId) + public + view + virtual + override(ERC165Upgradeable, IERC165) + returns (bool) + { + return interfaceId == 0x1e079198 // IAppAuth + || super.supportsInterface(interfaceId); + } + + // Function to authorize upgrades (required by UUPSUpgradeable) + function _authorizeUpgrade(address newImplementation) internal override onlyOwner { + _emitPolicy("implementation-upgrade", bytes32(uint256(uint160(newImplementation))), true); + } + + function _emitPolicy(string memory policy, bytes32 value, bool enabled) internal { + emit PolicyChanged(msg.sender, keccak256(bytes(policy)), value, enabled); + } + + // Function to set KMS information + function setKmsInfo(KmsInfo memory info) external onlyOwner { + kmsInfo = info; + emit KmsInfoSet(info.k256Pubkey); + _emitPolicy("kms-info", keccak256(info.k256Pubkey), true); + } + + // Function to set KMS quote + function setKmsQuote(bytes memory quote) external onlyOwner { + kmsInfo.quote = quote; + } + + // Function to set KMS eventlog + function setKmsEventlog(bytes memory eventlog) external onlyOwner { + kmsInfo.eventlog = eventlog; + } + + // Function to set trusted Gateway App ID + function setGatewayAppId(string memory appId) external onlyOwner { + gatewayAppId = appId; + emit GatewayAppIdSet(appId); + _emitPolicy("gateway-app-id", keccak256(bytes(appId)), true); + } + + /// @notice Register an app address as known to this KMS. + /// @dev Intentionally permissionless: any caller can mark any non-zero + /// address as registered. This is the factory hook used by + /// {deployAndRegisterApp}, and direct external registration is + /// also a supported use case (e.g. third parties bootstrapping + /// their own DstackApp under this KMS). Authorization is gated + /// downstream by the owner-controlled {allowedOsImages} whitelist + /// and by the registered app's own {IAppAuth-isAppAllowed}, so + /// registration alone confers no privilege. + function registerApp(address appId) public { + require(appId != address(0), "Invalid app ID"); + registeredApps[appId] = true; + emit AppRegistered(appId); + _emitPolicy("registered-app", bytes32(uint256(uint160(appId))), true); + } + + // Function to set DstackApp implementation contract address + function setAppImplementation(address _implementation) external onlyOwner { + require(_implementation != address(0), "Invalid implementation address"); + appImplementation = _implementation; + emit AppImplementationSet(_implementation); + _emitPolicy("app-implementation", bytes32(uint256(uint160(_implementation))), true); + } + + // Factory method: Deploy and register DstackApp in single transaction + function deployAndRegisterApp( + address initialOwner, + bool disableUpgrades, + bool requireTcbUpToDate, + bool allowAnyDevice, + bytes32 initialDeviceId, + bytes32 initialComposeHash + ) + public + returns (address appId) + { + require(appImplementation != address(0), "DstackApp implementation not set"); + require(initialOwner != address(0), "Invalid owner address"); + + bytes memory initData = abi.encodeWithSelector( + bytes4(keccak256("initialize(address,bool,bool,bool,bytes32,bytes32)")), + initialOwner, + disableUpgrades, + requireTcbUpToDate, + allowAnyDevice, + initialDeviceId, + initialComposeHash + ); + + // The ERC1967Proxy constructor delegatecalls into `appImplementation`'s + // initializer. The owner sets `appImplementation` via + // setAppImplementation; safety here rests on owner trust, not on a + // structural reentrancy impossibility — a malicious owner could in + // principle install an impl whose `initialize` reenters this contract. + // See docs/specification.md §1 for the owner trust scope and §6.1 for + // the malicious-registered-app threat model. + // slither-disable-next-line reentrancy-benign,reentrancy-events + appId = address(new ERC1967Proxy(appImplementation, initData)); + registerApp(appId); + emit AppDeployedViaFactory(appId, msg.sender); + } + + // Backward compatible factory method for old SDK callers (pre TCB flag) + function deployAndRegisterApp( + address initialOwner, + bool disableUpgrades, + bool allowAnyDevice, + bytes32 initialDeviceId, + bytes32 initialComposeHash + ) + external + returns (address appId) + { + return deployAndRegisterApp( + initialOwner, disableUpgrades, false, allowAnyDevice, initialDeviceId, initialComposeHash + ); + } + + // Function to register an aggregated MR measurement + function addKmsAggregatedMr(bytes32 mrAggregated) external onlyOwner { + kmsAllowedAggregatedMrs[mrAggregated] = true; + emit KmsAggregatedMrAdded(mrAggregated); + _emitPolicy("kms-aggregated-mr", mrAggregated, true); + } + + // Function to deregister an aggregated MR measurement + function removeKmsAggregatedMr(bytes32 mrAggregated) external onlyOwner { + kmsAllowedAggregatedMrs[mrAggregated] = false; + emit KmsAggregatedMrRemoved(mrAggregated); + _emitPolicy("kms-aggregated-mr", mrAggregated, false); + } + + // Function to register a KMS device ID + function addKmsDevice(bytes32 deviceId) external onlyOwner { + kmsAllowedDeviceIds[deviceId] = true; + emit KmsDeviceAdded(deviceId); + _emitPolicy("kms-device", deviceId, true); + } + + // Function to deregister a KMS device ID + function removeKmsDevice(bytes32 deviceId) external onlyOwner { + kmsAllowedDeviceIds[deviceId] = false; + emit KmsDeviceRemoved(deviceId); + _emitPolicy("kms-device", deviceId, false); + } + + // Function to register an image measurement + function addOsImageHash(bytes32 osImageHash) external onlyOwner { + allowedOsImages[osImageHash] = true; + emit OsImageHashAdded(osImageHash); + _emitPolicy("os-image", osImageHash, true); + } + + // Function to deregister an image measurement + function removeOsImageHash(bytes32 osImageHash) external onlyOwner { + allowedOsImages[osImageHash] = false; + emit OsImageHashRemoved(osImageHash); + _emitPolicy("os-image", osImageHash, false); + } + + // Function to check if KMS is allowed to boot + function isKmsAllowed(AppBootInfo calldata bootInfo) external view returns (bool isAllowed, string memory reason) { + // Check if the TCB status is up to date + if (keccak256(abi.encodePacked(bootInfo.tcbStatus)) != keccak256(abi.encodePacked("UpToDate"))) { + return (false, "TCB status is not up to date"); + } + + // Check if the OS image is allowed + if (!allowedOsImages[bootInfo.osImageHash]) { + return (false, "OS image is not allowed"); + } + + // Check if the aggregated MR is allowed + if (!kmsAllowedAggregatedMrs[bootInfo.mrAggregated]) { + return (false, "Aggregated MR not allowed"); + } + + // Check if the KMS device ID is allowed + if (!kmsAllowedDeviceIds[bootInfo.deviceId]) { + return (false, "KMS is not allowed to boot on this device"); + } + + return (true, ""); + } + + // Function to check if an app is allowed to boot + function isAppAllowed(AppBootInfo calldata bootInfo) + external + view + override + returns (bool isAllowed, string memory reason) + { + // Check if app is registered + if (!registeredApps[bootInfo.appId]) { + return (false, "App not registered"); + } + // Check if the OS image is allowed + if (!allowedOsImages[bootInfo.osImageHash]) { + return (false, "OS image is not allowed"); + } + + // Check if the contract exists at the appId address + if (!isContract(bootInfo.appId)) { + return (false, "App not deployed or invalid address"); + } + + // Call the app's isAppAllowed function. The tuple is forwarded as the + // function's return value; the slither detector trips on the named + // return + forward pattern but the value is actually used. + // slither-disable-next-line unused-return + return IAppAuth(bootInfo.appId).isAppAllowed(bootInfo); + } + + // Add storage gap for upgradeable contracts + uint256[50] private __gap; +} + +function isContract(address addr) view returns (bool) { + uint32 size; + assembly { + size := extcodesize(addr) + } + return (size > 0); +} diff --git a/dstack/kms/auth-eth/contracts/test-utils/reference/v0.6.0/IAppAuth.sol b/dstack/kms/auth-eth/contracts/test-utils/reference/v0.6.0/IAppAuth.sol new file mode 100644 index 0000000000..56b7689710 --- /dev/null +++ b/dstack/kms/auth-eth/contracts/test-utils/reference/v0.6.0/IAppAuth.sol @@ -0,0 +1,56 @@ +/* + * SPDX-FileCopyrightText: © 2025 Phala Network + * + * SPDX-License-Identifier: Apache-2.0 + */ + +pragma solidity ^0.8.0; + +import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; + +/** + * @title IAppAuth + * @notice Core interface for App Authentication contracts + * @dev This interface defines the core function for validating app boot information. + * Any contract implementing this interface should also implement ERC-165 to + * allow interface detection. + * + * Interface ID: 0x1e079198 + * + * This interface can be checked using: + * contract.supportsInterface(0x1e079198) + */ +interface IAppAuth is IERC165 { + /** + * @notice Information required to validate app boot authorization + * @param appId The unique identifier for the application + * @param composeHash Hash of the application composition/configuration + * @param instanceId Unique identifier for this specific app instance + * @param deviceId Unique identifier for the device/hardware + * @param mrAggregated Aggregated measurement register value + * @param mrSystem System measurement register value + * @param osImageHash Hash of the operating system image + * @param tcbStatus Trusted Computing Base status + * @param advisoryIds Array of security advisory identifiers + */ + struct AppBootInfo { + address appId; + bytes32 composeHash; + address instanceId; + bytes32 deviceId; + bytes32 mrAggregated; + bytes32 mrSystem; + bytes32 osImageHash; + string tcbStatus; + string[] advisoryIds; + } + + /** + * @notice Check if an application is allowed to boot with the given parameters + * @dev This is the core authorization function that validates all boot parameters + * @param bootInfo Struct containing all necessary boot validation information + * @return isAllowed True if the app is authorized to boot, false otherwise + * @return reason Human-readable reason for the decision (empty if allowed) + */ + function isAppAllowed(AppBootInfo calldata bootInfo) external view returns (bool isAllowed, string memory reason); +} diff --git a/dstack/kms/auth-eth/contracts/IAppAuthBasicManagement.sol b/dstack/kms/auth-eth/contracts/test-utils/reference/v0.6.0/IAppAuthBasicManagement.sol similarity index 100% rename from dstack/kms/auth-eth/contracts/IAppAuthBasicManagement.sol rename to dstack/kms/auth-eth/contracts/test-utils/reference/v0.6.0/IAppAuthBasicManagement.sol diff --git a/dstack/kms/auth-eth/docs/formal-verification.md b/dstack/kms/auth-eth/docs/formal-verification.md index 67d776c4a8..867edcc588 100644 --- a/dstack/kms/auth-eth/docs/formal-verification.md +++ b/dstack/kms/auth-eth/docs/formal-verification.md @@ -21,7 +21,7 @@ correctness matters more than gas. - `contracts/DstackApp.sol` (209 LOC) — per-app boot authorization - `contracts/DstackKms.sol` (276 LOC) — KMS whitelist + factory -- `contracts/IAppAuth.sol`, `contracts/IAppAuthBasicManagement.sol` — interfaces +- `contracts/IAppAuth.sol`, `contracts/IAppEpochAuth.sol`, `contracts/IAppEpochManagement.sol` — interfaces ## Layer 0 — Slither (static analysis) @@ -84,8 +84,8 @@ reuse the existing `.t.sol` scaffolding and OZ-foundry-upgrades plugin. ### Setup - [x] `pipx install halmos` documented in `README.md` -- [ ] No CI integration (intentional — see "What's intentionally not in - scope" below) +- [x] Runs in CI (`.github/workflows/halmos.yml`) when `dstack/kms/auth-eth` + changes, with pinned Halmos and Forge versions ### What we verify @@ -120,11 +120,117 @@ says `pre: msg.sender == owner()`, we trust the OZ modifier. init, both `initialize` overloads revert for any inputs. Verifies INV-3. +`test/DstackAppEpoch.symbolic.t.sol` (app epochs; setUp advances to epoch 2 +and admits one app per epoch, then one symbolic owner write where noted): +- [x] `check_AppEpoch_StepMonotonic` — no call to any enumerated mutating + function, by any caller, decreases `currentAppEpoch`; it moves only by + one, through the owner's `advanceAppEpoch(current)`. +- [x] `check_PolicyWrite_RejectsEpochPastNext` — every `*AtEpoch` setter + reverts for an epoch above the next one, and every `*AtEpochs` setter + for a range ending above it, for any caller; the owner may prepare the + next epoch's row before advancing. +- [x] `check_AuthorizeApp_RejectsInactiveEpochAndForeignOperation` — an + epoch above the current one or a non-app operation is never authorized. +- [x] `check_IsAppAllowed_RefusesAtNonzeroEpoch` — once the app epoch has + advanced, the legacy `isAppAllowed` refuses, since its callers derive + epoch-0 keys. +- [x] `check_IsAppAllowed_EqualsEpochZeroDecisionBeforeAdvance` — at app + epoch 0, with the next row prepared and any one owner write, the legacy + `isAppAllowed` returns exactly the `authorizeApp` result at epoch 0. +- [x] `check_PolicyWrite_PreservesOtherEpochDecisions` — a write never + changes an authorization decision at an epoch outside the rows it names + (one epoch, or a symbolic range), including epoch 0's legacy fields. +- [x] `check_TeeVariantPolicy_NarrowsDecision` — once the TEE platform + policy is restricted, `authorizeApp` allows exactly when it would + unrestricted and the request names a listed platform. +- [x] `check_AuthorizeApp_MatchesPolicy` — for both app operations, + `authorizeApp` allows exactly when the epoch is active, the TCB + requirement holds, that epoch admits the compose hash, and the device + is allowed by `allowAnyDevice` or that epoch's device row. +- [x] `check_PolicyWrite_TakesEffect` — each `*AtEpoch` setter on an epoch + up to the next one, and each `*AtEpochs` setter on every row of a range + ending at most there, either sets the value it was given or reverts on + a zero ID. +- [x] `check_FullRangeRemoval_RevokesAtEveryAppEpoch` — after removing a + compose hash from rows 0 through the next epoch, or a device from those + rows and clearing `allowAnyDevice`, no app epoch authorizes it, for + either app operation. + +Mutation-tested: requiring both the any-device flag and a listed device, +dropping a setter's epoch bound or widening it past the next epoch, aliasing epoch 1 onto the +legacy fields, letting `isAppAllowed` decide at a nonzero epoch or read the +prepared next row, a permissionless +`advanceAppEpoch` and dropping its stale-transaction guard each produce a +counterexample. Dropping the inactive-epoch check in `_authorizeApp` does +not: policy for an inactive epoch cannot be written, so that check is +defense in depth. + +`test/DstackKmsEpoch.symbolic.t.sol` (root epochs; setUp registers epochs +0-2, activates 1 so that 2 is pending, admits one KMS identity and OS image +per epoch, and deploys an app at app epoch 1): +- [x] `check_RootRegistry_StepInvariant` — after any single call to any + enumerated mutating function, by any caller with symbolic args: the + current epoch stays registered and moves only by one, through the + owner's activation naming its chain hash; the registry changes by at + most one entry at its end, and only the owner's pop of a pending + epoch naming its chain hash removes one; existing entries keep their + keys and hashes; every chain hash commits to its keys and the previous + hash; `kmsInfo` holds the current keys without legacy evidence. +- [x] `check_RegisterRootEpoch_AcceptsOnlyCanonicalEncodings` — registration + succeeds exactly for a 91-byte uncompressed P-256 SPKI and a 33-byte + compressed secp256k1 key. +- [x] `check_Authorize_EnforcesEpochBounds` — a wrong-kind operation, an app + or `kms_serve` root epoch above the current one, another KMS root epoch + above the latest registered one, or an app epoch above the app's current one is never + authorized; every result reports the current root epoch and hash. +- [x] `check_Authorize_OnlyBootstrapBeforeRegistration` — with no root epoch + registered, only `kms_bootstrap` can be authorized. +- [x] `check_AuthorizeKms_MatchesEpochPolicy` — after any one owner write, + KMS authorization allows exactly when the selected root epoch is + registered (current at most for `kms_serve`), the TCB is up to date, and that epoch's row admits the OS + image, aggregated MR and device. +- [x] `check_AuthorizeApp_MatchesKmsAndAppPolicy` — app authorization allows + exactly when both epochs are active, the selected root epoch admits + the OS image, and the app's own `authorizeApp` admits it. +- [x] `check_KmsPolicyWrite_PreservesOtherEpochDecisions` — a KMS policy + write never changes a KMS decision at a root epoch outside the rows it + names (one epoch, or a symbolic range). +- [x] `check_FullRangeRemoval_RevokesAtEveryEpoch` — after removing an OS + image, aggregated MR or KMS device from rows 0 through the latest, no + request carrying it is authorized at any root or app epoch, for any KMS + operation, nor for app operations in the OS image case. +- [x] `check_PopThenRegister_StartsWithEmptyRows` — popping the pending + epoch and registering the number again, with the same keys or others, + leaves all three of its rows empty. +- [x] `check_EpochZeroRows_AreTheLegacyMappings` — after any one owner + write, the v0.5.x getters and the epoch 0 getters agree. +- [x] `check_AuthorizeApp_LegacyPolicyOnlyAtAppEpochZero` — an app policy + without `IAppEpochAuth`, like v0.5.x and v0.6.0 `DstackApp`, is + authorized exactly when the KMS checks pass at the selected root epoch, + no nonzero app epoch is requested, and its `isAppAllowed` admits it; + its app epoch is reported as 0. +- [x] `check_LegacyEntryPoints_RefuseOnceRotated` — once a later root epoch + is current, `isKmsAllowed` and `isAppAllowed` refuse. +- [x] `check_LegacyKmsCheck_ReadsEpochZeroBeforeRotation` — before any + rotation, with the next epoch registered and prepared, `isKmsAllowed` + decides as `kms_serve` at root epoch 0. + +Mutation-tested: a chain hash that ignores the previous epoch, activation +that leaves `kmsInfo` stale, a pop that ignores the chain hash, app requests +selecting a pending root epoch, KMS requests limited to the current epoch, +`isKmsAllowed` reading the pending epoch or still deciding after a rotation, accepting an `0x04` k256 tag, an +OS image row aliasing epoch 1 onto the legacy row, an app check skipping the +OS image, and non-bootstrap operations before registration each produce a +counterexample. + +The bounds test found that wrong-kind rejections reported root epoch +`(0, 0x0)`, contrary to the KMS README; fixed in #1538. + Single-call (`test/DstackKms.symbolic.t.sol`): - [x] `check_RegisterApp_AnyCallerCanRegisterNonZeroAddress` + `_RejectsZeroAddress` — codifies the permissionless-by-design behavior; see "Findings" - [x] `check_IsAppAllowed_RejectsUnregisteredApp` / `_RejectsUnknownOsImage` - — fully symbolic `AppBootInfo`; the failing gate produces the + — fully symbolic `AppInfo`; the failing gate produces the right rejection reason without delegating - [x] `check_IsAppAllowed_DelegatesFaithfully` — when both KMS gates pass, the outer return equals the registered `IAppAuth`'s return. @@ -235,10 +341,8 @@ If we revisit, target the same invariants as Layer 2 but add: ## What's intentionally not in scope -- **CI gating of Slither / Halmos.** Symbolic execution is slow, solver- - version-sensitive, and produces non-actionable noise as a PR gate. - Run locally during development; treat these as design checks rather - than blocking lints. +- **CI gating of Slither.** It produces non-actionable noise as a PR gate; + run it locally during development. - **Echidna** — overlaps with Foundry's built-in fuzzer (already runs 10k iterations under `FOUNDRY_PROFILE=ci` in `.github/workflows/foundry-test.yml`). - **Manticore / Mythril** — bytecode-level tools, slow, awkward with our diff --git a/dstack/kms/auth-eth/docs/specification.md b/dstack/kms/auth-eth/docs/specification.md index 95a72e5067..dca837c451 100644 --- a/dstack/kms/auth-eth/docs/specification.md +++ b/dstack/kms/auth-eth/docs/specification.md @@ -52,12 +52,12 @@ return-value spoofing are still possible — see §6. | Slot | Name | Type | Writable by | Notes | |---|---|---|---|---| -| 0–3 | `kmsInfo` | `KmsInfo` (struct, 4 fields) | `setKmsInfo`, `setKmsQuote`, `setKmsEventlog` (owner) | | +| 0–3 | `kmsInfo` | `KmsInfo` (struct, 4 fields) | `registerRootEpoch` (epoch 0), `activateRootEpoch` (owner) | Preserved for proxy upgrades and legacy readers; quote and event log are cleared on activation | | 4 | `gatewayAppId` | `string` | `setGatewayAppId` (owner) | Renamed from `tproxyAppId`; carries `@custom:oz-renamed-from` | | 5 | `registeredApps` | `mapping(address => bool)` | `registerApp` (anyone), `deployAndRegisterApp` (anyone) | Permissionless — see §6.1 | -| 6 | `kmsAllowedAggregatedMrs` | `mapping(bytes32 => bool)` | `addKmsAggregatedMr`, `removeKmsAggregatedMr` (owner) | | -| 7 | `kmsAllowedDeviceIds` | `mapping(bytes32 => bool)` | `addKmsDevice`, `removeKmsDevice` (owner) | | -| 8 | `allowedOsImages` | `mapping(bytes32 => bool)` | `addOsImageHash`, `removeOsImageHash` (owner) | | +| 6 | `kmsAllowedAggregatedMrs` | `mapping(bytes32 => bool)` | `addKmsAggregatedMrAtEpochs`, `removeKmsAggregatedMrAtEpochs` at epoch 0 (owner) | | +| 7 | `kmsAllowedDeviceIds` | `mapping(bytes32 => bool)` | `addKmsDeviceAtEpochs`, `removeKmsDeviceAtEpochs` at epoch 0 (owner) | | +| 8 | `allowedOsImages` | `mapping(bytes32 => bool)` | `addOsImageHashAtEpochs`, `removeOsImageHashAtEpochs` at epoch 0 (owner) | | | 9 | `appImplementation` | `address` | `setAppImplementation` (owner) | Used by `deployAndRegisterApp` | | 10 | `__gap[50]` | `uint256[50]` | (none — must always read zero) | Reserved | @@ -69,9 +69,9 @@ Plus inherited storage in ERC-7201 namespaces: `OwnableUpgradeable`, | Slot | Name | Type | Writable by | |---|---|---|---| -| 0 | `allowedComposeHashes` | `mapping(bytes32 => bool)` | `addComposeHash`, `removeComposeHash` (owner); 5/6-arg initializer | -| 1 | `_upgradesDisabled` + `allowAnyDevice` (packed) | `bool` + `bool` | `disableUpgrades` (owner, monotonic); `setAllowAnyDevice` (owner); initializer | -| 2 | `allowedDeviceIds` | `mapping(bytes32 => bool)` | `addDevice`, `removeDevice` (owner); initializer | +| 0 | `allowedComposeHashes` | `mapping(bytes32 => bool)` | `addComposeHashAtEpoch(s)`, `removeComposeHashAtEpoch(s)` at epoch 0 (owner); 5/6-arg initializer | +| 1 | `_upgradesDisabled` + `allowAnyDevice` (packed) | `bool` + `bool` | `disableUpgrades` (owner, monotonic); `setAllowAnyDevice` (owner, every app epoch); initializer | +| 2 | `allowedDeviceIds` | `mapping(bytes32 => bool)` | `addDeviceAtEpoch(s)`, `removeDeviceAtEpoch(s)` at epoch 0 (owner); initializer | | 3 | `requireTcbUpToDate` | `bool` | `setRequireTcbUpToDate` (owner); 6-arg initializer only | | 4 | `__gap[49]` | `uint256[49]` | (none) | @@ -105,8 +105,9 @@ Signature: `deployAndRegisterApp(address initialOwner, bool disableUpgrades, boo - **pre**: `appImplementation != address(0)`; `initialOwner != address(0)`. - **post**: - `registeredApps[appId] == true`. - - `appId` is a freshly-deployed ERC1967 proxy whose implementation is - `appImplementation`. + - `appId` is the address `appImplementation.deployProxy()` returned: a + freshly-deployed ERC1967 proxy of `appImplementation` when that is a + `DstackApp` (an assumption on the owner-set implementation, see §5.2). - The proxy is initialized: `DstackApp(appId).owner() == initialOwner`; `DstackApp(appId).requireTcbUpToDate() == requireTcbUpToDate`; `DstackApp(appId).allowAnyDevice() == allowAnyDevice`; @@ -125,7 +126,7 @@ Signature: `deployAndRegisterApp(address initialOwner, bool disableUpgrades, boo - Semantics: equivalent to the 6-arg overload with `requireTcbUpToDate = false`. - (verified: `DstackKmsSymbolicTest.check_DeployAndRegisterApp5Arg_DefaultsTcbToFalse`) -### 3.5 `DstackKms.isAppAllowed(AppBootInfo b) external view returns (bool, string)` +### 3.5 `DstackKms.isAppAllowed(AppInfo b) external view returns (bool, string)` Decision (in order): @@ -147,7 +148,7 @@ Decision (in order): behavior of an adversarial registered app; those propagate to the outer call by EVM semantics (§5.1). -### 3.6 `DstackKms.isKmsAllowed(AppBootInfo b) external view returns (bool, string)` +### 3.6 `DstackKms.isKmsAllowed(AppInfo b) external view returns (bool, string)` Decision (in order): @@ -167,9 +168,15 @@ Decision (in order): ### 3.7 Owner-only KMS mutations (uniform pattern) -For each of `setKmsInfo`, `setKmsQuote`, `setKmsEventlog`, `setGatewayAppId`, -`setAppImplementation`, `addKmsAggregatedMr`, `removeKmsAggregatedMr`, -`addKmsDevice`, `removeKmsDevice`, `addOsImageHash`, `removeOsImageHash`: +The legacy `setKmsInfo`, `setKmsQuote`, and `setKmsEventlog` entry points are +removed: calls always revert, including before root epoch registration. Initial +setup uses `registerRootEpoch`. On an upgraded proxy with existing legacy roots, +epoch 0 must match the stored `kmsInfo` keys; the upgrade preserves that storage. + +For each of `setGatewayAppId`, +`setAppImplementation`, and the `*AtEpochs` forms of +`addKmsAggregatedMr`, `removeKmsAggregatedMr`, `addKmsDevice`, `removeKmsDevice`, +`addOsImageHash`, `removeOsImageHash`: - **pre**: `msg.sender == owner()`. - **frame**: every storage cell except the one mapped to the operation. @@ -195,7 +202,7 @@ For each of `setKmsInfo`, `setKmsQuote`, `setKmsEventlog`, `setGatewayAppId`, - (verified: `DstackAppSymbolicTest.check_Initialize5Arg_DefaultsTcbToFalse`, `check_Initialize6Arg_HonorsTcbFlag`) -### 3.9 `DstackApp.isAppAllowed(AppBootInfo b) external view returns (bool, string)` +### 3.9 `DstackApp.isAppAllowed(AppInfo b) external view returns (bool, string)` Decision (in order, all evaluated under `b.appId == address(this)` by convention): @@ -231,8 +238,9 @@ byte sequence — no case variations, no trailing nulls, no whitespace. ### 3.11 Owner-only App mutations -For each of `addComposeHash`, `removeComposeHash`, `addDevice`, `removeDevice`, -`setAllowAnyDevice`, `setRequireTcbUpToDate`, `disableUpgrades`: +For each of the `*AtEpoch` and `*AtEpochs` forms of `addComposeHash`, +`removeComposeHash`, `addDevice` and `removeDevice`, and for `setAllowAnyDevice`, +`setRequireTcbUpToDate` and `disableUpgrades`: - **pre**: `msg.sender == owner()`. - **frame**: every storage cell except the one mapped to the operation. @@ -288,14 +296,19 @@ KMS calls `IAppAuth(b.appId).isAppAllowed(b)` after confirming ### 5.2 KMS ↔ Proxy (factory deploy) -`deployAndRegisterApp` calls `new ERC1967Proxy(appImplementation, initData)`. -The proxy constructor delegatecalls into the implementation's initialize -function. Assumptions: +`deployAndRegisterApp` calls `DstackApp(appImplementation).deployProxy()`, +which runs `new ERC1967Proxy(address(this), "")` and refuses to run through a +proxy, then calls `initialize` on the new proxy itself, so the app's initial +`PolicyChanged` events name the KMS as `actor`. Assumptions: -- The constructor runs `initialize` exactly once on the new proxy. +- `deployProxy` returns a new, uninitialized proxy, and `initialize` runs + exactly once on it, in the same transaction. - `appImplementation` is a contract conforming to `DstackApp`'s storage - layout. Setting it to anything else is the owner's prerogative; the - spec does not constrain it beyond non-zero. + layout and exposing `deployProxy`. Setting it to anything else is the + owner's prerogative; the spec does not constrain it beyond non-zero. Such + an implementation could reenter the KMS from `deployProxy` or + `initialize`, or return an existing contract, which the KMS would then + register. ### 5.3 App ↔ Proxy (upgrade authorization) @@ -403,7 +416,7 @@ formal audit: apps have been deployed via the factory, the older proxies stay on the older impl. Is that intended (versioning) or should the KMS track which impl was current at deploy time? -3. **Removing an OS image.** `removeOsImageHash` does not retroactively +3. **Removing an OS image.** `removeOsImageHashAtEpochs` does not retroactively un-authorize already-running apps that booted under that image. Is that intended (revocation requires explicit downstream action) or should the spec require it? diff --git a/dstack/kms/auth-eth/foundry.toml b/dstack/kms/auth-eth/foundry.toml index 05f06a0b2b..a300d54c17 100644 --- a/dstack/kms/auth-eth/foundry.toml +++ b/dstack/kms/auth-eth/foundry.toml @@ -30,6 +30,8 @@ extra_output = ["storageLayout"] fuzz = { runs = 10_000 } [fmt] +# Released contract sources kept verbatim as upgrade references. +ignore = ["contracts/test-utils/reference/**"] bracket_spacing = true int_types = "long" line_length = 120 diff --git a/dstack/kms/auth-eth/index.test.ts b/dstack/kms/auth-eth/index.test.ts new file mode 100644 index 0000000000..6613128598 --- /dev/null +++ b/dstack/kms/auth-eth/index.test.ts @@ -0,0 +1,1667 @@ +// SPDX-FileCopyrightText: © 2025 Phala Network +// +// SPDX-License-Identifier: Apache-2.0 + +import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest'; +import openApiSpec from './openapi.json'; +import { keccak256, toBytes } from 'viem'; + +// Mock viem +const mockReadContract = vi.fn(); +const mockGetChainId = vi.fn(); +const mockGetBlock = vi.fn(); + +vi.mock('viem', async (importOriginal) => ({ + ...await importOriginal(), + createPublicClient: vi.fn(() => ({ + readContract: mockReadContract, + getChainId: mockGetChainId, + getBlock: mockGetBlock, + })), + http: vi.fn(() => () => ({ request: vi.fn() })), + getContract: vi.fn(), +})); + +// A chain whose tagged block is `tip` and whose block n has hash blockHash(n). +const blockHash = (n: bigint) => `0x${n.toString(16).padStart(64, '0')}`; +const chainAt = (tip: bigint, timestamp = 0n) => ({ blockTag, blockNumber }: { blockTag?: string; blockNumber?: bigint }) => + blockTag ? { number: tip } : { number: blockNumber, hash: blockHash(blockNumber!), timestamp }; + +// Dynamic import after mocking +let appFetch: any; + +beforeAll(async () => { + // Set environment variables for testing + process.env.ETH_RPC_URL = 'http://localhost:8545'; + process.env.KMS_CONTRACT_ADDR = '0x1234567890123456789012345678901234567890'; + process.env.PORT = '3001'; + process.env.ETH_CHAIN_ID = '1337'; + process.env.ETH_FINALITY_CONFIRMATIONS = '2'; + + // Import the app after mocking + const indexModule = await import('./index.ts'); + appFetch = indexModule.default.fetch; +}); + +beforeEach(() => { + // Reset mocks before each test + vi.clearAllMocks(); + mockGetChainId.mockResolvedValue(1337); + mockGetBlock.mockImplementation(chainAt(100n)); +}); + +describe('server runtime config', () => { + it('keeps Bun idleTimeout above the KMS webhook timeout', async () => { + // Vitest calls `fetch` directly and never hits Bun.serve, so this pins the + // config that production actually loads. Bun's default of 10s closes the + // socket while GET / is still awaiting eth_call. + const indexModule = await import('./index.ts'); + expect(indexModule.default.idleTimeout).toBeGreaterThanOrEqual(60); + }); +}); + +describe('API Compatibility Tests', () => { + describe('GET /', () => { + it('should return system info matching OpenAPI spec', async () => { + // Mock contract calls + mockReadContract.mockImplementation((params) => { + if (params.functionName === 'rootEpochCount') return 0n; + if (params.functionName === 'gatewayAppId') { + return '0xabcdefabcdefabcdefabcdefabcdefabcdefabcd'; + } + if (params.functionName === 'appImplementation') { + return '0x9876543210987654321098765432109876543210'; + } + }); + mockGetChainId.mockResolvedValue(1337); + + const response = await appFetch(new Request('http://localhost:3001/')); + const data = await response.json(); + + expect(response.status).toBe(200); + expect(data).toMatchObject({ + status: 'ok', + kmsContractAddr: '0x1234567890123456789012345678901234567890', + ethRpcUrl: 'http://localhost:8545', + gatewayAppId: expect.any(String), + chainId: expect.any(Number), + appAuthImplementation: expect.any(String), + appImplementation: expect.any(String), + }); + + // Verify response structure matches OpenAPI spec + const systemInfoSchema = openApiSpec.components.schemas.SystemInfo; + const requiredFields = systemInfoSchema.required; + + requiredFields.forEach(field => { + expect(data).toHaveProperty(field); + }); + }); + + it('should report public chain info in authApiInfo', async () => { + mockReadContract.mockImplementation((params) => { + if (params.functionName === 'rootEpochCount') return 0n; + if (params.functionName === 'gatewayAppId') { + return '0xabcdefabcdefabcdefabcdefabcdefabcdefabcd'; + } + if (params.functionName === 'appImplementation') { + return '0x9876543210987654321098765432109876543210'; + } + }); + + mockGetChainId.mockResolvedValue(1337); + + const response = await appFetch(new Request('http://localhost:3001/')); + const data = await response.json(); + + expect(response.status).toBe(200); + // ETH_BLOCK_TAG is unset (default 'finalized'), + // ETH_FINALITY_CONFIRMATIONS=2 and the tag resolves to block 100. + expect(JSON.parse(data.authApiInfo)).toEqual({ + kmsContractAddr: '0x1234567890123456789012345678901234567890', + chainId: 1337, + appImplementation: '0x9876543210987654321098765432109876543210', + ethRpcUrl: 'http://localhost:8545', + ethRpcUrls: ['http://localhost:8545'], + rpcQuorum: '1/1', + blockTag: 'finalized', + finalityConfirmations: 2, + policyBlockNumber: 98, + }); + }); + + it('should handle errors gracefully', async () => { + // Mock contract calls to throw error + mockReadContract.mockRejectedValue(new Error('contract error')); + mockGetChainId.mockRejectedValue(new Error('network error')); + + const response = await appFetch(new Request('http://localhost:3001/')); + const data = await response.json(); + + expect(response.status).toBe(500); + expect(data).toMatchObject({ + status: 'error', + message: 'authorization backend unavailable', + }); + }); + }); + + describe('POST /bootAuth/app', () => { + const validBootInfo = { + mrAggregated: '0x1234567890123456789012345678901234567890123456789012345678901234', + osImageHash: '0xabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcd', + appId: '0x1111111111111111111111111111111111111111', + composeHash: '0x2222222222222222222222222222222222222222222222222222222222222222', + instanceId: '0x3333333333333333333333333333333333333333', + deviceId: '0x4444444444444444444444444444444444444444444444444444444444444444', + }; + + it('should validate app boot with required fields only', async () => { + // Mock successful contract response + mockReadContract.mockImplementation((params) => { + if (params.functionName === 'rootEpochCount') return 0n; + if (params.functionName === 'isAppAllowed') { + return [true, 'success']; + } + if (params.functionName === 'gatewayAppId') { + return '0xgateway123456789012345678901234567890'; + } + }); + + const response = await appFetch(new Request('http://localhost:3001/bootAuth/app', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(validBootInfo), + })); + + const data = await response.json(); + + expect(response.status).toBe(200); + expect(data).toMatchObject({ + isAllowed: true, + reason: 'success', + gatewayAppId: expect.any(String), + }); + + // Verify response matches OpenAPI spec + const bootResponseSchema = openApiSpec.components.schemas.BootResponse; + const requiredFields = bootResponseSchema.required; + + requiredFields.forEach(field => { + expect(data).toHaveProperty(field); + }); + }); + + it('should handle full BootInfo with optional fields', async () => { + const fullBootInfo = { + ...validBootInfo, + tcbStatus: 'OK', + advisoryIds: ['INTEL-SA-00123'], + mrSystem: '0x5555555555555555555555555555555555555555555555555555555555555555', + }; + + mockReadContract.mockImplementation((params) => { + if (params.functionName === 'rootEpochCount') return 0n; + if (params.functionName === 'isAppAllowed') { + return [true, 'success with full info']; + } + if (params.functionName === 'gatewayAppId') { + return '0xgateway123456789012345678901234567890'; + } + }); + + const response = await appFetch(new Request('http://localhost:3001/bootAuth/app', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(fullBootInfo), + })); + + const data = await response.json(); + + expect(response.status).toBe(200); + expect(data.isAllowed).toBe(true); + expect(data.reason).toBe('success with full info'); + }); + + it('should handle contract errors', async () => { + mockReadContract.mockRejectedValue(new Error('contract call failed')); + + const response = await appFetch(new Request('http://localhost:3001/bootAuth/app', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(validBootInfo), + })); + + const data = await response.json(); + + expect(response.status).toBe(200); + expect(data).toMatchObject({ + isAllowed: false, + gatewayAppId: '', + reason: 'authorization backend unavailable', + }); + }); + + it('should reject invalid request body', async () => { + const invalidBootInfo = { + mrAggregated: '0x1234', // missing required fields + }; + + const response = await appFetch(new Request('http://localhost:3001/bootAuth/app', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(invalidBootInfo), + })); + + expect(response.status).toBe(400); + }); + + + it('should reject oversized and non-hex measurements before backend use', async () => { + for (const mrAggregated of ['0x' + 'ab'.repeat(33), 'not-hex']) { + const response = await appFetch(new Request('http://localhost:3001/bootAuth/app', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ...validBootInfo, mrAggregated }), + })); + + expect(response.status).toBe(400); + expect(await response.json()).toEqual({ isAllowed: false, reason: 'invalid authorization request', gatewayAppId: '' }); + } + expect(mockReadContract).not.toHaveBeenCalled(); + }); +}); + + describe('root epochs', () => { + const validBootInfo = { + mrAggregated: '0x' + '12'.repeat(32), + osImageHash: '0x' + 'ab'.repeat(32), + appId: '0x' + '11'.repeat(20), + composeHash: '0x' + '22'.repeat(32), + instanceId: '0x' + '33'.repeat(20), + deviceId: '0x' + '44'.repeat(32), + }; + + const hash = '0x' + '11'.repeat(32); + const mockChain = (currentRootEpoch: () => unknown, rootEpochCount = () => 2n) => + mockReadContract.mockImplementation((params) => { + switch (params.functionName) { + case 'isAppAllowed': return [true, '']; + case 'isKmsAllowed': return [true, '']; + case 'gatewayAppId': return '0xgateway'; + case 'appImplementation': return '0x9876543210987654321098765432109876543210'; + case 'rootEpochCount': return rootEpochCount(); + case 'currentRootEpoch': return currentRootEpoch(); + case 'rootEpoch': return ['0x30' + params.args[0].toString(16).padStart(2, '0'), '0x02', '', hash]; + } + }); + const boot = async (path: string, fields: object) => { + const response = await appFetch(new Request(`http://localhost:3001/bootAuth/${path}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ...validBootInfo, ...fields }), + })); + return response.json(); + }; + + it('allows only a KMS serving the current root epoch', async () => { + mockChain(() => [1n, hash]); + + expect((await boot('app', { rootEpoch: 1, rootEpochHash: hash })).isAllowed).toBe(true); + const stale = await boot('app', { rootEpoch: 0, rootEpochHash: hash }); + expect(stale.isAllowed).toBe(false); + expect(stale.reason).toMatch(/1 is current/); + const forked = await boot('app', { rootEpoch: 1, rootEpochHash: '0x' + '22'.repeat(32) }); + expect(forked.reason).toMatch(/not the registered/); + // A KMS predating root epochs, and its apps, are cut off. + expect((await boot('app', {})).reason).toMatch(/reports none/); + expect((await boot('kms', {})).reason).toMatch(/reports none/); + + const info = await appFetch(new Request('http://localhost:3001/')); + // The CA key of the current epoch, which signs every serving KMS's RPC certificate. + expect(await info.json()).toMatchObject({ rootEpoch: 1, rootEpochHash: hash, rootCaPubkey: '0x3001' }); + }); + + it('supports an upgraded empty registry without querying the current epoch', async () => { + const current = vi.fn(() => { throw new Error('no root epoch registered'); }); + mockChain(current, () => 0n); + + expect((await boot('app', {})).isAllowed).toBe(true); + expect((await boot('kms', {})).isAllowed).toBe(true); + expect((await boot('app', { rootEpoch: 0, rootEpochHash: hash })).isAllowed).toBe(true); + expect((await boot('app', { rootEpoch: 1, rootEpochHash: hash })).reason).toMatch(/not registered/); + const info = await appFetch(new Request('http://localhost:3001/')); + expect(info.status).toBe(200); + const body = await info.json(); + expect(body).not.toHaveProperty('rootEpoch'); + expect(body).not.toHaveProperty('rootCaPubkey'); + expect(current).not.toHaveBeenCalled(); + }); + + it('serves an old KMS, and its apps, while epoch 0 is current', async () => { + mockChain(() => [0n, hash], () => 1n); + expect((await boot('app', {})).isAllowed).toBe(true); + expect((await boot('kms', {})).isAllowed).toBe(true); + }); + + it.each(['app', 'info'])('reads the registry at the same finalized block for %s', async (endpoint) => { + mockChain(() => [1n, hash]); + if (endpoint === 'app') { + expect((await boot('app', { rootEpoch: 1, rootEpochHash: hash })).isAllowed).toBe(true); + } else { + const response = await appFetch(new Request('http://localhost:3001/')); + expect(response.status).toBe(200); + } + const calls = mockReadContract.mock.calls.map(([params]) => params) + .filter(({ functionName }) => ['rootEpochCount', 'currentRootEpoch', 'rootEpoch'].includes(functionName)); + expect(calls.map(({ functionName }) => functionName)).toEqual(endpoint === 'app' + ? ['rootEpochCount', 'currentRootEpoch'] + : ['rootEpochCount', 'currentRootEpoch', 'rootEpoch']); + expect(calls.every((call) => call.blockHash === blockHash(98n) && call.requireCanonical)).toBe(true); + expect(mockGetBlock).toHaveBeenCalledTimes(2); + }); + + describe.each(['rootEpochCount', 'currentRootEpoch'])('%s failures', (getter) => { + it.each([ + ['missing getter', { name: 'ContractFunctionZeroDataError' }], + ['revert', { name: 'ContractFunctionRevertedError' }], + ['RPC failure', new Error('RPC unavailable')], + ])('fails closed on %s', async (_name, cause) => { + const failure = () => { throw Object.assign(new Error('query failed'), { cause }); }; + mockChain(getter === 'currentRootEpoch' ? failure : () => [1n, hash], + getter === 'rootEpochCount' ? failure : () => 2n); + + for (const path of ['app', 'kms']) { + expect(await boot(path, {})).toEqual({ + isAllowed: false, reason: 'authorization backend unavailable', gatewayAppId: '', + }); + expect((await boot(path, { rootEpoch: 0, rootEpochHash: hash })).isAllowed).toBe(false); + } + const info = await appFetch(new Request('http://localhost:3001/')); + expect(info.status).toBe(500); + }); + + it.each(['0x', '0x1234'] as const)('fails closed on malformed ABI data %s', async (data) => { + const { decodeFunctionResult } = await vi.importActual('viem'); + mockReadContract.mockImplementation((params) => { + if (params.functionName === getter) return decodeFunctionResult({ ...params, data }); + if (params.functionName === 'rootEpochCount') return 2n; + if (params.functionName === 'isAppAllowed') return [true, '']; + if (params.functionName === 'gatewayAppId') return 'gateway-app'; + if (params.functionName === 'appImplementation') return '0x' + '11'.repeat(20); + throw new Error(`unexpected function ${params.functionName}`); + }); + expect((await boot('app', {})).isAllowed).toBe(false); + const info = await appFetch(new Request('http://localhost:3001/')); + expect(info.status).toBe(500); + }); + }); + }); + + describe('POST /bootAuth/kms', () => { + const validBootInfo = { + mrAggregated: '0x1234567890123456789012345678901234567890123456789012345678901234', + osImageHash: '0xabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcd', + appId: '0x1111111111111111111111111111111111111111', + composeHash: '0x2222222222222222222222222222222222222222222222222222222222222222', + instanceId: '0x3333333333333333333333333333333333333333', + deviceId: '0x4444444444444444444444444444444444444444444444444444444444444444', + }; + + it('should validate KMS boot successfully', async () => { + // Mock successful contract response + mockReadContract.mockImplementation((params) => { + if (params.functionName === 'rootEpochCount') return 0n; + if (params.functionName === 'isKmsAllowed') { + return [true, 'KMS allowed']; + } + if (params.functionName === 'gatewayAppId') { + return '0xgateway123456789012345678901234567890'; + } + }); + + const response = await appFetch(new Request('http://localhost:3001/bootAuth/kms', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(validBootInfo), + })); + + const data = await response.json(); + + expect(response.status).toBe(200); + expect(data).toMatchObject({ + isAllowed: true, + reason: 'KMS allowed', + gatewayAppId: expect.any(String), + }); + }); + + it('should handle KMS rejection', async () => { + mockReadContract.mockImplementation((params) => { + if (params.functionName === 'rootEpochCount') return 0n; + if (params.functionName === 'isKmsAllowed') { + return [false, 'KMS not authorized']; + } + if (params.functionName === 'gatewayAppId') { + return '0xgateway123456789012345678901234567890'; + } + }); + + const response = await appFetch(new Request('http://localhost:3001/bootAuth/kms', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(validBootInfo), + })); + + const data = await response.json(); + + expect(response.status).toBe(200); + expect(data).toMatchObject({ + isAllowed: false, + reason: 'KMS not authorized', + gatewayAppId: expect.any(String), + }); + }); + + it('should not log "Test backend error" messages', async () => { + const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); + + mockReadContract.mockRejectedValue(new Error('Test backend error')); + + const response = await appFetch(new Request('http://localhost:3001/bootAuth/kms', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(validBootInfo), + })); + + const data = await response.json(); + + expect(response.status).toBe(200); + expect(data.isAllowed).toBe(false); + expect(data.reason).toBe('authorization backend unavailable'); + + // Verify that console.error was not called for test errors + expect(consoleSpy).not.toHaveBeenCalled(); + + consoleSpy.mockRestore(); + }); + + it('should log other error messages', async () => { + const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); + + mockReadContract.mockRejectedValue(new Error('real error')); + + const response = await appFetch(new Request('http://localhost:3001/bootAuth/kms', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(validBootInfo), + })); + + const data = await response.json(); + + expect(response.status).toBe(200); + expect(data.isAllowed).toBe(false); + expect(data.reason).toBe('authorization backend unavailable'); + + // Diagnostics identify the failing boundary without retaining backend details. + expect(consoleSpy).toHaveBeenCalledWith('KMS authorization backend failed'); + expect(JSON.stringify(consoleSpy.mock.calls)).not.toContain('real error'); + + consoleSpy.mockRestore(); + }); + }); +}); + +describe('API Schema Compatibility', () => { + it('should match BootInfo schema requirements', () => { + const bootInfoSchema = openApiSpec.components.schemas.BootInfo; + + // Required fields should match original fastify schema + expect(bootInfoSchema.required).toEqual([ + 'mrAggregated', + 'osImageHash', + 'appId', + 'composeHash', + 'instanceId', + 'deviceId' + ]); + + // Optional fields should be present for full compatibility + expect(bootInfoSchema.properties).toHaveProperty('tcbStatus'); + expect(bootInfoSchema.properties).toHaveProperty('advisoryIds'); + expect(bootInfoSchema.properties).toHaveProperty('mrSystem'); + }); + + it('should match BootResponse schema requirements', () => { + const bootResponseSchema = openApiSpec.components.schemas.BootResponse; + + expect(bootResponseSchema.required).toEqual([ + 'isAllowed', + 'reason', + 'gatewayAppId' + ]); + }); + + it('should match SystemInfo schema requirements', () => { + const systemInfoSchema = openApiSpec.components.schemas.SystemInfo; + + expect(systemInfoSchema.required).toEqual([ + 'status', + 'kmsContractAddr', + 'ethRpcUrl', + 'gatewayAppId', + 'chainId', + 'appAuthImplementation', + 'appImplementation' + ]); + }); +}); + +describe('Hex Decoding Compatibility', () => { + it('should handle hex values with and without 0x prefix', async () => { + const bootInfoWithoutPrefix = { + mrAggregated: '1234567890123456789012345678901234567890123456789012345678901234', + osImageHash: 'abcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcd', + appId: '1111111111111111111111111111111111111111', + composeHash: '2222222222222222222222222222222222222222222222222222222222222222', + instanceId: '3333333333333333333333333333333333333333', + deviceId: '4444444444444444444444444444444444444444444444444444444444444444', + }; + + mockReadContract.mockImplementation((params) => { + if (params.functionName === 'rootEpochCount') return 0n; + if (params.functionName === 'isAppAllowed') { + // Verify that hex values are properly formatted + const [bootInfoStruct] = params.args; + expect(bootInfoStruct.mrAggregated).toMatch(/^0x[0-9a-f]{64}$/i); + expect(bootInfoStruct.appId).toMatch(/^0x[0-9a-f]{40}$/i); + return [true, 'success']; + } + if (params.functionName === 'gatewayAppId') { + return '0xgateway123456789012345678901234567890'; + } + }); + + const response = await appFetch(new Request('http://localhost:3001/bootAuth/app', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(bootInfoWithoutPrefix), + })); + + expect(response.status).toBe(200); + }); +}); + +describe('Authorization freshness and domain binding', () => { + const requestBody = { + mrAggregated: '0x' + '11'.repeat(32), + osImageHash: '0x' + '22'.repeat(32), + appId: '0x' + '33'.repeat(20), + composeHash: '0x' + '44'.repeat(32), + instanceId: '0x' + '55'.repeat(20), + deviceId: '0x' + '66'.repeat(32), + }; + + const postApp = (body = requestBody) => appFetch(new Request( + 'http://localhost:3001/bootAuth/app', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }, + )); + + it('re-evaluates replayed payloads instead of caching an earlier allow', async () => { + let decisions = 0; + mockReadContract.mockImplementation((params) => { + expect(params.address).toBe('0x1234567890123456789012345678901234567890'); + if (params.functionName === 'rootEpochCount') return 0n; + if (params.functionName === 'isAppAllowed') { + decisions += 1; + return decisions === 1 ? [true, 'initial allow'] : [false, 'policy changed']; + } + if (params.functionName === 'gatewayAppId') return 'gateway-app'; + throw new Error(`unexpected function ${params.functionName}`); + }); + + const first = await postApp(); + const replay = await postApp(); + + expect(await first.json()).toMatchObject({ isAllowed: true, reason: 'initial allow' }); + expect(await replay.json()).toMatchObject({ isAllowed: false, reason: 'policy changed' }); + expect(decisions).toBe(2); + }); + + it('binds changed measurements and identities into distinct contract arguments', async () => { + const calls: unknown[] = []; + mockReadContract.mockImplementation((params) => { + if (params.functionName === 'rootEpochCount') return 0n; + if (params.functionName === 'isAppAllowed') { + calls.push(params.args[0]); + return [true, 'allowed']; + } + if (params.functionName === 'gatewayAppId') return 'gateway-app'; + throw new Error(`unexpected function ${params.functionName}`); + }); + + await postApp(); + await postApp({ ...requestBody, composeHash: '0x' + '77'.repeat(32) }); + await postApp({ ...requestBody, appId: '0x' + '88'.repeat(20) }); + + expect(calls).toHaveLength(3); + expect(calls[0]).not.toEqual(calls[1]); + expect(calls[0]).not.toEqual(calls[2]); + }); + + it('fails closed during backend interruption and succeeds after recovery', async () => { + mockReadContract.mockRejectedValueOnce(new Error('backend unavailable')); + const interrupted = await postApp(); + expect(await interrupted.json()).toEqual({ + isAllowed: false, + gatewayAppId: '', + reason: 'authorization backend unavailable', + }); + + mockReadContract.mockImplementation((params) => { + if (params.functionName === 'rootEpochCount') return 0n; + if (params.functionName === 'isAppAllowed') return [true, 'recovered']; + if (params.functionName === 'gatewayAppId') return 'gateway-app'; + throw new Error(`unexpected function ${params.functionName}`); + }); + const recovered = await postApp(); + expect(await recovered.json()).toMatchObject({ isAllowed: true, reason: 'recovered' }); + }); +}); + + +describe('Ethereum finalized snapshot authorization', () => { + const requestBody = { + mrAggregated: '0x' + '11'.repeat(32), + osImageHash: '0x' + '22'.repeat(32), + appId: '0x' + '33'.repeat(20), + composeHash: '0x' + '44'.repeat(32), + instanceId: '0x' + '55'.repeat(20), + deviceId: '0x' + '66'.repeat(32), + }; + + const authorize = () => appFetch(new Request('http://localhost:3001/bootAuth/app', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(requestBody), + })); + + it('reads the decision and gateway identity from one confirmation-depth snapshot', async () => { + mockReadContract.mockImplementation((params) => { + expect(params.blockHash).toBe(blockHash(98n)); + if (params.functionName === 'rootEpochCount') return 0n; + if (params.functionName === 'isAppAllowed') return [true, 'finalized allow']; + if (params.functionName === 'gatewayAppId') return 'gateway-app'; + throw new Error(`unexpected function ${params.functionName}`); + }); + + const response = await authorize(); + expect(await response.json()).toMatchObject({ isAllowed: true, reason: 'finalized allow' }); + expect(mockGetBlock.mock.calls).toEqual([[{ blockTag: 'finalized' }], [{ blockNumber: 98n }]]); + }); + + it('probes the block tag and a pinned read at startup and names what the RPC cannot serve', async () => { + const { EthereumBackend } = await import('./index.ts'); + const getBlock = vi.fn(chainAt(5n)); + const call = vi.fn(async (_: unknown) => ({})); + const client = { getChainId: async () => 1337, getBlock, call }; + const backend = new EthereumBackend(client as never, '0x' + '11'.repeat(20), 1337, 'safe', 0n); + await expect(backend.probe()).resolves.toBeUndefined(); + expect(getBlock).toHaveBeenCalledWith({ blockTag: 'safe' }); + expect(call.mock.calls[0][0]).toMatchObject({ blockHash: blockHash(5n), requireCanonical: true }); + call.mockRejectedValueOnce(new Error('invalid params')); + await expect(backend.probe()).rejects.toThrow(/^cannot read at a block hash, .+ \(invalid params\)$/); + getBlock.mockRejectedValue(new Error('invalid block tag')); + await expect(backend.probe()).rejects.toThrow( + /^cannot resolve ETH_BLOCK_TAG=safe \(invalid block tag\); .+ requires latest$/, + ); + // Behind the confirmation depth counts as unavailable too. + getBlock.mockResolvedValue({ number: 1n }); + const deep = new EthereumBackend(client as never, '0x' + '11'.repeat(20), 1337, 'finalized', 2n); + await expect(deep.probe()).rejects.toThrow(/ETH_BLOCK_TAG=finalized/); + }); + + it('fails closed when the block is older than ETH_MAX_BLOCK_AGE', async () => { + const { EthereumBackend } = await import('./index.ts'); + const now = BigInt(Math.floor(Date.now() / 1000)); + const backend = (timestamp: bigint) => new EthereumBackend( + { getChainId: async () => 1337, getBlock: chainAt(5n, timestamp) } as never, '0x' + '11'.repeat(20), 1337, 'latest', 0n, 60, + ); + await expect(backend(now - 30n).resolveBlock()).resolves.toMatchObject({ number: 5n }); + await expect(backend(now - 90n).resolveBlock()).rejects.toThrow(/ETH_MAX_BLOCK_AGE/); + }); + + it('accepts only the supported block tags, defaulting to finalized', async () => { + const { parseBlockTag } = await import('./index.ts'); + expect(parseBlockTag(undefined)).toBe('finalized'); + expect(parseBlockTag('')).toBe('finalized'); + for (const tag of ['latest', 'safe', 'finalized']) expect(parseBlockTag(tag)).toBe(tag); + expect(() => parseBlockTag('pending')).toThrow(/ETH_BLOCK_TAG/); + expect(() => parseBlockTag('0x10')).toThrow(/ETH_BLOCK_TAG/); + }); + + it('re-evaluates the canonical finalized snapshot after a short reorg', async () => { + let decisions = 0; + const observedBlocks: string[] = []; + mockReadContract.mockImplementation((params) => { + if (params.functionName === 'rootEpochCount') return 0n; + if (params.functionName === 'isAppAllowed') { + observedBlocks.push(params.blockHash); + decisions += 1; + return decisions === 1 ? [true, 'old canonical allow'] : [false, 'new canonical deny']; + } + if (params.functionName === 'gatewayAppId') return 'gateway-app'; + throw new Error(`unexpected function ${params.functionName}`); + }); + + const before = await authorize(); + mockGetBlock.mockImplementation(chainAt(101n)); + const after = await authorize(); + expect(await before.json()).toMatchObject({ isAllowed: true }); + expect(await after.json()).toMatchObject({ isAllowed: false, reason: 'new canonical deny' }); + expect(observedBlocks).toEqual([blockHash(98n), blockHash(99n)]); + }); + + it.each([ + ['wrong chain', () => mockGetChainId.mockResolvedValue(1)], + ['stale head', () => mockGetBlock.mockResolvedValue({ number: 1n })], + ['head timeout', () => mockGetBlock.mockRejectedValue(new Error('timeout'))], + ['unsupported block tag', () => mockGetBlock.mockRejectedValue(new Error('invalid block tag'))], + ])('fails closed for %s and recovers without retained decisions', async (_name, inject) => { + inject(); + const failed = await authorize(); + expect(await failed.json()).toEqual({ + isAllowed: false, + gatewayAppId: '', + reason: 'authorization backend unavailable', + }); + + mockGetChainId.mockResolvedValue(1337); + mockGetBlock.mockImplementation(chainAt(102n)); + mockReadContract.mockImplementation((params) => { + if (params.functionName === 'rootEpochCount') return 0n; + if (params.functionName === 'isAppAllowed') return [true, 'recovered']; + if (params.functionName === 'gatewayAppId') return 'gateway-app'; + throw new Error(`unexpected function ${params.functionName}`); + }); + const recovered = await authorize(); + expect(await recovered.json()).toMatchObject({ isAllowed: true, reason: 'recovered' }); + }); +}); + +// The body dstack-kms 0.6.x posts: `dstack_verifier::PolicyBootInfo`, camelCase, +// bytes as unprefixed lowercase hex, plus fields this backend does not read. +describe('dstack-kms 0.6 bootAuth payload', () => { + const kmsPayload = (overrides: Record = {}) => ({ + teeVariant: 'dstack-tdx', + mrAggregated: '11'.repeat(32), + osImageHash: 'ec43cb8c5e04b6bb6c53b33b16076a01d83d01f7f4b703f2f78a0d947d6247e6', + mrSystem: '22'.repeat(32), + appId: '33'.repeat(20), + composeHash: '44'.repeat(32), + instanceId: '55'.repeat(20), + deviceId: '66'.repeat(32), + keyProviderInfo: '7b226e616d65223a226b6d73227d'.repeat(40), + tcbStatus: 'UpToDate', + advisoryIds: ['INTEL-SA-00837'], + ...overrides, + }); + + const post = (path: string, body: unknown) => + appFetch(new Request(`http://localhost:3001${path}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + })); + + const bootInfoArg = (functionName: string) => + mockReadContract.mock.calls.map(([params]) => params) + .find((params) => params.functionName === functionName).args[0]; + + beforeEach(() => { + mockReadContract.mockImplementation((params) => { + if (params.functionName === 'rootEpochCount') return 0n; + if (params.functionName === 'isKmsAllowed' || params.functionName === 'isAppAllowed') { + return [true, '']; + } + if (params.functionName === 'gatewayAppId') return 'gateway-app'; + throw new Error(`unexpected function ${params.functionName}`); + }); + }); + + it.each([ + ['/bootAuth/kms', 'isKmsAllowed'], + ['/bootAuth/app', 'isAppAllowed'], + ])('%s forwards every policy field to %s', async (path, functionName) => { + const response = await post(path, kmsPayload()); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ isAllowed: true, reason: '', gatewayAppId: 'gateway-app' }); + expect(bootInfoArg(functionName)).toEqual({ + appId: `0x${'33'.repeat(20)}`, + composeHash: `0x${'44'.repeat(32)}`, + instanceId: `0x${'55'.repeat(20)}`, + deviceId: `0x${'66'.repeat(32)}`, + mrAggregated: `0x${'11'.repeat(32)}`, + mrSystem: `0x${'22'.repeat(32)}`, + osImageHash: '0xec43cb8c5e04b6bb6c53b33b16076a01d83d01f7f4b703f2f78a0d947d6247e6', + tcbStatus: 'UpToDate', + advisoryIds: ['INTEL-SA-00837'], + }); + }); + + it('maps the empty instance ID of an instance-less app to the zero address', async () => { + const response = await post('/bootAuth/app', kmsPayload({ instanceId: '' })); + + expect(await response.json()).toMatchObject({ isAllowed: true }); + expect(bootInfoArg('isAppAllowed').instanceId).toBe(`0x${'00'.repeat(20)}`); + }); + + it('passes a non-UpToDate TCB status through for the contract to judge', async () => { + await post('/bootAuth/kms', kmsPayload({ tcbStatus: 'OutOfDate' })); + + expect(bootInfoArg('isKmsAllowed').tcbStatus).toBe('OutOfDate'); + }); +}); + +describe('request hardening', () => { + const bootInfo = { + mrAggregated: '11'.repeat(32), + osImageHash: '22'.repeat(32), + appId: '33'.repeat(20), + composeHash: '44'.repeat(32), + instanceId: '55'.repeat(20), + deviceId: '66'.repeat(32), + }; + + const post = (body: string, contentType: string) => + appFetch(new Request('http://localhost:3001/bootAuth/app', { + method: 'POST', + headers: { 'Content-Type': contentType, Origin: 'https://evil.example' }, + body, + })); + + it.each(['text/plain', 'application/x-www-form-urlencoded'])( + 'rejects a cross-origin simple request sent as %s without reading the contract', + async (contentType) => { + const response = await post(JSON.stringify(bootInfo), contentType); + + expect(response.status).toBe(400); + expect(response.headers.get('access-control-allow-origin')).toBeNull(); + expect(mockReadContract).not.toHaveBeenCalled(); + }, + ); + + it('rejects an oversized body before parsing it', async () => { + const response = await post( + JSON.stringify({ ...bootInfo, padding: 'a'.repeat(256 * 1024) }), + 'application/json', + ); + + expect(response.status).toBe(413); + expect(await response.json()).toEqual({ + isAllowed: false, + reason: 'invalid authorization request', + gatewayAppId: '', + }); + expect(mockReadContract).not.toHaveBeenCalled(); + }); + + it('marks JSON responses as not sniffable and not frameable', async () => { + const response = await appFetch(new Request('http://localhost:3001/no-such-route')); + + expect(response.headers.get('x-content-type-options')).toBe('nosniff'); + expect(response.headers.get('x-frame-options')).toBe('SAMEORIGIN'); + }); +}); + + +describe('GET /app/:appId', () => { + it('reports an app epoch only when the contract can vouch for it', async () => { + const url = `http://localhost/app/0x${'11'.repeat(20)}`; + mockReadContract.mockRejectedValueOnce(new Error('execution reverted: AppNotRegistered()')); + expect((await appFetch(new Request(url))).status).toBe(503); + mockReadContract.mockResolvedValueOnce(0n); + const legacy = await appFetch(new Request(url)); + expect(legacy.status).toBe(200); + expect(await legacy.json()).toEqual({ currentAppEpoch: 0 }); + expect(mockGetBlock).toHaveBeenCalledWith({ blockTag: 'latest' }); + expect(mockReadContract.mock.lastCall![0].blockHash).toBe(blockHash(100n)); + // Without agreement on the newest block, the read steps back by the confirmation depth. + mockGetBlock.mockImplementationOnce(chainAt(100n)).mockRejectedValueOnce(new Error('no quorum')); + mockReadContract.mockResolvedValueOnce(3n); + expect(await (await appFetch(new Request(url))).json()).toEqual({ currentAppEpoch: 3 }); + expect(mockReadContract.mock.lastCall![0].blockHash).toBe(blockHash(98n)); + }); +}); + +describe('GET /sevSnpTcbRequirements', () => { + it('serves the contract value, and fails closed when it cannot be read', async () => { + const url = 'http://localhost/sevSnpTcbRequirements'; + mockReadContract.mockResolvedValueOnce('[]'); + const response = await appFetch(new Request(url)); + expect(await response.json()).toEqual({ requirements: '[]' }); + expect(mockReadContract).toHaveBeenCalledWith( + expect.objectContaining({ functionName: 'sevSnpTcbRequirements', blockHash: blockHash(98n) }), + ); + mockReadContract.mockRejectedValueOnce(new Error('execution reverted')); + expect((await appFetch(new Request(url))).status).toBe(503); + }); +}); + +describe('POST /authorizeApp', () => { + const appInfo = { + teeVariant: 'dstack-amd-sev-snp', appId: '0x' + '11'.repeat(20), composeHash: '0x' + '22'.repeat(32), + instanceId: '', deviceId: '0x' + '33'.repeat(32), + mrAggregated: '0x' + '44'.repeat(32), mrSystem: '0x' + '55'.repeat(32), + osImageHash: '0x' + '66'.repeat(32), tcbStatus: 'UpToDate', advisoryIds: [], + }; + const authorize = (requestedRootEpoch?: number) => appFetch(new Request('http://localhost/authorizeApp', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...appInfo, operation: 'app_get_key', requestedRootEpoch }), + })); + + it('reads the complete result with one contract call at configured finality', async () => { + const result = { + authorized: false, rejectionReason: 'App not registered', gatewayAppId: 'gateway', + currentAppEpoch: 0n, currentRootEpoch: 2n, currentRootEpochHash: '0x' + '77'.repeat(32), + latestRootEpoch: 3n, latestRootEpochHash: '0x' + '88'.repeat(32), + }; + mockReadContract.mockResolvedValueOnce(result); + const response = await authorize(); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ ...result, currentRootEpoch: 2, currentAppEpoch: 0, latestRootEpoch: 3 }); + expect(mockReadContract).toHaveBeenCalledTimes(1); + expect(mockReadContract).toHaveBeenCalledWith(expect.objectContaining({ + functionName: 'authorizeApp', blockHash: blockHash(98n), + args: [expect.objectContaining({ appInfo: expect.objectContaining({ appId: appInfo.appId }), requestedAppEpoch: { isSet: false, value: 0n }, requestedRootEpoch: { isSet: false, value: 0n }, teeVariant: appInfo.teeVariant })], + })); + }); + + it('forwards the launch ticket hash, zero when absent', async () => { + const result = { + authorized: true, rejectionReason: '', gatewayAppId: 'gateway', + currentAppEpoch: 0n, currentRootEpoch: 1n, currentRootEpochHash: '0x' + '77'.repeat(32), + latestRootEpoch: 1n, latestRootEpochHash: '0x' + '77'.repeat(32), + }; + mockReadContract.mockResolvedValue(result); + const ticket = '0x' + '99'.repeat(32); + for (const [launchTicketHash, expected] of [[ticket, ticket], [undefined, '0x' + '00'.repeat(32)]]) { + const response = await appFetch(new Request('http://localhost/authorizeApp', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ...appInfo, operation: 'app_get_key', launchTicketHash }), + })); + expect(response.status).toBe(200); + expect(mockReadContract).toHaveBeenLastCalledWith(expect.objectContaining({ + args: [expect.objectContaining({ launchTicketHash: expected })], + })); + } + }); + + it('encodes an explicit epoch zero as present', async () => { + mockReadContract.mockResolvedValueOnce({ + authorized: true, rejectionReason: '', gatewayAppId: 'gateway', + currentAppEpoch: 0n, currentRootEpoch: 1n, currentRootEpochHash: '0x' + '77'.repeat(32), + latestRootEpoch: 1n, latestRootEpochHash: '0x' + '77'.repeat(32), + }); + expect((await authorize(0)).status).toBe(200); + expect(mockReadContract).toHaveBeenCalledWith(expect.objectContaining({ + args: [expect.objectContaining({ requestedRootEpoch: { isSet: true, value: 0n } })], + })); + }); + + it.each([ + ['authorizeKms', 'kms_import_keys', { requestedRootEpoch: 2 }], + ['authorizeApp', 'app_get_key', { requestedRootEpoch: 1, requestedAppEpoch: 3 }], + ['authorizeApp', 'app_get_cert', {}], + ] as const)('forwards the operation and both epochs to %s (%s)', async (method, operation, epochs) => { + mockReadContract.mockResolvedValueOnce({ + authorized: true, rejectionReason: '', gatewayAppId: 'gateway', + currentAppEpoch: 3n, currentRootEpoch: 2n, currentRootEpochHash: '0x' + '77'.repeat(32), + latestRootEpoch: 2n, latestRootEpochHash: '0x' + '77'.repeat(32), + }); + const response = await appFetch(new Request(`http://localhost/${method}`, { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ...appInfo, operation, ...epochs }), + })); + expect(response.status).toBe(200); + const selector = (value?: number) => ({ isSet: value !== undefined, value: BigInt(value ?? 0) }); + const { requestedRootEpoch, requestedAppEpoch } = epochs as { requestedRootEpoch?: number, requestedAppEpoch?: number }; + expect(mockReadContract).toHaveBeenCalledTimes(1); + expect(mockReadContract).toHaveBeenCalledWith(expect.objectContaining({ + functionName: method, + args: [expect.objectContaining({ + operation: keccak256(toBytes(operation)), + requestedRootEpoch: selector(requestedRootEpoch), + requestedAppEpoch: selector(requestedAppEpoch), + })], + })); + }); + + it('rejects invalid, malformed and oversized requests in the AuthorizationResult shape', async () => { + const rejection = { + authorized: false, rejectionReason: 'invalid authorization request', gatewayAppId: '', + currentRootEpoch: 0, currentRootEpochHash: '0x' + '00'.repeat(32), currentAppEpoch: 0, + latestRootEpoch: 0, latestRootEpochHash: '0x' + '00'.repeat(32), + }; + const requests = [ + { status: 400, body: JSON.stringify({ ...appInfo, operation: 'unknown' }) }, + { status: 400, body: JSON.stringify({ ...appInfo, operation: 'app_get_key', mrAggregated: 'not-hex' }) }, + { status: 400, body: JSON.stringify({ ...appInfo, operation: 'app_get_key', teeVariant: undefined }) }, + { status: 400, body: JSON.stringify({ ...appInfo, operation: 'app_get_key', teeVariant: '' }) }, + { status: 400, body: JSON.stringify({ ...appInfo, operation: 'app_get_key', launchTicketHash: '0x' + '99'.repeat(33) }) }, + { status: 400, body: '{"appId":' }, + { status: 413, body: JSON.stringify({ ...appInfo, operation: 'app_get_key', padding: 'a'.repeat(256 * 1024) }) }, + ]; + for (const path of ['/authorizeApp', '/authorizeKms']) { + for (const { status, body } of requests) { + const response = await appFetch(new Request(`http://localhost${path}`, { + method: 'POST', headers: { 'Content-Type': 'application/json' }, body, + })); + expect(response.status).toBe(status); + expect(await response.json()).toEqual(rejection); + } + } + expect(mockReadContract).not.toHaveBeenCalled(); + }); + + it('does not fall back to legacy authorization on a failed contract call', async () => { + mockReadContract.mockRejectedValueOnce(new Error('contract unavailable')); + expect((await authorize()).status).toBe(503); + expect(mockReadContract).toHaveBeenCalledTimes(1); + }); +}); + +describe('RPC quorum', () => { + const block = (number: number, fork = 'a') => ({ number: `0x${number.toString(16)}`, hash: `0x${fork}${number}`, timestamp: '0x1' }); + // Each answer is a value to return, or an Error to fail with. + const transport = async (threshold: number, answers: unknown[]) => { + const { quorumTransport } = await import('./index.ts'); + const providers = answers.map((answer, i) => ({ + origin: `https://rpc${i}.example`, + request: async () => { if (answer instanceof Error) throw answer; return answer; }, + })); + return quorumTransport(providers, threshold)({}); + }; + const call = { method: 'eth_call', params: [{}, 'latest'] }; + + it('answers only with what the threshold of providers agree on', async () => { + const request = async (threshold: number, answers: unknown[]) => (await transport(threshold, answers)).request(call); + await expect(request(2, ['0xAB', '0x01', '0xab'])).resolves.toBe('0xab'); + await expect(request(2, ['0x01', new Error('down'), '0x01'])).resolves.toBe('0x01'); + await expect(request(2, ['0x01', '0x02', '0x03'])).rejects.toThrow(/no 2 of 3 RPCs agree on eth_call/); + await expect(request(3, ['0x01', '0x01', new Error('execution reverted')])).rejects.toThrow( + 'https://rpc2.example: execution reverted', + ); + }); + + it('resolves a tag to the highest block the threshold has reached', async () => { + const tag = { method: 'eth_getBlockByNumber', params: ['finalized', false] }; + const request = async (answers: unknown[]) => (await transport(2, answers)).request(tag); + await expect(request([block(5), block(100), block(99)])).resolves.toEqual(block(99)); + await expect(request([block(1_000_000), block(100), block(100)])).resolves.toEqual(block(100)); + await expect(request([block(100), new Error('down'), block(98)])).resolves.toEqual(block(98)); + await expect(request([block(100), new Error('invalid block tag'), null])).rejects.toThrow( + /fewer than 2 RPCs serve block finalized \(https:\/\/rpc1\.example: invalid block tag/, + ); + }); + + it('agrees on a numbered block by hash and timestamp', async () => { + const numbered = { method: 'eth_getBlockByNumber', params: ['0x62', false] }; + const request = async (answers: unknown[]) => (await transport(2, answers)).request(numbered); + await expect(request([block(98), { ...block(98), extra: 1 }, block(98, 'b')])).resolves.toMatchObject(block(98)); + await expect(request([block(98), block(98, 'b'), null])).rejects.toThrow(/no 2 of 3 RPCs agree/); + await expect(request([block(98), { ...block(98), number: '0x1' }, null])).rejects.toThrow(/no 2 of 3 RPCs agree/); + }); + + it('refuses methods it has no agreement rule for', async () => { + const request = (await transport(1, ['0x1'])).request({ method: 'eth_getBalance', params: [] }); + await expect(request).rejects.toThrow(/eth_getBalance is not supported/); + }); + + it('pins the endpoint count and keeps URLs out of errors', async () => { + const { parseRpcConfig } = await import('./index.ts'); + const urls = 'https://a.example/v2/key1\n https://b.example/v3/key2\nhttps://c.example\n'; + expect(parseRpcConfig({ ETH_RPC_URLS: urls, ETH_RPC_QUORUM: '2/3', ETH_MAX_BLOCK_AGE: '1800' })).toMatchObject({ + origins: ['https://a.example', 'https://b.example', 'https://c.example'], threshold: 2, + }); + expect(parseRpcConfig({ ETH_RPC_URL: 'http://node:8545' })).toMatchObject({ quorum: '1/1', threshold: 1 }); + for (const [env, error] of [ + [{ ETH_RPC_URLS: urls }, /ETH_RPC_QUORUM must be n\/m/], + [{ ETH_RPC_URLS: urls, ETH_RPC_QUORUM: '4/3' }, /ETH_RPC_QUORUM must be n\/m/], + [{ ETH_RPC_URLS: urls, ETH_RPC_QUORUM: '2' }, /ETH_RPC_QUORUM must be n\/m/], + // One provider of three, or either half of four, could answer alone. + [{ ETH_RPC_URLS: urls, ETH_RPC_QUORUM: '1/3' }, /ETH_RPC_QUORUM must be n\/m/], + [{ ETH_RPC_URLS: urls + ' https://d.example', ETH_RPC_QUORUM: '2/4' }, /ETH_RPC_QUORUM must be n\/m/], + // A key that smuggles in an endpoint changes the count. + [{ ETH_RPC_URLS: urls + ' https://evil.example', ETH_RPC_QUORUM: '2/3' }, /expects 3 RPC URLs, got 4/], + [{ ETH_RPC_URLS: 'https://a.example/1 https://a.example/2', ETH_RPC_QUORUM: '2/2' }, /distinct origins/], + [{ ETH_RPC_URLS: 'https://a.example/key1 key2', ETH_RPC_QUORUM: '2/2' }, /^RPC URL 2 is invalid$/], + [{ ETH_RPC_URL: 'http://a', ETH_RPC_URLS: 'http://b', ETH_RPC_QUORUM: '1/1' }, /exactly one of/], + [{}, /exactly one of/], + [{ ETH_RPC_URLS: urls, ETH_RPC_QUORUM: '2/3' }, /ETH_MAX_BLOCK_AGE is required/], + ] as const) { + expect(() => parseRpcConfig(env)).toThrow(error); + } + }); +}); + +describe('delegated app authorization', () => { + const CURRENT_HASH = '0x' + 'aa'.repeat(32); + const LATEST_HASH = '0x' + 'bb'.repeat(32); + const GATEWAY = 'chain-gateway'; + const ZERO_HASH = '0x' + '00'.repeat(32); + const launchTicketHash = 'ab'.repeat(32); + const userConfigHash = 'cd'.repeat(32); + const appId = '0x' + '11'.repeat(20); + // The space after '{' distinguishes forwarding from a JSON parse/stringify + // round trip, even if the latter preserves key order and unknown fields. + const rawBody = [ + '{ ', + `"userConfigHash":"${userConfigHash}",`, + `"launchTicketHash":"${launchTicketHash}",`, + '"operation":"app_get_key",', + '"teeVariant":"dstack-tdx",', + `"requestedRootEpoch":1,`, + `"appId":"${appId}",`, + `"composeHash":"${'22'.repeat(32)}",`, + '"instanceId":"",', + `"deviceId":"${'33'.repeat(32)}",`, + `"mrAggregated":"${'44'.repeat(32)}",`, + `"osImageHash":"${'66'.repeat(32)}"`, + '}', + ].join(''); + + type DelegateCall = { + url: string; + method: string; + body?: Uint8Array; + redirect?: RequestRedirect; + signal?: AbortSignal | null; + }; + let calls: DelegateCall[]; + + const chainRoots = { + gatewayAppId: GATEWAY, + currentRootEpoch: 2, + currentRootEpochHash: CURRENT_HASH, + latestRootEpoch: 3, + latestRootEpochHash: LATEST_HASH, + }; + + // Emulates the KMS-owned checks of DstackKms.checkKmsAppPolicy (operation + // scope, root epochs) and reports `policyRejection` for the OS image and TEE + // variant allowlists it does not model. + function mockChain( + { count = 4n, fail = false, policyRejection = '' }: { count?: bigint; fail?: boolean; policyRejection?: string } = {}, + ) { + const APP_OPERATIONS = new Set(['app_get_key', 'app_get_cert'].map((op) => keccak256(toBytes(op)))); + mockReadContract.mockImplementation((params) => { + if (fail) return Promise.reject(new Error('rpc down')); + switch (params.functionName) { + case 'checkKmsAppPolicy': { + const [request] = params.args; + if (!APP_OPERATIONS.has(request.operation)) return 'Invalid authorization operation'; + if (count === 0n) return 'Root epoch not registered'; + if (request.requestedRootEpoch.isSet && request.requestedRootEpoch.value > 2n) { + return 'Requested root epoch is not active'; + } + return policyRejection; + } + case 'gatewayAppId': return GATEWAY; + case 'rootEpochCount': return count; + case 'currentRootEpoch': return [2n, CURRENT_HASH]; + case 'rootEpoch': return ['0x' + '11'.repeat(32), '0x' + '22'.repeat(32), 'evidence', LATEST_HASH]; + case 'appImplementation': return '0x' + '99'.repeat(20); + case 'sevSnpTcbRequirements': return '[]'; + case 'authorizeKms': return { + authorized: true, rejectionReason: '', gatewayAppId: GATEWAY, + currentAppEpoch: 0n, currentRootEpoch: 2n, currentRootEpochHash: CURRENT_HASH, + latestRootEpoch: 3n, latestRootEpochHash: LATEST_HASH, + }; + case 'isAppAllowed': return [true, 'on-chain']; + default: return Promise.reject(new Error(`unexpected contract call ${params.functionName}`)); + } + }); + } + + function stubDelegate(handler: (call: DelegateCall) => Response | Promise) { + calls = []; + vi.stubGlobal('fetch', async (url: string, init: RequestInit = {}) => { + const body = init.body == null ? undefined : new Uint8Array(await new Response(init.body).arrayBuffer()); + const call: DelegateCall = { + url: String(url), + method: init.method ?? 'GET', + body, + redirect: init.redirect, + signal: init.signal, + }; + calls.push(call); + return handler(call); + }); + } + + function delegateOk(extra: Record = {}) { + return new Response(JSON.stringify({ + authorized: true, + rejectionReason: '', + gatewayAppId: 'delegate-gateway', + currentRootEpoch: 9, + currentRootEpochHash: '0x' + 'ff'.repeat(32), + currentAppEpoch: 7, + latestRootEpoch: 9, + latestRootEpochHash: '0x' + 'ee'.repeat(32), + note: 'not-part-of-the-result', + ...extra, + }), { status: 200, headers: { 'content-type': 'application/json' } }); + } + + async function load(url?: string) { + if (url === undefined) delete process.env.APP_AUTH_URL; + else process.env.APP_AUTH_URL = url; + vi.resetModules(); + const mod = await import('./index.ts'); + return mod.default.fetch as (request: Request) => Promise; + } + + const postApp = (fetchApp: (request: Request) => Promise, body = rawBody) => fetchApp(new Request('http://localhost/authorizeApp', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, body, + })); + + beforeEach(() => { + calls = []; + vi.unstubAllGlobals(); + }); + + afterEach(() => { + delete process.env.APP_AUTH_URL; + vi.unstubAllGlobals(); + vi.resetModules(); + }); + + it('keeps the chain path when APP_AUTH_URL is unset, even if the env appears later', async () => { + const fetchSpy = vi.fn(); + vi.stubGlobal('fetch', fetchSpy); + process.env.APP_AUTH_URL = 'http://127.0.0.1:9'; + mockReadContract.mockResolvedValueOnce({ + authorized: false, rejectionReason: 'App not registered', gatewayAppId: 'gateway', + currentAppEpoch: 0n, currentRootEpoch: 2n, currentRootEpochHash: CURRENT_HASH, + latestRootEpoch: 2n, latestRootEpochHash: CURRENT_HASH, + }); + const response = await appFetch(new Request('http://localhost/authorizeApp', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + teeVariant: 'dstack-tdx', operation: 'app_get_key', appId, + composeHash: '0x' + '22'.repeat(32), instanceId: '', deviceId: '0x' + '33'.repeat(32), + mrAggregated: '0x' + '44'.repeat(32), osImageHash: '0x' + '66'.repeat(32), + }), + })); + expect(response.status).toBe(200); + expect((await response.json()).rejectionReason).toBe('App not registered'); + expect(fetchSpy).not.toHaveBeenCalled(); + expect(mockReadContract).toHaveBeenCalledWith(expect.objectContaining({ functionName: 'authorizeApp' })); + }); + + it('forwards the authorizeApp body byte for byte and overwrites root fields from the pinned chain block', async () => { + // A second resolution would pin a different block, even within one request. + let nextTip = 100n; + mockGetBlock.mockImplementation(({ blockTag, blockNumber }) => { + if (blockTag) return { number: nextTip++ }; + return { number: blockNumber, hash: blockHash(blockNumber), timestamp: 0n }; + }); + mockChain(); + stubDelegate(() => delegateOk()); + const fetchApp = await load('http://127.0.0.1:9/delegate/'); + // A UTF-8 BOM is accepted by the JSON parser but would be lost by text decoding. + const body = '\uFEFF' + rawBody; + const response = await postApp(fetchApp, body); + expect(response.status).toBe(200); + expect(calls).toEqual([{ + url: 'http://127.0.0.1:9/delegate/authorizeApp', + method: 'POST', + body: new TextEncoder().encode(body), + redirect: 'error', + signal: expect.any(AbortSignal), + }]); + expect(await response.json()).toEqual({ + authorized: true, + rejectionReason: '', + currentAppEpoch: 7, + ...chainRoots, + }); + expect(mockReadContract).not.toHaveBeenCalledWith(expect.objectContaining({ + functionName: 'authorizeApp', + })); + expect(mockReadContract).not.toHaveBeenCalledWith(expect.objectContaining({ + functionName: 'currentAppEpoch', + })); + // Policy, gateway, count, current root and latest root: no duplicate reads. + expect(mockReadContract).toHaveBeenCalledTimes(5); + for (const functionName of ['checkKmsAppPolicy', 'gatewayAppId', 'rootEpochCount', 'currentRootEpoch', 'rootEpoch']) { + const params = mockReadContract.mock.calls.find(([params]) => params.functionName === functionName)?.[0]; + expect(params).toMatchObject({ blockHash: blockHash(98n), requireCanonical: true }); + } + expect(mockReadContract).toHaveBeenCalledWith(expect.objectContaining({ + functionName: 'rootEpoch', args: [3n], + })); + expect(mockGetBlock.mock.calls).toEqual([[{ blockTag: 'finalized' }], [{ blockNumber: 98n }]]); + + const info = await (await fetchApp(new Request('http://localhost/'))).json(); + expect(info.gatewayAppId).toBe(GATEWAY); + expect(info.rootEpoch).toBe(2); + expect(info.rootEpochHash).toBe(CURRENT_HASH); + expect(calls).toHaveLength(1); + }); + + it('keeps a delegate denial, including its app epoch, and still overwrites root fields', async () => { + mockChain(); + stubDelegate(() => delegateOk({ + authorized: false, rejectionReason: 'compose hash is not allowed', currentAppEpoch: 4, + })); + const fetchApp = await load('http://127.0.0.1:9'); + const response = await postApp(fetchApp); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ + authorized: false, + rejectionReason: 'compose hash is not allowed', + currentAppEpoch: 4, + ...chainRoots, + }); + }); + + it('denies a requested root epoch newer than the current one without calling the delegate', async () => { + mockChain(); + stubDelegate(() => delegateOk()); + const fetchApp = await load('http://127.0.0.1:9'); + const newer = rawBody.replace('"requestedRootEpoch":1', '"requestedRootEpoch":3'); + const denied = await postApp(fetchApp, newer); + expect(denied.status).toBe(200); + expect(await denied.json()).toEqual({ + authorized: false, + rejectionReason: 'Requested root epoch is not active', + currentAppEpoch: 0, + ...chainRoots, + }); + expect(calls).toEqual([]); + + const current = rawBody.replace('"requestedRootEpoch":1', '"requestedRootEpoch":2'); + expect((await postApp(fetchApp, current)).status).toBe(200); + expect(calls).toHaveLength(1); + expect(calls[0].body).toEqual(new TextEncoder().encode(current)); + }); + + it('denies app authorization when no root epoch is registered, without calling the delegate', async () => { + mockChain({ count: 0n }); + stubDelegate(() => delegateOk()); + const fetchApp = await load('http://127.0.0.1:9'); + const response = await postApp(fetchApp); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ + authorized: false, + rejectionReason: 'Root epoch not registered', + gatewayAppId: GATEWAY, + currentRootEpoch: 0, + currentRootEpochHash: ZERO_HASH, + currentAppEpoch: 0, + latestRootEpoch: 0, + latestRootEpochHash: ZERO_HASH, + }); + expect(calls).toEqual([]); + expect(mockReadContract).not.toHaveBeenCalledWith(expect.objectContaining({ functionName: 'currentRootEpoch' })); + expect(mockReadContract).not.toHaveBeenCalledWith(expect.objectContaining({ functionName: 'rootEpoch' })); + }); + + it('denies a KMS operation on /authorizeApp without calling the delegate', async () => { + mockChain(); + stubDelegate(() => delegateOk()); + const fetchApp = await load('http://127.0.0.1:9'); + const response = await postApp(fetchApp, rawBody.replace('app_get_key', 'kms_serve')); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ + authorized: false, + rejectionReason: 'Invalid authorization operation', + currentAppEpoch: 0, + ...chainRoots, + }); + expect(calls).toEqual([]); + }); + + it.each([ + ['an OS image revoked from the allowlist', rawBody], + ['an OS image that was never allowed', rawBody.replace(`"osImageHash":"${'66'.repeat(32)}"`, `"osImageHash":"${'77'.repeat(32)}"`)], + ])('denies %s without calling the delegate', async (_label, body) => { + mockChain({ policyRejection: 'OS image is not allowed' }); + stubDelegate(() => delegateOk()); + const fetchApp = await load('http://127.0.0.1:9'); + const response = await postApp(fetchApp, body); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ + authorized: false, + rejectionReason: 'OS image is not allowed', + currentAppEpoch: 0, + ...chainRoots, + }); + expect(calls).toEqual([]); + }); + + it.each(['dstack-amd-sev-snp', 'dstack-gcp-tdx'])( + 'denies the disallowed TEE variant %s without calling the delegate', + async (teeVariant) => { + mockChain({ policyRejection: 'TEE variant not allowed' }); + stubDelegate(() => delegateOk()); + const fetchApp = await load('http://127.0.0.1:9'); + const response = await postApp(fetchApp, rawBody.replace('"teeVariant":"dstack-tdx"', `"teeVariant":"${teeVariant}"`)); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ + authorized: false, + rejectionReason: 'TEE variant not allowed', + currentAppEpoch: 0, + ...chainRoots, + }); + expect(calls).toEqual([]); + }, + ); + + it('reads the KMS policy at the pinned block and forwards the delegate answer when it passes', async () => { + mockChain(); + stubDelegate(() => delegateOk()); + const fetchApp = await load('http://127.0.0.1:9'); + const response = await postApp(fetchApp); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ + authorized: true, + rejectionReason: '', + currentAppEpoch: 7, + ...chainRoots, + }); + expect(calls).toHaveLength(1); + expect(mockReadContract).toHaveBeenCalledWith(expect.objectContaining({ + functionName: 'checkKmsAppPolicy', + blockHash: blockHash(98n), + requireCanonical: true, + })); + }); + + it.each([ + ['timeout', () => { throw new DOMException('The operation was timed out', 'TimeoutError'); }, 'app authorization delegate timed out'], + ['HTTP error', () => new Response('super-secret-policy', { status: 502 }), 'app authorization delegate returned HTTP 502'], + ['invalid JSON', () => new Response('not-json', { status: 200 }), 'app authorization delegate returned invalid JSON'], + ['invalid shape', () => new Response('{"authorized":true}', { status: 200 }), 'app authorization delegate returned an invalid response'], + ])('fails closed with 503 when the delegate returns %s', async (_label, respond, message) => { + mockChain(); + stubDelegate(respond); + const fetchApp = await load('http://127.0.0.1:9'); + const response = await postApp(fetchApp); + expect(response.status).toBe(503); + const data = await response.json(); + expect(data).toEqual({ status: 'error', message }); + expect(JSON.stringify(data)).not.toContain('super-secret-policy'); + // The delegate call must carry the timeout signal, whatever the failure. + expect(calls[0].signal).toBeInstanceOf(AbortSignal); + }); + + it.each(['POST /authorizeApp', 'GET /app/:appId'])( + 'logs delegate transport errors without disclosing details on %s', async (route) => { + mockChain(); + stubDelegate(() => { throw new TypeError('connect ECONNREFUSED'); }); + const fetchApp = await load('http://127.0.0.1:9'); + const log = vi.spyOn(console, 'error').mockImplementation(() => {}); + try { + const isPost = route === 'POST /authorizeApp'; + const response = await (isPost ? postApp(fetchApp) : fetchApp(new Request(`http://localhost/app/${appId}`))); + expect(response.status).toBe(503); + const body = await response.text(); + expect(body).not.toContain('ECONNREFUSED'); + const reason = 'app authorization delegate unavailable'; + expect(JSON.parse(body)).toEqual(isPost ? { status: 'error', message: reason } : { error: reason }); + expect(log).toHaveBeenCalledWith(expect.stringContaining('ECONNREFUSED')); + } finally { + log.mockRestore(); + } + }, + ); + + it('does not call the delegate when the chain cannot supply root fields', async () => { + mockChain({ fail: true }); + stubDelegate(() => delegateOk()); + const fetchApp = await load('http://127.0.0.1:9'); + const response = await postApp(fetchApp); + expect(response.status).toBe(503); + expect(calls).toEqual([]); + }); + + it('rejects an invalid authorizeApp body before calling the delegate', async () => { + mockChain(); + stubDelegate(() => delegateOk()); + const fetchApp = await load('http://127.0.0.1:9'); + const response = await postApp(fetchApp, '{"operation":"app_get_key"}'); + expect(response.status).toBe(400); + expect(calls).toEqual([]); + expect(mockReadContract).not.toHaveBeenCalled(); + }); + + it('leaves KMS authorization, boot, and TCB requirements on chain', async () => { + mockChain(); + stubDelegate(() => delegateOk()); + const fetchApp = await load('http://127.0.0.1:9'); + const kms = await fetchApp(new Request('http://localhost/authorizeKms', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: rawBody.replace('app_get_key', 'kms_serve'), + })); + expect(kms.status).toBe(200); + expect(mockReadContract).toHaveBeenCalledWith(expect.objectContaining({ functionName: 'authorizeKms' })); + + mockReadContract.mockClear(); + mockChain(); + const boot = await fetchApp(new Request('http://localhost/bootAuth/app', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + appId, composeHash: '0x' + '22'.repeat(32), instanceId: '0x' + '33'.repeat(20), + deviceId: '0x' + '44'.repeat(32), mrAggregated: '0x' + '55'.repeat(32), + osImageHash: '0x' + '66'.repeat(32), + rootEpoch: 2, rootEpochHash: CURRENT_HASH, + }), + })); + expect(boot.status).toBe(200); + expect(await boot.json()).toMatchObject({ isAllowed: true, reason: 'on-chain' }); + expect(mockReadContract).toHaveBeenCalledWith(expect.objectContaining({ functionName: 'isAppAllowed' })); + + const tcb = await fetchApp(new Request('http://localhost/sevSnpTcbRequirements')); + expect(await tcb.json()).toEqual({ requirements: '[]' }); + expect(calls).toEqual([]); + }); + + it('forwards GET /app/:appId and fails closed instead of inventing an epoch', async () => { + stubDelegate((call) => { + if (call.url.endsWith('/app/' + '0xAb' + 'cd'.repeat(19))) { + return new Response(JSON.stringify({ currentAppEpoch: 5, extra: true }), { status: 200 }); + } + return new Response('nope', { status: 500 }); + }); + const fetchApp = await load('http://127.0.0.1:9/delegate'); + const appIdPath = '0xAb' + 'cd'.repeat(19); + const ok = await fetchApp(new Request(`http://localhost/app/${appIdPath}`)); + expect(ok.status).toBe(200); + expect(await ok.json()).toEqual({ currentAppEpoch: 5 }); + expect(calls[0]).toMatchObject({ url: `http://127.0.0.1:9/delegate/app/${appIdPath}`, method: 'GET' }); + expect(mockReadContract).not.toHaveBeenCalled(); + + const failed = await fetchApp(new Request(`http://localhost/app/0x${'12'.repeat(20)}`)); + expect(failed.status).toBe(503); + expect(await failed.json()).not.toHaveProperty('currentAppEpoch'); + + const invalid = await fetchApp(new Request('http://localhost/app/not-an-id')); + expect(invalid.status).toBe(400); + expect(calls).toHaveLength(2); + }); + + it.each([ + ['not-json', 'app authorization delegate returned invalid JSON'], + ['{"authorized":true}', 'app authorization delegate returned an invalid response'], + ['{"currentAppEpoch":4294967296}', 'app authorization delegate returned an invalid response'], + ])('returns 503 when the app epoch delegate answers %s', async (body, error) => { + stubDelegate(() => new Response(body)); + const fetchApp = await load('http://127.0.0.1:9'); + const response = await fetchApp(new Request(`http://localhost/app/${appId}`)); + expect(response.status).toBe(503); + expect(await response.json()).toEqual({ error }); + expect(mockReadContract).not.toHaveBeenCalled(); + }); + + it('refuses to start when APP_AUTH_URL is not an absolute http(s) URL', async () => { + process.env.APP_AUTH_URL = 'file:///tmp/auth'; + vi.resetModules(); + await expect(import('./index.ts')).rejects.toThrow(/APP_AUTH_URL/); + }); + + it('treats a blank APP_AUTH_URL as unset and rejects credentials in the URL', async () => { + delete process.env.APP_AUTH_URL; + vi.resetModules(); + const { parseAppAuthUrl } = await import('./index.ts'); + expect(parseAppAuthUrl(undefined)).toBeUndefined(); + expect(parseAppAuthUrl(' ')).toBeUndefined(); + expect(() => parseAppAuthUrl('http://user:pass@127.0.0.1:9')).toThrow(/credentials/); + }); + + it('allows HTTP for loopback and same-compose service hostnames, and HTTPS for external delegates', async () => { + delete process.env.APP_AUTH_URL; + vi.resetModules(); + const { parseAppAuthUrl } = await import('./index.ts'); + for (const origin of [ + 'http://localhost:9', + 'http://127.0.0.1:9', + 'http://127.42.0.7:9', + 'http://[::1]:9', + 'http://app-auth:9', + 'https://auth.example', + ]) { + expect(parseAppAuthUrl(`${origin}/delegate/`)).toBe(`${origin}/delegate`); + } + }); + + it('requires HTTPS for external delegates', async () => { + delete process.env.APP_AUTH_URL; + vi.resetModules(); + const { parseAppAuthUrl } = await import('./index.ts'); + for (const url of ['http://auth.example', 'http://127.0.0.1.example', 'http://10.0.0.2', 'http://[fd00::1]']) { + expect(() => parseAppAuthUrl(url)).toThrow(/requires HTTPS/); + } + }); + + it('discards a query or fragment in APP_AUTH_URL, even an empty one', async () => { + delete process.env.APP_AUTH_URL; + vi.resetModules(); + const { parseAppAuthUrl } = await import('./index.ts'); + for (const value of [ + 'http://127.0.0.1:9/delegate?x=1', + 'http://127.0.0.1:9/delegate#x', + 'http://127.0.0.1:9/delegate?', + 'http://127.0.0.1:9/delegate#', + ]) { + expect(parseAppAuthUrl(value)).toBe('http://127.0.0.1:9/delegate'); + } + }); +}); diff --git a/dstack/kms/auth-eth/index.ts b/dstack/kms/auth-eth/index.ts new file mode 100644 index 0000000000..222440f1bc --- /dev/null +++ b/dstack/kms/auth-eth/index.ts @@ -0,0 +1,987 @@ +// SPDX-FileCopyrightText: © 2025 Phala Network +// +// SPDX-License-Identifier: Apache-2.0 + +import { Hono } from 'hono'; +import { bodyLimit } from 'hono/body-limit'; +import { secureHeaders } from 'hono/secure-headers'; +import { HTTPException } from 'hono/http-exception'; +import { zValidator } from '@hono/zod-validator'; +import { z } from 'zod'; +import { BaseError, createPublicClient, custom, http, keccak256, toBytes, zeroAddress, type Address, type Hex } from 'viem'; + +// zod schemas for validation - compatible with original fastify implementation +const boundedHex = (bytes: number, description: string) => + z.string() + .regex(/^(?:0x)?[0-9a-fA-F]*$/, `${description} must be hexadecimal`) + .refine( + (value) => value.replace(/^0x/, '').length <= bytes * 2, + `${description} exceeds ${bytes} bytes`, + ); + +const BootInfoSchema = z.object({ + // Short hexadecimal values remain compatible with the original backend, + // which left-pads them before making the contract call. + mrAggregated: boundedHex(32, 'aggregated MR measurement'), + osImageHash: boundedHex(32, 'OS Image hash'), + appId: boundedHex(20, 'application ID'), + composeHash: boundedHex(32, 'compose hash'), + instanceId: boundedHex(20, 'instance ID'), + deviceId: boundedHex(32, 'device ID'), + tcbStatus: z.string().max(128).optional().default(''), + advisoryIds: z.array(z.string().max(256)).max(128).optional().default([]), + mrSystem: boundedHex(32, 'system MR measurement').optional().default(''), + // The root epoch the asking KMS serves and its chain hash; absent from a KMS + // that predates root epochs, and from KMS checks made while onboarding. + rootEpoch: z.number().int().min(0).optional(), + rootEpochHash: boundedHex(32, 'root epoch chain hash').optional() +}); + +const AuthorizationRequestSchema = BootInfoSchema.omit({ rootEpoch: true, rootEpochHash: true }).extend({ + teeVariant: z.string().min(1).max(64), + operation: z.enum(['kms_bootstrap', 'kms_serve', 'kms_export_keys', 'kms_import_keys', 'app_get_key', 'app_get_cert']), + requestedAppEpoch: z.number().int().min(0).max(0xffffffff).optional(), + requestedRootEpoch: z.number().int().min(0).max(0xffffffff).optional(), + // The hash of the launch ticket the attested subject presented; absent when none. + launchTicketHash: boundedHex(32, 'launch ticket hash').optional(), +}); +type AuthorizationRequest = z.infer; + +const BootResponseSchema = z.object({ + isAllowed: z.boolean(), + reason: z.string(), + gatewayAppId: z.string() +}); + +// The current root epoch and its chain hash, which commits to the root public +// keys of epochs 0..=rootEpoch; both absent when none is registered. +type RootEpochInfo = { rootEpoch?: number; rootEpochHash?: Hex }; + +const ZERO_ROOT_HASH = `0x${'00'.repeat(32)}` as Hex; + +type AuthorizationRoots = { + gatewayAppId: string; + currentRootEpoch: number; + currentRootEpochHash: Hex; + latestRootEpoch: number; + latestRootEpochHash: Hex; +}; + +type BootInfo = z.infer; +type BootResponse = z.infer; + +const normHash = (hash?: string) => hash?.toLowerCase().replace(/^0x/, ''); + +// Only a KMS serving the current root epoch, with the registered keys up to it, +// may authorize. A KMS that predates root epochs reports none and holds only +// epoch 0, so it is served only until another epoch is activated. +function rootEpochDenial(bootInfo: BootInfo, current: RootEpochInfo): string | undefined { + const currentEpoch = current.rootEpoch ?? 0; + if (bootInfo.rootEpoch === undefined) { + return currentEpoch === 0 ? undefined : `root epoch ${currentEpoch} is current, but the KMS reports none`; + } + if (current.rootEpoch === undefined) { + return bootInfo.rootEpoch === 0 ? undefined : `root epoch ${bootInfo.rootEpoch} is not registered`; + } + if (bootInfo.rootEpoch !== currentEpoch) { + return `the KMS serves root epoch ${bootInfo.rootEpoch}, but ${currentEpoch} is current`; + } + if (normHash(bootInfo.rootEpochHash) !== normHash(current.rootEpochHash)) { + return `the KMS root keys up to epoch ${currentEpoch} are not the registered ones`; + } + return undefined; +} + +const APP_INFO_COMPONENTS = [ + { name: 'appId', type: 'address' }, + { name: 'composeHash', type: 'bytes32' }, + { name: 'instanceId', type: 'address' }, + { name: 'deviceId', type: 'bytes32' }, + { name: 'mrAggregated', type: 'bytes32' }, + { name: 'mrSystem', type: 'bytes32' }, + { name: 'osImageHash', type: 'bytes32' }, + { name: 'tcbStatus', type: 'string' }, + { name: 'advisoryIds', type: 'string[]' } +] as const; + +const AUTHORIZATION_ABI = { + type: 'function', + stateMutability: 'view', + inputs: [{ name: 'request', type: 'tuple', components: [ + { name: 'appInfo', type: 'tuple', components: APP_INFO_COMPONENTS }, + { name: 'operation', type: 'bytes32' }, + { name: 'requestedAppEpoch', type: 'tuple', components: [ + { name: 'isSet', type: 'bool' }, { name: 'value', type: 'uint256' }, + ] }, + { name: 'requestedRootEpoch', type: 'tuple', components: [ + { name: 'isSet', type: 'bool' }, { name: 'value', type: 'uint256' }, + ] }, + { name: 'teeVariant', type: 'string' }, + { name: 'launchTicketHash', type: 'bytes32' }, + ] }], + outputs: [{ + name: 'result', + type: 'tuple', + components: [ + { name: 'authorized', type: 'bool' }, + { name: 'rejectionReason', type: 'string' }, + { name: 'gatewayAppId', type: 'string' }, + { name: 'currentRootEpoch', type: 'uint256' }, + { name: 'currentRootEpochHash', type: 'bytes32' }, + { name: 'currentAppEpoch', type: 'uint256' }, + { name: 'latestRootEpoch', type: 'uint256' }, + { name: 'latestRootEpochHash', type: 'bytes32' }, + ], + }], +} as const; + +// DstackKms contract ABI (minimal required functions) +const DSTACK_KMS_ABI = [ + { name: 'currentAppEpoch', type: 'function', stateMutability: 'view', inputs: [{ name: 'appId', type: 'address' }], outputs: [{ name: '', type: 'uint256' }] }, + { ...AUTHORIZATION_ABI, name: 'authorizeKms' }, + { ...AUTHORIZATION_ABI, name: 'authorizeApp' }, + // The KMS-owned app policy without the identity checks a delegate owns; + // empty string admits the request at its selected root epoch. + { ...AUTHORIZATION_ABI, name: 'checkKmsAppPolicy', outputs: [{ name: '', type: 'string' }] }, + { + name: 'isKmsAllowed', + type: 'function', + stateMutability: 'view', + inputs: [ + { + name: 'bootInfo', + type: 'tuple', + components: APP_INFO_COMPONENTS + } + ], + outputs: [ + { name: 'isAllowed', type: 'bool' }, + { name: 'reason', type: 'string' } + ] + }, + { + name: 'isAppAllowed', + type: 'function', + stateMutability: 'view', + inputs: [ + { + name: 'bootInfo', + type: 'tuple', + components: APP_INFO_COMPONENTS + } + ], + outputs: [ + { name: 'isAllowed', type: 'bool' }, + { name: 'reason', type: 'string' } + ] + }, + { + name: 'gatewayAppId', + type: 'function', + stateMutability: 'view', + inputs: [], + outputs: [{ name: '', type: 'string' }] + }, + { + name: 'appImplementation', + type: 'function', + stateMutability: 'view', + inputs: [], + outputs: [{ name: '', type: 'address' }] + }, + { name: 'sevSnpTcbRequirements', type: 'function', stateMutability: 'view', inputs: [], outputs: [{ name: '', type: 'string' }] }, + { + name: 'rootEpochCount', + type: 'function', + stateMutability: 'view', + inputs: [], + outputs: [{ name: '', type: 'uint256' }] + }, + { + name: 'currentRootEpoch', + type: 'function', + stateMutability: 'view', + inputs: [], + outputs: [ + { name: 'epoch', type: 'uint256' }, + { name: 'chainHash', type: 'bytes32' } + ] + }, + { + name: 'rootEpoch', + type: 'function', + stateMutability: 'view', + inputs: [{ name: 'epoch', type: 'uint256' }], + outputs: [ + { name: 'caPubkey', type: 'bytes' }, + { name: 'k256Pubkey', type: 'bytes' }, + { name: 'evidenceUrl', type: 'string' }, + { name: 'chainHash', type: 'bytes32' } + ] + } +] as const; + +// ethereum backend class +const BLOCK_TAGS = ['latest', 'safe', 'finalized'] as const; +type BlockTag = typeof BLOCK_TAGS[number]; + +export function parseBlockTag(value: string | undefined): BlockTag { + const tag = value || 'finalized'; + if (!(BLOCK_TAGS as readonly string[]).includes(tag)) { + throw new Error(`ETH_BLOCK_TAG must be one of ${BLOCK_TAGS.join(', ')}`); + } + return tag as BlockTag; +} + +export function parseRpcConfig(env: Record) { + const { ETH_RPC_URL: single, ETH_RPC_URLS: list } = env; + const given = list || single; + if (!given || (single && list)) throw new Error('set exactly one of ETH_RPC_URL and ETH_RPC_URLS'); + const urls = given.trim().split(/\s+/); + + // A single ETH_RPC_URL needs no ETH_RPC_QUORUM. + const quorum = env.ETH_RPC_QUORUM || (list ? '' : '1/1'); + const match = /^(\d+)\/(\d+)$/.exec(quorum); + const threshold = Number(match?.[1]); + const total = Number(match?.[2]); + // Two answers cannot both reach n only when n is more than half of m. + if (!match || threshold > total || threshold * 2 <= total) { + throw new Error('ETH_RPC_QUORUM must be n/m with m/2 < n <= m'); + } + // The count is pinned apart from the list, so a value interpolated into one + // URL cannot add an endpoint. + if (urls.length !== total) throw new Error(`ETH_RPC_QUORUM expects ${total} RPC URLs, got ${urls.length}`); + + // URLs carry API keys: never put one in an error. + const origins = urls.map((url, i) => { + if (!URL.canParse(url)) throw new Error(`RPC URL ${i + 1} is invalid`); + return new URL(url).origin; + }); + if (new Set(origins).size !== total) throw new Error('RPC URLs must have distinct origins'); + // Providers that lag or lie can hold the block back; only its age bounds that. + if (total > 1 && !env.ETH_MAX_BLOCK_AGE) throw new Error('ETH_MAX_BLOCK_AGE is required with several RPC URLs'); + + return { urls, origins, quorum, threshold }; +} + +// One RPC endpoint; the origin is the only part of its URL that is public. +type RpcProvider = { + origin: string; + request: (args: { method: string; params?: unknown }) => Promise; +}; +type RpcBlock = { hash: string; number: string; timestamp: string }; + +// viem puts a one-line summary without the request URL in shortMessage. +const errorSummary = (err: unknown): string => + (err as { shortMessage?: string } | null | undefined)?.shortMessage ?? (err instanceof Error ? err.message : String(err)); + +// Only a viem error has that summary; the text of any other error stays out of the log. +const logFailure = (what: string, err: unknown) => { + const reason = (err as { shortMessage?: string }).shortMessage; + console.error(reason ? `${what}: ${reason}` : what); +}; + +/// A transport that answers a request only with what `threshold` of the +/// providers answer alike. A provider that fails or reverts casts no vote. +export function quorumTransport(providers: RpcProvider[], threshold: number) { + const failure = (i: number, err: unknown) => `${providers[i].origin}: ${errorSummary(err)}`; + + // The first answer that `threshold` votes share under `key`. + const agree = (method: string, votes: Promise[], key: (answer: T) => string) => { + const counts = new Map(); + const failures: string[] = []; + // A vote fulfils only if it is the one that completes a quorum. + const quorum = votes.map(async (vote, i) => { + try { + const answer = await vote; + const answerKey = key(answer).toLowerCase(); + const count = (counts.get(answerKey) ?? 0) + 1; + counts.set(answerKey, count); + if (count >= threshold) return answer; + } catch (err) { + failures.push(failure(i, err)); + } + throw new BaseError('no quorum'); + }); + return Promise.any(quorum).catch(() => { + const detail = failures.length ? ` (${failures.join('; ')})` : ''; + throw new BaseError(`no ${threshold} of ${votes.length} RPCs agree on ${method}${detail}`); + }); + }; + + // The highest block `threshold` of the providers have reached, since they + // reach a tag at different times. Fewer than `threshold` providers cannot + // push it past a block one of the others has reached, but as few as + // m - threshold + 1 that lag or lie can hold it back: only + // ETH_MAX_BLOCK_AGE bounds that. + const reached = async (tag: unknown, votes: Promise[]) => { + const settled = await Promise.allSettled(votes.map(async (vote) => { + const tip = await vote; + return { tip, height: BigInt(tip.number) }; + })); + const tips = settled + .flatMap((vote) => (vote.status === 'fulfilled' ? [vote.value] : [])) + .sort((a, b) => Number(b.height - a.height)); + if (tips.length >= threshold) return tips[threshold - 1].tip; + const failures = settled.flatMap((vote, i) => (vote.status === 'rejected' ? [failure(i, vote.reason)] : [])); + throw new BaseError(`fewer than ${threshold} RPCs serve block ${tag} (${failures.join('; ')})`); + }; + + return custom({ + async request({ method, params }: { method: string; params?: unknown[] }) { + if (!['eth_chainId', 'eth_call', 'eth_getBlockByNumber'].includes(method)) { + throw new BaseError(`RPC method ${method} is not supported`); + } + const votes = providers.map((provider) => provider.request({ method, params })); + if (method !== 'eth_getBlockByNumber') return agree(method, votes as Promise[], (result) => result); + const blocks = votes as Promise[]; + const block = params?.[0]; + if (!String(block).startsWith('0x')) return reached(block, blocks); + return agree(method, blocks, ({ hash, number, timestamp }) => `${hash}:${number}:${timestamp}`); + }, + }, { retryCount: 0 }); +} + +// The block every read of a request is pinned to. +type Snapshot = { number: bigint; at: { blockHash: Hex; requireCanonical: true } }; + +export class EthereumBackend { + private client: ReturnType; + private kmsContractAddr: Address; + private expectedChainId?: number; + readonly blockTag: BlockTag; + readonly finalityConfirmations: bigint; + readonly maxBlockAge?: number; + + constructor( + client: ReturnType, + kmsContractAddr: string, + expectedChainId: number | undefined, + blockTag: BlockTag, + finalityConfirmations: bigint, + maxBlockAge?: number, + ) { + this.client = client; + this.kmsContractAddr = kmsContractAddr as Address; + this.expectedChainId = expectedChainId; + this.blockTag = blockTag; + this.finalityConfirmations = finalityConfirmations; + this.maxBlockAge = maxBlockAge; + } + + /// Resolve the tag, less the confirmation depth, to one block so that every + /// read of a request sees the same state. Reads are pinned to its hash, so + /// they fail rather than follow a reorg. An RPC that does not support the + /// tag fails closed. + async resolveBlock(tag: BlockTag = this.blockTag, confirmations = this.finalityConfirmations): Promise { + const chainId = await this.client.getChainId(); + if (this.expectedChainId !== undefined && chainId !== this.expectedChainId) { + throw new BaseError('authorization backend chain ID mismatch'); + } + const tip = await this.client.getBlock({ blockTag: tag }); + if (tip.number === null || tip.number < confirmations) { + throw new BaseError('authorization backend has not reached configured finality'); + } + const { hash, number, timestamp } = await this.client.getBlock({ blockNumber: tip.number - confirmations }); + if (hash === null || number === null) throw new BaseError('authorization backend block is pending'); + if (this.maxBlockAge !== undefined && Date.now() / 1000 - Number(timestamp) > this.maxBlockAge) { + throw new BaseError('authorization backend block is older than ETH_MAX_BLOCK_AGE'); + } + return { number, at: { blockHash: hash, requireCanonical: true } }; + } + + /// Resolve the tag and read at its block once at startup, so an RPC that + /// cannot serve either fails the deployment instead of every later request. + async probe(): Promise { + const block = await this.resolveBlock().catch((err) => { + const hint = this.blockTag === 'latest' ? '' : '; an RPC that cannot serve the tag, as OP-stack via Helios, requires latest'; + throw new Error(`cannot resolve ETH_BLOCK_TAG=${this.blockTag} (${errorSummary(err)})${hint}`); + }); + await this.client.call({ to: zeroAddress, ...block.at }).catch((err) => { + throw new Error(`cannot read at a block hash, which requires EIP-1898 of the RPC (${errorSummary(err)})`); + }); + } + + private decodeHex(hex: string, sz: number = 32): Hex { + // remove '0x' prefix if present + hex = hex.startsWith('0x') ? hex.slice(2) : hex; + // pad hex string to specified size + hex = hex.padStart(sz * 2, '0'); + // add '0x' prefix back + return `0x${hex}` as Hex; + } + + private contractAppInfo(bootInfo: BootInfo) { + // create boot info struct for contract call + return { + appId: this.decodeHex(bootInfo.appId, 20) as Address, + composeHash: this.decodeHex(bootInfo.composeHash, 32), + instanceId: this.decodeHex(bootInfo.instanceId, 20) as Address, + deviceId: this.decodeHex(bootInfo.deviceId, 32), + mrAggregated: this.decodeHex(bootInfo.mrAggregated, 32), + mrSystem: this.decodeHex(bootInfo.mrSystem || '', 32), + osImageHash: this.decodeHex(bootInfo.osImageHash, 32), + tcbStatus: bootInfo.tcbStatus || '', + advisoryIds: bootInfo.advisoryIds || [] + }; + + } + + // The AuthorizationRequest tuple as the contract sees it; shared by every + // view that takes one. + private contractRequest(request: AuthorizationRequest) { + return { + appInfo: this.contractAppInfo(request), + operation: keccak256(toBytes(request.operation)), + requestedAppEpoch: { isSet: request.requestedAppEpoch !== undefined, value: BigInt(request.requestedAppEpoch ?? 0) }, + requestedRootEpoch: { isSet: request.requestedRootEpoch !== undefined, value: BigInt(request.requestedRootEpoch ?? 0) }, + teeVariant: request.teeVariant, + launchTicketHash: this.decodeHex(request.launchTicketHash ?? '', 32), + }; + } + + async checkAuthorization(appInfo: AuthorizationRequest, method: 'authorizeKms' | 'authorizeApp') { + const block = await this.resolveBlock(); + const result = await this.client.readContract({ + address: this.kmsContractAddr, + abi: DSTACK_KMS_ABI, + functionName: method, + args: [this.contractRequest(appInfo)], + ...block.at, + }); + const currentRootEpoch = Number(result.currentRootEpoch); + if (!Number.isSafeInteger(currentRootEpoch)) { + throw new Error('current root epoch exceeds the supported range'); + } + const currentAppEpoch = Number(result.currentAppEpoch); + if (!Number.isSafeInteger(currentAppEpoch)) throw new Error('current app epoch exceeds the supported range'); + const latestRootEpoch = Number(result.latestRootEpoch); + if (!Number.isSafeInteger(latestRootEpoch)) throw new Error('latest root epoch exceeds the supported range'); + return { ...result, currentRootEpoch, currentAppEpoch, latestRootEpoch }; + } + + async checkBoot(bootInfo: BootInfo, isKms: boolean): Promise { + const bootInfoStruct = this.contractAppInfo(bootInfo); + const block = await this.resolveBlock(); + let response; + if (isKms) { + response = await this.client.readContract({ + address: this.kmsContractAddr, + abi: DSTACK_KMS_ABI, + functionName: 'isKmsAllowed', + args: [bootInfoStruct], + ...block.at + }); + } else { + response = await this.client.readContract({ + address: this.kmsContractAddr, + abi: DSTACK_KMS_ABI, + functionName: 'isAppAllowed', + args: [bootInfoStruct], + ...block.at + }); + } + + const [allowed, contractReason] = response; + const gatewayAppId = await this.client.readContract({ + address: this.kmsContractAddr, + abi: DSTACK_KMS_ABI, + functionName: 'gatewayAppId', + ...block.at + }); + + const epochDenial = allowed + ? rootEpochDenial(bootInfo, await this.getRootEpoch(block)) + : undefined; + return { + isAllowed: allowed && !epochDenial, + reason: epochDenial ?? contractReason, + gatewayAppId: gatewayAppId as string, + }; + } + + private readRootEpochCount(block: Snapshot) { + return this.client.readContract({ + address: this.kmsContractAddr, + abi: DSTACK_KMS_ABI, + functionName: 'rootEpochCount', + ...block.at + }); + } + + private readCurrentRootEpoch(block: Snapshot) { + return this.client.readContract({ + address: this.kmsContractAddr, + abi: DSTACK_KMS_ABI, + functionName: 'currentRootEpoch', + ...block.at + }); + } + + private readRootEpoch(block: Snapshot, epoch: bigint) { + return this.client.readContract({ + address: this.kmsContractAddr, abi: DSTACK_KMS_ABI, functionName: 'rootEpoch', + args: [epoch], ...block.at, + }); + } + + private async readRootEpochs(block: Snapshot, { includeLatest = false } = {}) { + const count = await this.readRootEpochCount(block); + // currentRootEpoch and rootEpoch revert while the registry is empty. + if (count === 0n) return undefined; + const latest = count - 1n; + const [[epoch, chainHash], latestRoot] = await Promise.all([ + this.readCurrentRootEpoch(block), + includeLatest ? this.readRootEpoch(block, latest) : undefined, + ]); + return { + current: { epoch: Number(epoch), hash: chainHash }, + latest: latestRoot && { epoch: Number(latest), hash: latestRoot[3] }, + }; + } + + // The current root epoch and its chain hash; empty only when no epoch is registered. + async getRootEpoch(block: Snapshot): Promise { + const roots = await this.readRootEpochs(block); + return roots ? { rootEpoch: roots.current.epoch, rootEpochHash: roots.current.hash } : {}; + } + + // The root CA public key (P-256 SPKI DER) of the current root epoch, which + // signs the RPC certificate of every KMS serving it. + async getRootCaPubkey(block: Snapshot, current: RootEpochInfo): Promise { + if (current.rootEpoch === undefined) return undefined; + const [caPubkey] = await this.readRootEpoch(block, BigInt(current.rootEpoch)); + return caPubkey; + } + + async getAppEpoch(appId: string): Promise { + // Providers a block apart share no newest block once one of them reports + // a head the others lack, so fall back to the depth they do agree at. + const block = await this.resolveBlock('latest', 0n) + .catch(() => this.resolveBlock('latest', this.finalityConfirmations || 1n)); + const epoch = Number(await this.client.readContract({ + address: this.kmsContractAddr, abi: DSTACK_KMS_ABI, functionName: 'currentAppEpoch', + args: [this.decodeHex(appId, 20)], ...block.at, + })); + if (!Number.isSafeInteger(epoch)) throw new Error('app epoch exceeds the supported range'); + return epoch; + } + + async getSevSnpTcbRequirements(): Promise { + return await this.client.readContract({ + address: this.kmsContractAddr, abi: DSTACK_KMS_ABI, functionName: 'sevSnpTcbRequirements', + ...(await this.resolveBlock()).at, + }); + } + + async getGatewayAppId(block?: Snapshot): Promise { + const result = await this.client.readContract({ + address: this.kmsContractAddr, + abi: DSTACK_KMS_ABI, + functionName: 'gatewayAppId', + ...(block ?? await this.resolveBlock()).at, + }); + return result as string; + } + + async getChainId(): Promise { + const chainId = await this.client.getChainId(); + return Number(chainId); + } + + async getAppImplementation(block?: Snapshot): Promise { + const result = await this.client.readContract({ + address: this.kmsContractAddr, + abi: DSTACK_KMS_ABI, + functionName: 'appImplementation', + ...(block ?? await this.resolveBlock()).at, + }); + return result as string; + } + + // KMS-owned app policy (operation scope, selected root epoch, OS image and + // TEE variant allowlists) without the app identity checks a delegate owns. + // Non-empty denies. + async checkKmsAppPolicy(request: AuthorizationRequest, block: Snapshot): Promise { + return await this.client.readContract({ + address: this.kmsContractAddr, + abi: DSTACK_KMS_ABI, + functionName: 'checkKmsAppPolicy', + args: [this.contractRequest(request)], + ...block.at, + }); + } + + // Root fields of an AuthorizationResult, all read at the request's pinned block. + async getAuthorizationRoots(block: Snapshot): Promise { + const [gatewayAppId, roots] = await Promise.all([ + this.getGatewayAppId(block), + this.readRootEpochs(block, { includeLatest: true }), + ]); + const currentRootEpoch = roots?.current.epoch ?? 0; + const latestRootEpoch = roots?.latest?.epoch ?? 0; + if (!Number.isSafeInteger(currentRootEpoch) || !Number.isSafeInteger(latestRootEpoch)) { + throw new Error('root epoch exceeds the supported range'); + } + return { + gatewayAppId, + currentRootEpoch, + currentRootEpochHash: roots?.current.hash ?? ZERO_ROOT_HASH, + latestRootEpoch, + latestRootEpochHash: roots?.latest?.hash ?? ZERO_ROOT_HASH, + }; + } +} + +// initialize app +const app = new Hono(); + +// initialize ethereum backend +const rpc = parseRpcConfig(process.env); +const kmsContractAddr = process.env.KMS_CONTRACT_ADDR || '0x0000000000000000000000000000000000000000'; +const parseNonNegativeInteger = (name: string, value: string | undefined): number | undefined => { + if (value === undefined || value === '') return undefined; + if (!/^(?:0|[1-9][0-9]*)$/.test(value)) throw new Error(`${name} must be a non-negative integer`); + const parsed = Number(value); + if (!Number.isSafeInteger(parsed)) throw new Error(`${name} exceeds the safe integer range`); + return parsed; +}; +const expectedChainId = parseNonNegativeInteger('ETH_CHAIN_ID', process.env.ETH_CHAIN_ID); +const finalityConfirmations = BigInt( + parseNonNegativeInteger('ETH_FINALITY_CONFIRMATIONS', process.env.ETH_FINALITY_CONFIRMATIONS) ?? 0, +); +const client = createPublicClient({ + transport: quorumTransport(rpc.urls.map((url, i) => ({ + origin: rpc.origins[i], + // A redirect would take the request off the configured origin. With + // several providers the others stand in for a retry, which would only + // hold the decision up behind a dead one. + request: http(url, { + fetchOptions: { redirect: 'error' }, + retryCount: rpc.urls.length > 1 ? 0 : undefined, + })({}).request, + })), rpc.threshold), +}); +const ethereum = new EthereumBackend( + client, kmsContractAddr, expectedChainId, parseBlockTag(process.env.ETH_BLOCK_TAG), finalityConfirmations, + parseNonNegativeInteger('ETH_MAX_BLOCK_AGE', process.env.ETH_MAX_BLOCK_AGE), +); +const ethRpcUrl = rpc.origins.join(','); + +// Keep the delegate-specific timeout below the default KMS webhook budget +// (60s), which also has to cover the preceding chain reads. +export const APP_AUTH_TIMEOUT_MS = 20_000; + +// The answer of the app-authorization delegate; the root fields of an +// AuthorizationResult always come from the chain, never from the delegate. +const AppEpochSchema = z.number().int().min(0).max(0xffffffff); +const DelegatedAuthorizationSchema = z.object({ + authorized: z.boolean(), + rejectionReason: z.string(), + currentAppEpoch: AppEpochSchema, +}); +const AppEpochResponseSchema = DelegatedAuthorizationSchema.pick({ currentAppEpoch: true }); + +export function parseAppAuthUrl(value: string | undefined): string | undefined { + if (value === undefined) return undefined; + const trimmed = value.trim(); + if (trimmed === '') return undefined; + let url: URL; + try { + url = new URL(trimmed); + } catch { + throw new Error('APP_AUTH_URL must be an absolute http(s) URL'); + } + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + throw new Error('APP_AUTH_URL must be an absolute http(s) URL'); + } + if (url.username !== '' || url.password !== '') { + throw new Error('APP_AUTH_URL must not include credentials'); + } + if (url.protocol === 'http:') { + const host = url.hostname; + const isLoopback = host === 'localhost' || host === '[::1]' || /^127(?:\.\d{1,3}){3}$/.test(host); + const isServiceName = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(host); + if (!isLoopback && !isServiceName) { + throw new Error('APP_AUTH_URL requires HTTPS unless the host is loopback or a same-compose service name'); + } + } + return (url.origin + url.pathname).replace(/\/$/, ''); +} + +const appAuthBase = parseAppAuthUrl(process.env.APP_AUTH_URL); +const backendUnavailable = 'authorization backend unavailable'; + +type DelegateFailure = { ok: false; reason: string }; +type DelegateCall = { ok: true; data: T } | DelegateFailure; + +function delegateTimedOut(err: unknown): boolean { + return err instanceof DOMException && (err.name === 'TimeoutError' || err.name === 'AbortError'); +} + +async function callDelegate( + url: string, + init: { method: string; body?: ArrayBuffer }, + schema: z.ZodType, +): Promise> { + let body: string; + try { + const response = await fetch(url, { + method: init.method, + body: init.body, + headers: init.body === undefined ? undefined : { 'content-type': 'application/json' }, + redirect: 'error', + signal: AbortSignal.timeout(APP_AUTH_TIMEOUT_MS), + }); + if (!response.ok) { + return failedDelegate(`app authorization delegate returned HTTP ${response.status}`); + } + body = await response.text(); + } catch (err) { + const reason = delegateTimedOut(err) + ? 'app authorization delegate timed out' + : 'app authorization delegate unavailable'; + return failedDelegate(reason, errorSummary(err)); + } + let json: unknown; + try { + json = JSON.parse(body); + } catch { + return failedDelegate('app authorization delegate returned invalid JSON'); + } + const parsed = schema.safeParse(json); + if (!parsed.success) return failedDelegate('app authorization delegate returned an invalid response'); + return { ok: true, data: parsed.data }; +} + +function failedDelegate(reason: string, detail?: string): DelegateFailure { + console.error(`app authorization delegate failed: ${reason}${detail ? `: ${detail}` : ''}`); + return { ok: false, reason }; +} + +function appDenial(roots: AuthorizationRoots, rejectionReason: string) { + return { authorized: false, rejectionReason, currentAppEpoch: 0, ...roots }; +} + +// App identity policy comes from the delegate; the KMS-owned policy (OS image +// and TEE variant allowlists at the selected root epoch) and the root fields +// come from the chain at the request's pinned block. Chain read failures +// propagate to the route's 503 handler. +async function delegatedAppAuthorization( + base: string, + request: AuthorizationRequest, + rawBody: ArrayBuffer, +): Promise<{ status: 200 | 503; body: unknown }> { + const block = await ethereum.resolveBlock(); + const [roots, kmsRejection] = await Promise.all([ + ethereum.getAuthorizationRoots(block), + ethereum.checkKmsAppPolicy(request, block), + ]); + if (kmsRejection !== '') { + return { status: 200, body: appDenial(roots, kmsRejection) }; + } + const delegated = await callDelegate(`${base}/authorizeApp`, { method: 'POST', body: rawBody }, DelegatedAuthorizationSchema); + if (!delegated.ok) return { status: 503, body: { status: 'error', message: delegated.reason } }; + return { status: 200, body: { ...delegated.data, ...roots } }; +} + +const invalidRequest = { isAllowed: false, reason: 'invalid authorization request', gatewayAppId: '' }; +const invalidAuthorization = { + authorized: false, + rejectionReason: 'invalid authorization request', + gatewayAppId: '', + currentRootEpoch: 0, + currentRootEpochHash: '0x' + '00'.repeat(32), + currentAppEpoch: 0, + latestRootEpoch: 0, + latestRootEpochHash: '0x' + '00'.repeat(32), +}; + +// The schema caps a valid BootInfo well under this (advisoryIds alone at +// 128 x 256 chars is 32 KiB); the limit stops an oversized body from being +// buffered and parsed before validation rejects it. +const MAX_BOOT_INFO_BYTES = 128 * 1024; + +// Every response is JSON for the KMS, never a page; the headers keep a browser +// that reaches this port from sniffing or framing one. +app.use('*', secureHeaders()); +app.use('/bootAuth/*', bodyLimit({ + maxSize: MAX_BOOT_INFO_BYTES, + onError: (c) => c.json(invalidRequest, 413), +})); + +// health check and info endpoint +app.get('/', async (c) => { + try { + const block = await ethereum.resolveBlock(); + const batch = await Promise.all([ + ethereum.getGatewayAppId(block), + ethereum.getChainId(), + ethereum.getAppImplementation(block), + ethereum.getRootEpoch(block), + ]); + const rootCaPubkey = await ethereum.getRootCaPubkey(block, batch[3]); + + return c.json({ + status: 'ok', + kmsContractAddr: kmsContractAddr, + ethRpcUrl, + gatewayAppId: batch[0], + chainId: batch[1], + appAuthImplementation: batch[2], // NOTE: for backward compatibility + appImplementation: batch[2], + // Forwarded verbatim by the KMS's unauthenticated GetMeta: public only. + authApiInfo: JSON.stringify({ + kmsContractAddr, + chainId: batch[1], + appImplementation: batch[2], + ethRpcUrl, + ethRpcUrls: rpc.origins, + rpcQuorum: rpc.quorum, + blockTag: ethereum.blockTag, + finalityConfirmations: Number(ethereum.finalityConfirmations), + maxBlockAge: ethereum.maxBlockAge, + policyBlockNumber: Number(block.number), + }), + ...batch[3], + ...(rootCaPubkey && { rootCaPubkey }), + }); + } catch (err) { + logFailure('authorization backend health check failed', err); + return c.json({ + status: 'error', + message: backendUnavailable + }, 500); + } +}); + +app.get('/app/:appId', async (c) => { + const appId = c.req.param('appId'); + if (!/^0x[0-9a-fA-F]{40}$/.test(appId)) return c.json({ error: 'invalid app ID' }, 400); + if (appAuthBase) { + const delegated = await callDelegate(`${appAuthBase}/app/${appId}`, { method: 'GET' }, AppEpochResponseSchema); + if (!delegated.ok) return c.json({ error: delegated.reason }, 503); + return c.json(delegated.data); + } + try { + return c.json({ currentAppEpoch: await ethereum.getAppEpoch(appId) }); + } catch { + return c.json({ error: 'authorization backend unavailable' }, 503); + } +}); + +// The JSON list the KMS judges an SEV-SNP TCB against; empty when governance +// sets none. A contract that predates the list fails the read, and the KMS +// refuses SEV-SNP requests. +app.get('/sevSnpTcbRequirements', async (c) => { + try { + return c.json({ requirements: await ethereum.getSevSnpTcbRequirements() }); + } catch { + return c.json({ error: 'authorization backend unavailable' }, 503); + } +}); + +// Malformed JSON is rejected before the validator hook runs; keep the +// AuthorizationResult shape for it on the authorization routes. +const AUTHORIZATION_PATHS = new Set(['/authorizeKms', '/authorizeApp']); +app.onError((error, c) => { + if (error instanceof HTTPException) { + if (error.status === 400 && AUTHORIZATION_PATHS.has(c.req.path)) return c.json(invalidAuthorization, 400); + return error.getResponse(); + } + console.error(error); + return c.text('Internal Server Error', 500); +}); + +for (const method of ['authorizeKms', 'authorizeApp'] as const) { + app.post(`/${method}`, + bodyLimit({ maxSize: MAX_BOOT_INFO_BYTES, onError: (c) => c.json(invalidAuthorization, 413) }), + async (c, next) => { + if (method === 'authorizeApp' && appAuthBase) { + // Cache the bytes before the JSON validator decodes them to text. + try { + await c.req.arrayBuffer(); + } catch { + return c.json(invalidAuthorization, 400); + } + } + await next(); + }, + zValidator('json', AuthorizationRequestSchema, (result, c) => { + if (!result.success) return c.json(invalidAuthorization, 400); + }), + async (c) => { + try { + if (method === 'authorizeApp' && appAuthBase) { + const result = await delegatedAppAuthorization(appAuthBase, c.req.valid('json'), await c.req.arrayBuffer()); + return c.json(result.body, result.status); + } + return c.json(await ethereum.checkAuthorization(c.req.valid('json'), method)); + } catch (err) { + logFailure('authorization backend failed', err); + return c.json({ status: 'error', message: backendUnavailable }, 503); + } + } + ); +} + +// Legacy app boot. Left on chain when APP_AUTH_URL is set: KMS builds since +// 0.6.4 do not call it, and the response has no root-epoch fields to reconcile +// with a delegate. Do not point a pre-0.6.4 KMS at a delegated deployment. +app.post('/bootAuth/app', + zValidator('json', BootInfoSchema, (result, c) => { + if (!result.success) return c.json(invalidRequest, 400); + }), + async (c) => { + try { + const bootInfo = c.req.valid('json'); + const result = await ethereum.checkBoot(bootInfo, false); + return c.json(result); + } catch (err) { + logFailure('application authorization backend failed', err); + return c.json({ + isAllowed: false, + gatewayAppId: '', + reason: backendUnavailable + }); + } + } +); + +// KMS boot authentication +app.post('/bootAuth/kms', + zValidator('json', BootInfoSchema, (result, c) => { + if (!result.success) return c.json(invalidRequest, 400); + }), + async (c) => { + try { + const bootInfo = c.req.valid('json'); + const result = await ethereum.checkBoot(bootInfo, true); + return c.json(result); + } catch (error) { + // don't log test backend errors + if (!(error instanceof Error && "Test backend error" === error.message)) { + logFailure('KMS authorization backend failed', error); + } + return c.json({ + isAllowed: false, + gatewayAppId: '', + reason: backendUnavailable + }); + } + } +); + +// start server +if (import.meta.main) await ethereum.probe(); +const port = parseInt(process.env.PORT || '3000'); +console.log(`starting server on port ${port}`); + +// Bun defaults idleTimeout to 10s and closes the socket while the handler is +// still awaiting eth_call. KMS's webhook timeout is 60s; stay above that so the +// client times out first. Bun's documented maximum is 255. +export default { + port, + idleTimeout: 255, + fetch: app.fetch, +}; diff --git a/dstack/kms/auth-eth/jest.config.js b/dstack/kms/auth-eth/jest.config.js deleted file mode 100644 index dafec6254c..0000000000 --- a/dstack/kms/auth-eth/jest.config.js +++ /dev/null @@ -1,17 +0,0 @@ -// SPDX-FileCopyrightText: © 2025 Phala Network -// -// SPDX-License-Identifier: Apache-2.0 - -module.exports = { - preset: 'ts-jest', - testEnvironment: 'node', - roots: ['/src'], - testMatch: ['**/main.test.ts'], - moduleFileExtensions: ['ts', 'js', 'json', 'node'], - collectCoverageFrom: [ - 'src/**/*.ts', - '!src/**/*.d.ts' - ], - coverageDirectory: 'coverage', - verbose: true -}; diff --git a/dstack/kms/auth-eth/openapi.json b/dstack/kms/auth-eth/openapi.json new file mode 100644 index 0000000000..c35d6fdd9c --- /dev/null +++ b/dstack/kms/auth-eth/openapi.json @@ -0,0 +1,549 @@ +{ + "openapi": "3.0.0", + "info": { + "title": "dstack KMS Ethereum Backend API", + "description": "API for dstack KMS Ethereum backend authentication and system information", + "version": "1.0.0" + }, + "servers": [ + { + "url": "http://localhost:3000", + "description": "Development server" + } + ], + "paths": { + "/": { + "get": { + "summary": "Health check and system information", + "description": "Returns system status and configuration information", + "operationId": "getSystemInfo", + "responses": { + "200": { + "description": "System information", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SystemInfo" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/bootAuth/app": { + "post": { + "summary": "Application boot authentication", + "description": "Validates application boot information against smart contract", + "operationId": "authenticateAppBoot", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BootInfo" + } + } + } + }, + "responses": { + "200": { + "description": "Authentication result", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BootResponse" + } + } + } + } + } + } + }, + "/bootAuth/kms": { + "post": { + "summary": "KMS boot authentication", + "description": "Validates KMS boot information against smart contract", + "operationId": "authenticateKmsBoot", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BootInfo" + } + } + } + }, + "responses": { + "200": { + "description": "Authentication result", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BootResponse" + } + } + } + } + } + } + }, + "/authorizeKms": { + "post": { + "summary": "Authorize a Kms identity and return the current root epoch", + "operationId": "authorizeKms", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AuthorizationRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Authorization decision, including the epoch on rejection.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AuthorizationResult" + } + } + } + }, + "503": { + "description": "Authorization backend unavailable; no legacy fallback." + } + } + } + }, + "/authorizeApp": { + "post": { + "summary": "Authorize an app identity and return the current root epoch", + "description": "When APP_AUTH_URL is unset, the decision is read from DstackKms. When set, auth-eth first calls DstackKms.checkKmsAppPolicy at the request's pinned block to enforce app operation scope, root epoch registration, the requested root epoch, the selected-epoch OS image allowlist, and the TEE variant policy. A chain policy denial returns HTTP 200 without calling the delegate. Otherwise, the raw request body is forwarded unchanged to the delegate at the same path, including fields not in this schema. The delegate supplies the app identity decision (authorized and rejectionReason) and currentAppEpoch. auth-eth overwrites gatewayAppId and the current and latest root epoch fields with values from the same pinned block, including for a valid delegate denial. A delegate transport error, timeout, non-2xx response, or invalid answer returns HTTP 503, not an authorization denial, and does not include chain root fields.", + "operationId": "authorizeApp", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AuthorizationRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Authorization decision, including the chain root fields on a policy denial.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AuthorizationResult" + } + } + } + }, + "503": { + "description": "Chain read or delegate failure; no AuthorizationResult, chain root fields, or fallback." + } + } + } + }, + "/app/{appId}": { + "get": { + "summary": "Read the current application key epoch", + "description": "When APP_AUTH_URL is unset, the epoch is read from DstackKms at latest, falling back to the configured confirmation depth (or one block) when the RPC providers cannot agree at the head. When APP_AUTH_URL is set, the request is forwarded to that service at the same path. A delegate failure is 503 and does not fall back to the chain or to epoch 0.", + "parameters": [ + { + "name": "appId", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^0x[0-9a-fA-F]{40}$" + } + } + ], + "responses": { + "200": { + "description": "Current application epoch", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "currentAppEpoch" + ], + "properties": { + "currentAppEpoch": { + "type": "integer", + "minimum": 0, + "maximum": 4294967295 + } + } + } + } + } + }, + "503": { + "description": "Chain read or delegate failure; no app epoch is returned." + } + } + } + }, + "/sevSnpTcbRequirements": { + "get": { + "summary": "Read the minimum TCB each CPU must meet on SEV-SNP", + "responses": { + "200": { + "description": "The JSON list the KMS parses; empty when governance sets none", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "requirements" + ], + "properties": { + "requirements": { + "type": "string" + } + } + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "BootInfo": { + "type": "object", + "required": [ + "mrAggregated", + "osImageHash", + "appId", + "composeHash", + "instanceId", + "deviceId" + ], + "properties": { + "mrAggregated": { + "type": "string", + "description": "Aggregated MR measurement" + }, + "osImageHash": { + "type": "string", + "description": "OS Image hash" + }, + "appId": { + "type": "string", + "description": "Application ID" + }, + "composeHash": { + "type": "string", + "description": "Compose hash" + }, + "instanceId": { + "type": "string", + "description": "Instance ID" + }, + "deviceId": { + "type": "string", + "description": "Device ID" + }, + "tcbStatus": { + "type": "string", + "description": "TCB status (optional for compatibility)" + }, + "advisoryIds": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Advisory IDs (optional for compatibility)" + }, + "mrSystem": { + "type": "string", + "description": "MR System measurement (optional for compatibility)" + }, + "rootEpoch": { + "type": "integer", + "description": "KMS root epoch the asking KMS serves; absent from a KMS that predates root epochs and from KMS checks made while onboarding" + }, + "rootEpochHash": { + "type": "string", + "description": "Chain hash committing to the root public keys of epochs 0..=rootEpoch (hex)" + } + } + }, + "BootResponse": { + "type": "object", + "required": [ + "isAllowed", + "reason", + "gatewayAppId" + ], + "properties": { + "isAllowed": { + "type": "boolean", + "description": "Whether the boot is allowed" + }, + "reason": { + "type": "string", + "description": "Reason for the decision" + }, + "gatewayAppId": { + "type": "string", + "description": "Gateway application ID" + } + } + }, + "SystemInfo": { + "type": "object", + "required": [ + "status", + "kmsContractAddr", + "ethRpcUrl", + "gatewayAppId", + "chainId", + "appAuthImplementation", + "appImplementation" + ], + "properties": { + "status": { + "type": "string", + "enum": [ + "ok" + ], + "description": "System status" + }, + "kmsContractAddr": { + "type": "string", + "description": "KMS contract address" + }, + "ethRpcUrl": { + "type": "string", + "description": "Origins of the Ethereum RPC endpoints, joined by commas" + }, + "gatewayAppId": { + "type": "string", + "description": "Gateway application ID" + }, + "chainId": { + "type": "number", + "description": "Blockchain chain ID" + }, + "appAuthImplementation": { + "type": "string", + "description": "App auth implementation address (deprecated, use appImplementation)" + }, + "appImplementation": { + "type": "string", + "description": "App implementation address" + }, + "authApiInfo": { + "type": "string", + "description": "JSON-encoded public metadata the KMS forwards verbatim through GetMeta: kmsContractAddr, chainId, appImplementation, ethRpcUrl, ethRpcUrls, rpcQuorum, blockTag, finalityConfirmations, maxBlockAge, policyBlockNumber" + }, + "rootEpoch": { + "type": "integer", + "description": "Current KMS root epoch; absent when none is registered" + }, + "rootEpochHash": { + "type": "string", + "description": "Chain hash committing to the root public keys of epochs 0..=rootEpoch (hex)" + }, + "rootCaPubkey": { + "type": "string", + "description": "Root CA public key (P-256 SPKI DER, hex) of the current root epoch, which signs the RPC certificate of every KMS serving it; absent when none is registered." + } + } + }, + "Error": { + "type": "object", + "required": [ + "status", + "message" + ], + "properties": { + "status": { + "type": "string", + "enum": [ + "error" + ] + }, + "message": { + "type": "string", + "description": "Error message" + } + } + }, + "AppInfo": { + "type": "object", + "required": [ + "mrAggregated", + "osImageHash", + "appId", + "composeHash", + "instanceId", + "deviceId" + ], + "properties": { + "mrAggregated": { + "type": "string", + "description": "Aggregated MR measurement" + }, + "osImageHash": { + "type": "string", + "description": "OS Image hash" + }, + "appId": { + "type": "string", + "description": "Application ID" + }, + "composeHash": { + "type": "string", + "description": "Compose hash" + }, + "instanceId": { + "type": "string", + "description": "Instance ID" + }, + "deviceId": { + "type": "string", + "description": "Device ID" + }, + "tcbStatus": { + "type": "string", + "description": "TCB status (optional for compatibility)" + }, + "advisoryIds": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Advisory IDs (optional for compatibility)" + }, + "mrSystem": { + "type": "string", + "description": "MR System measurement (optional for compatibility)" + } + }, + "description": "Verified attestation identity. The KMS app ID is the KMS contract address." + }, + "AuthorizationResult": { + "type": "object", + "required": [ + "authorized", + "rejectionReason", + "gatewayAppId", + "currentRootEpoch", + "currentRootEpochHash", + "currentAppEpoch", + "latestRootEpoch", + "latestRootEpochHash" + ], + "properties": { + "authorized": { + "type": "boolean" + }, + "rejectionReason": { + "type": "string", + "description": "Empty when allowed." + }, + "gatewayAppId": { + "type": "string" + }, + "currentRootEpoch": { + "type": "integer", + "minimum": 0 + }, + "currentRootEpochHash": { + "type": "string", + "pattern": "^0x[0-9a-fA-F]{64}$", + "description": "Zero when no epoch is registered; authorization is denied." + }, + "currentAppEpoch": { + "type": "integer", + "minimum": 0, + "description": "Current application key epoch, which can be nonzero after app key rotation. For a delegated app decision, supplied by the delegate. KMS authorization uses zero." + }, + "latestRootEpoch": { + "type": "integer", + "minimum": 0, + "description": "Latest registered root epoch; may be pending activation. Zero when none is registered." + }, + "latestRootEpochHash": { + "type": "string", + "pattern": "^0x[0-9a-fA-F]{64}$", + "description": "Chain hash of the latest registered root epoch; zero when none is registered." + } + } + }, + "AuthorizationRequest": { + "allOf": [ + { + "$ref": "#/components/schemas/AppInfo" + } + ], + "type": "object", + "properties": { + "requestedRootEpoch": { + "type": "integer", + "minimum": 0, + "maximum": 4294967295, + "description": "Omit to use the current epoch. An explicit zero selects epoch 0; future epochs are denied." + }, + "requestedAppEpoch": { + "type": "integer", + "minimum": 0, + "maximum": 4294967295, + "description": "Omit to use the current application epoch. Explicit zero selects epoch 0; future epochs are denied." + }, + "teeVariant": { + "type": "string", + "minLength": 1, + "maxLength": 64, + "description": "TEE platform of the attested identity, as the KMS names it, e.g. dstack-tdx; passed to the contract unchanged." + }, + "launchTicketHash": { + "type": "string", + "pattern": "^(0x)?[0-9a-fA-F]{0,64}$", + "description": "Hash of the launch ticket the attested subject presented; omit when none. Passed to the contract left-padded to bytes32." + }, + "operation": { + "type": "string", + "enum": [ + "kms_bootstrap", + "kms_serve", + "kms_export_keys", + "kms_import_keys", + "app_get_key", + "app_get_cert" + ] + } + }, + "required": [ + "teeVariant", + "operation" + ] + } + } + } +} diff --git a/dstack/kms/auth-eth/package-lock.json b/dstack/kms/auth-eth/package-lock.json deleted file mode 100644 index 0007e2c2c6..0000000000 --- a/dstack/kms/auth-eth/package-lock.json +++ /dev/null @@ -1,5271 +0,0 @@ -{ - "name": "auth-eth", - "version": "1.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "auth-eth", - "version": "1.0.0", - "dependencies": { - "@fastify/swagger": "^8.12.0", - "@fastify/swagger-ui": "^6.1.1", - "dotenv": "^16.3.1", - "ethers": "^6.17.0", - "fastify": "^5.12.5", - "yargs": "^17.7.2" - }, - "devDependencies": { - "@types/jest": "^29.5.14", - "@types/node": "^20.17.12", - "jest": "^29.7.0", - "ts-jest": "^29.1.1", - "ts-node": "^10.9.1", - "typescript": "^5.3.3" - } - }, - "node_modules/@adraffy/ens-normalize": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@adraffy/ens-normalize/-/ens-normalize-1.11.1.tgz", - "integrity": "sha512-nhCBV3quEgesuf7c7KYfperqSS14T8bYuvJ8PcLJp6znkZpFc0AuW4qBtr8eKVyPPe/8RSr7sglCWPU5eaxwKQ==", - "license": "MIT" - }, - "node_modules/@babel/code-frame": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", - "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-validator-identifier": "^7.29.7", - "js-tokens": "^4.0.0", - "picocolors": "^1.1.1" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/compat-data": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", - "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/core": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz", - "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.29.7", - "@babel/generator": "^7.29.7", - "@babel/helper-compilation-targets": "^7.29.7", - "@babel/helper-module-transforms": "^7.29.7", - "@babel/helpers": "^7.29.7", - "@babel/parser": "^7.29.7", - "@babel/template": "^7.29.7", - "@babel/traverse": "^7.29.7", - "@babel/types": "^7.29.7", - "@jridgewell/remapping": "^2.3.5", - "convert-source-map": "^2.0.0", - "debug": "^4.1.0", - "gensync": "^1.0.0-beta.2", - "json5": "^2.2.3", - "semver": "^6.3.1" - }, - "engines": { - "node": ">=6.9.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/babel" - } - }, - "node_modules/@babel/core/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/@babel/generator": { - "version": "7.29.8", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.8.tgz", - "integrity": "sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.29.8", - "@babel/types": "^7.29.8", - "@jridgewell/gen-mapping": "^0.3.12", - "@jridgewell/trace-mapping": "^0.3.28", - "jsesc": "^3.0.2" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-compilation-targets": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz", - "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/compat-data": "^7.29.7", - "@babel/helper-validator-option": "^7.29.7", - "browserslist": "^4.24.0", - "lru-cache": "^5.1.1", - "semver": "^6.3.1" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-compilation-targets/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/@babel/helper-globals": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", - "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-module-imports": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", - "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/traverse": "^7.29.7", - "@babel/types": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-module-transforms": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz", - "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-module-imports": "^7.29.7", - "@babel/helper-validator-identifier": "^7.29.7", - "@babel/traverse": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/@babel/helper-plugin-utils": { - "version": "7.25.9", - "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.25.9.tgz", - "integrity": "sha512-kSMlyUVdWe25rEsRGviIgOWnoT/nfABVWlqt9N19/dIPWViAOW2s9wznP5tURbs/IDuNk4gPy3YdYRgH3uxhBw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-string-parser": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", - "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-validator-identifier": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", - "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-validator-option": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", - "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helpers": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz", - "integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/template": "^7.29.7", - "@babel/types": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/parser": { - "version": "7.29.8", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.8.tgz", - "integrity": "sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.29.8" - }, - "bin": { - "parser": "bin/babel-parser.js" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@babel/plugin-syntax-async-generators": { - "version": "7.8.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", - "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-bigint": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz", - "integrity": "sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-class-properties": { - "version": "7.12.13", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz", - "integrity": "sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.12.13" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-class-static-block": { - "version": "7.14.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-static-block/-/plugin-syntax-class-static-block-7.14.5.tgz", - "integrity": "sha512-b+YyPmr6ldyNnM6sqYeMWE+bgJcJpO6yS4QD7ymxgH34GBPNDM/THBh8iunyvKIZztiwLH4CJZ0RxTk9emgpjw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.14.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-import-attributes": { - "version": "7.26.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-attributes/-/plugin-syntax-import-attributes-7.26.0.tgz", - "integrity": "sha512-e2dttdsJ1ZTpi3B9UYGLw41hifAubg19AtCu/2I/F1QNVclOBr1dYpTdmdyZ84Xiz43BS/tCUkMAZNLv12Pi+A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.25.9" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-import-meta": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz", - "integrity": "sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.10.4" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-json-strings": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", - "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-jsx": { - "version": "7.25.9", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.25.9.tgz", - "integrity": "sha512-ld6oezHQMZsZfp6pWtbjaNDF2tiiCYYDqQszHt5VV437lewP9aSi2Of99CK0D0XB21k7FLgnLcmQKyKzynfeAA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.25.9" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-logical-assignment-operators": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", - "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.10.4" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-nullish-coalescing-operator": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz", - "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-numeric-separator": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz", - "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.10.4" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-object-rest-spread": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", - "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-optional-catch-binding": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", - "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-optional-chaining": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz", - "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-private-property-in-object": { - "version": "7.14.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-private-property-in-object/-/plugin-syntax-private-property-in-object-7.14.5.tgz", - "integrity": "sha512-0wVnp9dxJ72ZUJDV27ZfbSj6iHLoytYZmh3rFcxNnvsJF3ktkzLDZPy/mA17HGsaQT3/DQsWYX1f1QGWkCoVUg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.14.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-top-level-await": { - "version": "7.14.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz", - "integrity": "sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.14.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-typescript": { - "version": "7.25.9", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.25.9.tgz", - "integrity": "sha512-hjMgRy5hb8uJJjUcdWunWVcoi9bGpJp8p5Ol1229PoN6aytsLwNMgmdftO23wnCLMfVmTwZDWMPNq/D1SY60JQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.25.9" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/template": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", - "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.29.7", - "@babel/parser": "^7.29.7", - "@babel/types": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/traverse": { - "version": "7.29.8", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.8.tgz", - "integrity": "sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.29.7", - "@babel/generator": "^7.29.8", - "@babel/helper-globals": "^7.29.7", - "@babel/parser": "^7.29.8", - "@babel/template": "^7.29.7", - "@babel/types": "^7.29.8", - "debug": "^4.3.1" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/types": { - "version": "7.29.8", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz", - "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-string-parser": "^7.29.7", - "@babel/helper-validator-identifier": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@bcoe/v8-coverage": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz", - "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@cspotcode/source-map-support": { - "version": "0.8.1", - "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", - "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/trace-mapping": "0.3.9" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/@cspotcode/source-map-support/node_modules/@jridgewell/trace-mapping": { - "version": "0.3.9", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", - "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/resolve-uri": "^3.0.3", - "@jridgewell/sourcemap-codec": "^1.4.10" - } - }, - "node_modules/@fastify/accept-negotiator": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/@fastify/accept-negotiator/-/accept-negotiator-2.1.0.tgz", - "integrity": "sha512-F3EVbzWt+xcnVaOHmWyIlpuFtbxOln7HDZQsh09MtMmMm/CipMayNt8hnIL8VQi54u2ZociDbf+iluGYkf7B1A==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "MIT" - }, - "node_modules/@fastify/ajv-compiler": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/@fastify/ajv-compiler/-/ajv-compiler-4.0.5.tgz", - "integrity": "sha512-KoWKW+MhvfTRWL4qrhUwAAZoaChluo0m0vbiJlGMt2GXvL4LVPQEjt8kSpHI3IBq5Rez8fg+XeH3cneztq+C7A==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "MIT", - "dependencies": { - "ajv": "^8.12.0", - "ajv-formats": "^3.0.1", - "fast-uri": "^3.0.0" - } - }, - "node_modules/@fastify/error": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/@fastify/error/-/error-4.2.0.tgz", - "integrity": "sha512-RSo3sVDXfHskiBZKBPRgnQTtIqpi/7zhJOEmAxCiBcM7d0uwdGdxLlsCaLzGs8v8NnxIRlfG0N51p5yFaOentQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "MIT" - }, - "node_modules/@fastify/fast-json-stringify-compiler": { - "version": "5.0.3", - "resolved": "https://registry.npmjs.org/@fastify/fast-json-stringify-compiler/-/fast-json-stringify-compiler-5.0.3.tgz", - "integrity": "sha512-uik7yYHkLr6fxd8hJSZ8c+xF4WafPK+XzneQDPU+D10r5X19GW8lJcom2YijX2+qtFF1ENJlHXKFM9ouXNJYgQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "MIT", - "dependencies": { - "fast-json-stringify": "^6.0.0" - } - }, - "node_modules/@fastify/forwarded": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/@fastify/forwarded/-/forwarded-3.0.1.tgz", - "integrity": "sha512-JqDochHFqXs3C3Ml3gOY58zM7OqO9ENqPo0UqAjAjH8L01fRZqwX9iLeX34//kiJubF7r2ZQHtBRU36vONbLlw==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "MIT" - }, - "node_modules/@fastify/merge-json-schemas": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/@fastify/merge-json-schemas/-/merge-json-schemas-0.2.1.tgz", - "integrity": "sha512-OA3KGBCy6KtIvLf8DINC5880o5iBlDX4SxzLQS8HorJAbqluzLRn80UXU0bxZn7UOFhFgpRJDasfwn9nG4FG4A==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "MIT", - "dependencies": { - "dequal": "^2.0.3" - } - }, - "node_modules/@fastify/proxy-addr": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/@fastify/proxy-addr/-/proxy-addr-5.1.0.tgz", - "integrity": "sha512-INS+6gh91cLUjB+PVHfu1UqcB76Sqtpyp7bnL+FYojhjygvOPA9ctiD/JDKsyD9Xgu4hUhCSJBPig/w7duNajw==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "MIT", - "dependencies": { - "@fastify/forwarded": "^3.0.0", - "ipaddr.js": "^2.1.0" - } - }, - "node_modules/@fastify/send": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@fastify/send/-/send-4.1.1.tgz", - "integrity": "sha512-BYo+EiaKwlxH+WetGk6hAs1d39iP0y1gqB8lGF/qwkJ9ZZ/cBY1vx5NvExb9Sc3yRMFjD5X4Eyh4e4+TzRkzdw==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "MIT", - "dependencies": { - "@lukeed/ms": "^2.0.2", - "escape-html": "~1.0.3", - "fast-decode-uri-component": "^1.0.1", - "http-errors": "^2.0.0", - "mime": "^3" - } - }, - "node_modules/@fastify/static": { - "version": "10.1.3", - "resolved": "https://registry.npmjs.org/@fastify/static/-/static-10.1.3.tgz", - "integrity": "sha512-W6jqajYS974XjPjB5hQWoxPM8NKM4+p8YmQT6G5IbCa4uhdWSVadZUv75siy1wEA/3ty8RYdpBydfWeu9AqAqQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "MIT", - "dependencies": { - "@fastify/accept-negotiator": "^2.0.0", - "@fastify/error": "^4.0.0", - "@fastify/send": "^4.0.0", - "content-disposition": "^2.0.1", - "fastify-plugin": "^6.0.0", - "fastq": "^1.17.1", - "glob": "^13.0.0" - } - }, - "node_modules/@fastify/static/node_modules/fastify-plugin": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/fastify-plugin/-/fastify-plugin-6.0.0.tgz", - "integrity": "sha512-fZOty7z3O7vOliF6d8bHE3wiEh1KcNnKEQensSgTk9C1DvN6nRLS++XVd86v33Hw/8u9Un8A1zDrQ8ujcQDHEg==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "MIT" - }, - "node_modules/@fastify/swagger": { - "version": "8.15.0", - "resolved": "https://registry.npmjs.org/@fastify/swagger/-/swagger-8.15.0.tgz", - "integrity": "sha512-zy+HEEKFqPMS2sFUsQU5X0MHplhKJvWeohBwTCkBAJA/GDYGLGUWQaETEhptiqxK7Hs0fQB9B4MDb3pbwIiCwA==", - "license": "MIT", - "dependencies": { - "fastify-plugin": "^4.0.0", - "json-schema-resolver": "^2.0.0", - "openapi-types": "^12.0.0", - "rfdc": "^1.3.0", - "yaml": "^2.2.2" - } - }, - "node_modules/@fastify/swagger-ui": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/@fastify/swagger-ui/-/swagger-ui-6.1.1.tgz", - "integrity": "sha512-RKCLSHASlzS2JZvHWn14NmEpHyl0yNosGvqzhUumm/LGPG6RWQBf4oscTFt83QDvc5O5Tol3Beup8inAl/k4EA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "MIT", - "dependencies": { - "@fastify/static": "^10.1.0", - "fastify-plugin": "^6.0.0", - "openapi-types": "^12.1.3", - "rfdc": "^1.3.1", - "yaml": "^2.4.1" - } - }, - "node_modules/@fastify/swagger-ui/node_modules/fastify-plugin": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/fastify-plugin/-/fastify-plugin-6.0.0.tgz", - "integrity": "sha512-fZOty7z3O7vOliF6d8bHE3wiEh1KcNnKEQensSgTk9C1DvN6nRLS++XVd86v33Hw/8u9Un8A1zDrQ8ujcQDHEg==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "MIT" - }, - "node_modules/@istanbuljs/load-nyc-config": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", - "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "camelcase": "^5.3.1", - "find-up": "^4.1.0", - "get-package-type": "^0.1.0", - "js-yaml": "^3.13.1", - "resolve-from": "^5.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/@istanbuljs/schema": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", - "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/@jest/console": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/console/-/console-29.7.0.tgz", - "integrity": "sha512-5Ni4CU7XHQi32IJ398EEP4RrB8eV09sXP2ROqD4bksHrnTree52PsxvX8tpL8LvTZ3pFzXyPbNQReSN41CAhOg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/types": "^29.6.3", - "@types/node": "*", - "chalk": "^4.0.0", - "jest-message-util": "^29.7.0", - "jest-util": "^29.7.0", - "slash": "^3.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/core": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/core/-/core-29.7.0.tgz", - "integrity": "sha512-n7aeXWKMnGtDA48y8TLWJPJmLmmZ642Ceo78cYWEpiD7FzDgmNDV/GCVRorPABdXLJZ/9wzzgZAlHjXjxDHGsg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/console": "^29.7.0", - "@jest/reporters": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "ansi-escapes": "^4.2.1", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "exit": "^0.1.2", - "graceful-fs": "^4.2.9", - "jest-changed-files": "^29.7.0", - "jest-config": "^29.7.0", - "jest-haste-map": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-regex-util": "^29.6.3", - "jest-resolve": "^29.7.0", - "jest-resolve-dependencies": "^29.7.0", - "jest-runner": "^29.7.0", - "jest-runtime": "^29.7.0", - "jest-snapshot": "^29.7.0", - "jest-util": "^29.7.0", - "jest-validate": "^29.7.0", - "jest-watcher": "^29.7.0", - "micromatch": "^4.0.4", - "pretty-format": "^29.7.0", - "slash": "^3.0.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" - }, - "peerDependenciesMeta": { - "node-notifier": { - "optional": true - } - } - }, - "node_modules/@jest/environment": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-29.7.0.tgz", - "integrity": "sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/fake-timers": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "jest-mock": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/expect": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/expect/-/expect-29.7.0.tgz", - "integrity": "sha512-8uMeAMycttpva3P1lBHB8VciS9V0XAr3GymPpipdyQXbBcuhkLQOSe8E/p92RyAdToS6ZD1tFkX+CkhoECE0dQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "expect": "^29.7.0", - "jest-snapshot": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/expect-utils": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.7.0.tgz", - "integrity": "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA==", - "dev": true, - "license": "MIT", - "dependencies": { - "jest-get-type": "^29.6.3" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/fake-timers": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-29.7.0.tgz", - "integrity": "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/types": "^29.6.3", - "@sinonjs/fake-timers": "^10.0.2", - "@types/node": "*", - "jest-message-util": "^29.7.0", - "jest-mock": "^29.7.0", - "jest-util": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/globals": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-29.7.0.tgz", - "integrity": "sha512-mpiz3dutLbkW2MNFubUGUEVLkTGiqW6yLVTA+JbP6fI6J5iL9Y0Nlg8k95pcF8ctKwCS7WVxteBs29hhfAotzQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/environment": "^29.7.0", - "@jest/expect": "^29.7.0", - "@jest/types": "^29.6.3", - "jest-mock": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/reporters": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-29.7.0.tgz", - "integrity": "sha512-DApq0KJbJOEzAFYjHADNNxAE3KbhxQB1y5Kplb5Waqw6zVbuWatSnMjE5gs8FUgEPmNsnZA3NCWl9NG0ia04Pg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@bcoe/v8-coverage": "^0.2.3", - "@jest/console": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "@jridgewell/trace-mapping": "^0.3.18", - "@types/node": "*", - "chalk": "^4.0.0", - "collect-v8-coverage": "^1.0.0", - "exit": "^0.1.2", - "glob": "^7.1.3", - "graceful-fs": "^4.2.9", - "istanbul-lib-coverage": "^3.0.0", - "istanbul-lib-instrument": "^6.0.0", - "istanbul-lib-report": "^3.0.0", - "istanbul-lib-source-maps": "^4.0.0", - "istanbul-reports": "^3.1.3", - "jest-message-util": "^29.7.0", - "jest-util": "^29.7.0", - "jest-worker": "^29.7.0", - "slash": "^3.0.0", - "string-length": "^4.0.1", - "strip-ansi": "^6.0.0", - "v8-to-istanbul": "^9.0.1" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" - }, - "peerDependenciesMeta": { - "node-notifier": { - "optional": true - } - } - }, - "node_modules/@jest/reporters/node_modules/brace-expansion": { - "version": "1.1.21", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", - "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/@jest/reporters/node_modules/glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "deprecated": "Glob versions prior to v9 are no longer supported", - "dev": true, - "license": "ISC", - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - }, - "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/@jest/reporters/node_modules/minimatch": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", - "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/@jest/schemas": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz", - "integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@sinclair/typebox": "^0.27.8" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/source-map": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-29.6.3.tgz", - "integrity": "sha512-MHjT95QuipcPrpLM+8JMSzFx6eHp5Bm+4XeFDJlwsvVBjmKNiIAvasGK2fxz2WbGRlnvqehFbh07MMa7n3YJnw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/trace-mapping": "^0.3.18", - "callsites": "^3.0.0", - "graceful-fs": "^4.2.9" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/test-result": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-29.7.0.tgz", - "integrity": "sha512-Fdx+tv6x1zlkJPcWXmMDAG2HBnaR9XPSd5aDWQVsfrZmLVT3lU1cwyxLgRmXR9yrq4NBoEm9BMsfgFzTQAbJYA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/console": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/istanbul-lib-coverage": "^2.0.0", - "collect-v8-coverage": "^1.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/test-sequencer": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-29.7.0.tgz", - "integrity": "sha512-GQwJ5WZVrKnOJuiYiAF52UNUJXgTZx1NHjFSEB0qEMmSZKAkdMoIzw/Cj6x6NF4AvV23AUqDpFzQkN/eYCYTxw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/test-result": "^29.7.0", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.7.0", - "slash": "^3.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/transform": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-29.7.0.tgz", - "integrity": "sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/core": "^7.11.6", - "@jest/types": "^29.6.3", - "@jridgewell/trace-mapping": "^0.3.18", - "babel-plugin-istanbul": "^6.1.1", - "chalk": "^4.0.0", - "convert-source-map": "^2.0.0", - "fast-json-stable-stringify": "^2.1.0", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.7.0", - "jest-regex-util": "^29.6.3", - "jest-util": "^29.7.0", - "micromatch": "^4.0.4", - "pirates": "^4.0.4", - "slash": "^3.0.0", - "write-file-atomic": "^4.0.2" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/types": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/@jest/types/-/types-29.6.3.tgz", - "integrity": "sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/schemas": "^29.6.3", - "@types/istanbul-lib-coverage": "^2.0.0", - "@types/istanbul-reports": "^3.0.0", - "@types/node": "*", - "@types/yargs": "^17.0.8", - "chalk": "^4.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jridgewell/gen-mapping": { - "version": "0.3.13", - "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", - "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.0", - "@jridgewell/trace-mapping": "^0.3.24" - } - }, - "node_modules/@jridgewell/remapping": { - "version": "2.3.5", - "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", - "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/gen-mapping": "^0.3.5", - "@jridgewell/trace-mapping": "^0.3.24" - } - }, - "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", - "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz", - "integrity": "sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.31", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", - "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/resolve-uri": "^3.1.0", - "@jridgewell/sourcemap-codec": "^1.4.14" - } - }, - "node_modules/@lukeed/ms": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/@lukeed/ms/-/ms-2.0.2.tgz", - "integrity": "sha512-9I2Zn6+NJLfaGoz9jN3lpwDgAYvfGeNYdbAIjJOqzs4Tpc+VU3Jqq4IofSUBKajiDS8k9fZIg18/z13mpk1bsA==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/@noble/curves": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.2.0.tgz", - "integrity": "sha512-oYclrNgRaM9SsBUBVbb8M6DTV7ZHRTKugureoYEncY5c65HOmRzvSiTE3y5CYaPYJA/GVkrhXEoF0M3Ya9PMnw==", - "license": "MIT", - "dependencies": { - "@noble/hashes": "1.3.2" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@noble/hashes": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.3.2.tgz", - "integrity": "sha512-MVC8EAQp7MvEcm30KWENFjgR+Mkmf+D189XJTkFIlwohU5hcBbn1ZkKq7KVTi2Hme3PMGF390DaL52beVrIihQ==", - "license": "MIT", - "engines": { - "node": ">= 16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@pinojs/redact": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz", - "integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==", - "license": "MIT" - }, - "node_modules/@sinclair/typebox": { - "version": "0.27.8", - "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz", - "integrity": "sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@sinonjs/commons": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.1.tgz", - "integrity": "sha512-K3mCHKQ9sVh8o1C9cxkwxaOmXoAMlDxC1mYyHrjqOWEcBjYr76t96zL2zlj5dUGZ3HSw240X1qgH3Mjf1yJWpQ==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "type-detect": "4.0.8" - } - }, - "node_modules/@sinonjs/fake-timers": { - "version": "10.3.0", - "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-10.3.0.tgz", - "integrity": "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "@sinonjs/commons": "^3.0.0" - } - }, - "node_modules/@tsconfig/node10": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.11.tgz", - "integrity": "sha512-DcRjDCujK/kCk/cUe8Xz8ZSpm8mS3mNNpta+jGCA6USEDfktlNvm1+IuZ9eTcDbNk41BHwpHHeW+N1lKCz4zOw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@tsconfig/node12": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz", - "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==", - "dev": true, - "license": "MIT" - }, - "node_modules/@tsconfig/node14": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz", - "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==", - "dev": true, - "license": "MIT" - }, - "node_modules/@tsconfig/node16": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz", - "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/babel__core": { - "version": "7.20.5", - "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", - "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.20.7", - "@babel/types": "^7.20.7", - "@types/babel__generator": "*", - "@types/babel__template": "*", - "@types/babel__traverse": "*" - } - }, - "node_modules/@types/babel__generator": { - "version": "7.6.8", - "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.6.8.tgz", - "integrity": "sha512-ASsj+tpEDsEiFr1arWrlN6V3mdfjRMZt6LtK/Vp/kreFLnr5QH5+DhvD5nINYZXzwJvXeGq+05iUXcAzVrqWtw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.0.0" - } - }, - "node_modules/@types/babel__template": { - "version": "7.4.4", - "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", - "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.1.0", - "@babel/types": "^7.0.0" - } - }, - "node_modules/@types/babel__traverse": { - "version": "7.20.6", - "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.20.6.tgz", - "integrity": "sha512-r1bzfrm0tomOI8g1SzvCaQHo6Lcv6zu0EA+W2kHrt8dyrHQxGzBBL4kdkzIS+jBMV+EYcMAEAqXqYaLJq5rOZg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.20.7" - } - }, - "node_modules/@types/graceful-fs": { - "version": "4.1.9", - "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.9.tgz", - "integrity": "sha512-olP3sd1qOEe5dXTSaFvQG+02VdRXcdytWLAZsAq1PecU8uqQAhkrnbli7DagjtXKW/Bl7YJbUsa8MPcuc8LHEQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/istanbul-lib-coverage": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz", - "integrity": "sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/istanbul-lib-report": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.3.tgz", - "integrity": "sha512-NQn7AHQnk/RSLOxrBbGyJM/aVQ+pjj5HCgasFxc0K/KhoATfQ/47AyUl15I2yBUpihjmas+a+VJBOqecrFH+uA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/istanbul-lib-coverage": "*" - } - }, - "node_modules/@types/istanbul-reports": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.4.tgz", - "integrity": "sha512-pk2B1NWalF9toCRu6gjBzR69syFjP4Od8WRAX+0mmf9lAjCRicLOWc+ZrxZHx/0XRjotgkF9t6iaMJ+aXcOdZQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/istanbul-lib-report": "*" - } - }, - "node_modules/@types/jest": { - "version": "29.5.14", - "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.14.tgz", - "integrity": "sha512-ZN+4sdnLUbo8EVvVc2ao0GFW6oVrQRPn4K2lglySj7APvSrgzxHiNNK99us4WDMi57xxA2yggblIAMNhXOotLQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "expect": "^29.0.0", - "pretty-format": "^29.0.0" - } - }, - "node_modules/@types/node": { - "version": "20.17.12", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.17.12.tgz", - "integrity": "sha512-vo/wmBgMIiEA23A/knMfn/cf37VnuF52nZh5ZoW0GWt4e4sxNquibrMRJ7UQsA06+MBx9r/H1jsI9grYjQCQlw==", - "dev": true, - "license": "MIT", - "dependencies": { - "undici-types": "~6.19.2" - } - }, - "node_modules/@types/stack-utils": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz", - "integrity": "sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/yargs": { - "version": "17.0.33", - "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.33.tgz", - "integrity": "sha512-WpxBCKWPLr4xSsHgz511rFJAM+wS28w2zEO1QDNY5zM/S8ok70NNfztH0xwhqKyaK0OHCbN98LDAZuy1ctxDkA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/yargs-parser": "*" - } - }, - "node_modules/@types/yargs-parser": { - "version": "21.0.3", - "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.3.tgz", - "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/abstract-logging": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/abstract-logging/-/abstract-logging-2.0.1.tgz", - "integrity": "sha512-2BjRTZxTPvheOvGbBslFSYOUkr+SjPtOnrLP33f+VIWLzezQpZcqVg7ja3L4dBXmzzgwT+a029jRx5PCi3JuiA==", - "license": "MIT" - }, - "node_modules/acorn": { - "version": "8.14.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.0.tgz", - "integrity": "sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA==", - "dev": true, - "license": "MIT", - "bin": { - "acorn": "bin/acorn" - }, - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/acorn-walk": { - "version": "8.3.4", - "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.4.tgz", - "integrity": "sha512-ueEepnujpqee2o5aIYnvHU6C0A42MNdsIDeqy5BydrkuC5R1ZuUFnm27EeFJGoEHJQgn3uleRvmTXaJgfXbt4g==", - "dev": true, - "license": "MIT", - "dependencies": { - "acorn": "^8.11.0" - }, - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/aes-js": { - "version": "4.0.0-beta.5", - "resolved": "https://registry.npmjs.org/aes-js/-/aes-js-4.0.0-beta.5.tgz", - "integrity": "sha512-G965FqalsNyrPqgEGON7nIx1e/OVENSgiEIzyC63haUMuvNnwIgIjMs52hlTCKhkBny7A2ORNlfY9Zu+jmGk1Q==", - "license": "MIT" - }, - "node_modules/ajv": { - "version": "8.20.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", - "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.3", - "fast-uri": "^3.0.1", - "json-schema-traverse": "^1.0.0", - "require-from-string": "^2.0.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/ajv-formats": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", - "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", - "license": "MIT", - "dependencies": { - "ajv": "^8.0.0" - }, - "peerDependencies": { - "ajv": "^8.0.0" - }, - "peerDependenciesMeta": { - "ajv": { - "optional": true - } - } - }, - "node_modules/ansi-escapes": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", - "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "type-fest": "^0.21.3" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "license": "MIT", - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/anymatch": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", - "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", - "dev": true, - "license": "ISC", - "dependencies": { - "normalize-path": "^3.0.0", - "picomatch": "^2.0.4" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/arg": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", - "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", - "dev": true, - "license": "MIT" - }, - "node_modules/argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", - "dev": true, - "license": "MIT", - "dependencies": { - "sprintf-js": "~1.0.2" - } - }, - "node_modules/async": { - "version": "3.2.6", - "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", - "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", - "dev": true, - "license": "MIT" - }, - "node_modules/atomic-sleep": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz", - "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==", - "license": "MIT", - "engines": { - "node": ">=8.0.0" - } - }, - "node_modules/avvio": { - "version": "9.2.0", - "resolved": "https://registry.npmjs.org/avvio/-/avvio-9.2.0.tgz", - "integrity": "sha512-2t/sy01ArdHHE0vRH5Hsay+RtCZt3dLPji7W7/MMOCEgze5b7SNDC4j5H6FnVgPkI1MTNFGzHdHrVXDDl7QSSQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "MIT", - "dependencies": { - "@fastify/error": "^4.0.0", - "fastq": "^1.17.1" - } - }, - "node_modules/babel-jest": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-29.7.0.tgz", - "integrity": "sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/transform": "^29.7.0", - "@types/babel__core": "^7.1.14", - "babel-plugin-istanbul": "^6.1.1", - "babel-preset-jest": "^29.6.3", - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", - "slash": "^3.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "@babel/core": "^7.8.0" - } - }, - "node_modules/babel-plugin-istanbul": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-6.1.1.tgz", - "integrity": "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "@babel/helper-plugin-utils": "^7.0.0", - "@istanbuljs/load-nyc-config": "^1.0.0", - "@istanbuljs/schema": "^0.1.2", - "istanbul-lib-instrument": "^5.0.4", - "test-exclude": "^6.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/babel-plugin-istanbul/node_modules/istanbul-lib-instrument": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.1.tgz", - "integrity": "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "@babel/core": "^7.12.3", - "@babel/parser": "^7.14.7", - "@istanbuljs/schema": "^0.1.2", - "istanbul-lib-coverage": "^3.2.0", - "semver": "^6.3.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/babel-plugin-istanbul/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/babel-plugin-jest-hoist": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-29.6.3.tgz", - "integrity": "sha512-ESAc/RJvGTFEzRwOTT4+lNDk/GNHMkKbNzsvT0qKRfDyyYTskxB5rnU2njIDYVxXCBHHEI1c0YwHob3WaYujOg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/template": "^7.3.3", - "@babel/types": "^7.3.3", - "@types/babel__core": "^7.1.14", - "@types/babel__traverse": "^7.0.6" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/babel-preset-current-node-syntax": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.1.0.tgz", - "integrity": "sha512-ldYss8SbBlWva1bs28q78Ju5Zq1F+8BrqBZZ0VFhLBvhh6lCpC2o3gDJi/5DRLs9FgYZCnmPYIVFU4lRXCkyUw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/plugin-syntax-async-generators": "^7.8.4", - "@babel/plugin-syntax-bigint": "^7.8.3", - "@babel/plugin-syntax-class-properties": "^7.12.13", - "@babel/plugin-syntax-class-static-block": "^7.14.5", - "@babel/plugin-syntax-import-attributes": "^7.24.7", - "@babel/plugin-syntax-import-meta": "^7.10.4", - "@babel/plugin-syntax-json-strings": "^7.8.3", - "@babel/plugin-syntax-logical-assignment-operators": "^7.10.4", - "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", - "@babel/plugin-syntax-numeric-separator": "^7.10.4", - "@babel/plugin-syntax-object-rest-spread": "^7.8.3", - "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", - "@babel/plugin-syntax-optional-chaining": "^7.8.3", - "@babel/plugin-syntax-private-property-in-object": "^7.14.5", - "@babel/plugin-syntax-top-level-await": "^7.14.5" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/babel-preset-jest": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-29.6.3.tgz", - "integrity": "sha512-0B3bhxR6snWXJZtR/RliHTDPRgn1sNHOR0yVtq/IiQFyuOVjFS+wuio/R4gSNkyYmKmJB4wGZv2NZanmKmTnNA==", - "dev": true, - "license": "MIT", - "dependencies": { - "babel-plugin-jest-hoist": "^29.6.3", - "babel-preset-current-node-syntax": "^1.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "dev": true, - "license": "MIT" - }, - "node_modules/baseline-browser-mapping": { - "version": "2.11.23", - "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.23.tgz", - "integrity": "sha512-le521dGVfxM7yRX0EikCoSz+rOK+hHzdDt/E7mG1jOJB/6WAAUuwVroLwaB7ApaUsz5Q0kFlDXLSA9MheUIfRQ==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "baseline-browser-mapping": "dist/cli.cjs" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/brace-expansion": { - "version": "2.1.7", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", - "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0" - } - }, - "node_modules/braces": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", - "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", - "dev": true, - "license": "MIT", - "dependencies": { - "fill-range": "^7.1.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/browserslist": { - "version": "4.28.9", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.9.tgz", - "integrity": "sha512-EWazOblFYUvlGZcfGhPUPmYh3nikUxBVb+y9MJun5f3hBi812X+8MSQTujLBtgK3cf51fJWbWfOjyeO954d+Eg==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "baseline-browser-mapping": "^2.11.20", - "caniuse-lite": "^1.0.30001810", - "electron-to-chromium": "^1.5.420", - "node-releases": "^2.0.54", - "update-browserslist-db": "^1.3.2" - }, - "bin": { - "browserslist": "cli.js" - }, - "engines": { - "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" - } - }, - "node_modules/bs-logger": { - "version": "0.2.6", - "resolved": "https://registry.npmjs.org/bs-logger/-/bs-logger-0.2.6.tgz", - "integrity": "sha512-pd8DCoxmbgc7hyPKOvxtqNcjYoOsABPQdcCUjGp3d42VR2CX1ORhk2A87oqqu5R1kk+76nsxZupkmyd+MVtCog==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-json-stable-stringify": "2.x" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/bser": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.1.tgz", - "integrity": "sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "node-int64": "^0.4.0" - } - }, - "node_modules/buffer-from": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", - "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/callsites": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", - "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/camelcase": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", - "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/caniuse-lite": { - "version": "1.0.30001810", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001810.tgz", - "integrity": "sha512-TITQPUkaz+aVk5GL6NhOdwk1aEaNTSDPsGFWrTuhKGtjTF70jL/Oht2W4c6rXUe5fu7Ie19VIahAXHIIiWWNeg==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/caniuse-lite" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "CC-BY-4.0" - }, - "node_modules/chalk": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", - "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, - "node_modules/char-regex": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", - "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - } - }, - "node_modules/ci-info": { - "version": "3.9.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz", - "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/sibiraj-s" - } - ], - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/cjs-module-lexer": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.4.1.tgz", - "integrity": "sha512-cuSVIHi9/9E/+821Qjdvngor+xpnlwnuwIyZOaLmHBVdXL+gP+I6QQB9VkO7RI77YIcTV+S1W9AreJ5eN63JBA==", - "dev": true, - "license": "MIT" - }, - "node_modules/cliui": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", - "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", - "license": "ISC", - "dependencies": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.1", - "wrap-ansi": "^7.0.0" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/co": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", - "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==", - "dev": true, - "license": "MIT", - "engines": { - "iojs": ">= 1.0.0", - "node": ">= 0.12.0" - } - }, - "node_modules/collect-v8-coverage": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.2.tgz", - "integrity": "sha512-lHl4d5/ONEbLlJvaJNtsF/Lz+WvB07u2ycqTYbdrq7UypDXailES4valYb2eWiJFxZlVmpGekfqoxQhzyFdT4Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "license": "MIT", - "dependencies": { - "color-name": "~1.1.4" - }, - "engines": { - "node": ">=7.0.0" - } - }, - "node_modules/color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "license": "MIT" - }, - "node_modules/concat-map": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", - "dev": true, - "license": "MIT" - }, - "node_modules/content-disposition": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-2.0.1.tgz", - "integrity": "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==", - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/convert-source-map": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", - "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", - "dev": true, - "license": "MIT" - }, - "node_modules/cookie": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", - "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/create-jest": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/create-jest/-/create-jest-29.7.0.tgz", - "integrity": "sha512-Adz2bdH0Vq3F53KEMJOoftQFutWCukm6J24wbPWRO4k1kMY7gS7ds/uoJkNuV8wDCtWWnuwGcJwpWcih+zEW1Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/types": "^29.6.3", - "chalk": "^4.0.0", - "exit": "^0.1.2", - "graceful-fs": "^4.2.9", - "jest-config": "^29.7.0", - "jest-util": "^29.7.0", - "prompts": "^2.0.1" - }, - "bin": { - "create-jest": "bin/create-jest.js" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/create-require": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", - "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/cross-spawn": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", - "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", - "dev": true, - "license": "MIT", - "dependencies": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/debug": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", - "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", - "license": "MIT", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/dedent": { - "version": "1.5.3", - "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.5.3.tgz", - "integrity": "sha512-NHQtfOOW68WD8lgypbLA5oT+Bt0xXJhiYvoR6SmmNXZfpzOGXwdKWmcwG8N7PwVVWV3eF/68nmD9BaJSsTBhyQ==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "babel-plugin-macros": "^3.1.0" - }, - "peerDependenciesMeta": { - "babel-plugin-macros": { - "optional": true - } - } - }, - "node_modules/deepmerge": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", - "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/depd": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", - "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/dequal": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", - "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/detect-newline": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", - "integrity": "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/diff": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", - "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.3.1" - } - }, - "node_modules/diff-sequences": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", - "integrity": "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/dotenv": { - "version": "16.4.7", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.7.tgz", - "integrity": "sha512-47qPchRCykZC03FhkYAhrvwU4xDBFIj1QPqaarj6mdM/hgUzfPHcpkHJOn3mJAufFeeAxAzeGsr5X0M4k6fLZQ==", - "license": "BSD-2-Clause", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://dotenvx.com" - } - }, - "node_modules/ejs": { - "version": "3.1.10", - "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.10.tgz", - "integrity": "sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "jake": "^10.8.5" - }, - "bin": { - "ejs": "bin/cli.js" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/electron-to-chromium": { - "version": "1.5.427", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.427.tgz", - "integrity": "sha512-n14zb3FdsChZ2BNobqNHAJMcP3ifFv4paox2LvCrfVAQcqGiSURgbJl+PfMpHVCNFkStnNc+RRVtPBTVW5PDgw==", - "dev": true, - "license": "ISC" - }, - "node_modules/emittery": { - "version": "0.13.1", - "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.13.1.tgz", - "integrity": "sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sindresorhus/emittery?sponsor=1" - } - }, - "node_modules/emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "license": "MIT" - }, - "node_modules/error-ex": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", - "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-arrayish": "^0.2.1" - } - }, - "node_modules/escalade": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", - "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/escape-html": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", - "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", - "license": "MIT" - }, - "node_modules/escape-string-regexp": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", - "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/esprima": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", - "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", - "dev": true, - "license": "BSD-2-Clause", - "bin": { - "esparse": "bin/esparse.js", - "esvalidate": "bin/esvalidate.js" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/ethers": { - "version": "6.17.0", - "resolved": "https://registry.npmjs.org/ethers/-/ethers-6.17.0.tgz", - "integrity": "sha512-BpyrpIPJ3ydEVow8zGaz1DuPS7YU8DcWxuBnY9a0UA/lvAPwrMr+EPXsfrul628SRaekPNeIM4UFh/91GWZang==", - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/ethers-io/" - }, - { - "type": "individual", - "url": "https://www.buymeacoffee.com/ricmoo" - } - ], - "license": "MIT", - "dependencies": { - "@adraffy/ens-normalize": "1.11.1", - "@noble/curves": "1.2.0", - "@noble/hashes": "1.3.2", - "@types/node": "22.7.5", - "aes-js": "4.0.0-beta.5", - "tslib": "2.7.0", - "ws": "8.21.0" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/ethers/node_modules/@types/node": { - "version": "22.7.5", - "resolved": "https://registry.npmjs.org/@types/node/-/node-22.7.5.tgz", - "integrity": "sha512-jML7s2NAzMWc//QSJ1a3prpk78cOPchGvXJsC3C6R6PSMoooztvRVQEz89gmBTBY1SPMaqo5teB4uNHPdetShQ==", - "license": "MIT", - "dependencies": { - "undici-types": "~6.19.2" - } - }, - "node_modules/execa": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", - "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", - "dev": true, - "license": "MIT", - "dependencies": { - "cross-spawn": "^7.0.3", - "get-stream": "^6.0.0", - "human-signals": "^2.1.0", - "is-stream": "^2.0.0", - "merge-stream": "^2.0.0", - "npm-run-path": "^4.0.1", - "onetime": "^5.1.2", - "signal-exit": "^3.0.3", - "strip-final-newline": "^2.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sindresorhus/execa?sponsor=1" - } - }, - "node_modules/exit": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", - "integrity": "sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ==", - "dev": true, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/expect": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/expect/-/expect-29.7.0.tgz", - "integrity": "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/expect-utils": "^29.7.0", - "jest-get-type": "^29.6.3", - "jest-matcher-utils": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-util": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/fast-decode-uri-component": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/fast-decode-uri-component/-/fast-decode-uri-component-1.0.1.tgz", - "integrity": "sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg==", - "license": "MIT" - }, - "node_modules/fast-deep-equal": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "license": "MIT" - }, - "node_modules/fast-json-stable-stringify": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", - "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", - "dev": true, - "license": "MIT" - }, - "node_modules/fast-json-stringify": { - "version": "6.4.0", - "resolved": "https://registry.npmjs.org/fast-json-stringify/-/fast-json-stringify-6.4.0.tgz", - "integrity": "sha512-ibRCQ0GZKJIQ+P3Et1h0LhPgp3PMTYk0MH8O+kW3lNYsvmaQww5Nn3f1jf73Q0jR1Yz3a1CDP4/NZD3vOajWJQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "MIT", - "dependencies": { - "@fastify/merge-json-schemas": "^0.2.0", - "ajv": "^8.12.0", - "ajv-formats": "^3.0.1", - "fast-uri": "^3.0.0", - "json-schema-ref-resolver": "^3.0.0", - "rfdc": "^1.2.0" - } - }, - "node_modules/fast-querystring": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/fast-querystring/-/fast-querystring-1.1.2.tgz", - "integrity": "sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg==", - "license": "MIT", - "dependencies": { - "fast-decode-uri-component": "^1.0.1" - } - }, - "node_modules/fast-uri": { - "version": "3.1.7", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.7.tgz", - "integrity": "sha512-dOvZVzjdZdz7phd9v6jCbwxrBW3fK6n8Rc0CtdmM4bumzMnxywBYhuph6J819RRw/ku+rLbelwfMunktuzVVHg==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "BSD-3-Clause" - }, - "node_modules/fastify": { - "version": "5.12.5", - "resolved": "https://registry.npmjs.org/fastify/-/fastify-5.12.5.tgz", - "integrity": "sha512-OB2k1dlxs5/NAABqeKV2FUHkSD2BbENsCak8yULVcymn3fHIPDVa9TI3SDnJSWYSllZmSYuZXy2gTnsT+Sut1A==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "MIT", - "dependencies": { - "@fastify/ajv-compiler": "^4.0.5", - "@fastify/error": "^4.0.0", - "@fastify/fast-json-stringify-compiler": "^5.0.0", - "@fastify/proxy-addr": "^5.0.0", - "abstract-logging": "^2.0.1", - "avvio": "^9.0.0", - "fast-json-stringify": "^7.0.0", - "find-my-way": "^9.6.0", - "light-my-request": "^6.0.0", - "pino": "^9.14.0 || ^10.1.0", - "process-warning": "^5.1.0", - "rfdc": "^1.3.1", - "secure-json-parse": "^4.0.0", - "semver": "^7.6.0", - "toad-cache": "^3.7.0" - } - }, - "node_modules/fastify-plugin": { - "version": "4.5.1", - "resolved": "https://registry.npmjs.org/fastify-plugin/-/fastify-plugin-4.5.1.tgz", - "integrity": "sha512-stRHYGeuqpEZTL1Ef0Ovr2ltazUT9g844X5z/zEBFLG8RYlpDiOCIG+ATvYEp+/zmc7sN29mcIMp8gvYplYPIQ==", - "license": "MIT" - }, - "node_modules/fastify/node_modules/fast-json-stringify": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/fast-json-stringify/-/fast-json-stringify-7.0.1.tgz", - "integrity": "sha512-eRSayARSbbwlBjpP4vnTTIRD5QPcIrmihPxDeN1DtKnHPg66UuJLx+8hlK1kaFdjvzyQ/dzALoi4vwAQ+T+iZA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "MIT", - "dependencies": { - "@fastify/merge-json-schemas": "^0.2.0", - "ajv": "^8.12.0", - "ajv-formats": "^3.0.1", - "fast-uri": "^4.0.0", - "json-schema-ref-resolver": "^3.0.0", - "rfdc": "^1.2.0" - } - }, - "node_modules/fastify/node_modules/fast-uri": { - "version": "4.1.4", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-4.1.4.tgz", - "integrity": "sha512-dODXrIxlS9JSdgAnhIUKOosKV1oMtU2VtVw87QRaHzyl5jxO290Ii5tEZfCfzfWNHi3jKWwBSdQj0qIyshdZdQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "BSD-3-Clause" - }, - "node_modules/fastq": { - "version": "1.20.1", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz", - "integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==", - "license": "ISC", - "dependencies": { - "reusify": "^1.0.4" - } - }, - "node_modules/fb-watchman": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.2.tgz", - "integrity": "sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "bser": "2.1.1" - } - }, - "node_modules/filelist": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.4.tgz", - "integrity": "sha512-w1cEuf3S+DrLCQL7ET6kz+gmlJdbq9J7yXCSjK/OZCPA+qEN1WyF4ZAf0YYJa4/shHJra2t/d/r8SV4Ji+x+8Q==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "minimatch": "^5.0.1" - } - }, - "node_modules/fill-range": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", - "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", - "dev": true, - "license": "MIT", - "dependencies": { - "to-regex-range": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/find-my-way": { - "version": "9.7.0", - "resolved": "https://registry.npmjs.org/find-my-way/-/find-my-way-9.7.0.tgz", - "integrity": "sha512-f2JHn75x2JlwUwLenZypgczR7YWMb/uO9BvUXtus+JMgkbIkLADd38cI4EiV+OQqrGo1Zlq6V8wnqMJ8e62wUQ==", - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.3", - "fast-querystring": "^1.0.0", - "safe-regex2": "^5.0.0" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/find-up": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", - "dev": true, - "license": "MIT", - "dependencies": { - "locate-path": "^5.0.0", - "path-exists": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", - "dev": true, - "license": "ISC" - }, - "node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, - "node_modules/function-bind": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", - "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/gensync": { - "version": "1.0.0-beta.2", - "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", - "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/get-caller-file": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", - "license": "ISC", - "engines": { - "node": "6.* || 8.* || >= 10.*" - } - }, - "node_modules/get-package-type": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", - "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8.0.0" - } - }, - "node_modules/get-stream": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", - "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/glob": { - "version": "13.0.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", - "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", - "license": "BlueOak-1.0.0", - "dependencies": { - "minimatch": "^10.2.2", - "minipass": "^7.1.3", - "path-scurry": "^2.0.2" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/glob/node_modules/balanced-match": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", - "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", - "license": "MIT", - "engines": { - "node": "18 || 20 || >=22" - } - }, - "node_modules/glob/node_modules/brace-expansion": { - "version": "5.0.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", - "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", - "license": "MIT", - "dependencies": { - "balanced-match": "^4.0.2" - }, - "engines": { - "node": "20 || >=22" - } - }, - "node_modules/glob/node_modules/minimatch": { - "version": "10.2.6", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", - "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", - "license": "BlueOak-1.0.0", - "dependencies": { - "brace-expansion": "^5.0.8" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/graceful-fs": { - "version": "4.2.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", - "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/has-flag": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/hasown": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", - "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/html-escaper": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", - "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", - "dev": true, - "license": "MIT" - }, - "node_modules/http-errors": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", - "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", - "license": "MIT", - "dependencies": { - "depd": "~2.0.0", - "inherits": "~2.0.4", - "setprototypeof": "~1.2.0", - "statuses": "~2.0.2", - "toidentifier": "~1.0.1" - }, - "engines": { - "node": ">= 0.8" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/human-signals": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", - "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=10.17.0" - } - }, - "node_modules/import-local": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.2.0.tgz", - "integrity": "sha512-2SPlun1JUPWoM6t3F0dw0FkCF/jWY8kttcY4f599GLTSjh2OCuuhdTkJQsEcZzBqbXZGKMK2OqW1oZsjtf/gQA==", - "dev": true, - "license": "MIT", - "dependencies": { - "pkg-dir": "^4.2.0", - "resolve-cwd": "^3.0.0" - }, - "bin": { - "import-local-fixture": "fixtures/cli.js" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/imurmurhash": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", - "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.8.19" - } - }, - "node_modules/inflight": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", - "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", - "dev": true, - "license": "ISC", - "dependencies": { - "once": "^1.3.0", - "wrappy": "1" - } - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "license": "ISC" - }, - "node_modules/ipaddr.js": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.4.0.tgz", - "integrity": "sha512-9VGk3HGanVE6JoZXHiCpnGy5X0jYDnN4EA4lntFPj+1vIWlFhIylq2CrrCOJH9EAhc5CYhq18F2Av2tgoAPsYQ==", - "license": "MIT", - "engines": { - "node": ">= 10" - } - }, - "node_modules/is-arrayish": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", - "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", - "dev": true, - "license": "MIT" - }, - "node_modules/is-core-module": { - "version": "2.16.1", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", - "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", - "dev": true, - "license": "MIT", - "dependencies": { - "hasown": "^2.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/is-generator-fn": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz", - "integrity": "sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/is-number": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", - "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.12.0" - } - }, - "node_modules/is-stream": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", - "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "dev": true, - "license": "ISC" - }, - "node_modules/istanbul-lib-coverage": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz", - "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=8" - } - }, - "node_modules/istanbul-lib-instrument": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-6.0.3.tgz", - "integrity": "sha512-Vtgk7L/R2JHyyGW07spoFlB8/lpjiOLTjMdms6AFMraYt3BaJauod/NGrfnVG/y4Ix1JEuMRPDPEj2ua+zz1/Q==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "@babel/core": "^7.23.9", - "@babel/parser": "^7.23.9", - "@istanbuljs/schema": "^0.1.3", - "istanbul-lib-coverage": "^3.2.0", - "semver": "^7.5.4" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-lib-report": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", - "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "istanbul-lib-coverage": "^3.0.0", - "make-dir": "^4.0.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-lib-source-maps": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", - "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "debug": "^4.1.1", - "istanbul-lib-coverage": "^3.0.0", - "source-map": "^0.6.1" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-reports": { - "version": "3.1.7", - "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.1.7.tgz", - "integrity": "sha512-BewmUXImeuRk2YY0PVbxgKAysvhRPUQE0h5QRM++nVWyubKGV0l8qQ5op8+B2DOmwSe63Jivj0BjkPQVf8fP5g==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "html-escaper": "^2.0.0", - "istanbul-lib-report": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/jake": { - "version": "10.9.2", - "resolved": "https://registry.npmjs.org/jake/-/jake-10.9.2.tgz", - "integrity": "sha512-2P4SQ0HrLQ+fw6llpLnOaGAvN2Zu6778SJMrCUwns4fOoG9ayrTiZk3VV8sCPkVZF8ab0zksVpS8FDY5pRCNBA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "async": "^3.2.3", - "chalk": "^4.0.2", - "filelist": "^1.0.4", - "minimatch": "^3.1.2" - }, - "bin": { - "jake": "bin/cli.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/jake/node_modules/brace-expansion": { - "version": "1.1.21", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", - "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/jake/node_modules/minimatch": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", - "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/jest": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest/-/jest-29.7.0.tgz", - "integrity": "sha512-NIy3oAFp9shda19hy4HK0HRTWKtPJmGdnvywu01nOqNC2vZg+Z+fvJDxpMQA88eb2I9EcafcdjYgsDthnYTvGw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/core": "^29.7.0", - "@jest/types": "^29.6.3", - "import-local": "^3.0.2", - "jest-cli": "^29.7.0" - }, - "bin": { - "jest": "bin/jest.js" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" - }, - "peerDependenciesMeta": { - "node-notifier": { - "optional": true - } - } - }, - "node_modules/jest-changed-files": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-29.7.0.tgz", - "integrity": "sha512-fEArFiwf1BpQ+4bXSprcDc3/x4HSzL4al2tozwVpDFpsxALjLYdyiIK4e5Vz66GQJIbXJ82+35PtysofptNX2w==", - "dev": true, - "license": "MIT", - "dependencies": { - "execa": "^5.0.0", - "jest-util": "^29.7.0", - "p-limit": "^3.1.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-circus": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-29.7.0.tgz", - "integrity": "sha512-3E1nCMgipcTkCocFwM90XXQab9bS+GMsjdpmPrlelaxwD93Ad8iVEjX/vvHPdLPnFf+L40u+5+iutRdA1N9myw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/environment": "^29.7.0", - "@jest/expect": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "chalk": "^4.0.0", - "co": "^4.6.0", - "dedent": "^1.0.0", - "is-generator-fn": "^2.0.0", - "jest-each": "^29.7.0", - "jest-matcher-utils": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-runtime": "^29.7.0", - "jest-snapshot": "^29.7.0", - "jest-util": "^29.7.0", - "p-limit": "^3.1.0", - "pretty-format": "^29.7.0", - "pure-rand": "^6.0.0", - "slash": "^3.0.0", - "stack-utils": "^2.0.3" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-cli": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-29.7.0.tgz", - "integrity": "sha512-OVVobw2IubN/GSYsxETi+gOe7Ka59EFMR/twOU3Jb2GnKKeMGJB5SGUUrEz3SFVmJASUdZUzy83sLNNQ2gZslg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/core": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/types": "^29.6.3", - "chalk": "^4.0.0", - "create-jest": "^29.7.0", - "exit": "^0.1.2", - "import-local": "^3.0.2", - "jest-config": "^29.7.0", - "jest-util": "^29.7.0", - "jest-validate": "^29.7.0", - "yargs": "^17.3.1" - }, - "bin": { - "jest": "bin/jest.js" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" - }, - "peerDependenciesMeta": { - "node-notifier": { - "optional": true - } - } - }, - "node_modules/jest-config": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-29.7.0.tgz", - "integrity": "sha512-uXbpfeQ7R6TZBqI3/TxCU4q4ttk3u0PJeC+E0zbfSoSjq6bJ7buBPxzQPL0ifrkY4DNu4JUdk0ImlBUYi840eQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/core": "^7.11.6", - "@jest/test-sequencer": "^29.7.0", - "@jest/types": "^29.6.3", - "babel-jest": "^29.7.0", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "deepmerge": "^4.2.2", - "glob": "^7.1.3", - "graceful-fs": "^4.2.9", - "jest-circus": "^29.7.0", - "jest-environment-node": "^29.7.0", - "jest-get-type": "^29.6.3", - "jest-regex-util": "^29.6.3", - "jest-resolve": "^29.7.0", - "jest-runner": "^29.7.0", - "jest-util": "^29.7.0", - "jest-validate": "^29.7.0", - "micromatch": "^4.0.4", - "parse-json": "^5.2.0", - "pretty-format": "^29.7.0", - "slash": "^3.0.0", - "strip-json-comments": "^3.1.1" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "@types/node": "*", - "ts-node": ">=9.0.0" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - }, - "ts-node": { - "optional": true - } - } - }, - "node_modules/jest-config/node_modules/brace-expansion": { - "version": "1.1.21", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", - "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/jest-config/node_modules/glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "deprecated": "Glob versions prior to v9 are no longer supported", - "dev": true, - "license": "ISC", - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - }, - "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/jest-config/node_modules/minimatch": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", - "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/jest-diff": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.7.0.tgz", - "integrity": "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw==", - "dev": true, - "license": "MIT", - "dependencies": { - "chalk": "^4.0.0", - "diff-sequences": "^29.6.3", - "jest-get-type": "^29.6.3", - "pretty-format": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-docblock": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-29.7.0.tgz", - "integrity": "sha512-q617Auw3A612guyaFgsbFeYpNP5t2aoUNLwBUbc/0kD1R4t9ixDbyFTHd1nok4epoVFpr7PmeWHrhvuV3XaJ4g==", - "dev": true, - "license": "MIT", - "dependencies": { - "detect-newline": "^3.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-each": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-29.7.0.tgz", - "integrity": "sha512-gns+Er14+ZrEoC5fhOfYCY1LOHHr0TI+rQUHZS8Ttw2l7gl+80eHc/gFf2Ktkw0+SIACDTeWvpFcv3B04VembQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/types": "^29.6.3", - "chalk": "^4.0.0", - "jest-get-type": "^29.6.3", - "jest-util": "^29.7.0", - "pretty-format": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-environment-node": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-29.7.0.tgz", - "integrity": "sha512-DOSwCRqXirTOyheM+4d5YZOrWcdu0LNZ87ewUoywbcb2XR4wKgqiG8vNeYwhjFMbEkfju7wx2GYH0P2gevGvFw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/environment": "^29.7.0", - "@jest/fake-timers": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "jest-mock": "^29.7.0", - "jest-util": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-get-type": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.6.3.tgz", - "integrity": "sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-haste-map": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-29.7.0.tgz", - "integrity": "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/types": "^29.6.3", - "@types/graceful-fs": "^4.1.3", - "@types/node": "*", - "anymatch": "^3.0.3", - "fb-watchman": "^2.0.0", - "graceful-fs": "^4.2.9", - "jest-regex-util": "^29.6.3", - "jest-util": "^29.7.0", - "jest-worker": "^29.7.0", - "micromatch": "^4.0.4", - "walker": "^1.0.8" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "optionalDependencies": { - "fsevents": "^2.3.2" - } - }, - "node_modules/jest-leak-detector": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-29.7.0.tgz", - "integrity": "sha512-kYA8IJcSYtST2BY9I+SMC32nDpBT3J2NvWJx8+JCuCdl/CR1I4EKUJROiP8XtCcxqgTTBGJNdbB1A8XRKbTetw==", - "dev": true, - "license": "MIT", - "dependencies": { - "jest-get-type": "^29.6.3", - "pretty-format": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-matcher-utils": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.7.0.tgz", - "integrity": "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g==", - "dev": true, - "license": "MIT", - "dependencies": { - "chalk": "^4.0.0", - "jest-diff": "^29.7.0", - "jest-get-type": "^29.6.3", - "pretty-format": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-message-util": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.7.0.tgz", - "integrity": "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.12.13", - "@jest/types": "^29.6.3", - "@types/stack-utils": "^2.0.0", - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", - "micromatch": "^4.0.4", - "pretty-format": "^29.7.0", - "slash": "^3.0.0", - "stack-utils": "^2.0.3" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-mock": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-29.7.0.tgz", - "integrity": "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/types": "^29.6.3", - "@types/node": "*", - "jest-util": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-pnp-resolver": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/jest-pnp-resolver/-/jest-pnp-resolver-1.2.3.tgz", - "integrity": "sha512-+3NpwQEnRoIBtx4fyhblQDPgJI0H1IEIkX7ShLUjPGA7TtUTvI1oiKi3SR4oBR0hQhQR80l4WAe5RrXBwWMA8w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - }, - "peerDependencies": { - "jest-resolve": "*" - }, - "peerDependenciesMeta": { - "jest-resolve": { - "optional": true - } - } - }, - "node_modules/jest-regex-util": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-29.6.3.tgz", - "integrity": "sha512-KJJBsRCyyLNWCNBOvZyRDnAIfUiRJ8v+hOBQYGn8gDyF3UegwiP4gwRR3/SDa42g1YbVycTidUF3rKjyLFDWbg==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-resolve": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-29.7.0.tgz", - "integrity": "sha512-IOVhZSrg+UvVAshDSDtHyFCCBUl/Q3AAJv8iZ6ZjnZ74xzvwuzLXid9IIIPgTnY62SJjfuupMKZsZQRsCvxEgA==", - "dev": true, - "license": "MIT", - "dependencies": { - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.7.0", - "jest-pnp-resolver": "^1.2.2", - "jest-util": "^29.7.0", - "jest-validate": "^29.7.0", - "resolve": "^1.20.0", - "resolve.exports": "^2.0.0", - "slash": "^3.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-resolve-dependencies": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-29.7.0.tgz", - "integrity": "sha512-un0zD/6qxJ+S0et7WxeI3H5XSe9lTBBR7bOHCHXkKR6luG5mwDDlIzVQ0V5cZCuoTgEdcdwzTghYkTWfubi+nA==", - "dev": true, - "license": "MIT", - "dependencies": { - "jest-regex-util": "^29.6.3", - "jest-snapshot": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-runner": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-29.7.0.tgz", - "integrity": "sha512-fsc4N6cPCAahybGBfTRcq5wFR6fpLznMg47sY5aDpsoejOcVYFb07AHuSnR0liMcPTgBsA3ZJL6kFOjPdoNipQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/console": "^29.7.0", - "@jest/environment": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "chalk": "^4.0.0", - "emittery": "^0.13.1", - "graceful-fs": "^4.2.9", - "jest-docblock": "^29.7.0", - "jest-environment-node": "^29.7.0", - "jest-haste-map": "^29.7.0", - "jest-leak-detector": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-resolve": "^29.7.0", - "jest-runtime": "^29.7.0", - "jest-util": "^29.7.0", - "jest-watcher": "^29.7.0", - "jest-worker": "^29.7.0", - "p-limit": "^3.1.0", - "source-map-support": "0.5.13" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-runtime": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-29.7.0.tgz", - "integrity": "sha512-gUnLjgwdGqW7B4LvOIkbKs9WGbn+QLqRQQ9juC6HndeDiezIwhDP+mhMwHWCEcfQ5RUXa6OPnFF8BJh5xegwwQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/environment": "^29.7.0", - "@jest/fake-timers": "^29.7.0", - "@jest/globals": "^29.7.0", - "@jest/source-map": "^29.6.3", - "@jest/test-result": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "chalk": "^4.0.0", - "cjs-module-lexer": "^1.0.0", - "collect-v8-coverage": "^1.0.0", - "glob": "^7.1.3", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-mock": "^29.7.0", - "jest-regex-util": "^29.6.3", - "jest-resolve": "^29.7.0", - "jest-snapshot": "^29.7.0", - "jest-util": "^29.7.0", - "slash": "^3.0.0", - "strip-bom": "^4.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-runtime/node_modules/brace-expansion": { - "version": "1.1.21", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", - "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/jest-runtime/node_modules/glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "deprecated": "Glob versions prior to v9 are no longer supported", - "dev": true, - "license": "ISC", - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - }, - "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/jest-runtime/node_modules/minimatch": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", - "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/jest-snapshot": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-29.7.0.tgz", - "integrity": "sha512-Rm0BMWtxBcioHr1/OX5YCP8Uov4riHvKPknOGs804Zg9JGZgmIBkbtlxJC/7Z4msKYVbIJtfU+tKb8xlYNfdkw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/core": "^7.11.6", - "@babel/generator": "^7.7.2", - "@babel/plugin-syntax-jsx": "^7.7.2", - "@babel/plugin-syntax-typescript": "^7.7.2", - "@babel/types": "^7.3.3", - "@jest/expect-utils": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "babel-preset-current-node-syntax": "^1.0.0", - "chalk": "^4.0.0", - "expect": "^29.7.0", - "graceful-fs": "^4.2.9", - "jest-diff": "^29.7.0", - "jest-get-type": "^29.6.3", - "jest-matcher-utils": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-util": "^29.7.0", - "natural-compare": "^1.4.0", - "pretty-format": "^29.7.0", - "semver": "^7.5.3" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-util": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.7.0.tgz", - "integrity": "sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/types": "^29.6.3", - "@types/node": "*", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "graceful-fs": "^4.2.9", - "picomatch": "^2.2.3" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-validate": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-29.7.0.tgz", - "integrity": "sha512-ZB7wHqaRGVw/9hST/OuFUReG7M8vKeq0/J2egIGLdvjHCmYqGARhzXmtgi+gVeZ5uXFF219aOc3Ls2yLg27tkw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/types": "^29.6.3", - "camelcase": "^6.2.0", - "chalk": "^4.0.0", - "jest-get-type": "^29.6.3", - "leven": "^3.1.0", - "pretty-format": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-validate/node_modules/camelcase": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", - "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/jest-watcher": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-29.7.0.tgz", - "integrity": "sha512-49Fg7WXkU3Vl2h6LbLtMQ/HyB6rXSIX7SqvBLQmssRBGN9I0PNvPmAmCWSOY6SOvrjhI/F7/bGAv9RtnsPA03g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/test-result": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "ansi-escapes": "^4.2.1", - "chalk": "^4.0.0", - "emittery": "^0.13.1", - "jest-util": "^29.7.0", - "string-length": "^4.0.1" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-worker": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-29.7.0.tgz", - "integrity": "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*", - "jest-util": "^29.7.0", - "merge-stream": "^2.0.0", - "supports-color": "^8.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-worker/node_modules/supports-color": { - "version": "8.1.1", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", - "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/supports-color?sponsor=1" - } - }, - "node_modules/js-tokens": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/js-yaml": { - "version": "3.15.2", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.2.tgz", - "integrity": "sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==", - "dev": true, - "license": "MIT", - "dependencies": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" - }, - "bin": { - "js-yaml": "bin/js-yaml.js" - } - }, - "node_modules/jsesc": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", - "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", - "dev": true, - "license": "MIT", - "bin": { - "jsesc": "bin/jsesc" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/json-parse-even-better-errors": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", - "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", - "dev": true, - "license": "MIT" - }, - "node_modules/json-schema-ref-resolver": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/json-schema-ref-resolver/-/json-schema-ref-resolver-3.0.0.tgz", - "integrity": "sha512-hOrZIVL5jyYFjzk7+y7n5JDzGlU8rfWDuYyHwGa2WA8/pcmMHezp2xsVwxrebD/Q9t8Nc5DboieySDpCp4WG4A==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "MIT", - "dependencies": { - "dequal": "^2.0.3" - } - }, - "node_modules/json-schema-resolver": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/json-schema-resolver/-/json-schema-resolver-2.0.0.tgz", - "integrity": "sha512-pJ4XLQP4Q9HTxl6RVDLJ8Cyh1uitSs0CzDBAz1uoJ4sRD/Bk7cFSXL1FUXDW3zJ7YnfliJx6eu8Jn283bpZ4Yg==", - "license": "MIT", - "dependencies": { - "debug": "^4.1.1", - "rfdc": "^1.1.4", - "uri-js": "^4.2.2" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/Eomm/json-schema-resolver?sponsor=1" - } - }, - "node_modules/json-schema-traverse": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", - "license": "MIT" - }, - "node_modules/json5": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", - "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", - "dev": true, - "license": "MIT", - "bin": { - "json5": "lib/cli.js" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/kleur": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", - "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/leven": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", - "integrity": "sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/light-my-request": { - "version": "6.6.0", - "resolved": "https://registry.npmjs.org/light-my-request/-/light-my-request-6.6.0.tgz", - "integrity": "sha512-CHYbu8RtboSIoVsHZ6Ye4cj4Aw/yg2oAFimlF7mNvfDV192LR7nDiKtSIfCuLT7KokPSTn/9kfVLm5OGN0A28A==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "BSD-3-Clause", - "dependencies": { - "cookie": "^1.0.1", - "process-warning": "^4.0.0", - "set-cookie-parser": "^2.6.0" - } - }, - "node_modules/light-my-request/node_modules/process-warning": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-4.0.1.tgz", - "integrity": "sha512-3c2LzQ3rY9d0hc1emcsHhfT9Jwz0cChib/QN89oME2R451w5fy3f0afAhERFZAwrbDU43wk12d0ORBpDVME50Q==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "MIT" - }, - "node_modules/lines-and-columns": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", - "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", - "dev": true, - "license": "MIT" - }, - "node_modules/locate-path": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-locate": "^4.1.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/lodash.memoize": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", - "integrity": "sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag==", - "dev": true, - "license": "MIT" - }, - "node_modules/lru-cache": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", - "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^3.0.2" - } - }, - "node_modules/make-dir": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", - "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", - "dev": true, - "license": "MIT", - "dependencies": { - "semver": "^7.5.3" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/make-error": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", - "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", - "dev": true, - "license": "ISC" - }, - "node_modules/makeerror": { - "version": "1.0.12", - "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz", - "integrity": "sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "tmpl": "1.0.5" - } - }, - "node_modules/merge-stream": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", - "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", - "dev": true, - "license": "MIT" - }, - "node_modules/micromatch": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", - "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", - "dev": true, - "license": "MIT", - "dependencies": { - "braces": "^3.0.3", - "picomatch": "^2.3.1" - }, - "engines": { - "node": ">=8.6" - } - }, - "node_modules/mime": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz", - "integrity": "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==", - "license": "MIT", - "bin": { - "mime": "cli.js" - }, - "engines": { - "node": ">=10.0.0" - } - }, - "node_modules/mimic-fn": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", - "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/minimatch": { - "version": "5.1.9", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.9.tgz", - "integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^2.0.1" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/minipass": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", - "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, - "node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "license": "MIT" - }, - "node_modules/natural-compare": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", - "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", - "dev": true, - "license": "MIT" - }, - "node_modules/node-int64": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", - "integrity": "sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==", - "dev": true, - "license": "MIT" - }, - "node_modules/node-releases": { - "version": "2.0.55", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.55.tgz", - "integrity": "sha512-mIrE/Cw9y+9Au6dS5vDKDhQza9YvG6w+ZrS6X+ZzA7yFW/soAeaups4Qzn1bL6g5FVy8WtP79+0j82oPIbqRjQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - } - }, - "node_modules/normalize-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", - "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/npm-run-path": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", - "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", - "dev": true, - "license": "MIT", - "dependencies": { - "path-key": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/on-exit-leak-free": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz", - "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==", - "license": "MIT", - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "dev": true, - "license": "ISC", - "dependencies": { - "wrappy": "1" - } - }, - "node_modules/onetime": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", - "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", - "dev": true, - "license": "MIT", - "dependencies": { - "mimic-fn": "^2.1.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/openapi-types": { - "version": "12.1.3", - "resolved": "https://registry.npmjs.org/openapi-types/-/openapi-types-12.1.3.tgz", - "integrity": "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw==", - "license": "MIT" - }, - "node_modules/p-limit": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", - "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "yocto-queue": "^0.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-locate": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-limit": "^2.2.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/p-locate/node_modules/p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-try": "^2.0.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-try": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", - "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/parse-json": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", - "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.0.0", - "error-ex": "^1.3.1", - "json-parse-even-better-errors": "^2.3.0", - "lines-and-columns": "^1.1.6" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/path-exists": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/path-key": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/path-parse": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", - "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", - "dev": true, - "license": "MIT" - }, - "node_modules/path-scurry": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", - "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", - "license": "BlueOak-1.0.0", - "dependencies": { - "lru-cache": "^11.0.0", - "minipass": "^7.1.2" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/path-scurry/node_modules/lru-cache": { - "version": "11.5.2", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz", - "integrity": "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==", - "license": "BlueOak-1.0.0", - "engines": { - "node": "20 || >=22" - } - }, - "node_modules/picocolors": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", - "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", - "dev": true, - "license": "ISC" - }, - "node_modules/picomatch": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", - "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/pino": { - "version": "10.3.1", - "resolved": "https://registry.npmjs.org/pino/-/pino-10.3.1.tgz", - "integrity": "sha512-r34yH/GlQpKZbU1BvFFqOjhISRo1MNx1tWYsYvmj6KIRHSPMT2+yHOEb1SG6NMvRoHRF0a07kCOox/9yakl1vg==", - "license": "MIT", - "dependencies": { - "@pinojs/redact": "^0.4.0", - "atomic-sleep": "^1.0.0", - "on-exit-leak-free": "^2.1.0", - "pino-abstract-transport": "^3.0.0", - "pino-std-serializers": "^7.0.0", - "process-warning": "^5.0.0", - "quick-format-unescaped": "^4.0.3", - "real-require": "^0.2.0", - "safe-stable-stringify": "^2.3.1", - "sonic-boom": "^4.0.1", - "thread-stream": "^4.0.0" - }, - "bin": { - "pino": "bin.js" - } - }, - "node_modules/pino-abstract-transport": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-3.0.0.tgz", - "integrity": "sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg==", - "license": "MIT", - "dependencies": { - "split2": "^4.0.0" - } - }, - "node_modules/pino-std-serializers": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.1.0.tgz", - "integrity": "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==", - "license": "MIT" - }, - "node_modules/pirates": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.6.tgz", - "integrity": "sha512-saLsH7WeYYPiD25LDuLRRY/i+6HaPYr6G1OUlN39otzkSTxKnubR9RTxS3/Kk50s1g2JTgFwWQDQyplC5/SHZg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 6" - } - }, - "node_modules/pkg-dir": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", - "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "find-up": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/pretty-format": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", - "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/schemas": "^29.6.3", - "ansi-styles": "^5.0.0", - "react-is": "^18.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/pretty-format/node_modules/ansi-styles": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", - "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/process-warning": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.1.0.tgz", - "integrity": "sha512-jQSaVHsPgtyw60e1rQ/A+/ArPEj/S8pS/vFnyGa/gYFXrKk/6RuDkoqVDQ5NI5MmS01698ltlAk0NoDBNLujRw==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "MIT" - }, - "node_modules/prompts": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", - "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "kleur": "^3.0.3", - "sisteransi": "^1.0.5" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/punycode": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", - "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/pure-rand": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.1.0.tgz", - "integrity": "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==", - "dev": true, - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/dubzzz" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fast-check" - } - ], - "license": "MIT" - }, - "node_modules/quick-format-unescaped": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz", - "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==", - "license": "MIT" - }, - "node_modules/react-is": { - "version": "18.3.1", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", - "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", - "dev": true, - "license": "MIT" - }, - "node_modules/real-require": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz", - "integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==", - "license": "MIT", - "engines": { - "node": ">= 12.13.0" - } - }, - "node_modules/require-directory": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", - "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/require-from-string": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", - "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/resolve": { - "version": "1.22.10", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.10.tgz", - "integrity": "sha512-NPRy+/ncIMeDlTAsuqwKIiferiawhefFJtkNSW0qZJEqMEb+qBt/77B/jGeeek+F0uOeN05CDa6HXbbIgtVX4w==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-core-module": "^2.16.0", - "path-parse": "^1.0.7", - "supports-preserve-symlinks-flag": "^1.0.0" - }, - "bin": { - "resolve": "bin/resolve" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/resolve-cwd": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", - "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", - "dev": true, - "license": "MIT", - "dependencies": { - "resolve-from": "^5.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/resolve-from": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", - "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/resolve.exports": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-2.0.3.tgz", - "integrity": "sha512-OcXjMsGdhL4XnbShKpAcSqPMzQoYkYyhbEaeSko47MjRP9NfEQMhZkXL1DoFlt9LWQn4YttrdnV6X2OiyzBi+A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - } - }, - "node_modules/ret": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/ret/-/ret-0.5.0.tgz", - "integrity": "sha512-I1XxrZSQ+oErkRR4jYbAyEEu2I0avBvvMM5JN+6EBprOGRCs63ENqZ3vjavq8fBw2+62G5LF5XelKwuJpcvcxw==", - "license": "MIT", - "engines": { - "node": ">=10" - } - }, - "node_modules/reusify": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", - "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", - "license": "MIT", - "engines": { - "iojs": ">=1.0.0", - "node": ">=0.10.0" - } - }, - "node_modules/rfdc": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz", - "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", - "license": "MIT" - }, - "node_modules/safe-regex2": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/safe-regex2/-/safe-regex2-5.1.1.tgz", - "integrity": "sha512-mOSBvHGDZMuIEZMdOz/aCEYDCv0E7nfcNsIhUF+/P+xC7Hyf3FkvymqgPbg9D1EdSGu+uKbJgy09K/RKKc7kJA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "MIT", - "dependencies": { - "ret": "~0.5.0" - }, - "bin": { - "safe-regex2": "bin/safe-regex2.js" - } - }, - "node_modules/safe-stable-stringify": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz", - "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==", - "license": "MIT", - "engines": { - "node": ">=10" - } - }, - "node_modules/secure-json-parse": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-4.1.0.tgz", - "integrity": "sha512-l4KnYfEyqYJxDwlNVyRfO2E4NTHfMKAWdUuA8J0yve2Dz/E/PdBepY03RvyJpssIpRFwJoCD55wA+mEDs6ByWA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "BSD-3-Clause" - }, - "node_modules/semver": { - "version": "7.6.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", - "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/set-cookie-parser": { - "version": "2.7.2", - "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz", - "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==", - "license": "MIT" - }, - "node_modules/setprototypeof": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", - "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", - "license": "ISC" - }, - "node_modules/shebang-command": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "dev": true, - "license": "MIT", - "dependencies": { - "shebang-regex": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/shebang-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/signal-exit": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", - "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/sisteransi": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", - "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", - "dev": true, - "license": "MIT" - }, - "node_modules/slash": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", - "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/sonic-boom": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz", - "integrity": "sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==", - "license": "MIT", - "dependencies": { - "atomic-sleep": "^1.0.0" - } - }, - "node_modules/source-map": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/source-map-support": { - "version": "0.5.13", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.13.tgz", - "integrity": "sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w==", - "dev": true, - "license": "MIT", - "dependencies": { - "buffer-from": "^1.0.0", - "source-map": "^0.6.0" - } - }, - "node_modules/split2": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", - "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", - "license": "ISC", - "engines": { - "node": ">= 10.x" - } - }, - "node_modules/sprintf-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", - "dev": true, - "license": "BSD-3-Clause" - }, - "node_modules/stack-utils": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", - "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "escape-string-regexp": "^2.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/statuses": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", - "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/string-length": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", - "integrity": "sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "char-regex": "^1.0.2", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "license": "MIT", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-bom": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", - "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-final-newline": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", - "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/strip-json-comments": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", - "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/supports-color": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "dev": true, - "license": "MIT", - "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/supports-preserve-symlinks-flag": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", - "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/test-exclude": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", - "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", - "dev": true, - "license": "ISC", - "dependencies": { - "@istanbuljs/schema": "^0.1.2", - "glob": "^7.1.4", - "minimatch": "^3.0.4" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/test-exclude/node_modules/brace-expansion": { - "version": "1.1.21", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", - "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/test-exclude/node_modules/glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "deprecated": "Glob versions prior to v9 are no longer supported", - "dev": true, - "license": "ISC", - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - }, - "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/test-exclude/node_modules/minimatch": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", - "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/thread-stream": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-4.2.0.tgz", - "integrity": "sha512-e2zZ96wSChazBsbENf/Pcm/4swHt2cEKQ92rhUjkL9GCKiTDJIaTBenjE/m9DXi0QBmTMDkFDdOomUy20A1tDQ==", - "license": "MIT", - "dependencies": { - "real-require": "^1.0.0" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/thread-stream/node_modules/real-require": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/real-require/-/real-require-1.0.0.tgz", - "integrity": "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==", - "license": "MIT" - }, - "node_modules/tmpl": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz", - "integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==", - "dev": true, - "license": "BSD-3-Clause" - }, - "node_modules/to-regex-range": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", - "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-number": "^7.0.0" - }, - "engines": { - "node": ">=8.0" - } - }, - "node_modules/toad-cache": { - "version": "3.7.0", - "resolved": "https://registry.npmjs.org/toad-cache/-/toad-cache-3.7.0.tgz", - "integrity": "sha512-/m8M+2BJUpoJdgAHoG+baCwBT+tf2VraSfkBgl0Y00qIWt41DJ8R5B8nsEw0I58YwF5IZH6z24/2TobDKnqSWw==", - "license": "MIT", - "engines": { - "node": ">=12" - } - }, - "node_modules/toidentifier": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", - "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", - "license": "MIT", - "engines": { - "node": ">=0.6" - } - }, - "node_modules/ts-jest": { - "version": "29.2.5", - "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.2.5.tgz", - "integrity": "sha512-KD8zB2aAZrcKIdGk4OwpJggeLcH1FgrICqDSROWqlnJXGCXK4Mn6FcdK2B6670Xr73lHMG1kHw8R87A0ecZ+vA==", - "dev": true, - "license": "MIT", - "dependencies": { - "bs-logger": "^0.2.6", - "ejs": "^3.1.10", - "fast-json-stable-stringify": "^2.1.0", - "jest-util": "^29.0.0", - "json5": "^2.2.3", - "lodash.memoize": "^4.1.2", - "make-error": "^1.3.6", - "semver": "^7.6.3", - "yargs-parser": "^21.1.1" - }, - "bin": { - "ts-jest": "cli.js" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || ^18.0.0 || >=20.0.0" - }, - "peerDependencies": { - "@babel/core": ">=7.0.0-beta.0 <8", - "@jest/transform": "^29.0.0", - "@jest/types": "^29.0.0", - "babel-jest": "^29.0.0", - "jest": "^29.0.0", - "typescript": ">=4.3 <6" - }, - "peerDependenciesMeta": { - "@babel/core": { - "optional": true - }, - "@jest/transform": { - "optional": true - }, - "@jest/types": { - "optional": true - }, - "babel-jest": { - "optional": true - }, - "esbuild": { - "optional": true - } - } - }, - "node_modules/ts-node": { - "version": "10.9.2", - "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz", - "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspotcode/source-map-support": "^0.8.0", - "@tsconfig/node10": "^1.0.7", - "@tsconfig/node12": "^1.0.7", - "@tsconfig/node14": "^1.0.0", - "@tsconfig/node16": "^1.0.2", - "acorn": "^8.4.1", - "acorn-walk": "^8.1.1", - "arg": "^4.1.0", - "create-require": "^1.1.0", - "diff": "^4.0.1", - "make-error": "^1.1.1", - "v8-compile-cache-lib": "^3.0.1", - "yn": "3.1.1" - }, - "bin": { - "ts-node": "dist/bin.js", - "ts-node-cwd": "dist/bin-cwd.js", - "ts-node-esm": "dist/bin-esm.js", - "ts-node-script": "dist/bin-script.js", - "ts-node-transpile-only": "dist/bin-transpile.js", - "ts-script": "dist/bin-script-deprecated.js" - }, - "peerDependencies": { - "@swc/core": ">=1.2.50", - "@swc/wasm": ">=1.2.50", - "@types/node": "*", - "typescript": ">=2.7" - }, - "peerDependenciesMeta": { - "@swc/core": { - "optional": true - }, - "@swc/wasm": { - "optional": true - } - } - }, - "node_modules/tslib": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz", - "integrity": "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==", - "license": "0BSD" - }, - "node_modules/type-detect": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", - "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/type-fest": { - "version": "0.21.3", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", - "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", - "dev": true, - "license": "(MIT OR CC0-1.0)", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/typescript": { - "version": "5.7.2", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.2.tgz", - "integrity": "sha512-i5t66RHxDvVN40HfDd1PsEThGNnlMCMT3jMUuoh9/0TaqWevNontacunWyN02LA9/fIbEWlcHZcgTKb9QoaLfg==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - }, - "node_modules/undici-types": { - "version": "6.19.8", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", - "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==", - "license": "MIT" - }, - "node_modules/update-browserslist-db": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.3.tgz", - "integrity": "sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "escalade": "^3.2.0", - "picocolors": "^1.1.1" - }, - "bin": { - "update-browserslist-db": "cli.js" - }, - "peerDependencies": { - "browserslist": ">= 4.21.0" - } - }, - "node_modules/uri-js": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", - "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", - "license": "BSD-2-Clause", - "dependencies": { - "punycode": "^2.1.0" - } - }, - "node_modules/v8-compile-cache-lib": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", - "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==", - "dev": true, - "license": "MIT" - }, - "node_modules/v8-to-istanbul": { - "version": "9.3.0", - "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.3.0.tgz", - "integrity": "sha512-kiGUalWN+rgBJ/1OHZsBtU4rXZOfj/7rKQxULKlIzwzQSvMJUUNgPwJEEh7gU6xEVxC0ahoOBvN2YI8GH6FNgA==", - "dev": true, - "license": "ISC", - "dependencies": { - "@jridgewell/trace-mapping": "^0.3.12", - "@types/istanbul-lib-coverage": "^2.0.1", - "convert-source-map": "^2.0.0" - }, - "engines": { - "node": ">=10.12.0" - } - }, - "node_modules/walker": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.8.tgz", - "integrity": "sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "makeerror": "1.0.12" - } - }, - "node_modules/which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, - "license": "ISC", - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/node-which" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/wrap-ansi": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/write-file-atomic": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-4.0.2.tgz", - "integrity": "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==", - "dev": true, - "license": "ISC", - "dependencies": { - "imurmurhash": "^0.1.4", - "signal-exit": "^3.0.7" - }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" - } - }, - "node_modules/ws": { - "version": "8.21.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", - "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", - "license": "MIT", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - }, - "node_modules/y18n": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", - "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", - "license": "ISC", - "engines": { - "node": ">=10" - } - }, - "node_modules/yallist": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", - "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", - "dev": true, - "license": "ISC" - }, - "node_modules/yaml": { - "version": "2.9.0", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz", - "integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==", - "license": "ISC", - "bin": { - "yaml": "bin.mjs" - }, - "engines": { - "node": ">= 14.6" - }, - "funding": { - "url": "https://github.com/sponsors/eemeli" - } - }, - "node_modules/yargs": { - "version": "17.7.2", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", - "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", - "license": "MIT", - "dependencies": { - "cliui": "^8.0.1", - "escalade": "^3.1.1", - "get-caller-file": "^2.0.5", - "require-directory": "^2.1.1", - "string-width": "^4.2.3", - "y18n": "^5.0.5", - "yargs-parser": "^21.1.1" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/yargs-parser": { - "version": "21.1.1", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", - "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", - "license": "ISC", - "engines": { - "node": ">=12" - } - }, - "node_modules/yn": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", - "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/yocto-queue": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", - "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - } - } -} diff --git a/dstack/kms/auth-eth/package.json b/dstack/kms/auth-eth/package.json index c2e25c2bbd..1d11d9ba77 100644 --- a/dstack/kms/auth-eth/package.json +++ b/dstack/kms/auth-eth/package.json @@ -1,36 +1,35 @@ { "name": "auth-eth", "version": "1.0.0", - "description": "dstack KMS Ethereum Backend", - "main": "dist/main.js", + "description": "dstack KMS ethereum backend with bun + hono + zod", + "main": "index.ts", "scripts": { - "build": "tsc", - "start": "node dist/main.js", - "dev": "ts-node src/main.ts", - "test": "jest", - "test:watch": "jest --watch", - "test:coverage": "jest --coverage", - "test:foundry": "forge test --ffi", - "test:foundry:all": "forge clean && forge build && forge test --ffi", - "test:setup": "./scripts/setup-local-chain.sh", - "test:run": "./scripts/run-tests.sh", - "test:all": "./scripts/test-all.sh", - "test:cleanup": "./scripts/cleanup.sh" + "dev": "bun run --watch index.ts", + "start": "bun run index.ts", + "build": "bun build index.ts --outdir ./dist --target bun", + "test": "vitest", + "test:run": "vitest run", + "lint": "oxlint .", + "lint:fix": "oxlint --fix .", + "fmt": "oxlint --fix .", + "check": "bun run lint && bun run test:run" }, "dependencies": { - "@fastify/swagger": "^8.12.0", - "@fastify/swagger-ui": "^6.1.1", - "dotenv": "^16.3.1", - "ethers": "^6.17.0", - "fastify": "^5.12.5", - "yargs": "^17.7.2" + "@hono/zod-validator": "0.9.1", + "hono": "4.13.16", + "viem": "2.57.5", + "zod": "4.6.7" }, "devDependencies": { - "@types/jest": "^29.5.14", - "@types/node": "^20.17.12", - "jest": "^29.7.0", - "ts-jest": "^29.1.1", - "ts-node": "^10.9.1", - "typescript": "^5.3.3" + "@types/bun": "1.4.2", + "@types/node": "24.19.2", + "oxlint": "1.88.0", + "typescript": "5.9.3", + "vite": "8.3.3", + "vitest": "5.0.4" + }, + "type": "module", + "overrides": { + "source-map-js": "1.2.2" } } diff --git a/dstack/kms/auth-eth/run-tests.sh b/dstack/kms/auth-eth/run-tests.sh deleted file mode 100644 index e8dd6ea0fc..0000000000 --- a/dstack/kms/auth-eth/run-tests.sh +++ /dev/null @@ -1,5 +0,0 @@ -# SPDX-FileCopyrightText: © 2025 Phala Network -# -# SPDX-License-Identifier: Apache-2.0 - -npm run test diff --git a/dstack/kms/auth-eth/script/Manage.s.sol b/dstack/kms/auth-eth/script/Manage.s.sol index 110612b7e5..75e64be378 100644 --- a/dstack/kms/auth-eth/script/Manage.s.sol +++ b/dstack/kms/auth-eth/script/Manage.s.sol @@ -9,6 +9,16 @@ pragma solidity ^0.8.24; import "forge-std/Script.sol"; import "../contracts/DstackKms.sol"; import "../contracts/DstackApp.sol"; +import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; + +// The epoch-less setters of app policies predating app epochs (v0.5.x, +// v0.6.0), which report IAppAuthBasicManagement instead of IAppEpochManagement. +interface ILegacyAppManagement { + function addComposeHash(bytes32 composeHash) external; + function removeComposeHash(bytes32 composeHash) external; + function addDevice(bytes32 deviceId) external; + function removeDevice(bytes32 deviceId) external; +} // Base contract with common functionality abstract contract BaseScript is Script { @@ -25,6 +35,56 @@ abstract contract BaseScript is Script { app = DstackApp(appAddr); } } + + // The rows a policy change applies to: `single` names one epoch, `from` and + // `to` a range. There is no default, so a change never misses a row + // silently. + function epochRange( + string memory single, + string memory from, + string memory to + ) + internal + view + returns (uint256, uint256) + { + if (vm.envExists(single)) { + uint256 epoch = vm.envUint(single); + return (epoch, epoch); + } + require(vm.envExists(from) && vm.envExists(to), string.concat("set ", single, ", or ", from, " and ", to)); + return (vm.envUint(from), vm.envUint(to)); + } + + // TEE_VARIANTS: `any`, or the comma-separated platform names, as the KMS + // reports them, that alone are allowed. + function teeVariants() internal view returns (bool any, string[] memory names) { + names = vm.envString("TEE_VARIANTS", ","); + require(names.length > 0 && bytes(names[0]).length > 0, "set TEE_VARIANTS to any or platform names"); + any = names.length == 1 && keccak256(bytes(names[0])) == keccak256("any"); + } + + function rootEpochs() internal view returns (uint256, uint256) { + return epochRange("ROOT_EPOCH", "FROM_ROOT_EPOCH", "TO_ROOT_EPOCH"); + } + + function appEpochs() internal view returns (uint256, uint256) { + return epochRange("APP_EPOCH", "FROM_APP_EPOCH", "TO_APP_EPOCH"); + } + + // The legacy setters of an app without IAppEpochManagement, or none. Such + // an app has only app epoch 0, so only APP_EPOCH=0, or no epoch, applies. + function legacyApp() internal view returns (ILegacyAppManagement legacy) { + require(address(app) != address(0), "APP_CONTRACT_ADDR not set"); + if (ERC165Checker.supportsInterface(address(app), type(IAppEpochManagement).interfaceId)) { + return ILegacyAppManagement(address(0)); + } + require( + !vm.envExists("FROM_APP_EPOCH") && !vm.envExists("TO_APP_EPOCH") && vm.envOr("APP_EPOCH", uint256(0)) == 0, + "this app predates app epochs: only APP_EPOCH=0 applies" + ); + return ILegacyAppManagement(address(app)); + } } // KMS Management Scripts @@ -32,8 +92,9 @@ contract AddKmsAggregatedMr is BaseScript { function run() external { bytes32 mrAggregated = vm.envBytes32("MR_AGGREGATED"); + (uint256 from, uint256 to) = rootEpochs(); vm.startBroadcast(vm.envUint("PRIVATE_KEY")); - kms.addKmsAggregatedMr(mrAggregated); + kms.addKmsAggregatedMrAtEpochs(from, to, mrAggregated); vm.stopBroadcast(); console.log("Added KMS aggregated MR:", vm.toString(mrAggregated)); @@ -44,8 +105,9 @@ contract RemoveKmsAggregatedMr is BaseScript { function run() external { bytes32 mrAggregated = vm.envBytes32("MR_AGGREGATED"); + (uint256 from, uint256 to) = rootEpochs(); vm.startBroadcast(vm.envUint("PRIVATE_KEY")); - kms.removeKmsAggregatedMr(mrAggregated); + kms.removeKmsAggregatedMrAtEpochs(from, to, mrAggregated); vm.stopBroadcast(); console.log("Removed KMS aggregated MR:", vm.toString(mrAggregated)); @@ -56,8 +118,9 @@ contract AddOsImage is BaseScript { function run() external { bytes32 imageHash = vm.envBytes32("OS_IMAGE_HASH"); + (uint256 from, uint256 to) = rootEpochs(); vm.startBroadcast(vm.envUint("PRIVATE_KEY")); - kms.addOsImageHash(imageHash); + kms.addOsImageHashAtEpochs(from, to, imageHash); vm.stopBroadcast(); console.log("Added OS image hash:", vm.toString(imageHash)); @@ -68,14 +131,70 @@ contract AddKmsDevice is BaseScript { function run() external { bytes32 deviceId = vm.envBytes32("DEVICE_ID"); + (uint256 from, uint256 to) = rootEpochs(); vm.startBroadcast(vm.envUint("PRIVATE_KEY")); - kms.addKmsDevice(deviceId); + kms.addKmsDeviceAtEpochs(from, to, deviceId); vm.stopBroadcast(); console.log("Added KMS device:", vm.toString(deviceId)); } } +contract SetKmsTeeVariants is BaseScript { + function run() external { + (bool any, string[] memory names) = teeVariants(); + + vm.startBroadcast(vm.envUint("PRIVATE_KEY")); + // Write the list before restricting, so the restriction never applies to a stale one. + if (!any) kms.setAllowedTeeVariants(names); + kms.setAllowAnyTeeVariant(any); + vm.stopBroadcast(); + + console.log("Set KMS TEE variants to:", vm.envString("TEE_VARIANTS")); + } +} + +contract RequireKmsLaunchTicket is BaseScript { + function run() external { + bool required = vm.envBool("REQUIRE_LAUNCH_TICKET"); + vm.broadcast(vm.envUint("PRIVATE_KEY")); + kms.setRequireKmsLaunchTicket(required); + console.log("Set requireKmsLaunchTicket to:", required); + } +} + +contract AddKmsLaunchTicket is BaseScript { + function run() external { + bytes32 ticketHash = vm.envBytes32("LAUNCH_TICKET_HASH"); + vm.broadcast(vm.envUint("PRIVATE_KEY")); + kms.addKmsLaunchTicket(ticketHash, vm.envString("LAUNCH_TICKET_LABEL")); + console.log("Added KMS launch ticket:", vm.toString(ticketHash)); + } +} + +contract RemoveKmsLaunchTicket is BaseScript { + function run() external { + bytes32 ticketHash = vm.envBytes32("LAUNCH_TICKET_HASH"); + vm.broadcast(vm.envUint("PRIVATE_KEY")); + kms.removeKmsLaunchTicket(ticketHash); + console.log("Removed KMS launch ticket:", vm.toString(ticketHash)); + } +} + +contract SetSevSnpTcbRequirements is BaseScript { + function run() external { + string memory requirements = vm.envString("SEV_SNP_TCB_REQUIREMENTS"); + // Reject malformed JSON: the KMS refuses every SEV-SNP request while it cannot parse the list. + if (bytes(requirements).length != 0) vm.parseJson(requirements); + + vm.startBroadcast(vm.envUint("PRIVATE_KEY")); + kms.setSevSnpTcbRequirements(requirements); + vm.stopBroadcast(); + + console.log("Set SEV-SNP TCB requirements:", requirements); + } +} + contract SetGatewayAppId is BaseScript { function run() external { string memory gatewayId = vm.envString("GATEWAY_APP_ID"); @@ -88,36 +207,73 @@ contract SetGatewayAppId is BaseScript { } } -contract SetKmsInfo is BaseScript { +contract RegisterRootEpoch is BaseScript { function run() external { - bytes memory k256Pubkey = vm.envBytes("K256_PUBKEY"); bytes memory caPubkey = vm.envBytes("CA_PUBKEY"); - bytes memory quote = vm.envBytes("QUOTE"); - bytes memory eventlog = vm.envBytes("EVENTLOG"); + bytes memory k256Pubkey = vm.envBytes("K256_PUBKEY"); + string memory evidenceUrl = vm.envString("EVIDENCE_URL"); vm.startBroadcast(vm.envUint("PRIVATE_KEY")); - kms.setKmsInfo( - DstackKms.KmsInfo({ k256Pubkey: k256Pubkey, caPubkey: caPubkey, quote: quote, eventlog: eventlog }) - ); + uint256 epoch = kms.registerRootEpoch(caPubkey, k256Pubkey, evidenceUrl); vm.stopBroadcast(); - console.log("KMS info set successfully"); - console.log(" K256 Pubkey length:", k256Pubkey.length); - console.log(" CA Pubkey length:", caPubkey.length); - console.log(" Quote length:", quote.length); - console.log(" Eventlog length:", eventlog.length); + console.log("Registered KMS root epoch", epoch); + } +} + +contract ActivateRootEpoch is BaseScript { + function run() external { + uint256 epoch = vm.envUint("ROOT_EPOCH"); + bytes32 chainHash = vm.envBytes32("CHAIN_HASH"); + + vm.startBroadcast(vm.envUint("PRIVATE_KEY")); + kms.activateRootEpoch(epoch, chainHash); + vm.stopBroadcast(); + + console.log("Activated KMS root epoch", epoch); + } +} + +contract SetRootEpochEvidenceUrl is BaseScript { + function run() external { + uint256 epoch = vm.envUint("ROOT_EPOCH"); + string memory evidenceUrl = vm.envString("EVIDENCE_URL"); + + vm.startBroadcast(vm.envUint("PRIVATE_KEY")); + kms.setRootEpochEvidenceUrl(epoch, evidenceUrl); + vm.stopBroadcast(); + + console.log("Updated the evidence URL of KMS root epoch", epoch); + } +} + +contract PopRootEpoch is BaseScript { + function run() external { + uint256 epoch = vm.envUint("ROOT_EPOCH"); + bytes32 chainHash = vm.envBytes32("CHAIN_HASH"); + + vm.startBroadcast(vm.envUint("PRIVATE_KEY")); + kms.popRootEpoch(epoch, chainHash); + vm.stopBroadcast(); + + console.log("Popped pending KMS root epoch", epoch); } } // App Management Scripts contract AddComposeHash is BaseScript { function run() external { - require(address(app) != address(0), "APP_CONTRACT_ADDR not set"); bytes32 composeHash = vm.envBytes32("COMPOSE_HASH"); - vm.startBroadcast(vm.envUint("PRIVATE_KEY")); - app.addComposeHash(composeHash); - vm.stopBroadcast(); + ILegacyAppManagement legacy = legacyApp(); + if (address(legacy) != address(0)) { + vm.broadcast(vm.envUint("PRIVATE_KEY")); + legacy.addComposeHash(composeHash); + } else { + (uint256 from, uint256 to) = appEpochs(); + vm.broadcast(vm.envUint("PRIVATE_KEY")); + app.addComposeHashAtEpochs(from, to, composeHash); + } console.log("Added compose hash:", vm.toString(composeHash)); } @@ -125,12 +281,17 @@ contract AddComposeHash is BaseScript { contract AddDevice is BaseScript { function run() external { - require(address(app) != address(0), "APP_CONTRACT_ADDR not set"); bytes32 deviceId = vm.envBytes32("DEVICE_ID"); - vm.startBroadcast(vm.envUint("PRIVATE_KEY")); - app.addDevice(deviceId); - vm.stopBroadcast(); + ILegacyAppManagement legacy = legacyApp(); + if (address(legacy) != address(0)) { + vm.broadcast(vm.envUint("PRIVATE_KEY")); + legacy.addDevice(deviceId); + } else { + (uint256 from, uint256 to) = appEpochs(); + vm.broadcast(vm.envUint("PRIVATE_KEY")); + app.addDeviceAtEpochs(from, to, deviceId); + } console.log("Added device:", vm.toString(deviceId)); } @@ -138,17 +299,66 @@ contract AddDevice is BaseScript { contract SetAllowAnyDevice is BaseScript { function run() external { - require(address(app) != address(0), "APP_CONTRACT_ADDR not set"); bool allow = vm.envBool("ALLOW_ANY_DEVICE"); + require(address(app) != address(0), "APP_CONTRACT_ADDR not set"); + require( + !vm.envExists("APP_EPOCH") && !vm.envExists("FROM_APP_EPOCH") && !vm.envExists("TO_APP_EPOCH"), + "allowAnyDevice covers every app epoch: unset APP_EPOCH, FROM_APP_EPOCH and TO_APP_EPOCH" + ); - vm.startBroadcast(vm.envUint("PRIVATE_KEY")); + // Apps with and without app epochs share this setter. + vm.broadcast(vm.envUint("PRIVATE_KEY")); app.setAllowAnyDevice(allow); - vm.stopBroadcast(); console.log("Set allowAnyDevice to:", allow); } } +contract SetTeeVariants is BaseScript { + function run() external { + (bool any, string[] memory names) = teeVariants(); + require(address(legacyApp()) == address(0), "this app predates TEE variant policies"); + + vm.startBroadcast(vm.envUint("PRIVATE_KEY")); + // Write the list before restricting, so the restriction never applies to a stale one. + if (!any) app.setAllowedTeeVariants(names); + app.setAllowAnyTeeVariant(any); + vm.stopBroadcast(); + + console.log("Set TEE variants to:", vm.envString("TEE_VARIANTS")); + } +} + +contract RequireLaunchTicket is BaseScript { + function run() external { + bool required = vm.envBool("REQUIRE_LAUNCH_TICKET"); + require(address(app) != address(0), "APP_CONTRACT_ADDR not set"); + vm.broadcast(vm.envUint("PRIVATE_KEY")); + app.setRequireLaunchTicket(required); + console.log("Set requireLaunchTicket to:", required); + } +} + +contract AddLaunchTicket is BaseScript { + function run() external { + bytes32 ticketHash = vm.envBytes32("LAUNCH_TICKET_HASH"); + require(address(app) != address(0), "APP_CONTRACT_ADDR not set"); + vm.broadcast(vm.envUint("PRIVATE_KEY")); + app.addLaunchTicket(ticketHash, vm.envString("LAUNCH_TICKET_LABEL")); + console.log("Added launch ticket:", vm.toString(ticketHash)); + } +} + +contract RemoveLaunchTicket is BaseScript { + function run() external { + bytes32 ticketHash = vm.envBytes32("LAUNCH_TICKET_HASH"); + require(address(app) != address(0), "APP_CONTRACT_ADDR not set"); + vm.broadcast(vm.envUint("PRIVATE_KEY")); + app.removeLaunchTicket(ticketHash); + console.log("Removed launch ticket:", vm.toString(ticketHash)); + } +} + // Factory Deployment contract DeployApp is BaseScript { function run() external returns (address) { @@ -202,6 +412,7 @@ contract BatchKmsSetup is BaseScript { bytes32[] memory osImages = vm.envOr("OS_IMAGE_LIST", ",", new bytes32[](0)); bytes32[] memory devices = vm.envOr("DEVICE_LIST", ",", new bytes32[](0)); + (uint256 from, uint256 to) = rootEpochs(); vm.startBroadcast(vm.envUint("PRIVATE_KEY")); // Set gateway ID if provided @@ -212,19 +423,19 @@ contract BatchKmsSetup is BaseScript { // Add aggregated MRs for (uint256 i = 0; i < mrAggregated.length; i++) { - kms.addKmsAggregatedMr(mrAggregated[i]); + kms.addKmsAggregatedMrAtEpochs(from, to, mrAggregated[i]); console.log("Added MR aggregated:", vm.toString(mrAggregated[i])); } // Add OS images for (uint256 i = 0; i < osImages.length; i++) { - kms.addOsImageHash(osImages[i]); + kms.addOsImageHashAtEpochs(from, to, osImages[i]); console.log("Added OS image:", vm.toString(osImages[i])); } // Add devices for (uint256 i = 0; i < devices.length; i++) { - kms.addKmsDevice(devices[i]); + kms.addKmsDeviceAtEpochs(from, to, devices[i]); console.log("Added device:", vm.toString(devices[i])); } @@ -240,8 +451,9 @@ contract RemoveOsImage is BaseScript { function run() external { bytes32 imageHash = vm.envBytes32("OS_IMAGE_HASH"); + (uint256 from, uint256 to) = rootEpochs(); vm.startBroadcast(vm.envUint("PRIVATE_KEY")); - kms.removeOsImageHash(imageHash); + kms.removeOsImageHashAtEpochs(from, to, imageHash); vm.stopBroadcast(); console.log("Removed OS image hash:", vm.toString(imageHash)); @@ -252,8 +464,9 @@ contract RemoveKmsDevice is BaseScript { function run() external { bytes32 deviceId = vm.envBytes32("DEVICE_ID"); + (uint256 from, uint256 to) = rootEpochs(); vm.startBroadcast(vm.envUint("PRIVATE_KEY")); - kms.removeKmsDevice(deviceId); + kms.removeKmsDeviceAtEpochs(from, to, deviceId); vm.stopBroadcast(); console.log("Removed KMS device:", vm.toString(deviceId)); @@ -263,12 +476,17 @@ contract RemoveKmsDevice is BaseScript { // Remove operations for App management contract RemoveComposeHash is BaseScript { function run() external { - require(address(app) != address(0), "APP_CONTRACT_ADDR not set"); bytes32 composeHash = vm.envBytes32("COMPOSE_HASH"); - vm.startBroadcast(vm.envUint("PRIVATE_KEY")); - app.removeComposeHash(composeHash); - vm.stopBroadcast(); + ILegacyAppManagement legacy = legacyApp(); + if (address(legacy) != address(0)) { + vm.broadcast(vm.envUint("PRIVATE_KEY")); + legacy.removeComposeHash(composeHash); + } else { + (uint256 from, uint256 to) = appEpochs(); + vm.broadcast(vm.envUint("PRIVATE_KEY")); + app.removeComposeHashAtEpochs(from, to, composeHash); + } console.log("Removed compose hash:", vm.toString(composeHash)); } @@ -276,12 +494,17 @@ contract RemoveComposeHash is BaseScript { contract RemoveDevice is BaseScript { function run() external { - require(address(app) != address(0), "APP_CONTRACT_ADDR not set"); bytes32 deviceId = vm.envBytes32("DEVICE_ID"); - vm.startBroadcast(vm.envUint("PRIVATE_KEY")); - app.removeDevice(deviceId); - vm.stopBroadcast(); + ILegacyAppManagement legacy = legacyApp(); + if (address(legacy) != address(0)) { + vm.broadcast(vm.envUint("PRIVATE_KEY")); + legacy.removeDevice(deviceId); + } else { + (uint256 from, uint256 to) = appEpochs(); + vm.broadcast(vm.envUint("PRIVATE_KEY")); + app.removeDeviceAtEpochs(from, to, deviceId); + } console.log("Removed device:", vm.toString(deviceId)); } @@ -331,3 +554,14 @@ contract DisableAppUpgrades is BaseScript { // a live proxy to the current `contracts/DstackKms.sol` / `contracts/DstackApp.sol` // source. The `UpgradeKmsToV2` / `UpgradeAppToV2` variants target the V2 test // mocks under `contracts/test-utils/` and are for upgrade-flow tests only. + +contract AdvanceAppEpoch is BaseScript { + function run() external { + require(address(app) != address(0), "APP_CONTRACT_ADDR not set"); + uint256 expected = vm.envUint("EXPECTED_APP_EPOCH"); + vm.startBroadcast(vm.envUint("PRIVATE_KEY")); + app.advanceAppEpoch(expected); + vm.stopBroadcast(); + console.log("Current app epoch:", app.currentAppEpoch()); + } +} diff --git a/dstack/kms/auth-eth/script/Query.s.sol b/dstack/kms/auth-eth/script/Query.s.sol index 4a9a01496a..9e35ba3765 100644 --- a/dstack/kms/auth-eth/script/Query.s.sol +++ b/dstack/kms/auth-eth/script/Query.s.sol @@ -21,6 +21,13 @@ abstract contract BaseQueryScript is Script { DstackKms public kms; DstackApp public app; + function logTeeVariants(bool any, string[] memory names) internal pure { + console.log("Allow Any TEE Variant:", any); + for (uint256 i = 0; i < names.length; ++i) { + console.log(" Allowed TEE variant:", names[i]); + } + } + function setUp() public virtual { address kmsAddr = vm.envOr("KMS_CONTRACT_ADDR", address(0)); if (kmsAddr != address(0)) { @@ -124,7 +131,7 @@ contract CheckKmsAllowed is BaseQueryScript { require(address(kms) != address(0), "KMS_CONTRACT_ADDR not set"); // Read boot info from environment - IAppAuth.AppBootInfo memory bootInfo = IAppAuth.AppBootInfo({ + IAppAuth.AppInfo memory bootInfo = IAppAuth.AppInfo({ appId: vm.envAddress("APP_ID"), composeHash: vm.envBytes32("COMPOSE_HASH"), instanceId: vm.envOr("INSTANCE_ID", address(0)), @@ -150,7 +157,7 @@ contract CheckAppAllowed is BaseQueryScript { require(address(kms) != address(0), "KMS_CONTRACT_ADDR not set"); // Read boot info from environment - IAppAuth.AppBootInfo memory bootInfo = IAppAuth.AppBootInfo({ + IAppAuth.AppInfo memory bootInfo = IAppAuth.AppInfo({ appId: vm.envAddress("APP_ID"), composeHash: vm.envBytes32("COMPOSE_HASH"), instanceId: vm.envOr("INSTANCE_ID", address(0)), @@ -202,6 +209,8 @@ contract GetKmsSettings is BaseQueryScript { console.log("Owner:", kms.owner()); console.log("Gateway App ID:", kms.gatewayAppId()); console.log("App Implementation:", kms.appImplementation()); + logTeeVariants(kms.allowAnyTeeVariant(), kms.allowedTeeVariants()); + console.log("SEV-SNP TCB Requirements:", kms.sevSnpTcbRequirements()); // Get KMS info (bytes memory k256Pubkey, bytes memory caPubkey, bytes memory quote, bytes memory eventlog) = kms.kmsInfo(); @@ -211,6 +220,22 @@ contract GetKmsSettings is BaseQueryScript { console.log(" Quote length:", quote.length); console.log(" Eventlog length:", eventlog.length); + uint256 epochCount = kms.rootEpochCount(); + console.log("\nRegistered root epochs:", epochCount); + if (epochCount > 0) { + (uint256 current,) = kms.currentRootEpoch(); + console.log("Current root epoch:", current); + } + for (uint256 epoch = 0; epoch < epochCount; epoch++) { + (bytes memory epochCa, bytes memory epochK256, string memory evidenceUrl, bytes32 chainHash) = + kms.rootEpoch(epoch); + console.log(" Epoch", epoch); + console.log(" CA Pubkey:", vm.toString(epochCa)); + console.log(" K256 Pubkey:", vm.toString(epochK256)); + console.log(" Evidence URL:", evidenceUrl); + console.log(" Chain hash:", vm.toString(chainHash)); + } + // Check implementation via storage bytes32 implSlot = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; address implementation = address(uint160(uint256(vm.load(address(kms), implSlot)))); @@ -227,6 +252,7 @@ contract GetAppSettings is BaseQueryScript { console.log("Contract Address:", address(app)); console.log("Owner:", app.owner()); console.log("Allow Any Device:", app.allowAnyDevice()); + logTeeVariants(app.allowAnyTeeVariant(), app.allowedTeeVariants()); // Check implementation via storage bytes32 implSlot = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; @@ -234,3 +260,11 @@ contract GetAppSettings is BaseQueryScript { console.log("\nProxy Implementation:", implementation); } } + +contract GetAppEpoch is BaseQueryScript { + function run() external view { + require(address(kms) != address(0), "KMS_CONTRACT_ADDR not set"); + require(address(app) != address(0), "APP_CONTRACT_ADDR not set"); + console.log("Current app epoch:", kms.currentAppEpoch(address(app))); + } +} diff --git a/dstack/kms/auth-eth/script/README.md b/dstack/kms/auth-eth/script/README.md index 8ff68a00e6..90e7b5db74 100644 --- a/dstack/kms/auth-eth/script/README.md +++ b/dstack/kms/auth-eth/script/README.md @@ -11,7 +11,8 @@ forge script script/Deploy.s.sol:DeployScript --broadcast --rpc-url $RPC_URL ``` ### DeployKmsOnly -Deploys only DstackKms (requires APP_IMPLEMENTATION): +Deploys only DstackKms (requires APP_IMPLEMENTATION, a `DstackApp` with +`deployProxy`; with an older one, `deployAndRegisterApp` reverts): ```bash APP_IMPLEMENTATION=0x... forge script script/Deploy.s.sol:DeployKmsOnly --broadcast --rpc-url $RPC_URL ``` @@ -28,51 +29,137 @@ Type-safe contract management scripts. Set the environment variables and run the ### KMS Management +The KMS material scripts below write root epoch rows: `ROOT_EPOCH=e` one row, or +`FROM_ROOT_EPOCH` through `TO_ROOT_EPOCH`. One of them is required. A request +may select any epoch up to the current one, so revoke a value with +`FROM_ROOT_EPOCH=0` and `TO_ROOT_EPOCH` the latest registered epoch. + #### Add KMS Aggregated MR ```bash -KMS_CONTRACT_ADDR=0x... MR_AGGREGATED=0x1234... \ +KMS_CONTRACT_ADDR=0x... ROOT_EPOCH=0 MR_AGGREGATED=0x1234... \ forge script script/Manage.s.sol:AddKmsAggregatedMr --broadcast --rpc-url $RPC_URL ``` #### Add OS Image ```bash -KMS_CONTRACT_ADDR=0x... OS_IMAGE_HASH=0x1234... \ +KMS_CONTRACT_ADDR=0x... ROOT_EPOCH=0 OS_IMAGE_HASH=0x1234... \ forge script script/Manage.s.sol:AddOsImage --broadcast --rpc-url $RPC_URL ``` #### Add KMS Device ```bash -KMS_CONTRACT_ADDR=0x... DEVICE_ID=0x1234... \ +KMS_CONTRACT_ADDR=0x... ROOT_EPOCH=0 DEVICE_ID=0x1234... \ forge script script/Manage.s.sol:AddKmsDevice --broadcast --rpc-url $RPC_URL ``` +#### Set KMS TEE Variants +`TEE_VARIANTS` is `any`, or the comma-separated platform names, as the KMS reports +them, that alone are allowed: `dstack-tdx`, `dstack-gcp-tdx`, `dstack-nitro-enclave`, +`dstack-amd-sev-snp` or `dstack-aws-nitro-tpm` (see `contracts/TeeVariantPolicy.sol`). +It applies to KMS instances and every app at every root epoch. A restricted policy +refuses the legacy `isKmsAllowed`/`isAppAllowed`, whose callers report no platform. +```bash +KMS_CONTRACT_ADDR=0x... TEE_VARIANTS=dstack-tdx \ +forge script script/Manage.s.sol:SetKmsTeeVariants --broadcast --rpc-url $RPC_URL +``` + +#### Require KMS Launch Tickets +A KMS instance must then present an allowed launch ticket to import the root keys. +Upgrade every KMS instance to 0.6.4 first: older ones authorize serving through +`isKmsAllowed`, which then refuses, so they stop serving every app. +```bash +KMS_CONTRACT_ADDR=0x... REQUIRE_LAUNCH_TICKET=true \ +forge script script/Manage.s.sol:RequireKmsLaunchTicket --broadcast --rpc-url $RPC_URL +``` + +#### Add or Remove a KMS Launch Ticket +`LAUNCH_TICKET_HASH` is `sha256("dstack-launch-ticket/v1:" || ticket)`; the +label is public. Remove the ticket once the instance has joined. +```bash +LAUNCH_TICKET_HASH=0x$(printf 'dstack-launch-ticket/v1:%s' "$TICKET" | sha256sum | cut -d' ' -f1) +KMS_CONTRACT_ADDR=0x... LAUNCH_TICKET_HASH=$LAUNCH_TICKET_HASH LAUNCH_TICKET_LABEL=kms-node-2 \ +forge script script/Manage.s.sol:AddKmsLaunchTicket --broadcast --rpc-url $RPC_URL +KMS_CONTRACT_ADDR=0x... LAUNCH_TICKET_HASH=$LAUNCH_TICKET_HASH \ +forge script script/Manage.s.sol:RemoveKmsLaunchTicket --broadcast --rpc-url $RPC_URL +``` + +#### Set SEV-SNP TCB Requirements +The minimum TCB each CPU must meet for an SEV-SNP TCB to report `UpToDate`, as a JSON list +(see [AMD SEV-SNP](../../../../docs/amd-sev-snp.md)). While it is empty, +a KMS judges a CPU only against its own list, and refuses one neither lists. +```bash +KMS_CONTRACT_ADDR=0x... \ +SEV_SNP_TCB_REQUIREMENTS='[{"cpuid":"00a00f11","bootloader":0,"tee":0,"snp":27,"microcode":222}]' \ +forge script script/Manage.s.sol:SetSevSnpTcbRequirements --broadcast --rpc-url $RPC_URL +``` + #### Set Gateway App ID ```bash KMS_CONTRACT_ADDR=0x... GATEWAY_APP_ID="my-gateway" \ forge script script/Manage.s.sol:SetGatewayAppId --broadcast --rpc-url $RPC_URL ``` -#### Set KMS Info +#### Register a KMS Root Epoch +Use this for initial setup as well as subsequent root rotations. The legacy +`setKmsInfo`, `setKmsQuote`, and `setKmsEventlog` entry points have been removed; +calls to them revert even before epoch 0 is registered. For an upgraded proxy +with legacy roots in `kmsInfo`, epoch 0 must register those same public keys. + +Appends the next root epoch (the original roots are epoch 0). Epoch 0 takes +effect when registered; later epochs take effect when activated, and each takes +over `kmsInfo` then, clearing its quote and event log. `EVIDENCE_URL` +points to the attestation the KMS returned when it generated the keys (Bootstrap, +or Onboard with `rotate`), published where verifiers can fetch it; verify it +before registering. Registered keys cannot be changed, only a pending epoch popped; +the evidence URL can be updated when the evidence moves. +```bash +KMS_CONTRACT_ADDR=0x... CA_PUBKEY=0x... K256_PUBKEY=0x... EVIDENCE_URL=ipfs://... \ +forge script script/Manage.s.sol:RegisterRootEpoch --broadcast --rpc-url $RPC_URL +``` + +#### Activate a KMS Root Epoch +Makes the next registered root epoch the one KMS instances serve. Activate it +only once every KMS node holds it; nodes still at the previous epoch stop +serving, and nodes holding it restart to switch. Epochs only move forward. +`CHAIN_HASH` is the expected epoch chain hash (see `Query.s.sol`), +so a stale activation cannot activate replacement keys at the same epoch. ```bash -KMS_CONTRACT_ADDR=0x... K256_PUBKEY=0x... CA_PUBKEY=0x... QUOTE=0x... EVENTLOG=0x... \ -forge script script/Manage.s.sol:SetKmsInfo --broadcast --rpc-url $RPC_URL +KMS_CONTRACT_ADDR=0x... ROOT_EPOCH=1 CHAIN_HASH=0x... \ +forge script script/Manage.s.sol:ActivateRootEpoch --broadcast --rpc-url $RPC_URL +``` + +#### Update a Root Epoch's Evidence URL +Points an epoch at a new copy of its attestation, e.g. when the old host goes away. +```bash +KMS_CONTRACT_ADDR=0x... ROOT_EPOCH=0 EVIDENCE_URL=ipfs://... \ +forge script script/Manage.s.sol:SetRootEpochEvidenceUrl --broadcast --rpc-url $RPC_URL +``` + +#### Pop a Pending KMS Root Epoch +Drops the last registered epoch while it is not yet current, e.g. when the nodes +holding it are lost before it could be activated. Re-rotate to register a new one. +`CHAIN_HASH` is the epoch's chain hash (see `Query.s.sol`), so only that exact +registration is dropped. +```bash +KMS_CONTRACT_ADDR=0x... ROOT_EPOCH=1 CHAIN_HASH=0x... \ +forge script script/Manage.s.sol:PopRootEpoch --broadcast --rpc-url $RPC_URL ``` #### Remove KMS Aggregated MR ```bash -KMS_CONTRACT_ADDR=0x... MR_AGGREGATED=0x1234... \ +KMS_CONTRACT_ADDR=0x... ROOT_EPOCH=0 MR_AGGREGATED=0x1234... \ forge script script/Manage.s.sol:RemoveKmsAggregatedMr --broadcast --rpc-url $RPC_URL ``` #### Remove OS Image ```bash -KMS_CONTRACT_ADDR=0x... OS_IMAGE_HASH=0x1234... \ +KMS_CONTRACT_ADDR=0x... ROOT_EPOCH=0 OS_IMAGE_HASH=0x1234... \ forge script script/Manage.s.sol:RemoveOsImage --broadcast --rpc-url $RPC_URL ``` #### Remove KMS Device ```bash -KMS_CONTRACT_ADDR=0x... DEVICE_ID=0x1234... \ +KMS_CONTRACT_ADDR=0x... ROOT_EPOCH=0 DEVICE_ID=0x1234... \ forge script script/Manage.s.sol:RemoveKmsDevice --broadcast --rpc-url $RPC_URL ``` @@ -91,7 +178,7 @@ forge script script/Manage.s.sol:RegisterApp --broadcast --rpc-url $RPC_URL #### Batch KMS Setup Configure multiple settings at once: ```bash -KMS_CONTRACT_ADDR=0x... \ +KMS_CONTRACT_ADDR=0x... ROOT_EPOCH=0 \ GATEWAY_APP_ID="my-gateway" \ MR_AGGREGATED_LIST=0x1111...,0x2222...,0x3333... \ OS_IMAGE_LIST=0xaaaa...,0xbbbb... \ @@ -101,15 +188,21 @@ forge script script/Manage.s.sol:BatchKmsSetup --broadcast --rpc-url $RPC_URL ### App Management +The app scripts write app epoch rows: `APP_EPOCH=e`, or `FROM_APP_EPOCH` through +`TO_APP_EPOCH` (at most the next epoch); one of them is required. Revoke a value +with `FROM_APP_EPOCH=0` and `TO_APP_EPOCH` the current app epoch. App contracts +deployed before app epochs (no `IAppEpochManagement`) have only app epoch 0: the +scripts call their epoch-less setters and accept only `APP_EPOCH=0` or no epoch. + #### Add Compose Hash ```bash -KMS_CONTRACT_ADDR=0x... APP_CONTRACT_ADDR=0x... COMPOSE_HASH=0x1234... \ +KMS_CONTRACT_ADDR=0x... APP_CONTRACT_ADDR=0x... APP_EPOCH=0 COMPOSE_HASH=0x1234... \ forge script script/Manage.s.sol:AddComposeHash --broadcast --rpc-url $RPC_URL ``` #### Add Device ```bash -KMS_CONTRACT_ADDR=0x... APP_CONTRACT_ADDR=0x... DEVICE_ID=0x1234... \ +KMS_CONTRACT_ADDR=0x... APP_CONTRACT_ADDR=0x... APP_EPOCH=0 DEVICE_ID=0x1234... \ forge script script/Manage.s.sol:AddDevice --broadcast --rpc-url $RPC_URL ``` @@ -119,15 +212,42 @@ KMS_CONTRACT_ADDR=0x... APP_CONTRACT_ADDR=0x... ALLOW_ANY_DEVICE=true \ forge script script/Manage.s.sol:SetAllowAnyDevice --broadcast --rpc-url $RPC_URL ``` +#### Set TEE Variants +Same `TEE_VARIANTS` values as for the KMS; applies to every app epoch. +```bash +KMS_CONTRACT_ADDR=0x... APP_CONTRACT_ADDR=0x... TEE_VARIANTS=dstack-tdx,dstack-gcp-tdx \ +forge script script/Manage.s.sol:SetTeeVariants --broadcast --rpc-url $RPC_URL +``` + +#### Require Launch Tickets +The app must then present an allowed launch ticket, at every app epoch. For a new +app, deploy it without `INITIAL_COMPOSE_HASH`, require the ticket and add it, then +add the compose hash: a key released in between cannot be taken back. +```bash +KMS_CONTRACT_ADDR=0x... APP_CONTRACT_ADDR=0x... REQUIRE_LAUNCH_TICKET=true \ +forge script script/Manage.s.sol:RequireLaunchTicket --broadcast --rpc-url $RPC_URL +``` + +#### Add or Remove a Launch Ticket +`LAUNCH_TICKET_HASH` is `sha256("dstack-launch-ticket/v1:" || ticket)`; the label +is public. +```bash +LAUNCH_TICKET_HASH=0x$(printf 'dstack-launch-ticket/v1:%s' "$TICKET" | sha256sum | cut -d' ' -f1) +KMS_CONTRACT_ADDR=0x... APP_CONTRACT_ADDR=0x... LAUNCH_TICKET_HASH=$LAUNCH_TICKET_HASH LAUNCH_TICKET_LABEL=prod \ +forge script script/Manage.s.sol:AddLaunchTicket --broadcast --rpc-url $RPC_URL +KMS_CONTRACT_ADDR=0x... APP_CONTRACT_ADDR=0x... LAUNCH_TICKET_HASH=$LAUNCH_TICKET_HASH \ +forge script script/Manage.s.sol:RemoveLaunchTicket --broadcast --rpc-url $RPC_URL +``` + #### Remove Compose Hash ```bash -KMS_CONTRACT_ADDR=0x... APP_CONTRACT_ADDR=0x... COMPOSE_HASH=0x1234... \ +KMS_CONTRACT_ADDR=0x... APP_CONTRACT_ADDR=0x... APP_EPOCH=0 COMPOSE_HASH=0x1234... \ forge script script/Manage.s.sol:RemoveComposeHash --broadcast --rpc-url $RPC_URL ``` #### Remove Device ```bash -KMS_CONTRACT_ADDR=0x... APP_CONTRACT_ADDR=0x... DEVICE_ID=0x1234... \ +KMS_CONTRACT_ADDR=0x... APP_CONTRACT_ADDR=0x... APP_EPOCH=0 DEVICE_ID=0x1234... \ forge script script/Manage.s.sol:RemoveDevice --broadcast --rpc-url $RPC_URL ``` @@ -251,6 +371,13 @@ KMS_CONTRACT_ADDR=0x... \ forge script script/Upgrade.s.sol:UpgradeKms --broadcast --rpc-url $RPC_URL --ffi ``` +`DstackKms` deploys apps through its `appImplementation`, which must be a +`DstackApp` with `deployProxy`. The script sets it in the same upgrade call: +to `APP_IMPLEMENTATION` if set, otherwise to a newly deployed `DstackApp`, so +the upgrade replaces whatever implementation was set before. If you upgrade +another way, also call `setAppImplementation`; until then, +`deployAndRegisterApp` reverts. + #### Upgrade App ```bash APP_CONTRACT_ADDR=0x... \ diff --git a/dstack/kms/auth-eth/script/Upgrade.s.sol b/dstack/kms/auth-eth/script/Upgrade.s.sol index 94562b05fe..6e32cd25de 100644 --- a/dstack/kms/auth-eth/script/Upgrade.s.sol +++ b/dstack/kms/auth-eth/script/Upgrade.s.sol @@ -13,6 +13,9 @@ import "../contracts/DstackApp.sol"; // Production upgrade path: upgrade the live DstackKms proxy to the current // `contracts/DstackKms.sol` implementation. Use this for routine upgrades. +// DstackKms deploys apps through `appImplementation`, so the upgrade also +// points it at a current DstackApp implementation: APP_IMPLEMENTATION if set, +// otherwise a newly deployed one. contract UpgradeKms is Script { function run() external { address kmsProxy = vm.envAddress("KMS_CONTRACT_ADDR"); @@ -21,9 +24,12 @@ contract UpgradeKms is Script { console.log("Proxy address:", kmsProxy); vm.startBroadcast(); - Upgrades.upgradeProxy(kmsProxy, "DstackKms.sol", ""); + address appImpl = vm.envOr("APP_IMPLEMENTATION", address(0)); + if (appImpl == address(0)) appImpl = address(new DstackApp()); + Upgrades.upgradeProxy(kmsProxy, "DstackKms.sol", abi.encodeCall(DstackKms.setAppImplementation, (appImpl))); vm.stopBroadcast(); + console.log("DstackApp implementation:", appImpl); console.log("Success: DstackKms upgraded."); } } diff --git a/dstack/kms/auth-eth/scripts/README.md b/dstack/kms/auth-eth/scripts/README.md deleted file mode 100644 index c58b743d7c..0000000000 --- a/dstack/kms/auth-eth/scripts/README.md +++ /dev/null @@ -1,124 +0,0 @@ -# Test Scripts - -This directory contains automated test scripts for the dstack KMS Ethereum backend. - -## Scripts Overview - -### 🚀 setup-local-chain.sh -Sets up a local Anvil blockchain and deploys the dstack contracts. -- Starts Anvil on port 8545 -- Deploys DstackKms and DstackApp contracts -- Saves configuration to `.env.test` - -```bash -npm run test:setup -# or -./scripts/setup-local-chain.sh -``` - -### 🧪 run-tests.sh -Runs all tests against the deployed contracts on the local chain. -- Requires local chain to be already set up -- Runs Jest unit tests -- Runs integration tests -- Optionally runs Foundry tests - -```bash -npm run test:run # Run JS/TS tests only -npm run test:run:foundry # Include Foundry tests -# or -./scripts/run-tests.sh -./scripts/run-tests.sh --with-foundry -``` - -### 🎯 test-all.sh -Complete test suite - sets up chain and runs all tests. -- Combines setup-local-chain.sh and run-tests.sh -- Perfect for CI/CD or fresh test runs - -```bash -npm run test:all # Complete test suite -npm run test:all:foundry # Include Foundry tests -# or -./scripts/test-all.sh -./scripts/test-all.sh --with-foundry -``` - -### 🧹 cleanup.sh -Cleans up all test processes and temporary files. -- Stops Anvil and API server -- Removes temporary files and logs - -```bash -npm run test:cleanup -# or -./scripts/cleanup.sh -``` - -## Typical Workflows - -### One-time Setup, Multiple Test Runs -```bash -# Set up once -npm run test:setup - -# Run tests multiple times -npm run test:run -npm run test:run -npm run test:run - -# Clean up when done -npm run test:cleanup -``` - -### Complete Test Run -```bash -# Run everything in one go -npm run test:all - -# Or with Foundry tests -npm run test:all:foundry -``` - -### Development Workflow -```bash -# Set up chain -npm run test:setup - -# Keep chain running, develop and test -npm run test:run -# ... make changes ... -npm run test:run -# ... make more changes ... -npm run test:run - -# Clean up when done -npm run test:cleanup -``` - -## Environment Variables - -After running `setup-local-chain.sh`, the following environment variables are saved to `.env.test`: - -- `ANVIL_PID` - Process ID of the Anvil instance -- `ETH_RPC_URL` - RPC endpoint (http://127.0.0.1:8545) -- `CHAIN_ID` - Chain ID (31337) -- `KMS_CONTRACT_ADDR` - Deployed KMS proxy contract address -- `APP_IMPLEMENTATION` - DstackApp implementation address -- `KMS_IMPLEMENTATION` - DstackKms implementation address -- `DEPLOYER_ADDRESS` - Address that deployed the contracts -- `DEPLOYER_PRIVATE_KEY` - Private key of the deployer - -## Logs - -The scripts generate the following log files: - -- `anvil.log` - Anvil blockchain logs -- `deploy.log` - Contract deployment logs -- `server-test.log` - API server logs during tests - -## Requirements - -- Node.js and npm -- Foundry (forge, anvil) -- All npm dependencies installed (`npm install`) diff --git a/dstack/kms/auth-eth/scripts/cleanup.sh b/dstack/kms/auth-eth/scripts/cleanup.sh deleted file mode 100755 index 8b428d4b20..0000000000 --- a/dstack/kms/auth-eth/scripts/cleanup.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/bin/bash - -# SPDX-FileCopyrightText: © 2025 Phala Network -# -# SPDX-License-Identifier: Apache-2.0 - -# Cleanup script to stop all test processes - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" -ENV_FILE="$PROJECT_ROOT/.env.test" - -# Colors for output -GREEN='\033[0;32m' -NC='\033[0m' - -echo "🧹 Cleaning up test environment..." - -# Kill any running API servers -echo "Stopping API servers..." -pkill -f "ts-node src/main.ts" || true -pkill -f "node dist/main.js" || true - -# Load environment if exists -if [ -f "$ENV_FILE" ]; then - # shellcheck source=/dev/null - source "$ENV_FILE" - - # Kill Anvil if PID is set - if [ -n "$ANVIL_PID" ]; then - echo "Stopping Anvil (PID: $ANVIL_PID)..." - kill "$ANVIL_PID" 2>/dev/null || true - fi -fi - -# Kill any other Anvil processes -echo "Stopping any other Anvil processes..." -pkill -f "anvil" || true - -# Clean up files -echo "Removing temporary files..." -rm -f "$PROJECT_ROOT/.env.test" -rm -f "$PROJECT_ROOT/anvil.log" -rm -f "$PROJECT_ROOT/deploy.log" -rm -f "$PROJECT_ROOT/server-test.log" -rm -f "$PROJECT_ROOT/integration-test.js" - -echo -e "${GREEN}✅ Cleanup complete!${NC}" diff --git a/dstack/kms/auth-eth/scripts/run-tests.sh b/dstack/kms/auth-eth/scripts/run-tests.sh deleted file mode 100755 index 0835def672..0000000000 --- a/dstack/kms/auth-eth/scripts/run-tests.sh +++ /dev/null @@ -1,265 +0,0 @@ -#!/bin/bash - -# SPDX-FileCopyrightText: © 2025 Phala Network -# -# SPDX-License-Identifier: Apache-2.0 - -# Script to run all tests against the local chain - -set -e - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" -ENV_FILE="$PROJECT_ROOT/.env.test" - -# Colors for output -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -BLUE='\033[0;34m' -NC='\033[0m' # No Color - -echo "🧪 Running test suite..." - -# Check if environment file exists -if [ ! -f "$ENV_FILE" ]; then - echo -e "${RED}❌ Error: Environment file not found at $ENV_FILE${NC}" - echo -e "${YELLOW}Please run ./scripts/setup-local-chain.sh first${NC}" - exit 1 -fi - -# Load environment variables -# shellcheck source=/dev/null -source "$ENV_FILE" - -# Export for child processes -export ETH_RPC_URL -export KMS_CONTRACT_ADDR -export APP_IMPLEMENTATION - -# Check if Anvil is running -if ! kill -0 "$ANVIL_PID" 2>/dev/null; then - echo -e "${RED}❌ Error: Anvil is not running (PID: $ANVIL_PID)${NC}" - echo -e "${YELLOW}Please run ./scripts/setup-local-chain.sh first${NC}" - exit 1 -fi - -echo -e "${GREEN}✅ Local chain is running${NC}" -echo " KMS Contract: $KMS_CONTRACT_ADDR" -echo " App Implementation: $APP_IMPLEMENTATION" -echo "" - -# Change to project root -cd "$PROJECT_ROOT" - -# Build TypeScript -echo -e "${BLUE}🔨 Building TypeScript...${NC}" -npm run build - -# Function to cleanup on exit -cleanup() { - echo "" - echo "🧹 Cleaning up..." - if [ -n "$SERVER_PID" ]; then - kill "$SERVER_PID" 2>/dev/null || true - fi -} -trap cleanup EXIT - -# Start API server -echo -e "${BLUE}🌐 Starting API server...${NC}" -npm run dev > "$PROJECT_ROOT/server-test.log" 2>&1 & -SERVER_PID=$! - -# Wait for server to be ready -echo "⏳ Waiting for API server to start..." -for i in {1..30}; do - if curl -s http://127.0.0.1:8000 > /dev/null 2>&1; then - echo -e "${GREEN}✅ API server is ready!${NC}" - break - fi - if [ "$i" -eq 30 ]; then - echo -e "${RED}❌ API server failed to start within 30 seconds${NC}" - cat "$PROJECT_ROOT/server-test.log" - exit 1 - fi - sleep 1 -done - -# Run Jest unit tests -echo "" -echo -e "${BLUE}📋 Running Jest unit tests...${NC}" -npm test - -# Run integration tests -echo "" -echo -e "${BLUE}🔗 Running integration tests...${NC}" - -# Create and run integration test -cat > "$PROJECT_ROOT/integration-test.js" << 'EOF' -const { ethers } = require('ethers'); - -async function runIntegrationTests() { - const baseUrl = 'http://127.0.0.1:8000'; - const rpcUrl = process.env.ETH_RPC_URL; - const kmsAddress = process.env.KMS_CONTRACT_ADDR; - - console.log('Testing against:'); - console.log(' API URL:', baseUrl); - console.log(' RPC URL:', rpcUrl); - console.log(' KMS Contract:', kmsAddress); - console.log(''); - - const testData = { - tcbStatus: 'UpToDate', - advisoryIds: [], - mrAggregated: '0x' + '1234567890abcdef'.repeat(4), - osImageHash: '0x' + 'abcdefabcdefabcd'.repeat(4), - mrSystem: '0x' + '9012901290129012'.repeat(4), - appId: '0x9012345678901234567890123456789012345678', - composeHash: '0x' + 'abcdabcdabcdabcd'.repeat(4), - instanceId: '0x3456789012345678901234567890123456789012', - deviceId: '0x' + 'ef12ef12ef12ef12'.repeat(4) - }; - - const tests = [ - { - name: 'Health Check', - run: async () => { - const res = await fetch(baseUrl + '/'); - const data = await res.json(); - return { - passed: res.status === 200 && data.kmsContractAddr === kmsAddress, - details: `Status: ${res.status}, Contract: ${data.kmsContractAddr}` - }; - } - }, - { - name: 'App Authorization', - run: async () => { - const res = await fetch(baseUrl + '/bootAuth/app', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(testData) - }); - const data = await res.json(); - return { - passed: res.status === 200 && data.hasOwnProperty('isAllowed'), - details: `Status: ${res.status}, Response: ${JSON.stringify(data)}` - }; - } - }, - { - name: 'KMS Authorization', - run: async () => { - const res = await fetch(baseUrl + '/bootAuth/kms', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(testData) - }); - const data = await res.json(); - return { - passed: res.status === 200 && data.hasOwnProperty('isAllowed'), - details: `Status: ${res.status}, Response: ${JSON.stringify(data)}` - }; - } - }, - { - name: 'Invalid Request Validation', - run: async () => { - const res = await fetch(baseUrl + '/bootAuth/app', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ mrAggregated: '0x1234' }) - }); - return { - passed: res.status === 400, - details: `Status: ${res.status} (expected 400)` - }; - } - }, - { - name: 'Contract Interaction', - run: async () => { - const provider = new ethers.JsonRpcProvider(rpcUrl); - const abi = ['function owner() view returns (address)']; - const contract = new ethers.Contract(kmsAddress, abi, provider); - const owner = await contract.owner(); - return { - passed: ethers.isAddress(owner), - details: `Owner: ${owner}` - }; - } - } - ]; - - let passed = 0; - let failed = 0; - - for (const test of tests) { - try { - const result = await test.run(); - if (result.passed) { - console.log(`✅ ${test.name}`); - console.log(` ${result.details}`); - passed++; - } else { - console.log(`❌ ${test.name}`); - console.log(` ${result.details}`); - failed++; - } - } catch (error) { - console.log(`❌ ${test.name}`); - console.log(` Error: ${error.message}`); - failed++; - } - } - - console.log(''); - console.log(`Summary: ${passed} passed, ${failed} failed`); - - return failed === 0; -} - -runIntegrationTests().then(success => { - process.exit(success ? 0 : 1); -}).catch(error => { - console.error('Test runner error:', error); - process.exit(1); -}); -EOF - -node "$PROJECT_ROOT/integration-test.js" -INTEGRATION_RESULT=$? - -# Clean up integration test file -rm -f "$PROJECT_ROOT/integration-test.js" - -# Run Foundry tests -echo "" -echo -e "${BLUE}🔨 Running Foundry tests...${NC}" -ETHERSCAN_API_KEY=dummy forge test --ffi --rpc-url "$ETH_RPC_URL" -FOUNDRY_RESULT=$? - -# Summary -echo "" -echo "📊 Test Summary:" -echo " Jest Tests: ${GREEN}✅ Passed${NC}" -if [ $INTEGRATION_RESULT -eq 0 ]; then - echo " Integration Tests: ${GREEN}✅ Passed${NC}" -else - echo " Integration Tests: ${RED}❌ Failed${NC}" -fi -if [ $FOUNDRY_RESULT -eq 0 ]; then - echo " Foundry Tests: ${GREEN}✅ Passed${NC}" -else - echo " Foundry Tests: ${RED}❌ Failed${NC}" -fi - -# Exit with appropriate code -if [ $INTEGRATION_RESULT -ne 0 ] || [ $FOUNDRY_RESULT -ne 0 ]; then - exit 1 -fi - -echo "" -echo -e "${GREEN}✅ All tests passed!${NC}" diff --git a/dstack/kms/auth-eth/scripts/setup-local-chain.sh b/dstack/kms/auth-eth/scripts/setup-local-chain.sh deleted file mode 100755 index ef306eb998..0000000000 --- a/dstack/kms/auth-eth/scripts/setup-local-chain.sh +++ /dev/null @@ -1,128 +0,0 @@ -#!/bin/bash - -# SPDX-FileCopyrightText: © 2025 Phala Network -# -# SPDX-License-Identifier: Apache-2.0 - -# Script to set up local Anvil chain and deploy contracts - -set -e - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" -ENV_FILE="$PROJECT_ROOT/.env.test" - -echo "🔧 Setting up local test environment..." - -# Colors for output -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -NC='\033[0m' # No Color - -# Check if anvil is available -if ! command -v anvil &> /dev/null; then - echo -e "${RED}❌ Error: anvil not found. Install Foundry first:${NC}" - echo "curl -L https://foundry.paradigm.xyz | bash" - echo "foundryup" - exit 1 -fi - -# Clean up any existing Anvil process -echo "🧹 Cleaning up existing Anvil processes..." -pkill -f "anvil" || true -sleep 1 - -# Start Anvil in the background -echo "🚀 Starting Anvil local node..." -anvil \ - --host 0.0.0.0 \ - --port 8545 \ - --accounts 10 \ - --balance 1000 \ - --block-time 1 \ - > "$PROJECT_ROOT/anvil.log" 2>&1 & - -ANVIL_PID=$! -echo " Anvil PID: $ANVIL_PID" - -# Wait for Anvil to be ready -echo "⏳ Waiting for Anvil to start..." -for i in {1..30}; do - if curl -s http://127.0.0.1:8545 > /dev/null 2>&1; then - echo -e "${GREEN}✅ Anvil is ready!${NC}" - break - fi - if [ "$i" -eq 30 ]; then - echo -e "${RED}❌ Anvil failed to start within 30 seconds${NC}" - cat "$PROJECT_ROOT/anvil.log" - exit 1 - fi - sleep 1 -done - -# Deploy contracts -echo "📦 Deploying contracts..." -cd "$PROJECT_ROOT" - -# Use the first Anvil account private key -PRIVATE_KEY="0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" - -# Run deployment and capture output -DEPLOY_OUTPUT=$(PRIVATE_KEY=$PRIVATE_KEY \ - ETHERSCAN_API_KEY=dummy \ - forge script script/Deploy.s.sol:DeployScript \ - --broadcast \ - --rpc-url http://127.0.0.1:8545 \ - -vvv 2>&1) - -echo "$DEPLOY_OUTPUT" > "$PROJECT_ROOT/deploy.log" - -# Extract contract addresses -KMS_PROXY=$(echo "$DEPLOY_OUTPUT" | grep "DstackKms proxy deployed to:" | awk '{print $NF}') -APP_IMPL=$(echo "$DEPLOY_OUTPUT" | grep "DstackApp implementation deployed to:" | awk '{print $NF}') -KMS_IMPL=$(echo "$DEPLOY_OUTPUT" | grep "DstackKms implementation deployed to:" | awk '{print $NF}') - -if [ -z "$KMS_PROXY" ] || [ -z "$APP_IMPL" ]; then - echo -e "${RED}❌ Failed to extract contract addresses from deployment${NC}" - echo "Check deploy.log for details" - kill $ANVIL_PID 2>/dev/null - exit 1 -fi - -# Save environment variables -cat > "$ENV_FILE" << EOF -# Auto-generated test environment configuration -# Generated at: $(date) - -# Anvil Configuration -ANVIL_PID=$ANVIL_PID -ETH_RPC_URL=http://127.0.0.1:8545 -CHAIN_ID=31337 - -# Deployed Contracts -KMS_CONTRACT_ADDR=$KMS_PROXY -APP_IMPLEMENTATION=$APP_IMPL -KMS_IMPLEMENTATION=$KMS_IMPL - -# Test Account (Anvil account #0) -DEPLOYER_ADDRESS=0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 -DEPLOYER_PRIVATE_KEY=$PRIVATE_KEY -EOF - -echo -e "${GREEN}✅ Local chain setup complete!${NC}" -echo "" -echo "📊 Deployment Summary:" -echo " Chain ID: 31337" -echo " RPC URL: http://127.0.0.1:8545" -echo " KMS Proxy: $KMS_PROXY" -echo " App Implementation: $APP_IMPL" -echo "" -echo "📄 Configuration saved to: $ENV_FILE" -echo "" -echo "🔍 Logs available at:" -echo " Anvil: $PROJECT_ROOT/anvil.log" -echo " Deploy: $PROJECT_ROOT/deploy.log" -echo "" -echo -e "${YELLOW}ℹ️ To stop Anvil: kill $ANVIL_PID${NC}" -echo -e "${YELLOW}ℹ️ To run tests: ./scripts/run-tests.sh${NC}" diff --git a/dstack/kms/auth-eth/scripts/test-all.sh b/dstack/kms/auth-eth/scripts/test-all.sh deleted file mode 100755 index 5814952332..0000000000 --- a/dstack/kms/auth-eth/scripts/test-all.sh +++ /dev/null @@ -1,38 +0,0 @@ -#!/bin/bash - -# SPDX-FileCopyrightText: © 2025 Phala Network -# -# SPDX-License-Identifier: Apache-2.0 - -# Complete test runner - sets up chain and runs all tests - -set -e - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" - -# Colors for output -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -NC='\033[0m' - -echo "🚀 Complete Test Suite" -echo "====================" -echo "" - -# Setup local chain -echo "Step 1: Setting up local chain..." -"$SCRIPT_DIR/setup-local-chain.sh" - -echo "" -echo "Step 2: Running tests..." -"$SCRIPT_DIR/run-tests.sh" "$@" - -# Load env to get PID -# shellcheck source=/dev/null -source "$SCRIPT_DIR/../.env.test" - -echo "" -echo -e "${GREEN}✅ Complete test suite finished!${NC}" -echo "" -echo -e "${YELLOW}ℹ️ To stop the local chain: kill $ANVIL_PID${NC}" -echo -e "${YELLOW}ℹ️ To run tests again: ./scripts/run-tests.sh${NC}" diff --git a/dstack/kms/auth-eth/src/ethereum.ts b/dstack/kms/auth-eth/src/ethereum.ts deleted file mode 100644 index ebd6551407..0000000000 --- a/dstack/kms/auth-eth/src/ethereum.ts +++ /dev/null @@ -1,82 +0,0 @@ -// SPDX-FileCopyrightText: © 2025 Phala Network -// -// SPDX-License-Identifier: Apache-2.0 - -import { ethers } from 'ethers'; -import { BootInfo, BootResponse } from './types'; - -// Minimal ABI for DstackKms contract -const DSTACK_KMS_ABI = [ - "function isAppAllowed((address appId,bytes32 composeHash,address instanceId,bytes32 deviceId,bytes32 mrAggregated,bytes32 mrSystem,bytes32 osImageHash,string tcbStatus,string[] advisoryIds) bootInfo) view returns (bool, string)", - "function isKmsAllowed((address appId,bytes32 composeHash,address instanceId,bytes32 deviceId,bytes32 mrAggregated,bytes32 mrSystem,bytes32 osImageHash,string tcbStatus,string[] advisoryIds) bootInfo) view returns (bool, string)", - "function gatewayAppId() view returns (string)", - "function appImplementation() view returns (address)" -]; - -export class EthereumBackend { - private provider: ethers.JsonRpcProvider; - private kmsContract: ethers.Contract; - - constructor(provider: ethers.JsonRpcProvider, kmsContractAddr: string) { - this.provider = provider; - this.kmsContract = new ethers.Contract( - ethers.getAddress(kmsContractAddr), - DSTACK_KMS_ABI, - provider - ); - } - - private decodeHex(hex: string, sz: number = 32): string { - // Remove '0x' prefix if present - hex = hex.startsWith('0x') ? hex.slice(2) : hex; - - // Pad hex string to 64 characters (32 bytes) - hex = hex.padStart(sz * 2, '0'); - - // Add '0x' prefix back - return '0x' + hex; - } - - async checkBoot(bootInfo: BootInfo, isKms: boolean): Promise { - // Create boot info struct for contract call - const bootInfoStruct = { - appId: this.decodeHex(bootInfo.appId, 20), - instanceId: this.decodeHex(bootInfo.instanceId, 20), - composeHash: this.decodeHex(bootInfo.composeHash, 32), - deviceId: this.decodeHex(bootInfo.deviceId, 32), - mrSystem: this.decodeHex(bootInfo.mrSystem, 32), - mrAggregated: this.decodeHex(bootInfo.mrAggregated, 32), - osImageHash: this.decodeHex(bootInfo.osImageHash, 32), - tcbStatus: bootInfo.tcbStatus, - advisoryIds: bootInfo.advisoryIds - }; - // Read the whole decision from one block. - const blockTag = await this.provider.getBlockNumber(); - let response; - if (isKms) { - response = await this.kmsContract.isKmsAllowed(bootInfoStruct, { blockTag }); - } else { - response = await this.kmsContract.isAppAllowed(bootInfoStruct, { blockTag }); - } - const [isAllowed, reason] = response; - const gatewayAppId = await this.kmsContract.gatewayAppId({ blockTag }); - return { - isAllowed, - reason, - gatewayAppId, - } - } - - async getGatewayAppId(): Promise { - return await this.kmsContract.gatewayAppId(); - } - - async getChainId(): Promise { - const chainId = await this.provider.getNetwork().then((network) => network.chainId); - return Number(chainId); - } - - async getAppImplementation(): Promise { - return await this.kmsContract.appImplementation(); - } -} diff --git a/dstack/kms/auth-eth/src/main.test.ts b/dstack/kms/auth-eth/src/main.test.ts deleted file mode 100644 index 842f1e36bd..0000000000 --- a/dstack/kms/auth-eth/src/main.test.ts +++ /dev/null @@ -1,131 +0,0 @@ -// SPDX-FileCopyrightText: © 2025 Phala Network -// -// SPDX-License-Identifier: Apache-2.0 - -import { FastifyInstance } from 'fastify'; -import { build } from './server'; -import { BootInfo } from './types'; - -// Mock EthereumBackend -jest.mock('./ethereum', () => { - return { - EthereumBackend: jest.fn().mockImplementation(() => ({ - checkBoot: jest.fn() - })) - }; -}); - -describe('Server', () => { - let app: FastifyInstance; - const mockBootInfo: BootInfo = { - tcbStatus: "UpToDate", - advisoryIds: [], - mrAggregated: '0x1234', - osImageHash: '0x5678', - mrSystem: '0x9012', - appId: '0x9012345678901234567890123456789012345678', - composeHash: '0xabcd', - instanceId: '0x3456789012345678901234567890123456789012', - deviceId: '0xef12' - }; - - beforeAll(async () => { - app = await build(); - }); - - afterAll(async () => { - await app.close(); - }); - - describe('POST /bootAuth/app', () => { - it('should return 200 when backend check passes', async () => { - // Mock successful response - const mockCheckBoot = jest.fn().mockResolvedValue({ - isAllowed: true, - reason: '', - gatewayAppId: '' - }); - app.ethereum.checkBoot = mockCheckBoot; - - const response = await app.inject({ - method: 'POST', - url: '/bootAuth/app', - payload: mockBootInfo - }); - - expect(response.statusCode).toBe(200); - const result = JSON.parse(response.payload); - expect(result.isAllowed).toBe(true); - expect(result.reason).toBe(''); - expect(mockCheckBoot).toHaveBeenCalledWith(mockBootInfo, false); - }); - - it('should reject oversized and non-hex measurements before backend use', async () => { - jest.clearAllMocks(); - for (const mrAggregated of ['0x' + 'ab'.repeat(33), 'not-hex']) { - const response = await app.inject({ - method: 'POST', - url: '/bootAuth/app', - payload: { ...mockBootInfo, mrAggregated } - }); - expect(response.statusCode).toBe(400); - expect(JSON.parse(response.payload)).toEqual({ isAllowed: false, reason: 'invalid authorization request', gatewayAppId: '' }); - } - expect(app.ethereum.checkBoot).not.toHaveBeenCalled(); - }); - - it('should return 400 for invalid boot info', async () => { - const response = await app.inject({ - method: 'POST', - url: '/bootAuth/app', - payload: { - // Missing required fields - mrAggregated: '0x1234' - } - }); - - expect(response.statusCode).toBe(400); - }); - }); - - describe('POST /bootAuth/kms', () => { - it('should return 200 when backend check passes', async () => { - // Mock successful response - const mockCheckBoot = jest.fn().mockResolvedValue({ - isAllowed: true, - reason: '', - gatewayAppId: '0x1234', - }); - app.ethereum.checkBoot = mockCheckBoot; - - const response = await app.inject({ - method: 'POST', - url: '/bootAuth/kms', - payload: mockBootInfo, - }); - - const result = JSON.parse(response.payload); - expect(response.statusCode).toBe(200); - expect(result.isAllowed).toBe(true); - expect(result.reason).toBe(''); - expect(mockCheckBoot).toHaveBeenCalledWith(mockBootInfo, true); - }); - - it('should handle backend errors gracefully', async () => { - // Mock error response - const mockCheckBoot = jest.fn().mockRejectedValue(new Error('Test backend error')); - app.ethereum.checkBoot = mockCheckBoot; - - const response = await app.inject({ - method: 'POST', - url: '/bootAuth/kms', - payload: mockBootInfo - }); - - expect(response.statusCode).toBe(200); - const result = JSON.parse(response.payload); - expect(result.isAllowed).toBe(false); - expect(result.reason).toBe('authorization backend unavailable'); - }); - }); -}); diff --git a/dstack/kms/auth-eth/src/main.ts b/dstack/kms/auth-eth/src/main.ts deleted file mode 100644 index cdbf2e7c52..0000000000 --- a/dstack/kms/auth-eth/src/main.ts +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-FileCopyrightText: © 2025 Phala Network -// -// SPDX-License-Identifier: Apache-2.0 - -import { config } from 'dotenv'; -import { build } from './server'; - -// Load environment variables -config(); - -async function main() { - try { - const port = process.env.PORT ? parseInt(process.env.PORT) : 8000; - const host = process.env.HOST || '127.0.0.1'; - - const server = await build(); - await server.listen({ port, host }); - console.log(`Server listening on ${host}:${port}`); - - // Handle graceful shutdown - const signals = ['SIGINT', 'SIGTERM']; - for (const signal of signals) { - process.on(signal, async () => { - try { - await server.close(); - process.exit(0); - } catch (err) { - console.error('Error during shutdown:', err); - process.exit(1); - } - }); - } - } catch (err) { - console.error('Error starting server:', err); - process.exit(1); - } -} - -main(); diff --git a/dstack/kms/auth-eth/src/server.ts b/dstack/kms/auth-eth/src/server.ts deleted file mode 100644 index 54dd143466..0000000000 --- a/dstack/kms/auth-eth/src/server.ts +++ /dev/null @@ -1,153 +0,0 @@ -// SPDX-FileCopyrightText: © 2025 Phala Network -// -// SPDX-License-Identifier: Apache-2.0 - -import fastify, { FastifyInstance } from 'fastify'; -import { EthereumBackend } from './ethereum'; -import { BootInfo, BootResponse } from './types'; -import { ethers } from 'ethers'; - -declare module 'fastify' { - interface FastifyInstance { - ethereum: EthereumBackend; - } -} - -export async function build(): Promise { - const server = fastify({ - logger: true - }); - - // Register schema for request/response validation - const hex = (bytes: number, description: string) => ({ - type: 'string', - pattern: `^(?:0x[0-9a-fA-F]{0,${bytes * 2}}|[0-9a-fA-F]{0,${bytes * 2}})$`, - description, - }); - - server.addSchema({ - $id: 'bootInfo', - type: 'object', - required: ['mrAggregated', 'osImageHash', 'appId', 'composeHash', 'instanceId', 'deviceId'], - properties: { - mrAggregated: hex(32, 'Aggregated MR measurement'), - osImageHash: hex(32, 'OS Image hash'), - appId: hex(20, 'Application ID'), - composeHash: hex(32, 'Compose hash'), - instanceId: hex(20, 'Instance ID'), - deviceId: hex(32, 'Device ID'), - tcbStatus: { type: 'string', maxLength: 128, default: '' }, - advisoryIds: { type: 'array', maxItems: 128, items: { type: 'string', maxLength: 256 }, default: [] }, - mrSystem: { ...hex(32, 'System MR measurement'), default: '' }, - } - }); - - server.addSchema({ - $id: 'bootResponse', - type: 'object', - required: ['isAllowed', 'reason', 'gatewayAppId'], - properties: { - isAllowed: { type: 'boolean' }, - reason: { type: 'string' }, - gatewayAppId: { type: 'string' }, - } - }); - - // Initialize backend - const rpcUrl = process.env.ETH_RPC_URL || 'http://localhost:8545'; - const kmsContractAddr = process.env.KMS_CONTRACT_ADDR || '0x0000000000000000000000000000000000000000'; - const provider = new ethers.JsonRpcProvider(rpcUrl); - server.decorate('ethereum', new EthereumBackend(provider, kmsContractAddr)); - - const publicRpcEndpoint = (value: string): string => { - try { - const endpoint = new URL(value); - return `${endpoint.protocol}//${endpoint.host}`; - } catch { - return 'configured'; - } - }; - const backendUnavailable = 'authorization backend unavailable'; - const invalidRequest = { isAllowed: false, reason: 'invalid authorization request', gatewayAppId: '' }; - - server.setErrorHandler((error, request, reply) => { - if (typeof error === 'object' && error !== null && 'validation' in error) { - return reply.code(400).send(invalidRequest); - } - request.log.error('authorization request failed'); - return reply.code(500).send({ status: 'error', message: backendUnavailable }); - }); - - server.get('/', async (_request, reply) => { - try { - const batch = await Promise.all([ - server.ethereum.getGatewayAppId(), - server.ethereum.getChainId(), - server.ethereum.getAppImplementation(), - ]); - return { - status: 'ok', - kmsContractAddr: kmsContractAddr, - ethRpcUrl: publicRpcEndpoint(rpcUrl), - gatewayAppId: batch[0], - chainId: batch[1], - appAuthImplementation: batch[2], // NOTE: for backward compatibility - appImplementation: batch[2], - }; - } catch { - _request.log.error('authorization backend health check failed'); - return reply.code(500).send({ status: 'error', message: backendUnavailable }); - } - }); - - // Define routes - server.post<{ - Body: BootInfo; - Reply: BootResponse; - }>('/bootAuth/app', { - schema: { - body: { $ref: 'bootInfo#' }, - response: { - 200: { $ref: 'bootResponse#' } - } - } - }, async (request, reply) => { - try { - return await server.ethereum.checkBoot(request.body, false); - } catch (error) { - request.log.error('application authorization backend failed'); - reply.code(200).send({ - isAllowed: false, - gatewayAppId: '', - reason: backendUnavailable - }); - } - }); - - server.post<{ - Body: BootInfo; - Reply: BootResponse; - }>('/bootAuth/kms', { - schema: { - body: { $ref: 'bootInfo#' }, - response: { - 200: { $ref: 'bootResponse#' } - } - } - }, async (request, reply) => { - try { - return await server.ethereum.checkBoot(request.body, true); - } catch (error) { - if (!(error instanceof Error && "Test backend error" == error.message)) { - request.log.error('KMS authorization backend failed'); - } - reply.code(200).send({ - isAllowed: false, - gatewayAppId: '', - reason: backendUnavailable - }); - } - }); - - return server; -} diff --git a/dstack/kms/auth-eth/src/types.ts b/dstack/kms/auth-eth/src/types.ts deleted file mode 100644 index fd1a891434..0000000000 --- a/dstack/kms/auth-eth/src/types.ts +++ /dev/null @@ -1,23 +0,0 @@ -// SPDX-FileCopyrightText: © 2025 Phala Network -// -// SPDX-License-Identifier: Apache-2.0 - -export interface BootInfo { - tcbStatus: string; - advisoryIds: string[]; - mrAggregated: string; - mrSystem: string; - osImageHash: string; - appId: string; - composeHash: string; - instanceId: string; - deviceId: string; -} - -export interface BootResponse { - isAllowed: boolean; - gatewayAppId: string; - reason: string; -} - -// Removed KMS_CONTRACT_ABI and APP_CONTRACT_ABI since we're using typechain types now diff --git a/dstack/kms/auth-eth/test/DstackApp.symbolic.t.sol b/dstack/kms/auth-eth/test/DstackApp.symbolic.t.sol index 2af3492f84..d6541b0546 100644 --- a/dstack/kms/auth-eth/test/DstackApp.symbolic.t.sol +++ b/dstack/kms/auth-eth/test/DstackApp.symbolic.t.sol @@ -111,18 +111,37 @@ contract DstackAppSymbolicTest is Test { assert(_upgradesDisabledFlag(address(app))); // base: flag is set bytes memory data; - if (which == 0) data = abi.encodeWithSelector(DstackApp.addComposeHash.selector, word); - else if (which == 1) data = abi.encodeWithSelector(DstackApp.removeComposeHash.selector, word); - else if (which == 2) data = abi.encodeWithSelector(DstackApp.addDevice.selector, word); - else if (which == 3) data = abi.encodeWithSelector(DstackApp.removeDevice.selector, word); - else if (which == 4) data = abi.encodeWithSelector(DstackApp.setAllowAnyDevice.selector, flag); - else if (which == 5) data = abi.encodeWithSelector(DstackApp.setRequireTcbUpToDate.selector, flag); - else if (which == 6) data = abi.encodeWithSelector(DstackApp.disableUpgrades.selector); - else if (which == 7) data = abi.encodeWithSelector(UUPSUpgradeable.upgradeToAndCall.selector, addr, ""); - else if (which == 8) data = abi.encodeWithSelector(Ownable2StepUpgradeable.transferOwnership.selector, addr); - else if (which == 9) data = abi.encodeWithSelector(Ownable2StepUpgradeable.acceptOwnership.selector); - else if (which == 10) data = abi.encodeWithSelector(OwnableUpgradeable.renounceOwnership.selector); - else return; // outside the enumerated mutating surface + if (which == 0) { + data = abi.encodeWithSelector(DstackApp.addComposeHashAtEpoch.selector, uint256(0), word); + } else if (which == 1) { + data = abi.encodeWithSelector(DstackApp.removeComposeHashAtEpoch.selector, uint256(0), word); + } else if (which == 2) { + data = abi.encodeWithSelector(DstackApp.addDeviceAtEpoch.selector, uint256(0), word); + } else if (which == 3) { + data = abi.encodeWithSelector(DstackApp.removeDeviceAtEpoch.selector, uint256(0), word); + } else if (which == 4) { + data = abi.encodeWithSelector(DstackApp.setAllowAnyDevice.selector, flag); + } else if (which == 5) { + data = abi.encodeWithSelector(DstackApp.setRequireTcbUpToDate.selector, flag); + } else if (which == 6) { + data = abi.encodeWithSelector(DstackApp.disableUpgrades.selector); + } else if (which == 7) { + data = abi.encodeWithSelector(UUPSUpgradeable.upgradeToAndCall.selector, addr, ""); + } else if (which == 8) { + data = abi.encodeWithSelector(Ownable2StepUpgradeable.transferOwnership.selector, addr); + } else if (which == 9) { + data = abi.encodeWithSelector(Ownable2StepUpgradeable.acceptOwnership.selector); + } else if (which == 10) { + data = abi.encodeWithSelector(OwnableUpgradeable.renounceOwnership.selector); + } else if (which == 11) { + data = abi.encodeWithSelector(DstackApp.setRequireLaunchTicket.selector, flag); + } else if (which == 12) { + data = abi.encodeWithSelector(DstackApp.addLaunchTicket.selector, word, ""); + } else if (which == 13) { + data = abi.encodeWithSelector(DstackApp.removeLaunchTicket.selector, word); + } else { + return; // outside the enumerated mutating surface + } vm.prank(caller); (bool ok,) = address(app).call(data); diff --git a/dstack/kms/auth-eth/test/DstackApp.t.sol b/dstack/kms/auth-eth/test/DstackApp.t.sol index 9f590d2e38..2f797718d2 100644 --- a/dstack/kms/auth-eth/test/DstackApp.t.sol +++ b/dstack/kms/auth-eth/test/DstackApp.t.sol @@ -76,7 +76,7 @@ contract DstackAppTest is Test { vm.expectEmit(true, true, true, true); emit ComposeHashAdded(hash); - app.addComposeHash(hash); + app.addComposeHashAtEpoch(0, hash); assertTrue(app.allowedComposeHashes(hash)); } @@ -84,13 +84,13 @@ contract DstackAppTest is Test { bytes32 hash = bytes32(uint256(123)); vm.startPrank(owner); - app.addComposeHash(hash); + app.addComposeHashAtEpoch(0, hash); assertTrue(app.allowedComposeHashes(hash)); vm.expectEmit(true, true, true, true); emit ComposeHashRemoved(hash); - app.removeComposeHash(hash); + app.removeComposeHashAtEpoch(0, hash); assertFalse(app.allowedComposeHashes(hash)); vm.stopPrank(); } @@ -102,7 +102,7 @@ contract DstackAppTest is Test { vm.expectEmit(true, true, true, true); emit DeviceAdded(deviceId); - app.addDevice(deviceId); + app.addDeviceAtEpoch(0, deviceId); assertTrue(app.allowedDeviceIds(deviceId)); } @@ -110,13 +110,13 @@ contract DstackAppTest is Test { bytes32 deviceId = bytes32(uint256(456)); vm.startPrank(owner); - app.addDevice(deviceId); + app.addDeviceAtEpoch(0, deviceId); assertTrue(app.allowedDeviceIds(deviceId)); vm.expectEmit(true, true, true, true); emit DeviceRemoved(deviceId); - app.removeDevice(deviceId); + app.removeDeviceAtEpoch(0, deviceId); assertFalse(app.allowedDeviceIds(deviceId)); vm.stopPrank(); } @@ -144,16 +144,16 @@ contract DstackAppTest is Test { vm.startPrank(user); vm.expectRevert(); - app.addComposeHash(hash); + app.addComposeHashAtEpoch(0, hash); vm.expectRevert(); - app.removeComposeHash(hash); + app.removeComposeHashAtEpoch(0, hash); vm.expectRevert(); - app.addDevice(deviceId); + app.addDeviceAtEpoch(0, deviceId); vm.expectRevert(); - app.removeDevice(deviceId); + app.removeDeviceAtEpoch(0, deviceId); vm.expectRevert(); app.setAllowAnyDevice(true); @@ -166,11 +166,11 @@ contract DstackAppTest is Test { bytes32 composeHash = bytes32(uint256(456)); vm.startPrank(owner); - app.addDevice(deviceId); - app.addComposeHash(composeHash); + app.addDeviceAtEpoch(0, deviceId); + app.addComposeHashAtEpoch(0, composeHash); vm.stopPrank(); - IAppAuth.AppBootInfo memory bootInfo = IAppAuth.AppBootInfo({ + IAppAuth.AppInfo memory bootInfo = IAppAuth.AppInfo({ appId: address(app), composeHash: composeHash, instanceId: address(0), @@ -208,11 +208,11 @@ contract DstackAppTest is Test { bytes32 unallowedHash = bytes32(uint256(789)); vm.startPrank(owner); - app.addDevice(deviceId); - app.addComposeHash(allowedHash); + app.addDeviceAtEpoch(0, deviceId); + app.addComposeHashAtEpoch(0, allowedHash); vm.stopPrank(); - IAppAuth.AppBootInfo memory bootInfo = IAppAuth.AppBootInfo({ + IAppAuth.AppInfo memory bootInfo = IAppAuth.AppInfo({ appId: address(app), composeHash: unallowedHash, instanceId: address(0), @@ -263,14 +263,14 @@ contract DstackAppTest is Test { bytes32 composeHash = bytes32(uint256(456)); vm.startPrank(owner); - app.addDevice(deviceId); - app.addComposeHash(composeHash); + app.addDeviceAtEpoch(0, deviceId); + app.addComposeHashAtEpoch(0, composeHash); vm.stopPrank(); string[] memory advisoryIds = new string[](1); advisoryIds[0] = "INTEL-SA-00614"; - IAppAuth.AppBootInfo memory bootInfo = IAppAuth.AppBootInfo({ + IAppAuth.AppInfo memory bootInfo = IAppAuth.AppInfo({ appId: address(app), composeHash: composeHash, instanceId: address(0), @@ -282,8 +282,8 @@ contract DstackAppTest is Test { advisoryIds: advisoryIds }); - // Legacy 5-arg init skips the TCB check (specification.md §3.4). This deliberately - // diverges from auth-simple's strict default; see auth-simple/index.test.ts. + // Legacy 5-arg init skips the TCB check (specification.md §3.4), like dstack-auth + // without `allowedTcbStatuses`. (bool allowed, string memory reason) = app.isAppAllowed(bootInfo); assertTrue(allowed); @@ -318,7 +318,7 @@ contract DstackAppTest is Test { assertTrue(tcbApp.allowedDeviceIds(deviceId)); assertTrue(tcbApp.allowedComposeHashes(composeHash)); - IAppAuth.AppBootInfo memory bootInfo = IAppAuth.AppBootInfo({ + IAppAuth.AppInfo memory bootInfo = IAppAuth.AppInfo({ appId: address(tcbApp), composeHash: composeHash, instanceId: address(0), @@ -352,8 +352,8 @@ contract DstackAppTest is Test { // Test IAppAuth interface assertTrue(app.supportsInterface(0x1e079198)); - // Test IAppAuthBasicManagement interface - assertTrue(app.supportsInterface(0x8fd37527)); + // IAppAuthBasicManagement, whose epoch-less setters are gone + assertFalse(app.supportsInterface(0x8fd37527)); // Test IERC165 interface assertTrue(app.supportsInterface(0x01ffc9a7)); @@ -394,19 +394,428 @@ contract DstackAppTest is Test { // owner-only authority follows the new owner vm.prank(owner); vm.expectRevert(abi.encodeWithSignature("OwnableUnauthorizedAccount(address)", owner)); - app.addComposeHash(bytes32(uint256(1))); + app.addComposeHashAtEpoch(0, bytes32(uint256(1))); vm.prank(newOwner); - app.addComposeHash(bytes32(uint256(1))); + app.addComposeHashAtEpoch(0, bytes32(uint256(1))); assertTrue(app.allowedComposeHashes(bytes32(uint256(1)))); } function test_AddZeroValuedPolicyEntriesIsRejected() public { vm.startPrank(owner); vm.expectRevert("invalid compose hash"); - app.addComposeHash(bytes32(0)); + app.addComposeHashAtEpoch(0, bytes32(0)); vm.expectRevert("invalid device ID"); - app.addDevice(bytes32(0)); + app.addDeviceAtEpoch(0, bytes32(0)); vm.stopPrank(); } + + function epochInfo() internal view returns (IAppAuth.AppInfo memory info) { + info.appId = address(app); + info.composeHash = bytes32(uint256(1)); + info.deviceId = bytes32(uint256(2)); + info.tcbStatus = "UpToDate"; + } + + function appRequest( + IAppAuth.AppInfo memory info, + OptionalUint256 memory appEpoch, + bytes32 operation + ) + internal + pure + returns (AuthorizationRequest memory) + { + return AuthorizationRequest(info, operation, appEpoch, OptionalUint256(false, 0), "dstack-tdx", bytes32(0)); + } + + function authorizeAt( + IAppAuth.AppInfo memory info, + uint256 epoch, + bytes32 operation + ) + internal + view + returns (bool, string memory) + { + AuthorizationResult memory result = app.authorizeApp(appRequest(info, OptionalUint256(true, epoch), operation)); + return (result.authorized, result.rejectionReason); + } + + function test_TeeVariantsAreUnrestrictedUntilRestrictedAndCoverEveryEpoch() public { + IAppAuth.AppInfo memory info = epochInfo(); + vm.startPrank(owner); + app.addComposeHashAtEpochs(0, 1, info.composeHash); + app.addDeviceAtEpochs(0, 1, info.deviceId); + vm.stopPrank(); + AuthorizationRequest memory request = appRequest(info, OptionalUint256(true, 0), keccak256("app_get_key")); + request.teeVariant = "dstack-amd-sev-snp"; + assertTrue(app.allowAnyTeeVariant()); + assertTrue(app.authorizeApp(request).authorized); + + string[] memory tdx = new string[](1); + tdx[0] = "dstack-tdx"; + vm.startPrank(owner); + app.setAllowedTeeVariants(tdx); + // The list applies only once the policy is restricted. + assertTrue(app.authorizeApp(request).authorized); + app.setAllowAnyTeeVariant(false); + vm.stopPrank(); + assertEq(app.allowedTeeVariants()[0], "dstack-tdx"); + assertEq(app.authorizeApp(request).rejectionReason, "TEE variant not allowed"); + (bool allowed, string memory reason) = app.isAppAllowed(info); + assertFalse(allowed); + assertEq(reason, "TEE variant not allowed"); + request.teeVariant = "dstack-tdx"; + assertTrue(app.authorizeApp(request).authorized); + + // The policy covers every app epoch. + vm.prank(owner); + app.advanceAppEpoch(0); + request.requestedAppEpoch = OptionalUint256(true, 1); + assertTrue(app.authorizeApp(request).authorized); + request.teeVariant = "dstack-amd-sev-snp"; + assertEq(app.authorizeApp(request).rejectionReason, "TEE variant not allowed"); + + // Only known platforms can be listed, and an empty list admits none. + string[] memory unknown = new string[](1); + unknown[0] = "dstack-unknown"; + vm.startPrank(owner); + vm.expectRevert("unknown TEE variant"); + app.setAllowedTeeVariants(unknown); + app.setAllowedTeeVariants(new string[](0)); + vm.stopPrank(); + assertEq(app.allowedTeeVariants().length, 0); + request.teeVariant = "dstack-tdx"; + assertEq(app.authorizeApp(request).rejectionReason, "TEE variant not allowed"); + + vm.startPrank(user); + bytes memory unauthorized = abi.encodeWithSelector(OwnableUpgradeable.OwnableUnauthorizedAccount.selector, user); + vm.expectRevert(unauthorized); + app.setAllowAnyTeeVariant(true); + vm.expectRevert(unauthorized); + app.setAllowedTeeVariants(tdx); + vm.stopPrank(); + } + + function test_LaunchTicketGatesEveryEpochOnceRequired() public { + IAppAuth.AppInfo memory info = epochInfo(); + bytes32 ticket = sha256("dstack-launch-ticket/v1:prod"); + vm.startPrank(owner); + app.addComposeHashAtEpochs(0, 1, info.composeHash); + app.addDeviceAtEpochs(0, 1, info.deviceId); + vm.stopPrank(); + AuthorizationRequest memory request = appRequest(info, OptionalUint256(true, 0), keccak256("app_get_key")); + // Not required: any ticket, or none, is admitted. + assertTrue(app.authorizeApp(request).authorized); + + vm.startPrank(owner); + app.setRequireLaunchTicket(true); + vm.expectRevert("invalid launch ticket hash"); + app.addLaunchTicket(bytes32(0), "zero"); + app.addLaunchTicket(ticket, "prod"); + vm.stopPrank(); + assertEq(app.launchTickets().length, 1); + assertEq(app.launchTickets()[0], ticket); + assertEq(app.authorizeApp(request).rejectionReason, "Invalid launch ticket"); + (bool allowed, string memory reason) = app.isAppAllowed(info); + assertFalse(allowed); + assertEq(reason, "Invalid launch ticket"); + + request.launchTicketHash = ticket; + assertTrue(app.authorizeApp(request).authorized); + request.operation = keccak256("app_get_cert"); + assertTrue(app.authorizeApp(request).authorized); + // The allowlist covers every app epoch. + vm.prank(owner); + app.advanceAppEpoch(0); + request.requestedAppEpoch = OptionalUint256(true, 1); + assertTrue(app.authorizeApp(request).authorized); + + vm.prank(owner); + app.removeLaunchTicket(ticket); + assertEq(app.launchTickets().length, 0); + assertEq(app.authorizeApp(request).rejectionReason, "Invalid launch ticket"); + + vm.startPrank(user); + bytes memory unauthorized = abi.encodeWithSelector(OwnableUpgradeable.OwnableUnauthorizedAccount.selector, user); + vm.expectRevert(unauthorized); + app.setRequireLaunchTicket(false); + vm.expectRevert(unauthorized); + app.addLaunchTicket(ticket, "prod"); + vm.expectRevert(unauthorized); + app.removeLaunchTicket(ticket); + vm.stopPrank(); + } + + function test_AuthorizeAppOwnsOperationScopeAndAppEpoch() public { + IAppAuth.AppInfo memory info = epochInfo(); + vm.startPrank(owner); + app.addComposeHashAtEpoch(0, info.composeHash); + app.addDeviceAtEpoch(0, info.deviceId); + app.advanceAppEpoch(0); + vm.stopPrank(); + + AuthorizationResult memory result = + app.authorizeApp(appRequest(info, OptionalUint256(true, 0), keccak256("kms_serve"))); + assertFalse(result.authorized); + assertEq(result.rejectionReason, "Invalid authorization operation"); + assertEq(result.currentAppEpoch, 1); + + result = app.authorizeApp(appRequest(info, OptionalUint256(true, 2), keccak256("app_get_key"))); + assertFalse(result.authorized); + assertEq(result.rejectionReason, "Requested app epoch is not active"); + assertEq(result.currentAppEpoch, 1); + + // Omission selects the current epoch, whose row is still empty. + result = app.authorizeApp(appRequest(info, OptionalUint256(false, 0), keccak256("app_get_key"))); + assertFalse(result.authorized); + assertEq(result.rejectionReason, "Compose hash not allowed"); + assertEq(result.currentAppEpoch, 1); + + result = app.authorizeApp(appRequest(info, OptionalUint256(true, 0), keccak256("app_get_key"))); + assertTrue(result.authorized); + assertEq(result.rejectionReason, ""); + assertEq(result.currentAppEpoch, 1); + // Gateway and root epoch fields belong to the KMS. + assertEq(result.gatewayAppId, ""); + assertEq(result.currentRootEpoch, 0); + assertEq(result.currentRootEpochHash, bytes32(0)); + } + + function test_AppOperationsSharePolicyButRejectUnknownOrKmsOperations() public { + IAppAuth.AppInfo memory info = epochInfo(); + vm.startPrank(owner); + app.addComposeHashAtEpoch(0, info.composeHash); + app.addDeviceAtEpoch(0, info.deviceId); + vm.stopPrank(); + (bool allowed,) = authorizeAt(info, 0, keccak256("app_get_cert")); + assertTrue(allowed); + (allowed,) = authorizeAt(info, 0, keccak256("app_get_key")); + assertTrue(allowed); + (allowed,) = authorizeAt(info, 0, keccak256("kms_import_keys")); + assertFalse(allowed); + (allowed,) = authorizeAt(info, 0, bytes32(0)); + assertFalse(allowed); + } + + function test_AppEpochRowsAreIndependentAndDefaultsUseCurrentEpoch() public { + IAppAuth.AppInfo memory info = epochInfo(); + vm.startPrank(owner); + app.addComposeHashAtEpoch(0, info.composeHash); + app.addDeviceAtEpoch(0, info.deviceId); + app.advanceAppEpoch(0); + bool allowed = authorizeCurrent(info); + assertFalse(allowed); + (allowed,) = authorizeAt(info, 0, keccak256("app_get_key")); + assertTrue(allowed); + app.addComposeHashAtEpoch(1, info.composeHash); + allowed = authorizeCurrent(info); + assertFalse(allowed, "each material must be approved in the selected row"); + app.addDeviceAtEpoch(1, info.deviceId); + allowed = authorizeCurrent(info); + assertTrue(allowed); + app.removeComposeHashAtEpoch(1, info.composeHash); + assertFalse(app.allowedComposeHashesAtEpoch(1, info.composeHash)); + assertTrue(app.allowedComposeHashes(info.composeHash)); + (allowed,) = authorizeAt(info, 0, keccak256("app_get_key")); + assertTrue(allowed); + app.addComposeHashAtEpoch(1, info.composeHash); + app.removeDeviceAtEpoch(0, info.deviceId); + assertFalse(app.allowedDeviceIds(info.deviceId)); + (allowed,) = authorizeAt(info, 0, keccak256("app_get_key")); + assertFalse(allowed); + allowed = authorizeCurrent(info); + assertTrue(allowed, "revoking epoch zero must not revoke epoch one"); + (allowed,) = authorizeAt(info, 2, keccak256("app_get_key")); + assertFalse(allowed); + vm.stopPrank(); + } + + function test_NewImageCanBeExplicitlyAddedToOldRowForHandover() public { + IAppAuth.AppInfo memory oldInfo = epochInfo(); + IAppAuth.AppInfo memory newInfo = epochInfo(); + newInfo.composeHash = bytes32(uint256(3)); + vm.startPrank(owner); + app.addComposeHashAtEpoch(0, oldInfo.composeHash); + app.addDeviceAtEpoch(0, oldInfo.deviceId); + app.advanceAppEpoch(0); + app.addComposeHashAtEpoch(1, newInfo.composeHash); + app.addDeviceAtEpoch(1, newInfo.deviceId); + (bool allowed,) = authorizeAt(newInfo, 0, keccak256("app_get_key")); + assertFalse(allowed, "new epoch approval must not imply historical access"); + app.addComposeHashAtEpoch(0, newInfo.composeHash); + (allowed,) = authorizeAt(newInfo, 0, keccak256("app_get_key")); + assertTrue(allowed); + allowed = authorizeCurrent(oldInfo); + assertFalse(allowed, "old image cannot read new keys"); + app.removeComposeHashAtEpoch(0, oldInfo.composeHash); + (allowed,) = authorizeAt(oldInfo, 0, keccak256("app_get_key")); + assertFalse(allowed); + allowed = authorizeCurrent(newInfo); + assertTrue(allowed); + vm.stopPrank(); + } + + function test_AllowAnyDeviceCoversEveryAppEpoch() public { + IAppAuth.AppInfo memory info = epochInfo(); + vm.startPrank(owner); + app.addComposeHashAtEpochs(0, 1, info.composeHash); + app.advanceAppEpoch(0); + assertFalse(authorizeCurrent(info)); + app.setAllowAnyDevice(true); + (bool allowed,) = authorizeAt(info, 0, keccak256("app_get_key")); + assertTrue(allowed); + assertTrue(authorizeCurrent(info)); + + // Clearing it leaves every epoch to its own device row at once. + app.addDeviceAtEpoch(1, info.deviceId); + app.setAllowAnyDevice(false); + (allowed,) = authorizeAt(info, 0, keccak256("app_get_key")); + assertFalse(allowed); + assertTrue(authorizeCurrent(info)); + vm.stopPrank(); + } + + function authorizeCurrent(IAppAuth.AppInfo memory info) internal view returns (bool allowed) { + (allowed,) = authorizeAt(info, app.currentAppEpoch(), keccak256("app_get_key")); + } + + function test_LegacyAppCheckRefusesOnceTheAppEpochAdvances() public { + IAppAuth.AppInfo memory info = epochInfo(); + vm.startPrank(owner); + app.addComposeHashAtEpochs(0, 1, info.composeHash); + app.addDeviceAtEpochs(0, 1, info.deviceId); + // At epoch 0 the legacy check reads row 0, as in v0.6.0. + (bool allowed, string memory reason) = app.isAppAllowed(info); + assertTrue(allowed, reason); + app.removeComposeHashAtEpoch(1, info.composeHash); + (allowed,) = app.isAppAllowed(info); + assertTrue(allowed, "the prepared next row does not affect the legacy check"); + app.addComposeHashAtEpoch(1, info.composeHash); + + app.advanceAppEpoch(0); + (allowed, reason) = app.isAppAllowed(info); + assertFalse(allowed); + assertEq(reason, "App epoch requires epoch-aware authorization"); + // Epoch-aware callers keep working at both epochs. + (allowed,) = authorizeAt(info, 1, keccak256("app_get_key")); + assertTrue(allowed); + (allowed,) = authorizeAt(info, 0, keccak256("app_get_key")); + assertTrue(allowed); + vm.stopPrank(); + } + + function test_NextAppEpochRowCanBePreparedBeforeAdvancing() public { + IAppAuth.AppInfo memory info = epochInfo(); + IAppAuth.AppInfo memory next = epochInfo(); + next.composeHash = bytes32(uint256(3)); + vm.startPrank(owner); + app.addComposeHashAtEpoch(0, info.composeHash); + app.addDeviceAtEpoch(0, info.deviceId); + app.addComposeHashAtEpoch(1, next.composeHash); + app.addDeviceAtEpoch(1, next.deviceId); + // Preparing the next row leaves the current one as it was. + bool allowed = authorizeCurrent(info); + assertTrue(allowed); + allowed = authorizeCurrent(next); + assertFalse(allowed); + (allowed,) = authorizeAt(next, 1, keccak256("app_get_key")); + assertFalse(allowed, "the next row is not active before advancing"); + vm.expectRevert("Unknown app epoch"); + app.addComposeHashAtEpoch(2, next.composeHash); + + app.advanceAppEpoch(0); + allowed = authorizeCurrent(next); + assertTrue(allowed, "a prepared row authorizes as soon as it is current"); + (allowed,) = authorizeAt(next, 1, keccak256("app_get_key")); + assertTrue(allowed); + (allowed,) = authorizeAt(info, 0, keccak256("app_get_key")); + assertTrue(allowed); + app.addComposeHashAtEpoch(2, next.composeHash); + vm.stopPrank(); + } + + function test_RangeAppSettersChangeEveryRowInRange() public { + IAppAuth.AppInfo memory info = epochInfo(); + vm.startPrank(owner); + app.advanceAppEpoch(0); + app.addComposeHashAtEpochs(0, 2, info.composeHash); + app.addDeviceAtEpochs(0, 2, info.deviceId); + for (uint256 epoch = 0; epoch <= 2; ++epoch) { + assertTrue(app.allowedComposeHashesAtEpoch(epoch, info.composeHash)); + assertTrue(app.allowedDeviceIdsAtEpoch(epoch, info.deviceId)); + } + (bool allowed,) = authorizeAt(info, 0, keccak256("app_get_key")); + assertTrue(allowed); + + // Removing from every row revokes at every selectable epoch. + app.removeComposeHashAtEpochs(0, 2, info.composeHash); + app.removeDeviceAtEpochs(0, 2, info.deviceId); + for (uint256 epoch = 0; epoch <= 2; ++epoch) { + assertFalse(app.allowedComposeHashesAtEpoch(epoch, info.composeHash)); + assertFalse(app.allowedDeviceIdsAtEpoch(epoch, info.deviceId)); + } + (allowed,) = authorizeAt(info, 0, keccak256("app_get_key")); + assertFalse(allowed); + assertFalse(authorizeCurrent(info)); + + vm.expectRevert("Invalid app epoch range"); + app.removeComposeHashAtEpochs(1, 0, info.composeHash); + vm.expectRevert("Unknown app epoch"); + app.removeComposeHashAtEpochs(0, 3, info.composeHash); + vm.expectRevert("invalid compose hash"); + app.addComposeHashAtEpochs(0, 1, bytes32(0)); + vm.stopPrank(); + } + + function test_ExplicitAppEpochSettersRequireOwnerAndKnownEpoch() public { + vm.startPrank(owner); + // Only the current row and the next one can be written. + vm.expectRevert("Unknown app epoch"); + app.addComposeHashAtEpoch(2, bytes32(uint256(1))); + vm.expectRevert("Unknown app epoch"); + app.removeComposeHashAtEpoch(2, bytes32(uint256(1))); + vm.expectRevert("Unknown app epoch"); + app.addDeviceAtEpoch(2, bytes32(uint256(1))); + vm.expectRevert("Unknown app epoch"); + app.removeDeviceAtEpoch(2, bytes32(uint256(1))); + vm.stopPrank(); + bytes memory unauthorized = abi.encodeWithSelector(OwnableUpgradeable.OwnableUnauthorizedAccount.selector, user); + vm.startPrank(user); + vm.expectRevert(unauthorized); + app.addComposeHashAtEpoch(0, bytes32(uint256(1))); + vm.expectRevert(unauthorized); + app.removeComposeHashAtEpoch(0, bytes32(uint256(1))); + vm.expectRevert(unauthorized); + app.addDeviceAtEpoch(0, bytes32(uint256(1))); + vm.expectRevert(unauthorized); + app.removeDeviceAtEpoch(0, bytes32(uint256(1))); + vm.expectRevert(unauthorized); + app.setAllowAnyDevice(true); + vm.stopPrank(); + } + + function test_epoch_auth_interface_combines_discovery_and_authorization() public view { + bytes4 combined = IAppEpochAuth.currentAppEpoch.selector ^ IAppEpochAuth.authorizeApp.selector; + assertEq(bytes32(type(IAppEpochAuth).interfaceId), bytes32(combined)); + assertTrue(app.supportsInterface(combined)); + assertFalse(app.supportsInterface(IAppEpochAuth.currentAppEpoch.selector)); + assertFalse(app.supportsInterface(IAppEpochAuth.authorizeApp.selector)); + } + + function testFuzz_AppAuthorizationMatchesOnlyTheSelectedRow(uint8 approved, uint8 requested) public { + uint256 row = bound(approved, 0, 4); + uint256 selected = bound(requested, 0, 6); + IAppAuth.AppInfo memory info = epochInfo(); + vm.startPrank(owner); + for (uint256 i; i < 5; i++) { + app.advanceAppEpoch(i); + } + app.addComposeHashAtEpoch(row, info.composeHash); + app.addDeviceAtEpoch(row, info.deviceId); + vm.stopPrank(); + (bool allowed,) = authorizeAt(info, selected, keccak256("app_get_key")); + assertEq(allowed, selected == row); + } } diff --git a/dstack/kms/auth-eth/test/DstackAppEpoch.symbolic.t.sol b/dstack/kms/auth-eth/test/DstackAppEpoch.symbolic.t.sol new file mode 100644 index 0000000000..9282247110 --- /dev/null +++ b/dstack/kms/auth-eth/test/DstackAppEpoch.symbolic.t.sol @@ -0,0 +1,406 @@ +/* + * SPDX-FileCopyrightText: © 2026 Phala Network + * + * SPDX-License-Identifier: Apache-2.0 + */ + +pragma solidity ^0.8.24; + +import "forge-std/Test.sol"; +import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol"; +import "../contracts/AuthorizationOperation.sol"; +import "../contracts/DstackApp.sol"; + +function _appAuth( + DstackApp target, + IAppAuth.AppInfo memory info, + uint256 epoch, + bytes32 operation +) + view + returns (bool, string memory) +{ + AuthorizationResult memory result = target.authorizeApp( + AuthorizationRequest( + info, operation, OptionalUint256(true, epoch), OptionalUint256(false, 0), "dstack-tdx", bytes32(0) + ) + ); + return (result.authorized, result.rejectionReason); +} + +/// @notice Halmos symbolic tests for DstackApp app epochs. +/// +/// Halmos has no symbolic storage, so tests that quantify over policy states +/// first apply one symbolic owner write on top of setUp's concrete state. +/// DstackApp reads only the compose hash, device ID and TCB status of an +/// AppInfo, so those are the symbolic inputs; the remaining fields stay zero. +/// +/// Run with `halmos --contract DstackAppEpochSymbolicTest`. +/// @custom:halmos --loop 5 +contract DstackAppEpochSymbolicTest is Test { + DstackApp internal app; + address internal constant OWNER = address(0xA11CE); + uint256 internal constant POLICY_SETTERS = 8; + + function setUp() public { + DstackApp impl = new DstackApp(); + bytes memory initData = abi.encodeWithSignature( + "initialize(address,bool,bool,bytes32,bytes32)", OWNER, false, false, bytes32(0), bytes32(0) + ); + app = DstackApp(address(new ERC1967Proxy(address(impl), initData))); + // Epoch 0 keeps the legacy storage fields; epochs 1 and 2 use the + // per-epoch maps. Each epoch admits some app so that decisions can be + // allowed as well as denied. + vm.startPrank(OWNER); + app.addComposeHashAtEpoch(0, bytes32(uint256(0xc0))); + app.addDeviceAtEpoch(0, bytes32(uint256(0xd0))); + app.advanceAppEpoch(0); + app.addComposeHashAtEpoch(1, bytes32(uint256(0xc1))); + app.addDeviceAtEpoch(1, bytes32(uint256(0xd1))); + app.advanceAppEpoch(1); + app.addComposeHashAtEpoch(2, bytes32(uint256(0xc2))); + app.addDeviceAtEpoch(2, bytes32(uint256(0xd2))); + vm.stopPrank(); + } + + /// Calldata of one epoch-scoped policy setter: 0-3 write the row of `epoch`, + /// 4-7 are their range forms, writing every row from `epoch` through the next one. + function _policyCall(uint256 which, uint256 epoch, bytes32 word) internal view returns (bytes memory) { + return _rangePolicyCall(which, epoch, app.currentAppEpoch() + 1, word); + } + + /// As _policyCall, with the range setters writing `epoch` through `next`. + function _rangePolicyCall( + uint256 which, + uint256 epoch, + uint256 next, + bytes32 word + ) + internal + pure + returns (bytes memory data) + { + if (which == 0) data = abi.encodeCall(DstackApp.addComposeHashAtEpoch, (epoch, word)); + else if (which == 1) data = abi.encodeCall(DstackApp.removeComposeHashAtEpoch, (epoch, word)); + else if (which == 2) data = abi.encodeCall(DstackApp.addDeviceAtEpoch, (epoch, word)); + else if (which == 3) data = abi.encodeCall(DstackApp.removeDeviceAtEpoch, (epoch, word)); + else if (which == 4) data = abi.encodeCall(DstackApp.addComposeHashAtEpochs, (epoch, next, word)); + else if (which == 5) data = abi.encodeCall(DstackApp.removeComposeHashAtEpochs, (epoch, next, word)); + else if (which == 6) data = abi.encodeCall(DstackApp.addDeviceAtEpochs, (epoch, next, word)); + else data = abi.encodeCall(DstackApp.removeDeviceAtEpochs, (epoch, next, word)); + } + + function _ownerPolicyWrite(uint256 which, uint256 epoch, bytes32 word) internal { + if (which >= POLICY_SETTERS) return; + bytes memory data = _policyCall(which, epoch, word); + vm.prank(OWNER); + (bool ok,) = address(app).call(data); + ok; // a reverted write leaves the setUp state, which is also a valid pre-state + } + + function _info( + bytes32 composeHash, + bytes32 deviceId, + bool upToDate + ) + internal + pure + returns (IAppAuth.AppInfo memory info) + { + info.composeHash = composeHash; + info.deviceId = deviceId; + info.tcbStatus = upToDate ? "UpToDate" : "OutOfDate"; + } + + function _decision(IAppAuth.AppInfo memory info, uint256 epoch) internal view returns (bool, bytes32) { + (bool allowed, string memory reason) = _appAuth(app, info, epoch, AuthorizationOperation.APP_GET_KEY); + return (allowed, keccak256(bytes(reason))); + } + + // --------------------------------------------------------------- + // The app epoch never decreases, and only the owner's + // advanceAppEpoch(current) moves it, by exactly one. + // --------------------------------------------------------------- + + function check_AppEpoch_StepMonotonic( + address caller, + uint256 which, + uint256 epoch, + bytes32 word, + bool flag, + address addr + ) + external + { + uint256 before = app.currentAppEpoch(); + + bytes memory data; + if (which < POLICY_SETTERS) data = _policyCall(which, epoch, word); + else if (which == 8) data = abi.encodeCall(DstackApp.setAllowAnyDevice, (flag)); + else if (which == 9) data = abi.encodeCall(DstackApp.advanceAppEpoch, (epoch)); + else if (which == 10) data = abi.encodeCall(DstackApp.setRequireTcbUpToDate, (flag)); + else if (which == 11) data = abi.encodeCall(DstackApp.disableUpgrades, ()); + else if (which == 12) data = abi.encodeCall(UUPSUpgradeable.upgradeToAndCall, (addr, "")); + else if (which == 13) data = abi.encodeCall(Ownable2StepUpgradeable.transferOwnership, (addr)); + else if (which == 14) data = abi.encodeCall(Ownable2StepUpgradeable.acceptOwnership, ()); + else if (which == 15) data = abi.encodeCall(OwnableUpgradeable.renounceOwnership, ()); + else if (which == 16) data = abi.encodeCall(DstackApp.setRequireLaunchTicket, (flag)); + else if (which == 17) data = abi.encodeCall(DstackApp.addLaunchTicket, (word, "")); + else if (which == 18) data = abi.encodeCall(DstackApp.removeLaunchTicket, (word)); + else return; + + vm.prank(caller); + (bool ok,) = address(app).call(data); + ok; + + uint256 afterEpoch = app.currentAppEpoch(); + if (afterEpoch != before) { + assert(afterEpoch == before + 1); + assert(caller == OWNER && which == 9 && epoch == before); + } + } + + // --------------------------------------------------------------- + // No caller can write policy for an epoch that is not active yet. + // --------------------------------------------------------------- + + function check_PolicyWrite_RejectsEpochPastNext( + address caller, + uint256 which, + uint256 epoch, + uint256 to, + bytes32 word + ) + external + { + vm.assume(which < POLICY_SETTERS && (which < 4 ? epoch : to) > app.currentAppEpoch() + 1); + bytes memory data = _rangePolicyCall(which, epoch, to, word); + vm.prank(caller); + (bool ok,) = address(app).call(data); + assert(!ok); + } + + // --------------------------------------------------------------- + // An epoch that is not active is never authorized, and only app + // operations are authorized. + // --------------------------------------------------------------- + + function check_AuthorizeApp_RejectsInactiveEpochAndForeignOperation( + uint256 which, + uint256 writeEpoch, + bytes32 word, + bytes32 composeHash, + bytes32 deviceId, + bool upToDate, + uint256 epoch, + bytes32 operation + ) + external + { + _ownerPolicyWrite(which, writeEpoch, word); + IAppAuth.AppInfo memory info = _info(composeHash, deviceId, upToDate); + vm.assume(epoch > app.currentAppEpoch() || !AuthorizationOperation.isApp(operation)); + (bool allowed,) = _appAuth(app, info, epoch, operation); + assert(!allowed); + } + + // --------------------------------------------------------------- + // The legacy IAppAuth entry point decides exactly as the + // epoch-aware one at the current epoch, never an older policy. + // --------------------------------------------------------------- + + function check_IsAppAllowed_RefusesAtNonzeroEpoch( + uint256 which, + uint256 writeEpoch, + bytes32 word, + bytes32 composeHash, + bytes32 deviceId, + bool upToDate + ) + external + { + _ownerPolicyWrite(which, writeEpoch, word); + (bool allowed, string memory reason) = app.isAppAllowed(_info(composeHash, deviceId, upToDate)); + assert(!allowed); + assert(keccak256(bytes(reason)) == keccak256("App epoch requires epoch-aware authorization")); + } + + function check_IsAppAllowed_EqualsEpochZeroDecisionBeforeAdvance( + uint256 which, + uint256 writeEpoch, + bytes32 word, + bool anyDevice, + bytes32 composeHash, + bytes32 deviceId, + bool upToDate + ) + external + { + bytes memory initData = abi.encodeWithSignature( + "initialize(address,bool,bool,bytes32,bytes32)", OWNER, false, false, bytes32(0), bytes32(0) + ); + app = DstackApp(address(new ERC1967Proxy(address(new DstackApp()), initData))); + vm.startPrank(OWNER); + app.addComposeHashAtEpoch(0, bytes32(uint256(0xc0))); + app.addDeviceAtEpoch(0, bytes32(uint256(0xd0))); + // A prepared next row must not leak into the legacy decision. + app.addComposeHashAtEpoch(1, bytes32(uint256(0xc1))); + app.addDeviceAtEpoch(1, bytes32(uint256(0xd1))); + app.setAllowAnyDevice(anyDevice); + vm.stopPrank(); + _ownerPolicyWrite(which, writeEpoch, word); + IAppAuth.AppInfo memory info = _info(composeHash, deviceId, upToDate); + (bool allowed, string memory reason) = app.isAppAllowed(info); + (bool expected, bytes32 expectedReason) = _decision(info, 0); + assert(allowed == expected && keccak256(bytes(reason)) == expectedReason); + } + + // --------------------------------------------------------------- + // Epoch isolation: a policy write never changes an authorization decision + // at an epoch it did not write, including epoch 0's legacy fields. + // --------------------------------------------------------------- + + function check_PolicyWrite_PreservesOtherEpochDecisions( + uint256 which, + uint256 writeEpoch, + uint256 writeTo, + bytes32 word, + bytes32 composeHash, + bytes32 deviceId, + bool upToDate, + uint256 epoch + ) + external + { + vm.assume(which < POLICY_SETTERS); + vm.assume(which < 4 ? writeEpoch != epoch : epoch < writeEpoch || epoch > writeTo); + bytes memory data = _rangePolicyCall(which, writeEpoch, writeTo, word); + + IAppAuth.AppInfo memory info = _info(composeHash, deviceId, upToDate); + (bool allowedBefore, bytes32 reasonBefore) = _decision(info, epoch); + vm.prank(OWNER); + (bool ok,) = address(app).call(data); + ok; + (bool allowedAfter, bytes32 reasonAfter) = _decision(info, epoch); + + assert(allowedBefore == allowedAfter && reasonBefore == reasonAfter); + } + + // A TEE platform policy only ever narrows a decision: once restricted, a + // request passes exactly when it passes unrestricted and names a listed platform. + function check_TeeVariantPolicy_NarrowsDecision( + bool restrict, + bool listed, + bytes32 composeHash, + bytes32 deviceId, + bool upToDate, + uint256 epoch + ) + external + { + IAppAuth.AppInfo memory info = _info(composeHash, deviceId, upToDate); + (bool unrestricted,) = _appAuth(app, info, epoch, AuthorizationOperation.APP_GET_KEY); + string[] memory tdx = new string[](1); + tdx[0] = "dstack-tdx"; + vm.startPrank(OWNER); + app.setAllowedTeeVariants(tdx); + app.setAllowAnyTeeVariant(!restrict); + vm.stopPrank(); + AuthorizationResult memory result = app.authorizeApp( + AuthorizationRequest( + info, + AuthorizationOperation.APP_GET_KEY, + OptionalUint256(true, epoch), + OptionalUint256(false, 0), + listed ? "dstack-tdx" : "dstack-amd-sev-snp", + bytes32(0) + ) + ); + assert(result.authorized == (unrestricted && (!restrict || listed))); + } + + function check_AuthorizeApp_MatchesPolicy( + uint256 which, + uint256 writeEpoch, + bytes32 word, + bool anyDevice, + bool tcbFlag, + bytes32 composeHash, + bytes32 deviceId, + bool upToDate, + uint256 epoch, + bool getCert + ) + external + { + vm.startPrank(OWNER); + app.setRequireTcbUpToDate(tcbFlag); + app.setAllowAnyDevice(anyDevice); + vm.stopPrank(); + _ownerPolicyWrite(which, writeEpoch, word); + IAppAuth.AppInfo memory info = _info(composeHash, deviceId, upToDate); + bytes32 op = getCert ? AuthorizationOperation.APP_GET_CERT : AuthorizationOperation.APP_GET_KEY; + (bool allowed,) = _appAuth(app, info, epoch, op); + bool expected = epoch <= app.currentAppEpoch() && (!tcbFlag || upToDate) + && app.allowedComposeHashesAtEpoch(epoch, composeHash) + && (anyDevice || app.allowedDeviceIdsAtEpoch(epoch, deviceId)); + assert(allowed == expected); + } + + // A write takes effect on its row, and a range write on every row in its + // range. + function check_PolicyWrite_TakesEffect( + uint256 which, + uint256 from, + uint256 to, + uint256 epoch, + bytes32 word + ) + external + { + vm.assume(which < POLICY_SETTERS && epoch <= app.currentAppEpoch() + 1); + vm.assume(which < 4 ? epoch == from : from <= epoch && epoch <= to && to <= app.currentAppEpoch() + 1); + bytes memory data = _rangePolicyCall(which, from, to, word); + vm.prank(OWNER); + (bool ok,) = address(app).call(data); + uint256 kind = which % 4; + if (!ok) { + assert(word == bytes32(0) && (kind == 0 || kind == 2)); + return; + } + if (kind == 0) assert(app.allowedComposeHashesAtEpoch(epoch, word)); + if (kind == 1) assert(!app.allowedComposeHashesAtEpoch(epoch, word)); + if (kind == 2) assert(app.allowedDeviceIdsAtEpoch(epoch, word)); + if (kind == 3) assert(!app.allowedDeviceIdsAtEpoch(epoch, word)); + } + + // --------------------------------------------------------------- + // Revocation: removing a compose hash from every row, or a device from + // every row and clearing the any-device flag, 0 through the next epoch, + // leaves no selectable app epoch at which it is authorized. + // --------------------------------------------------------------- + + function check_FullRangeRemoval_RevokesAtEveryAppEpoch( + bool byDevice, + bytes32 composeHash, + bytes32 deviceId, + bool upToDate, + uint256 epoch, + bool getCert + ) + external + { + uint256 next = app.currentAppEpoch() + 1; + vm.startPrank(OWNER); + if (byDevice) { + app.removeDeviceAtEpochs(0, next, deviceId); + app.setAllowAnyDevice(false); + } else { + app.removeComposeHashAtEpochs(0, next, composeHash); + } + vm.stopPrank(); + bytes32 op = getCert ? AuthorizationOperation.APP_GET_CERT : AuthorizationOperation.APP_GET_KEY; + (bool allowed,) = _appAuth(app, _info(composeHash, deviceId, upToDate), epoch, op); + assert(!allowed); + } +} diff --git a/dstack/kms/auth-eth/test/DstackKms.symbolic.t.sol b/dstack/kms/auth-eth/test/DstackKms.symbolic.t.sol index 573aa8cc20..67648e18b6 100644 --- a/dstack/kms/auth-eth/test/DstackKms.symbolic.t.sol +++ b/dstack/kms/auth-eth/test/DstackKms.symbolic.t.sol @@ -32,7 +32,7 @@ contract MockConfigurableApp { _ret = ret; } - function isAppAllowed(IAppAuth.AppBootInfo calldata) external view returns (bool, string memory) { + function isAppAllowed(IAppAuth.AppInfo calldata) external view returns (bool, string memory) { return (_ret, ""); } } @@ -41,7 +41,7 @@ contract MockConfigurableApp { /// to verify that a malicious registered contract's revert /// propagates out of `kms.isAppAllowed` rather than being swallowed. contract MockRevertingApp { - function isAppAllowed(IAppAuth.AppBootInfo calldata) external pure returns (bool, string memory) { + function isAppAllowed(IAppAuth.AppInfo calldata) external pure returns (bool, string memory) { revert("malicious app revert"); } } @@ -87,14 +87,14 @@ contract DstackKmsSymbolicTest is Test { // the (false, reason) return without delegating. // --------------------------------------------------------------- - function check_IsAppAllowed_RejectsUnregisteredApp(IAppAuth.AppBootInfo calldata bootInfo) external view { + function check_IsAppAllowed_RejectsUnregisteredApp(IAppAuth.AppInfo calldata bootInfo) external view { // No apps registered in setUp(), so any bootInfo.appId is rejected. (bool allowed, string memory reason) = kms.isAppAllowed(bootInfo); assert(!allowed); assert(keccak256(bytes(reason)) == keccak256(bytes("App not registered"))); } - function check_IsAppAllowed_RejectsUnknownOsImage(address appId, IAppAuth.AppBootInfo calldata bootInfo) external { + function check_IsAppAllowed_RejectsUnknownOsImage(address appId, IAppAuth.AppInfo calldata bootInfo) external { vm.assume(appId != address(0)); // Register the appId so the registration check passes. @@ -125,10 +125,10 @@ contract DstackKmsSymbolicTest is Test { vm.startPrank(OWNER); kms.registerApp(address(mock)); - kms.addOsImageHash(osImageHash); + kms.addOsImageHashAtEpochs(0, 0, osImageHash); vm.stopPrank(); - IAppAuth.AppBootInfo memory b = IAppAuth.AppBootInfo({ + IAppAuth.AppInfo memory b = IAppAuth.AppInfo({ appId: address(mock), composeHash: bytes32(0), instanceId: address(0), @@ -155,10 +155,10 @@ contract DstackKmsSymbolicTest is Test { vm.startPrank(OWNER); kms.registerApp(address(mock)); - kms.addOsImageHash(osImageHash); + kms.addOsImageHashAtEpochs(0, 0, osImageHash); vm.stopPrank(); - IAppAuth.AppBootInfo memory b = IAppAuth.AppBootInfo({ + IAppAuth.AppInfo memory b = IAppAuth.AppInfo({ appId: address(mock), composeHash: bytes32(0), instanceId: address(0), @@ -190,9 +190,9 @@ contract DstackKmsSymbolicTest is Test { // Allow the OS image so the second gate passes; leave // kmsAllowedAggregatedMrs empty. vm.prank(OWNER); - kms.addOsImageHash(osImageHash); + kms.addOsImageHashAtEpochs(0, 0, osImageHash); - IAppAuth.AppBootInfo memory b = IAppAuth.AppBootInfo({ + IAppAuth.AppInfo memory b = IAppAuth.AppInfo({ appId: address(0), composeHash: bytes32(0), instanceId: address(0), @@ -217,12 +217,12 @@ contract DstackKmsSymbolicTest is Test { external { vm.startPrank(OWNER); - kms.addOsImageHash(osImageHash); - kms.addKmsAggregatedMr(mrAggregated); + kms.addOsImageHashAtEpochs(0, 0, osImageHash); + kms.addKmsAggregatedMrAtEpochs(0, 0, mrAggregated); vm.stopPrank(); // kmsAllowedDeviceIds is left empty. - IAppAuth.AppBootInfo memory b = IAppAuth.AppBootInfo({ + IAppAuth.AppInfo memory b = IAppAuth.AppInfo({ appId: address(0), composeHash: bytes32(0), instanceId: address(0), @@ -338,17 +338,18 @@ contract DstackKmsSymbolicTest is Test { } else if (which == 2) { data = abi.encodeWithSelector(DstackKms.registerApp.selector, addr); } else if (which == 3) { - data = abi.encodeWithSelector(DstackKms.addKmsAggregatedMr.selector, word); + data = abi.encodeWithSelector(DstackKms.addKmsAggregatedMrAtEpochs.selector, uint256(0), uint256(0), word); } else if (which == 4) { - data = abi.encodeWithSelector(DstackKms.removeKmsAggregatedMr.selector, word); + data = + abi.encodeWithSelector(DstackKms.removeKmsAggregatedMrAtEpochs.selector, uint256(0), uint256(0), word); } else if (which == 5) { - data = abi.encodeWithSelector(DstackKms.addKmsDevice.selector, word); + data = abi.encodeWithSelector(DstackKms.addKmsDeviceAtEpochs.selector, uint256(0), uint256(0), word); } else if (which == 6) { - data = abi.encodeWithSelector(DstackKms.removeKmsDevice.selector, word); + data = abi.encodeWithSelector(DstackKms.removeKmsDeviceAtEpochs.selector, uint256(0), uint256(0), word); } else if (which == 7) { - data = abi.encodeWithSelector(DstackKms.addOsImageHash.selector, word); + data = abi.encodeWithSelector(DstackKms.addOsImageHashAtEpochs.selector, uint256(0), uint256(0), word); } else if (which == 8) { - data = abi.encodeWithSelector(DstackKms.removeOsImageHash.selector, word); + data = abi.encodeWithSelector(DstackKms.removeOsImageHashAtEpochs.selector, uint256(0), uint256(0), word); } else if (which == 9) { data = abi.encodeWithSelector( bytes4(keccak256("deployAndRegisterApp(address,bool,bool,bool,bytes32,bytes32)")), @@ -369,11 +370,13 @@ contract DstackKmsSymbolicTest is Test { word ); } else if (which == 11) { - data = abi.encodeWithSelector(DstackKms.setKmsQuote.selector, ""); + data = abi.encodeWithSelector(UUPSUpgradeable.upgradeToAndCall.selector, addr, ""); } else if (which == 12) { - data = abi.encodeWithSelector(DstackKms.setKmsEventlog.selector, ""); + data = abi.encodeWithSelector(DstackKms.setRequireKmsLaunchTicket.selector, flag); } else if (which == 13) { - data = abi.encodeWithSelector(UUPSUpgradeable.upgradeToAndCall.selector, addr, ""); + data = abi.encodeWithSelector(DstackKms.addKmsLaunchTicket.selector, word, ""); + } else if (which == 14) { + data = abi.encodeWithSelector(DstackKms.removeKmsLaunchTicket.selector, word); } else { return; // outside the enumerated KMS-own mutating surface } diff --git a/dstack/kms/auth-eth/test/DstackKms.t.sol b/dstack/kms/auth-eth/test/DstackKms.t.sol index 899b2b7b9c..ce580a30b7 100644 --- a/dstack/kms/auth-eth/test/DstackKms.t.sol +++ b/dstack/kms/auth-eth/test/DstackKms.t.sol @@ -11,6 +11,7 @@ import "openzeppelin-foundry-upgrades/Upgrades.sol"; import "../contracts/DstackKms.sol"; import "../contracts/DstackApp.sol"; import "../contracts/IAppAuth.sol"; +import { DstackKms as DstackKmsV059 } from "../contracts/test-utils/reference/v0.5.9/DstackKmsV059.sol"; contract DstackKmsTest is Test { DstackKms public kms; @@ -19,6 +20,12 @@ contract DstackKmsTest is Test { address public user; event KmsInfoSet(bytes k256Pubkey); + event RootEpochRegistered( + uint256 indexed epoch, bytes32 chainHash, bytes caPubkey, bytes k256Pubkey, string evidenceUrl + ); + event RootEpochActivated(uint256 indexed epoch); + event RootEpochPopped(uint256 indexed epoch, bytes32 chainHash); + event RootEpochEvidenceUrlSet(uint256 indexed epoch, string evidenceUrl); event AppRegistered(address appId); @@ -44,46 +51,350 @@ contract DstackKmsTest is Test { assertEq(kms.appImplementation(), address(appImpl)); } - function test_SetKmsInfo() public { - bytes memory k256Pubkey = hex"123456"; - bytes memory caPubkey = hex"789abc"; - bytes memory quote = hex"defdef"; - bytes memory eventlog = hex"abcabc"; - - vm.prank(owner); - vm.expectEmit(true, true, true, true); - emit KmsInfoSet(k256Pubkey); - - kms.setKmsInfo( - DstackKms.KmsInfo({ k256Pubkey: k256Pubkey, caPubkey: caPubkey, quote: quote, eventlog: eventlog }) + function upgradeLegacyKms() internal { + vm.startPrank(owner); + address proxy = Upgrades.deployUUPSProxy( + "DstackKmsV059.sol:DstackKms", abi.encodeCall(DstackKmsV059.initialize, (owner, address(appImpl))) ); + DstackKmsV059(proxy).setKmsInfo(DstackKmsV059.KmsInfo(k256(0xb0), ca(0xa0), hex"0d", hex"0e")); + Options memory opts; + opts.referenceContract = "DstackKmsV059.sol:DstackKms"; + Upgrades.upgradeProxy(proxy, "DstackKms.sol", "", opts); + vm.stopPrank(); + kms = DstackKms(proxy); - (bytes memory storedK256, bytes memory storedCa, bytes memory storedQuote, bytes memory storedEventlog) = + assertEq(kms.owner(), owner); + assertEq(kms.appImplementation(), address(appImpl)); + assertEq(kms.rootEpochCount(), 0); + (bytes memory storedK256, bytes memory storedCa, bytes memory quote, bytes memory eventlog) = kms.kmsInfo(); + assertEq(storedK256, k256(0xb0)); + assertEq(storedCa, ca(0xa0)); + assertEq(quote, hex"0d"); + assertEq(eventlog, hex"0e"); + } + + function assertLegacySettersDisabled(address caller) internal { + (bytes memory key, bytes memory caKey, bytes memory quote, bytes memory eventlog) = kms.kmsInfo(); + vm.startPrank(caller); + (bool ok,) = address(kms) + .call( + abi.encodeWithSignature( + "setKmsInfo((bytes,bytes,bytes,bytes))", DstackKms.KmsInfo(k256(0xb1), ca(0xa1), hex"ff", hex"ff") + ) + ); + assertFalse(ok); + (ok,) = address(kms).call(abi.encodeWithSignature("setKmsQuote(bytes)", hex"ff")); + assertFalse(ok); + (ok,) = address(kms).call(abi.encodeWithSignature("setKmsEventlog(bytes)", hex"ff")); + assertFalse(ok); + vm.stopPrank(); + (bytes memory storedKey, bytes memory storedCa, bytes memory storedQuote, bytes memory storedEventlog) = kms.kmsInfo(); - assertEq(storedK256, k256Pubkey); - assertEq(storedCa, caPubkey); + assertEq(storedKey, key); + assertEq(storedCa, caKey); assertEq(storedQuote, quote); assertEq(storedEventlog, eventlog); } - function test_SetKmsInfoOnlyOwner() public { - bytes memory k256Pubkey = hex"123456"; - bytes memory caPubkey = hex"789abc"; - bytes memory quote = hex"defdef"; - bytes memory eventlog = hex"abcabc"; + function test_legacy_setters_disabled_before_and_after_epoch_registration() public { + assertLegacySettersDisabled(owner); + assertLegacySettersDisabled(user); + vm.prank(owner); + kms.registerRootEpoch(ca(0xa0), k256(0xb0), "ipfs://c0"); + assertLegacySettersDisabled(owner); + assertLegacySettersDisabled(user); + } + + function test_legacy_setters_disabled_after_upgrade() public { + upgradeLegacyKms(); + assertLegacySettersDisabled(owner); + assertLegacySettersDisabled(user); + } + + // Well-formed root public keys whose point bytes are all `fill`; shared with + // the off-chain implementations' tests. + function ca(uint8 fill) internal pure returns (bytes memory key) { + key = bytes.concat(hex"3059301306072a8648ce3d020106082a8648ce3d03010703420004", new bytes(64)); + for (uint256 i = 27; i < 91; i++) { + key[i] = bytes1(fill); + } + } + + function k256(uint8 fill) internal pure returns (bytes memory key) { + key = new bytes(33); + key[0] = 0x02; + for (uint256 i = 1; i < 33; i++) { + key[i] = bytes1(fill); + } + } + + function chainHash(bytes32 previous, bytes memory caKey, bytes memory k256Key) internal pure returns (bytes32) { + return keccak256(abi.encodePacked(previous, keccak256(caKey), keccak256(k256Key))); + } + + function test_RegisterRootEpochAppendsAndChains() public { + assertEq(kms.rootEpochCount(), 0); + vm.expectRevert(DstackKms.NoRootEpochRegistered.selector); + kms.currentRootEpoch(); + + bytes32 h0 = chainHash(bytes32(0), ca(0xa0), k256(0xb0)); + bytes32 h1 = chainHash(h0, ca(0xa1), k256(0xb1)); + // Shared with the off-chain implementations' tests. + assertEq(h0, 0x10ab6b6c8e7601901b0f1767985bf40d35bf3129e0866fe12dcc7c8f04a298f2); + assertEq(h1, 0x50152a82023f2219a31723b476c13bc5f608ab4147946dabdec15d4f3d648ed4); + vm.startPrank(owner); + vm.expectEmit(true, true, true, true); + emit RootEpochRegistered(0, h0, ca(0xa0), k256(0xb0), "ipfs://c0"); + vm.expectEmit(true, true, true, true); + emit RootEpochActivated(0); + assertEq(kms.registerRootEpoch(ca(0xa0), k256(0xb0), "ipfs://c0"), 0); + assertEq(kms.registerRootEpoch(ca(0xa1), k256(0xb1), "ipfs://c1"), 1); + vm.stopPrank(); + + assertEq(kms.rootEpochCount(), 2); + (bytes memory caKey, bytes memory k256Key, string memory evidenceUrl, bytes32 h) = kms.rootEpoch(1); + assertEq(caKey, ca(0xa1)); + assertEq(k256Key, k256(0xb1)); + assertEq(evidenceUrl, "ipfs://c1"); + assertEq(h, h1); + vm.expectRevert(DstackKms.UnknownRootEpoch.selector); + kms.rootEpoch(2); + + // Epoch 1 is registered but epoch 0 is still served. + (uint256 current, bytes32 currentHash) = kms.currentRootEpoch(); + assertEq(current, 0); + assertEq(currentHash, h0); + } + + function test_ActivateRootEpochMovesForwardOneAtATime() public { + bytes32 h0 = chainHash(bytes32(0), ca(0xa0), k256(0xb0)); + bytes32 h1 = chainHash(h0, ca(0xa1), k256(0xb1)); + bytes32 h2 = chainHash(h1, ca(0xa2), k256(0xb2)); + vm.startPrank(owner); + kms.registerRootEpoch(ca(0xa0), k256(0xb0), "ipfs://c0"); + vm.expectRevert(DstackKms.InvalidRootEpochActivation.selector); + kms.activateRootEpoch(1, h1); + kms.registerRootEpoch(ca(0xa1), k256(0xb1), "ipfs://c1"); + kms.registerRootEpoch(ca(0xa2), k256(0xb2), "ipfs://c2"); + vm.expectRevert(DstackKms.InvalidRootEpochActivation.selector); + kms.activateRootEpoch(2, h2); + vm.expectEmit(true, true, true, true); + emit RootEpochActivated(1); + kms.activateRootEpoch(1, h1); + vm.expectRevert(DstackKms.InvalidRootEpochActivation.selector); + kms.activateRootEpoch(1, h1); + vm.expectRevert(DstackKms.InvalidRootEpochActivation.selector); + kms.activateRootEpoch(0, h0); + vm.stopPrank(); + + (uint256 current,) = kms.currentRootEpoch(); + assertEq(current, 1); vm.prank(user); - vm.expectRevert(); - kms.setKmsInfo( - DstackKms.KmsInfo({ k256Pubkey: k256Pubkey, caPubkey: caPubkey, quote: quote, eventlog: eventlog }) - ); + vm.expectRevert(abi.encodeWithSelector(OwnableUpgradeable.OwnableUnauthorizedAccount.selector, user)); + kms.activateRootEpoch(2, h2); + } + + function test_activate_root_epoch_rejects_replaced_pending_epoch() public { + bytes32 h0 = chainHash(bytes32(0), ca(0xa0), k256(0xb0)); + bytes32 h1 = chainHash(h0, ca(0xa1), k256(0xb1)); + bytes32 replacementHash = chainHash(h0, ca(0xa2), k256(0xb2)); + vm.startPrank(owner); + kms.registerRootEpoch(ca(0xa0), k256(0xb0), "ipfs://c0"); + kms.registerRootEpoch(ca(0xa1), k256(0xb1), "ipfs://c1"); + kms.popRootEpoch(1, h1); + kms.registerRootEpoch(ca(0xa2), k256(0xb2), "ipfs://replacement"); + + vm.expectRevert(DstackKms.RootEpochChainHashMismatch.selector); + kms.activateRootEpoch(1, h1); + (uint256 current, bytes32 currentHash) = kms.currentRootEpoch(); + assertEq(current, 0); + assertEq(currentHash, h0); + (bytes memory k256Key, bytes memory caKey,,) = kms.kmsInfo(); + assertEq(caKey, ca(0xa0)); + assertEq(k256Key, k256(0xb0)); + + kms.activateRootEpoch(1, replacementHash); + (current, currentHash) = kms.currentRootEpoch(); + assertEq(current, 1); + assertEq(currentHash, replacementHash); + (k256Key, caKey,,) = kms.kmsInfo(); + assertEq(caKey, ca(0xa2)); + assertEq(k256Key, k256(0xb2)); + vm.stopPrank(); + } + + function test_RegisterRootEpochZeroMustMatchKmsInfo() public { + upgradeLegacyKms(); + vm.startPrank(owner); + vm.expectRevert(DstackKms.Epoch0KeysDifferFromKmsInfo.selector); + kms.registerRootEpoch(ca(0xa1), k256(0xb0), "ipfs://c0"); + vm.expectRevert(DstackKms.Epoch0KeysDifferFromKmsInfo.selector); + kms.registerRootEpoch(ca(0xa0), k256(0xb1), "ipfs://c0"); + assertEq(kms.registerRootEpoch(ca(0xa0), k256(0xb0), "ipfs://c0"), 0); + // Later epochs are new keys by definition. + assertEq(kms.registerRootEpoch(ca(0xa1), k256(0xb1), "ipfs://c1"), 1); + vm.stopPrank(); + } + + function test_PopRootEpochDropsOnlyThePendingOne() public { + bytes32 h0 = chainHash(bytes32(0), ca(0xa0), k256(0xb0)); + bytes32 h1 = chainHash(h0, ca(0xa1), k256(0xb1)); + bytes32 h1b = chainHash(h0, ca(0xa2), k256(0xb2)); + vm.startPrank(owner); + vm.expectRevert(DstackKms.NotPendingRootEpoch.selector); + kms.popRootEpoch(0, h0); + kms.registerRootEpoch(ca(0xa0), k256(0xb0), "ipfs://c0"); + vm.expectRevert(DstackKms.NotPendingRootEpoch.selector); + kms.popRootEpoch(0, h0); + kms.registerRootEpoch(ca(0xa1), k256(0xb1), "ipfs://c1"); + vm.expectRevert(DstackKms.NotPendingRootEpoch.selector); + kms.popRootEpoch(2, h1); + vm.expectRevert(DstackKms.RootEpochChainHashMismatch.selector); + kms.popRootEpoch(1, h1b); + + vm.expectEmit(true, true, true, true); + emit RootEpochPopped(1, h1); + kms.popRootEpoch(1, h1); + assertEq(kms.rootEpochCount(), 1); + + // A new epoch 1 replaces the dropped one; a stale pop of the old one + // cannot drop it. + assertEq(kms.registerRootEpoch(ca(0xa2), k256(0xb2), "ipfs://c2"), 1); + vm.expectRevert(DstackKms.RootEpochChainHashMismatch.selector); + kms.popRootEpoch(1, h1); + kms.activateRootEpoch(1, h1b); + vm.expectRevert(DstackKms.NotPendingRootEpoch.selector); + kms.popRootEpoch(1, h1b); + vm.stopPrank(); + + (uint256 epoch, bytes32 h) = kms.currentRootEpoch(); + assertEq(epoch, 1); + assertEq(h, h1b); + + vm.prank(user); + vm.expectRevert(abi.encodeWithSelector(OwnableUpgradeable.OwnableUnauthorizedAccount.selector, user)); + kms.popRootEpoch(1, h1b); + } + + function test_PolicyRowsBelongToTheRegisteredKeysOfAnEpoch() public { + IAppAuth.AppInfo memory info = authorizationInfo(address(kms)); + vm.startPrank(owner); + // Epoch 0 keeps the legacy mappings, even before any registration. + approveKmsAtEpoch(info, 0); + assertTrue(kms.allowedOsImages(info.osImageHash)); + assertTrue(kms.kmsAllowedAggregatedMrs(info.mrAggregated)); + assertTrue(kms.kmsAllowedDeviceIds(info.deviceId)); + // Rows of an unregistered epoch can be neither written nor read. + vm.expectRevert(DstackKms.UnknownRootEpoch.selector); + kms.addOsImageHashAtEpochs(1, 1, info.osImageHash); + vm.expectRevert(DstackKms.UnknownRootEpoch.selector); + kms.addKmsAggregatedMrAtEpochs(1, 1, info.mrAggregated); + vm.expectRevert(DstackKms.UnknownRootEpoch.selector); + kms.addKmsDeviceAtEpochs(1, 1, info.deviceId); + registerNextRootEpoch(); + registerNextRootEpoch(); + approveKmsAtEpoch(info, 1); + assertTrue(kms.authorizeKms(kmsEpochRequest(info, 1, 0)).authorized); + + (,,, bytes32 h1) = kms.rootEpoch(1); + kms.popRootEpoch(1, h1); + assertFalse(kms.allowedOsImagesAtEpoch(1, info.osImageHash)); + // Other keys registered under the same number start with empty rows. + kms.registerRootEpoch(ca(0xc1), k256(0xd1), "ipfs://replacement"); + assertFalse(kms.allowedOsImagesAtEpoch(1, info.osImageHash)); + assertFalse(kms.kmsAllowedAggregatedMrsAtEpoch(1, info.mrAggregated)); + assertFalse(kms.kmsAllowedDeviceIdsAtEpoch(1, info.deviceId)); + assertFalse(kms.authorizeKms(kmsEpochRequest(info, 1, 0)).authorized); + approveKmsAtEpoch(info, 1); + assertTrue(kms.authorizeKms(kmsEpochRequest(info, 1, 0)).authorized); + // Epoch 0 is untouched throughout. + assertTrue(kms.allowedOsImagesAtEpoch(0, info.osImageHash)); + vm.stopPrank(); + } + + function test_SetRootEpochEvidenceUrl() public { + vm.startPrank(owner); + vm.expectRevert(DstackKms.UnknownRootEpoch.selector); + kms.setRootEpochEvidenceUrl(0, "ipfs://moved"); + kms.registerRootEpoch(ca(0xa0), k256(0xb0), "ipfs://c0"); + vm.expectRevert(DstackKms.EmptyEpochEvidenceUrl.selector); + kms.setRootEpochEvidenceUrl(0, ""); + vm.expectEmit(true, true, true, true); + emit RootEpochEvidenceUrlSet(0, "https://mirror/c0"); + kms.setRootEpochEvidenceUrl(0, "https://mirror/c0"); + vm.stopPrank(); + + (,, string memory evidenceUrl, bytes32 h) = kms.rootEpoch(0); + assertEq(evidenceUrl, "https://mirror/c0"); + assertEq(h, chainHash(bytes32(0), ca(0xa0), k256(0xb0))); + + vm.prank(user); + vm.expectRevert(abi.encodeWithSelector(OwnableUpgradeable.OwnableUnauthorizedAccount.selector, user)); + kms.setRootEpochEvidenceUrl(0, "ipfs://evil"); + } + + function test_KmsInfoFollowsTheCurrentRootEpoch() public { + upgradeLegacyKms(); + vm.startPrank(owner); + kms.registerRootEpoch(ca(0xa0), k256(0xb0), "ipfs://c0"); + (bytes memory k256Key, bytes memory caKey, bytes memory quote, bytes memory eventlog) = kms.kmsInfo(); + assertEq(caKey, ca(0xa0)); + assertEq(k256Key, k256(0xb0)); + assertEq(quote.length + eventlog.length, 0); + + // A pending epoch is not the KMS identity yet. + kms.registerRootEpoch(ca(0xa1), k256(0xb1), "ipfs://c1"); + (k256Key, caKey,,) = kms.kmsInfo(); + assertEq(caKey, ca(0xa0)); + (,,, bytes32 h1) = kms.rootEpoch(1); + kms.activateRootEpoch(1, h1); + (k256Key, caKey,,) = kms.kmsInfo(); + assertEq(caKey, ca(0xa1)); + assertEq(k256Key, k256(0xb1)); + + vm.stopPrank(); + assertLegacySettersDisabled(owner); + assertLegacySettersDisabled(user); + } + + function test_RegisterRootEpochOnlyOwner() public { + vm.prank(user); + vm.expectRevert(abi.encodeWithSelector(OwnableUpgradeable.OwnableUnauthorizedAccount.selector, user)); + kms.registerRootEpoch(ca(0xa0), k256(0xb0), "ipfs://c0"); + } + + function test_RegisterRootEpochRejectsMalformedKeys() public { + bytes memory compressedCa = ca(0xa0); + compressedCa[26] = 0x02; + bytes memory otherCurve = ca(0xa0); + otherCurve[25] = 0x0a; + bytes memory uncompressedK256 = bytes.concat(hex"04", new bytes(64)); + vm.startPrank(owner); + vm.expectRevert(DstackKms.InvalidEpochCaPubkey.selector); + kms.registerRootEpoch("", k256(0xb0), "ipfs://c0"); + vm.expectRevert(DstackKms.InvalidEpochCaPubkey.selector); + kms.registerRootEpoch(bytes.concat(ca(0xa0), hex"00"), k256(0xb0), "ipfs://c0"); + vm.expectRevert(DstackKms.InvalidEpochCaPubkey.selector); + kms.registerRootEpoch(compressedCa, k256(0xb0), "ipfs://c0"); + vm.expectRevert(DstackKms.InvalidEpochCaPubkey.selector); + kms.registerRootEpoch(otherCurve, k256(0xb0), "ipfs://c0"); + vm.expectRevert(DstackKms.InvalidEpochK256Pubkey.selector); + kms.registerRootEpoch(ca(0xa0), "", "ipfs://c0"); + vm.expectRevert(DstackKms.InvalidEpochK256Pubkey.selector); + kms.registerRootEpoch(ca(0xa0), uncompressedK256, "ipfs://c0"); + vm.expectRevert(DstackKms.InvalidEpochK256Pubkey.selector); + kms.registerRootEpoch(ca(0xa0), bytes.concat(hex"04", new bytes(32)), "ipfs://c0"); + vm.expectRevert(DstackKms.EmptyEpochEvidenceUrl.selector); + kms.registerRootEpoch(ca(0xa0), k256(0xb0), ""); + vm.stopPrank(); } function test_AddKmsAggregatedMr() public { bytes32 mr = bytes32(uint256(123)); vm.prank(owner); - kms.addKmsAggregatedMr(mr); + kms.addKmsAggregatedMrAtEpochs(0, 0, mr); assertTrue(kms.kmsAllowedAggregatedMrs(mr)); } @@ -92,10 +403,10 @@ contract DstackKmsTest is Test { bytes32 mr = bytes32(uint256(123)); vm.startPrank(owner); - kms.addKmsAggregatedMr(mr); + kms.addKmsAggregatedMrAtEpochs(0, 0, mr); assertTrue(kms.kmsAllowedAggregatedMrs(mr)); - kms.removeKmsAggregatedMr(mr); + kms.removeKmsAggregatedMrAtEpochs(0, 0, mr); assertFalse(kms.kmsAllowedAggregatedMrs(mr)); vm.stopPrank(); } @@ -143,14 +454,31 @@ contract DstackKmsTest is Test { assertEq(kms.gatewayAppId(), gatewayAppId); } + function test_SetSevSnpTcbRequirements() public { + string memory requirements = '[{"cpuid":"00a00f11","bootloader":0,"tee":0,"snp":27,"microcode":222}]'; + assertEq(kms.sevSnpTcbRequirements(), ""); + + vm.expectEmit(address(kms)); + emit DstackKms.SevSnpTcbRequirementsSet(requirements); + vm.expectEmit(address(kms)); + emit DstackKms.PolicyChanged(owner, keccak256("sev-snp-tcb-requirements"), keccak256(bytes(requirements)), true); + vm.prank(owner); + kms.setSevSnpTcbRequirements(requirements); + assertEq(kms.sevSnpTcbRequirements(), requirements); + + vm.prank(user); + vm.expectRevert(abi.encodeWithSelector(OwnableUpgradeable.OwnableUnauthorizedAccount.selector, user)); + kms.setSevSnpTcbRequirements(""); + } + function test_AddAndRemoveKmsDevice() public { bytes32 deviceId = bytes32(uint256(999)); vm.startPrank(owner); - kms.addKmsDevice(deviceId); + kms.addKmsDeviceAtEpochs(0, 0, deviceId); assertTrue(kms.kmsAllowedDeviceIds(deviceId)); - kms.removeKmsDevice(deviceId); + kms.removeKmsDeviceAtEpochs(0, 0, deviceId); assertFalse(kms.kmsAllowedDeviceIds(deviceId)); vm.stopPrank(); } @@ -159,26 +487,475 @@ contract DstackKmsTest is Test { bytes32 imageHash = bytes32(uint256(888)); vm.startPrank(owner); - kms.addOsImageHash(imageHash); + kms.addOsImageHashAtEpochs(0, 0, imageHash); assertTrue(kms.allowedOsImages(imageHash)); - kms.removeOsImageHash(imageHash); + kms.removeOsImageHashAtEpochs(0, 0, imageHash); assertFalse(kms.allowedOsImages(imageHash)); vm.stopPrank(); } - function test_SetKmsQuoteAndEventlog() public { - bytes memory newQuote = hex"deadbeef"; - bytes memory newEventlog = hex"cafebabe"; + function authorizationInfo(address appId) internal pure returns (IAppAuth.AppInfo memory) { + return IAppAuth.AppInfo({ + appId: appId, + composeHash: bytes32(uint256(789)), + instanceId: address(0), + deviceId: bytes32(uint256(123)), + mrAggregated: bytes32(uint256(456)), + mrSystem: bytes32(0), + osImageHash: bytes32(uint256(111)), + tcbStatus: "UpToDate", + advisoryIds: new string[](0) + }); + } + + function authorize(IAppAuth.AppInfo memory info, bool isKms) internal view returns (AuthorizationResult memory) { + AuthorizationRequest memory request = AuthorizationRequest( + info, + isKms ? keccak256("kms_serve") : keccak256("app_get_key"), + OptionalUint256(false, 0), + OptionalUint256(false, 0), + "dstack-tdx", + bytes32(0) + ); + return isKms ? kms.authorizeKms(request) : kms.authorizeApp(request); + } + + function test_TeeVariantsRestrictKmsAndApps() public { + IAppAuth.AppInfo memory info = authorizationInfo(address(kms)); + assertTrue(kms.allowAnyTeeVariant()); + string[] memory tdx = new string[](2); + tdx[0] = "dstack-tdx"; + tdx[1] = "dstack-gcp-tdx"; + vm.startPrank(owner); + kms.registerRootEpoch(ca(0xa0), k256(0xb0), "https://example.com/epoch-0"); + kms.addOsImageHashAtEpochs(0, 0, info.osImageHash); + kms.addKmsDeviceAtEpochs(0, 0, info.deviceId); + kms.addKmsAggregatedMrAtEpochs(0, 0, info.mrAggregated); + address appId = kms.deployAndRegisterApp(user, false, true, info.deviceId, info.composeHash); + kms.setAllowedTeeVariants(tdx); + kms.setAllowAnyTeeVariant(false); + vm.stopPrank(); + + assertTrue(authorize(info, true).authorized); + (bool allowed, string memory reason) = kms.isKmsAllowed(info); + assertFalse(allowed); + assertEq(reason, "TEE variant not allowed"); + AuthorizationRequest memory request = AuthorizationRequest( + info, keccak256("kms_serve"), OptionalUint256(false, 0), OptionalUint256(false, 0), "dstack-tdx", bytes32(0) + ); + request.teeVariant = "dstack-gcp-tdx"; + assertTrue(kms.authorizeKms(request).authorized); + request.teeVariant = "dstack-amd-sev-snp"; + assertEq(kms.authorizeKms(request).rejectionReason, "TEE variant not allowed"); + // A platform the contract does not know is refused once restricted. + request.teeVariant = "dstack-new-platform"; + assertEq(kms.authorizeKms(request).rejectionReason, "TEE variant not allowed"); + + info.appId = appId; + assertTrue(authorize(info, false).authorized); + (allowed, reason) = kms.isAppAllowed(info); + assertFalse(allowed); + assertEq(reason, "TEE variant not allowed"); + request = AuthorizationRequest( + info, + keccak256("app_get_key"), + OptionalUint256(false, 0), + OptionalUint256(false, 0), + "dstack-tdx", + bytes32(0) + ); + request.teeVariant = "dstack-amd-sev-snp"; + assertEq(kms.authorizeApp(request).rejectionReason, "TEE variant not allowed"); + + // Allowing any platform lifts the restriction, including for legacy callers. + vm.prank(owner); + kms.setAllowAnyTeeVariant(true); + assertTrue(kms.authorizeApp(request).authorized); + (allowed,) = kms.isAppAllowed(info); + assertTrue(allowed); + + // With the KMS unrestricted, the app's own policy still applies. + vm.startPrank(user); + DstackApp(appId).setAllowedTeeVariants(tdx); + DstackApp(appId).setAllowAnyTeeVariant(false); + vm.stopPrank(); + assertEq(kms.authorizeApp(request).rejectionReason, "TEE variant not allowed"); + (allowed, reason) = kms.isAppAllowed(info); + assertFalse(allowed); + assertEq(reason, "TEE variant not allowed"); + request.teeVariant = "dstack-gcp-tdx"; + assertTrue(kms.authorizeApp(request).authorized); + + vm.prank(user); + vm.expectRevert(abi.encodeWithSelector(OwnableUpgradeable.OwnableUnauthorizedAccount.selector, user)); + kms.setAllowAnyTeeVariant(false); + } + + function test_AuthorizationOperationsFailClosedAndBootstrapBeforeRegistration() public { + IAppAuth.AppInfo memory info = authorizationInfo(address(kms)); + vm.startPrank(owner); + kms.addOsImageHashAtEpochs(0, 0, info.osImageHash); + kms.addKmsDeviceAtEpochs(0, 0, info.deviceId); + kms.addKmsAggregatedMrAtEpochs(0, 0, info.mrAggregated); + vm.stopPrank(); + AuthorizationRequest memory request = AuthorizationRequest( + info, + keccak256("kms_bootstrap"), + OptionalUint256(false, 0), + OptionalUint256(false, 0), + "dstack-tdx", + bytes32(0) + ); + assertTrue(kms.authorizeKms(request).authorized); + assertEq(kms.authorizeKms(request).currentRootEpochHash, bytes32(0)); + request.operation = keccak256("kms_export_keys"); + assertEq(kms.authorizeKms(request).rejectionReason, "Root epoch not registered"); + vm.prank(owner); + kms.registerRootEpoch(ca(0xa0), k256(0xb0), "https://example.com/epoch-0"); + assertTrue(kms.authorizeKms(request).authorized); + request.operation = keccak256("kms_import_keys"); + assertTrue(kms.authorizeKms(request).authorized); + assertEq(kms.authorizeApp(request).rejectionReason, "Invalid authorization operation"); + request.operation = keccak256("app_get_cert"); + assertEq(kms.authorizeKms(request).rejectionReason, "Invalid authorization operation"); + request.operation = bytes32(0); + assertEq(kms.authorizeKms(request).rejectionReason, "Invalid authorization operation"); + assertEq(kms.authorizeApp(request).rejectionReason, "Invalid authorization operation"); + } + + function test_KmsLaunchTicketGatesOnlyTheKeyImport() public { + IAppAuth.AppInfo memory info = authorizationInfo(address(kms)); + bytes32 ticket = sha256("dstack-launch-ticket/v1:replica"); + vm.startPrank(owner); + kms.registerRootEpoch(ca(0xa0), k256(0xb0), "https://example.com/epoch-0"); + kms.addOsImageHashAtEpochs(0, 0, info.osImageHash); + kms.addKmsDeviceAtEpochs(0, 0, info.deviceId); + kms.addKmsAggregatedMrAtEpochs(0, 0, info.mrAggregated); + kms.setRequireKmsLaunchTicket(true); + vm.expectRevert(DstackKms.InvalidLaunchTicketHash.selector); + kms.addKmsLaunchTicket(bytes32(0), "zero"); + kms.addKmsLaunchTicket(ticket, "replica"); + vm.stopPrank(); + assertEq(kms.kmsLaunchTickets()[0], ticket); + + AuthorizationRequest memory request = AuthorizationRequest( + info, + keccak256("kms_import_keys"), + OptionalUint256(false, 0), + OptionalUint256(false, 0), + "dstack-tdx", + bytes32(0) + ); + assertEq(kms.authorizeKms(request).rejectionReason, "Invalid launch ticket"); + request.launchTicketHash = ticket; + assertTrue(kms.authorizeKms(request).authorized); + // The other operations hand out no root keys and need no ticket. + request.launchTicketHash = bytes32(0); + request.operation = keccak256("kms_export_keys"); + assertTrue(kms.authorizeKms(request).authorized); + request.operation = keccak256("kms_serve"); + assertTrue(kms.authorizeKms(request).authorized); + request.operation = keccak256("kms_bootstrap"); + assertTrue(kms.authorizeKms(request).authorized); + // Legacy callers cannot present one. + (bool allowed, string memory reason) = kms.isKmsAllowed(info); + assertFalse(allowed); + assertEq(reason, "Invalid launch ticket"); + + vm.prank(owner); + kms.removeKmsLaunchTicket(ticket); + assertEq(kms.kmsLaunchTickets().length, 0); + request.operation = keccak256("kms_import_keys"); + request.launchTicketHash = ticket; + assertEq(kms.authorizeKms(request).rejectionReason, "Invalid launch ticket"); + + vm.startPrank(user); + bytes memory unauthorized = abi.encodeWithSignature("OwnableUnauthorizedAccount(address)", user); + vm.expectRevert(unauthorized); + kms.setRequireKmsLaunchTicket(false); + vm.expectRevert(unauthorized); + kms.addKmsLaunchTicket(ticket, "replica"); + vm.expectRevert(unauthorized); + kms.removeKmsLaunchTicket(ticket); + vm.stopPrank(); + } + + function test_CheckAuthorization_OptionalUint256DistinguishesZeroFromDefault() public { + IAppAuth.AppInfo memory info = authorizationInfo(address(kms)); + vm.startPrank(owner); + registerNextRootEpoch(); + registerNextRootEpoch(); + approveKmsAtEpoch(info, 1); + assertFalse(kms.allowedOsImages(info.osImageHash)); + assertTrue(kms.allowedOsImagesAtEpoch(1, info.osImageHash)); + assertFalse(authorize(info, true).authorized); + assertTrue( + kms.authorizeKms(kmsEpochRequest(info, 1, 0)).authorized, "pending handover must be explicitly approved" + ); + assertFalse(kms.authorizeApp(epochRequest(info, 1, 0)).authorized, "apps cannot fetch pending keys"); + AuthorizationResult memory result = kms.authorizeKms(kmsEpochRequest(info, 2, 0)); + assertFalse(result.authorized); + assertEq(result.rejectionReason, "Requested root epoch is not registered"); + activateNextRootEpoch(); + result = authorize(info, true); + assertTrue(result.authorized); + assertEq(result.currentRootEpoch, 1); + assertFalse(kms.authorizeKms(kmsEpochRequest(info, 0, 0)).authorized, "epoch one does not imply epoch zero"); + approveKmsAtEpoch(info, 0); + assertTrue(kms.authorizeKms(kmsEpochRequest(info, 0, 0)).authorized); + vm.stopPrank(); + } + + function test_CheckAuthorization_UnregisteredEpochReturnsRejection() public view { + AuthorizationResult memory result = authorize(authorizationInfo(address(kms)), true); + assertFalse(result.authorized); + assertEq(result.rejectionReason, "Root epoch not registered"); + assertEq(result.currentRootEpoch, 0); + assertEq(result.currentRootEpochHash, bytes32(0)); + } + + function test_CheckAuthorization_ValidatesRequestedPolicy() public { + IAppAuth.AppInfo memory info = authorizationInfo(address(kms)); + vm.startPrank(owner); + kms.registerRootEpoch(ca(0xa0), k256(0xb0), "https://example.com/epoch-0"); + kms.setGatewayAppId("gateway"); + kms.addOsImageHashAtEpochs(0, 0, info.osImageHash); + kms.addKmsDeviceAtEpochs(0, 0, info.deviceId); + kms.addKmsAggregatedMrAtEpochs(0, 0, info.mrAggregated); + address appId = kms.deployAndRegisterApp(user, false, false, info.deviceId, info.composeHash); + vm.stopPrank(); + + AuthorizationResult memory result = authorize(info, true); + assertTrue(result.authorized); + assertEq(result.rejectionReason, ""); + assertEq(result.gatewayAppId, "gateway"); + assertEq(result.currentRootEpochHash, chainHash(bytes32(0), ca(0xa0), k256(0xb0))); + + info.appId = user; + result = authorize(info, false); + assertFalse(result.authorized); + assertEq(result.rejectionReason, "App not registered"); + + info.appId = appId; + info.mrAggregated = bytes32(0); + result = authorize(info, false); + assertTrue(result.authorized); + result = authorize(info, true); + assertFalse(result.authorized); + assertEq(result.rejectionReason, "Aggregated MR not allowed"); + AuthorizationRequest memory appRequest = AuthorizationRequest( + info, + keccak256("app_get_key"), + OptionalUint256(true, 1), + OptionalUint256(false, 0), + "dstack-tdx", + bytes32(0) + ); + result = kms.authorizeApp(appRequest); + assertFalse(result.authorized); + assertEq(result.rejectionReason, "Requested app epoch is not active"); + assertEq(result.currentRootEpochHash, chainHash(bytes32(0), ca(0xa0), k256(0xb0))); + info.appId = address(kms); + result = authorize(info, false); + assertFalse(result.authorized); + assertEq(result.rejectionReason, "App not registered"); + result = authorize(info, true); + assertFalse(result.authorized); + assertEq(result.rejectionReason, "Aggregated MR not allowed"); + } + + function test_CheckKmsAppPolicyKeepsKmsPolicyAndSkipsAppIdentity() public { + // The app is never registered and has no code: identity is the delegate's. + IAppAuth.AppInfo memory info = authorizationInfo(makeAddr("offchain-app")); + AuthorizationRequest memory request = AuthorizationRequest( + info, + keccak256("app_get_key"), + OptionalUint256(false, 0), + OptionalUint256(false, 0), + "dstack-tdx", + bytes32(0) + ); + + assertEq(kms.checkKmsAppPolicy(request), "Root epoch not registered"); + + vm.startPrank(owner); + kms.registerRootEpoch(ca(0xa0), k256(0xb0), "https://example.com/epoch-0"); + kms.addOsImageHashAtEpochs(0, 0, info.osImageHash); + string[] memory tdx = new string[](1); + tdx[0] = "dstack-tdx"; + kms.setAllowedTeeVariants(tdx); + kms.setAllowAnyTeeVariant(false); + vm.stopPrank(); + + assertEq(kms.checkKmsAppPolicy(request), "", "unregistered, codeless apps pass the KMS policy"); + + request.operation = keccak256("kms_serve"); + assertEq(kms.checkKmsAppPolicy(request), "Invalid authorization operation"); + request.operation = keccak256("app_get_cert"); + assertEq(kms.checkKmsAppPolicy(request), ""); + + request.requestedRootEpoch = OptionalUint256(true, 1); + assertEq(kms.checkKmsAppPolicy(request), "Requested root epoch is not active"); + request.requestedRootEpoch = OptionalUint256(true, 0); + assertEq(kms.checkKmsAppPolicy(request), ""); + + vm.startPrank(owner); + registerNextRootEpoch(); + activateNextRootEpoch(); + vm.stopPrank(); + assertEq(kms.checkKmsAppPolicy(request), "", "epoch zero allows the image"); + request.requestedRootEpoch = OptionalUint256(false, 0); + assertEq(kms.checkKmsAppPolicy(request), "OS image is not allowed", "epoch one does not allow the image"); vm.startPrank(owner); - kms.setKmsQuote(newQuote); - kms.setKmsEventlog(newEventlog); + kms.removeOsImageHashAtEpochs(0, 0, info.osImageHash); + kms.addOsImageHashAtEpochs(1, 1, info.osImageHash); vm.stopPrank(); + assertEq(kms.checkKmsAppPolicy(request), "", "epoch one now allows the image"); + request.requestedRootEpoch = OptionalUint256(true, 0); + assertEq(kms.checkKmsAppPolicy(request), "OS image is not allowed", "epoch zero no longer allows the image"); + + request.requestedRootEpoch = OptionalUint256(false, 0); + request.teeVariant = "dstack-amd-sev-snp"; + assertEq(kms.checkKmsAppPolicy(request), "TEE variant not allowed"); + request.teeVariant = "dstack-gcp-tdx"; + assertEq(kms.checkKmsAppPolicy(request), "TEE variant not allowed"); + + // The same request is denied on the chain path at the identity check + // first, so the on-chain precedence is unchanged. + assertEq(kms.authorizeApp(request).rejectionReason, "App not registered"); + + request.teeVariant = "dstack-tdx"; + request.appInfo.osImageHash = bytes32(uint256(999)); + assertEq(kms.checkKmsAppPolicy(request), "OS image is not allowed"); + } - (,, bytes memory storedQuote, bytes memory storedEventlog) = kms.kmsInfo(); - assertEq(storedQuote, newQuote); - assertEq(storedEventlog, newEventlog); + function test_AppEpochCapabilityIsOptionalButGetterFailuresPropagate() public { + address policy = address(new DstackApp()); + kms.registerApp(policy); + vm.mockCall(policy, abi.encodeCall(IAppEpochAuth.currentAppEpoch, ()), abi.encode(uint256(7))); + assertEq(kms.currentAppEpoch(policy), 7); + vm.mockCall( + policy, abi.encodeCall(IERC165.supportsInterface, (type(IAppEpochAuth).interfaceId)), abi.encode(false) + ); + // Advertising either old single-method interface does not opt into the combined capability. + vm.mockCall( + policy, + abi.encodeCall(IERC165.supportsInterface, (IAppEpochAuth.currentAppEpoch.selector)), + abi.encode(true) + ); + vm.mockCall( + policy, abi.encodeCall(IERC165.supportsInterface, (IAppEpochAuth.authorizeApp.selector)), abi.encode(true) + ); + assertEq(kms.currentAppEpoch(policy), 0); + vm.clearMockedCalls(); + vm.mockCallRevert(policy, abi.encodeCall(IAppEpochAuth.currentAppEpoch, ()), "epoch unavailable"); + vm.expectRevert("epoch unavailable"); + kms.currentAppEpoch(policy); + } + + function test_AppEpochQueryRevertsForUnregisteredOrUndeployedApps() public { + address policy = address(new DstackApp()); + vm.expectRevert(DstackKms.AppNotRegistered.selector); + kms.currentAppEpoch(policy); + address eoa = address(0xbeef); + kms.registerApp(eoa); + vm.expectRevert(DstackKms.AppNotDeployed.selector); + kms.currentAppEpoch(eoa); + // A registered legacy policy without the capability is epoch zero. + kms.registerApp(policy); + vm.mockCall( + policy, abi.encodeCall(IERC165.supportsInterface, (type(IAppEpochAuth).interfaceId)), abi.encode(false) + ); + assertEq(kms.currentAppEpoch(policy), 0); + // The authorization paths still report the rejection instead of reverting. + DstackKms.AppInfo memory info = authorizationInfo(address(0x1234)); + (bool allowed, string memory reason) = kms.isAppAllowed(info); + assertFalse(allowed); + assertEq(reason, "App not registered"); + vm.prank(owner); + kms.registerRootEpoch(ca(0xa0), k256(0xb0), "https://example.com/epoch-0"); + assertEq(authorize(info, false).rejectionReason, "App not registered"); + } + + function test_AppEpochRotationIsOwnerScopedAndDoesNotChangeRootEpoch() public { + DstackKms.AppInfo memory info = authorizationInfo(address(0)); + vm.startPrank(owner); + kms.registerRootEpoch(ca(0xa0), k256(0xb0), "https://example.com/epoch-0"); + kms.addOsImageHashAtEpochs(0, 0, info.osImageHash); + address appId = kms.deployAndRegisterApp(user, false, false, info.deviceId, info.composeHash); + address otherApp = kms.deployAndRegisterApp(user, false, false, info.deviceId, info.composeHash); + vm.stopPrank(); + info.appId = appId; + assertEq(kms.currentAppEpoch(appId), 0); + vm.prank(owner); + vm.expectRevert(); + DstackApp(appId).advanceAppEpoch(0); + vm.prank(user); + DstackApp(appId).advanceAppEpoch(0); + vm.prank(user); + vm.expectRevert("App epoch changed"); + DstackApp(appId).advanceAppEpoch(0); + assertEq(kms.currentAppEpoch(appId), 1); + assertEq(kms.currentAppEpoch(otherApp), 0); + (uint256 rootEpoch,) = kms.currentRootEpoch(); + assertEq(rootEpoch, 0); + AuthorizationRequest memory request = AuthorizationRequest( + info, + keccak256("app_get_key"), + OptionalUint256(false, 0), + OptionalUint256(false, 0), + "dstack-tdx", + bytes32(0) + ); + AuthorizationResult memory result = kms.authorizeApp(request); + assertFalse(result.authorized); + assertEq(result.rejectionReason, "Compose hash not allowed"); + assertEq(result.currentAppEpoch, 1); + request.requestedAppEpoch = OptionalUint256(true, 0); + assertTrue(kms.authorizeApp(request).authorized); + request.requestedAppEpoch.value = 2; + result = kms.authorizeApp(request); + assertFalse(result.authorized); + assertEq(result.currentAppEpoch, 1); + assertEq(result.rejectionReason, "Requested app epoch is not active"); + request.requestedAppEpoch = OptionalUint256(false, 0); + request.appInfo.composeHash = bytes32(0); + result = kms.authorizeApp(request); + assertFalse(result.authorized); + assertEq(result.currentAppEpoch, 1); + vm.prank(user); + DstackApp(appId).advanceAppEpoch(1); + assertEq(kms.currentAppEpoch(appId), 2); + } + + function test_CheckAuthorization_RejectionIncludesActivatedEpoch() public { + vm.startPrank(owner); + kms.registerRootEpoch(ca(0xa0), k256(0xb0), "https://example.com/epoch-0"); + kms.registerRootEpoch(ca(0xa1), k256(0xb1), "https://example.com/epoch-1"); + kms.activateRootEpoch(1, chainHash(chainHash(bytes32(0), ca(0xa0), k256(0xb0)), ca(0xa1), k256(0xb1))); + vm.stopPrank(); + + bytes32 hash1 = chainHash(chainHash(bytes32(0), ca(0xa0), k256(0xb0)), ca(0xa1), k256(0xb1)); + AuthorizationResult memory result = authorize(authorizationInfo(user), false); + assertFalse(result.authorized); + assertEq(result.rejectionReason, "App not registered"); + assertEq(result.currentRootEpoch, 1); + assertEq(result.currentRootEpochHash, hash1); + + AuthorizationRequest memory request = AuthorizationRequest( + authorizationInfo(user), + keccak256("kms_serve"), + OptionalUint256(false, 0), + OptionalUint256(false, 0), + "dstack-tdx", + bytes32(0) + ); + result = kms.authorizeApp(request); + assertEq(result.rejectionReason, "Invalid authorization operation"); + assertEq(result.currentRootEpoch, 1); + assertEq(result.currentRootEpochHash, hash1); } function test_IsKmsAllowed() public { @@ -188,12 +965,12 @@ contract DstackKmsTest is Test { // Setup allowed values vm.startPrank(owner); - kms.addKmsDevice(deviceId); - kms.addKmsAggregatedMr(mrAggregated); - kms.addOsImageHash(osImageHash); + kms.addKmsDeviceAtEpochs(0, 0, deviceId); + kms.addKmsAggregatedMrAtEpochs(0, 0, mrAggregated); + kms.addOsImageHashAtEpochs(0, 0, osImageHash); vm.stopPrank(); - IAppAuth.AppBootInfo memory bootInfo = IAppAuth.AppBootInfo({ + IAppAuth.AppInfo memory bootInfo = IAppAuth.AppInfo({ appId: address(0), composeHash: bytes32(0), instanceId: address(0), @@ -217,12 +994,12 @@ contract DstackKmsTest is Test { // Setup allowed values vm.startPrank(owner); - kms.addKmsDevice(deviceId); - kms.addKmsAggregatedMr(mrAggregated); - kms.addOsImageHash(osImageHash); + kms.addKmsDeviceAtEpochs(0, 0, deviceId); + kms.addKmsAggregatedMrAtEpochs(0, 0, mrAggregated); + kms.addOsImageHashAtEpochs(0, 0, osImageHash); vm.stopPrank(); - IAppAuth.AppBootInfo memory bootInfo = IAppAuth.AppBootInfo({ + IAppAuth.AppInfo memory bootInfo = IAppAuth.AppInfo({ appId: address(0), composeHash: bytes32(0), instanceId: address(0), @@ -246,11 +1023,11 @@ contract DstackKmsTest is Test { bytes32 osImageHash = bytes32(uint256(111)); vm.startPrank(owner); - kms.addOsImageHash(osImageHash); + kms.addOsImageHashAtEpochs(0, 0, osImageHash); address appId = kms.deployAndRegisterApp(user, false, false, deviceId, composeHash); vm.stopPrank(); - IAppAuth.AppBootInfo memory bootInfo = IAppAuth.AppBootInfo({ + IAppAuth.AppInfo memory bootInfo = IAppAuth.AppInfo({ appId: appId, composeHash: composeHash, instanceId: address(0), @@ -378,11 +1155,440 @@ contract DstackKmsTest is Test { // Old owner has lost authority. vm.prank(owner); vm.expectRevert(abi.encodeWithSignature("OwnableUnauthorizedAccount(address)", owner)); - kms.addKmsAggregatedMr(mr); + kms.addKmsAggregatedMrAtEpochs(0, 0, mr); // New owner has it. vm.prank(newOwner); - kms.addKmsAggregatedMr(mr); + kms.addKmsAggregatedMrAtEpochs(0, 0, mr); assertTrue(kms.kmsAllowedAggregatedMrs(mr)); } + + function registerNextRootEpoch() internal { + uint256 epoch = kms.rootEpochCount(); + kms.registerRootEpoch(ca(uint8(0xa0 + epoch)), k256(uint8(0xb0 + epoch)), "ipfs://epoch"); + } + + function activateNextRootEpoch() internal { + (uint256 current,) = kms.currentRootEpoch(); + (,,, bytes32 hash) = kms.rootEpoch(current + 1); + kms.activateRootEpoch(current + 1, hash); + } + + function epochRequest( + IAppAuth.AppInfo memory info, + uint256 root, + uint256 appEpoch + ) + internal + pure + returns (AuthorizationRequest memory) + { + return AuthorizationRequest( + info, + keccak256("app_get_key"), + OptionalUint256(true, appEpoch), + OptionalUint256(true, root), + "dstack-tdx", + bytes32(0) + ); + } + + function kmsEpochRequest( + IAppAuth.AppInfo memory info, + uint256 root, + uint256 appEpoch + ) + internal + pure + returns (AuthorizationRequest memory request) + { + request = epochRequest(info, root, appEpoch); + request.operation = keccak256("kms_import_keys"); + } + + function approveKmsAtEpoch(IAppAuth.AppInfo memory info, uint256 epoch) internal { + kms.addOsImageHashAtEpochs(epoch, epoch, info.osImageHash); + kms.addKmsAggregatedMrAtEpochs(epoch, epoch, info.mrAggregated); + kms.addKmsDeviceAtEpochs(epoch, epoch, info.deviceId); + } + + function test_KmsEpochRowsDoNotInheritAndCanBeRevokedIndependently() public { + IAppAuth.AppInfo memory info = authorizationInfo(address(kms)); + vm.startPrank(owner); + registerNextRootEpoch(); + approveKmsAtEpoch(info, 0); + registerNextRootEpoch(); + activateNextRootEpoch(); + assertTrue(kms.authorizeKms(kmsEpochRequest(info, 0, 0)).authorized); + assertFalse(authorize(info, true).authorized); + (bool allowed, string memory reason) = kms.isKmsAllowed(info); + assertFalse(allowed, "legacy KMS check ends at rotation"); + assertEq(reason, "Root epoch requires epoch-aware authorization"); + kms.addOsImageHashAtEpochs(1, 1, info.osImageHash); + assertFalse(authorize(info, true).authorized); + kms.addKmsAggregatedMrAtEpochs(1, 1, info.mrAggregated); + assertFalse(authorize(info, true).authorized); + kms.addKmsDeviceAtEpochs(1, 1, info.deviceId); + assertTrue(authorize(info, true).authorized); + kms.removeOsImageHashAtEpochs(1, 1, info.osImageHash); + assertFalse(authorize(info, true).authorized); + assertTrue(kms.allowedOsImages(info.osImageHash)); + assertTrue(kms.authorizeKms(kmsEpochRequest(info, 0, 0)).authorized); + kms.addOsImageHashAtEpochs(1, 1, info.osImageHash); + kms.removeKmsAggregatedMrAtEpochs(0, 0, info.mrAggregated); + assertFalse(kms.authorizeKms(kmsEpochRequest(info, 0, 0)).authorized); + assertTrue(authorize(info, true).authorized); + kms.addKmsAggregatedMrAtEpochs(0, 0, info.mrAggregated); + kms.removeKmsDeviceAtEpochs(0, 0, info.deviceId); + assertFalse(kms.authorizeKms(kmsEpochRequest(info, 0, 0)).authorized); + assertTrue(authorize(info, true).authorized); + vm.stopPrank(); + } + + function test_AppAndRootRowsAreSelectedIndependently() public { + IAppAuth.AppInfo memory info = authorizationInfo(address(0)); + vm.startPrank(owner); + registerNextRootEpoch(); + kms.addOsImageHashAtEpochs(0, 0, info.osImageHash); + info.appId = kms.deployAndRegisterApp(user, false, false, info.deviceId, info.composeHash); + registerNextRootEpoch(); + activateNextRootEpoch(); + vm.stopPrank(); + DstackApp policy = DstackApp(info.appId); + vm.prank(user); + policy.advanceAppEpoch(0); + assertFalse(kms.authorizeApp(epochRequest(info, 0, 1)).authorized); + assertFalse(kms.authorizeApp(epochRequest(info, 1, 0)).authorized); + assertTrue(kms.authorizeApp(epochRequest(info, 0, 0)).authorized); + vm.startPrank(user); + policy.addComposeHashAtEpoch(1, info.composeHash); + policy.addDeviceAtEpoch(1, info.deviceId); + vm.stopPrank(); + assertTrue(kms.authorizeApp(epochRequest(info, 0, 1)).authorized); + assertFalse(authorize(info, false).authorized); + vm.prank(owner); + kms.addOsImageHashAtEpochs(1, 1, info.osImageHash); + assertTrue(authorize(info, false).authorized); + assertTrue(kms.authorizeApp(epochRequest(info, 1, 0)).authorized); + vm.prank(owner); + kms.removeOsImageHashAtEpochs(0, 0, info.osImageHash); + assertFalse(kms.authorizeApp(epochRequest(info, 0, 0)).authorized); + assertTrue(authorize(info, false).authorized); + } + + function test_ExplicitRootEpochSettersRequireOwnerAndRegisteredEpoch() public { + vm.startPrank(owner); + vm.expectRevert(DstackKms.UnknownRootEpoch.selector); + kms.addOsImageHashAtEpochs(1, 1, bytes32(uint256(1))); + vm.expectRevert(DstackKms.UnknownRootEpoch.selector); + kms.removeOsImageHashAtEpochs(1, 1, bytes32(uint256(1))); + vm.expectRevert(DstackKms.UnknownRootEpoch.selector); + kms.addKmsAggregatedMrAtEpochs(1, 1, bytes32(uint256(1))); + vm.expectRevert(DstackKms.UnknownRootEpoch.selector); + kms.removeKmsAggregatedMrAtEpochs(1, 1, bytes32(uint256(1))); + vm.expectRevert(DstackKms.UnknownRootEpoch.selector); + kms.addKmsDeviceAtEpochs(1, 1, bytes32(uint256(1))); + vm.expectRevert(DstackKms.UnknownRootEpoch.selector); + kms.removeKmsDeviceAtEpochs(1, 1, bytes32(uint256(1))); + vm.stopPrank(); + bytes memory unauthorized = abi.encodeWithSelector(OwnableUpgradeable.OwnableUnauthorizedAccount.selector, user); + vm.startPrank(user); + vm.expectRevert(unauthorized); + kms.addOsImageHashAtEpochs(0, 0, bytes32(uint256(1))); + vm.expectRevert(unauthorized); + kms.removeOsImageHashAtEpochs(0, 0, bytes32(uint256(1))); + vm.expectRevert(unauthorized); + kms.addKmsAggregatedMrAtEpochs(0, 0, bytes32(uint256(1))); + vm.expectRevert(unauthorized); + kms.removeKmsAggregatedMrAtEpochs(0, 0, bytes32(uint256(1))); + vm.expectRevert(unauthorized); + kms.addKmsDeviceAtEpochs(0, 0, bytes32(uint256(1))); + vm.expectRevert(unauthorized); + kms.removeKmsDeviceAtEpochs(0, 0, bytes32(uint256(1))); + vm.stopPrank(); + } + + function test_AppOperationIsForwardedAndLegacyAuthorizationEndsAtRotation() public { + IAppAuth.AppInfo memory info = authorizationInfo(address(0)); + vm.startPrank(owner); + registerNextRootEpoch(); + kms.addOsImageHashAtEpochs(0, 0, info.osImageHash); + info.appId = kms.deployAndRegisterApp(user, false, false, info.deviceId, info.composeHash); + vm.stopPrank(); + AuthorizationRequest memory request = epochRequest(info, 0, 0); + vm.mockCall( + info.appId, + abi.encodeCall(IAppEpochAuth.authorizeApp, (request)), + abi.encode(AuthorizationResult(false, "key retrieval denied", "", 0, bytes32(0), 0, 0, bytes32(0))) + ); + assertEq(kms.authorizeApp(request).rejectionReason, "key retrieval denied"); + request.operation = keccak256("app_get_cert"); + vm.mockCall( + info.appId, + abi.encodeCall(IAppEpochAuth.authorizeApp, (request)), + abi.encode(AuthorizationResult(true, "", "", 0, bytes32(0), 0, 0, bytes32(0))) + ); + assertTrue(kms.authorizeApp(request).authorized); + (bool allowed,) = kms.isAppAllowed(info); + assertTrue(allowed); + + vm.startPrank(owner); + registerNextRootEpoch(); + activateNextRootEpoch(); + vm.stopPrank(); + string memory reason; + (allowed, reason) = kms.isAppAllowed(info); + assertFalse(allowed); + assertEq(reason, "Root epoch requires epoch-aware authorization"); + } + + function test_LegacyAppCheckRefusesOnceTheAppEpochAdvances() public { + IAppAuth.AppInfo memory info = authorizationInfo(address(0)); + vm.startPrank(owner); + registerNextRootEpoch(); + kms.addOsImageHashAtEpochs(0, 0, info.osImageHash); + info.appId = kms.deployAndRegisterApp(user, false, false, info.deviceId, info.composeHash); + vm.stopPrank(); + (bool allowed,) = kms.isAppAllowed(info); + assertTrue(allowed); + + vm.prank(user); + DstackApp(info.appId).advanceAppEpoch(0); + string memory reason; + (allowed, reason) = kms.isAppAllowed(info); + assertFalse(allowed); + assertEq(reason, "App epoch requires epoch-aware authorization"); + } + + function test_AuthorizeAppForwardsRequestAndFillsKmsFields() public { + IAppAuth.AppInfo memory info = authorizationInfo(address(0)); + vm.startPrank(owner); + registerNextRootEpoch(); + kms.setGatewayAppId("gateway"); + kms.addOsImageHashAtEpochs(0, 0, info.osImageHash); + info.appId = kms.deployAndRegisterApp(user, false, false, info.deviceId, info.composeHash); + vm.stopPrank(); + (, bytes32 rootHash) = kms.currentRootEpoch(); + AuthorizationRequest memory request = epochRequest(info, 0, 3); + request.requestedRootEpoch = OptionalUint256(false, 0); + // The KMS overwrites whatever the policy reports for fields it owns. + vm.mockCall( + info.appId, + abi.encodeCall(IAppEpochAuth.authorizeApp, (request)), + abi.encode( + AuthorizationResult(true, "", "policy-gateway", 9, bytes32(uint256(9)), 3, 9, bytes32(uint256(9))) + ) + ); + vm.expectCall(info.appId, abi.encodeCall(IAppEpochAuth.authorizeApp, (request)), 1); + // The app epoch comes from the forwarded decision only. + vm.expectCall(info.appId, abi.encodeCall(IAppEpochAuth.currentAppEpoch, ()), 0); + AuthorizationResult memory result = kms.authorizeApp(request); + assertTrue(result.authorized); + assertEq(result.currentAppEpoch, 3); + assertEq(result.gatewayAppId, "gateway"); + assertEq(result.currentRootEpoch, 0); + assertEq(result.currentRootEpochHash, rootHash); + assertEq(result.latestRootEpoch, 0); + assertEq(result.latestRootEpochHash, rootHash); + } + + function test_AuthorizationReportsTheLatestRegisteredRootEpoch() public { + IAppAuth.AppInfo memory info = authorizationInfo(address(0)); + AuthorizationResult memory result = authorize(authorizationInfo(address(kms)), true); + assertEq(result.latestRootEpoch, 0); + assertEq(result.latestRootEpochHash, bytes32(0)); + vm.startPrank(owner); + registerNextRootEpoch(); + kms.addOsImageHashAtEpochs(0, 0, info.osImageHash); + info.appId = kms.deployAndRegisterApp(user, false, false, info.deviceId, info.composeHash); + registerNextRootEpoch(); + vm.stopPrank(); + (,,, bytes32 currentHash) = kms.rootEpoch(0); + (,,, bytes32 pendingHash) = kms.rootEpoch(1); + assertTrue(currentHash != pendingHash); + AuthorizationRequest memory request = epochRequest(info, 0, 0); + AuthorizationResult[3] memory results = [ + kms.authorizeKms(kmsEpochRequest(authorizationInfo(address(kms)), 1, 0)), + kms.authorizeApp(request), + // A KMS-side rejection still reports both epochs. + kms.authorizeApp(epochRequest(info, 1, 0)) + ]; + for (uint256 i; i < results.length; i++) { + assertEq(results[i].currentRootEpoch, 0); + assertEq(results[i].currentRootEpochHash, currentHash); + assertEq(results[i].latestRootEpoch, 1); + assertEq(results[i].latestRootEpochHash, pendingHash); + } + assertTrue(results[1].authorized); + assertEq(results[2].rejectionReason, "Requested root epoch is not active"); + } + + function test_AuthorizeAppKeepsKmsChecksBeforeForwarding() public { + IAppAuth.AppInfo memory info = authorizationInfo(address(0)); + vm.startPrank(owner); + registerNextRootEpoch(); + info.appId = kms.deployAndRegisterApp(user, false, false, info.deviceId, info.composeHash); + vm.stopPrank(); + bytes memory forwarded = abi.encodeWithSelector(IAppEpochAuth.authorizeApp.selector); + vm.expectCall(info.appId, forwarded, 0); + assertEq(kms.authorizeApp(epochRequest(info, 0, 0)).rejectionReason, "OS image is not allowed"); + AuthorizationRequest memory request = epochRequest(info, 0, 0); + request.operation = keccak256("kms_serve"); + assertEq(kms.authorizeApp(request).rejectionReason, "Invalid authorization operation"); + assertEq(kms.authorizeApp(epochRequest(info, 1, 0)).rejectionReason, "Requested root epoch is not active"); + info.appId = user; + assertEq(kms.authorizeApp(epochRequest(info, 0, 0)).rejectionReason, "App not registered"); + } + + function test_LegacyAppPolicyCannotAuthorizeNonzeroAppEpochs() public { + IAppAuth.AppInfo memory info = authorizationInfo(address(0)); + vm.startPrank(owner); + registerNextRootEpoch(); + kms.addOsImageHashAtEpochs(0, 0, info.osImageHash); + info.appId = kms.deployAndRegisterApp(user, false, false, info.deviceId, info.composeHash); + vm.stopPrank(); + vm.prank(user); + DstackApp(info.appId).advanceAppEpoch(0); + vm.mockCall( + info.appId, abi.encodeCall(IERC165.supportsInterface, (type(IAppEpochAuth).interfaceId)), abi.encode(false) + ); + vm.mockCall(info.appId, abi.encodeCall(IAppAuth.isAppAllowed, (info)), abi.encode(true, "")); + assertTrue(kms.authorizeApp(epochRequest(info, 0, 0)).authorized); + AuthorizationResult memory result = authorize(info, false); + assertTrue(result.authorized); + assertEq(result.currentAppEpoch, 0); + result = kms.authorizeApp(epochRequest(info, 0, 1)); + assertFalse(result.authorized); + assertEq(result.rejectionReason, "Requested app epoch is not active"); + vm.clearMockedCalls(); + vm.mockCallRevert( + info.appId, abi.encodeCall(IAppEpochAuth.authorizeApp, (epochRequest(info, 0, 0))), "policy unavailable" + ); + vm.expectRevert(bytes("policy unavailable")); + kms.authorizeApp(epochRequest(info, 0, 0)); + } + + function test_RangeSettersCoverEveryRowInRange() public { + IAppAuth.AppInfo memory info = authorizationInfo(address(0)); + vm.startPrank(owner); + registerNextRootEpoch(); + registerNextRootEpoch(); + kms.addOsImageHashAtEpochs(0, 1, info.osImageHash); + kms.addKmsAggregatedMrAtEpochs(0, 1, info.mrAggregated); + kms.addKmsDeviceAtEpochs(0, 1, info.deviceId); + info.appId = kms.deployAndRegisterApp(user, false, false, info.deviceId, info.composeHash); + for (uint256 epoch = 0; epoch < 2; ++epoch) { + assertTrue(kms.allowedOsImagesAtEpoch(epoch, info.osImageHash)); + assertTrue(kms.kmsAllowedAggregatedMrsAtEpoch(epoch, info.mrAggregated)); + assertTrue(kms.kmsAllowedDeviceIdsAtEpoch(epoch, info.deviceId)); + } + assertTrue(authorize(info, true).authorized); + assertTrue(kms.authorizeKms(kmsEpochRequest(info, 1, 0)).authorized); + assertTrue(authorize(info, false).authorized); + + kms.removeKmsAggregatedMrAtEpochs(0, 1, info.mrAggregated); + assertFalse(authorize(info, true).authorized); + assertFalse(kms.authorizeKms(kmsEpochRequest(info, 1, 0)).authorized); + kms.addKmsAggregatedMrAtEpochs(0, 1, info.mrAggregated); + kms.removeKmsDeviceAtEpochs(0, 1, info.deviceId); + assertFalse(authorize(info, true).authorized); + assertFalse(kms.authorizeKms(kmsEpochRequest(info, 1, 0)).authorized); + kms.addKmsDeviceAtEpochs(0, 1, info.deviceId); + + vm.expectRevert(DstackKms.InvalidRootEpochRange.selector); + kms.removeOsImageHashAtEpochs(1, 0, info.osImageHash); + vm.expectRevert(DstackKms.UnknownRootEpoch.selector); + kms.removeOsImageHashAtEpochs(0, 2, info.osImageHash); + vm.stopPrank(); + } + + function test_RangeRemovalRevokesOlderRootRows() public { + IAppAuth.AppInfo memory info = authorizationInfo(address(0)); + vm.startPrank(owner); + registerNextRootEpoch(); + kms.addOsImageHashAtEpochs(0, 0, info.osImageHash); + info.appId = kms.deployAndRegisterApp(user, false, false, info.deviceId, info.composeHash); + registerNextRootEpoch(); + activateNextRootEpoch(); + kms.addOsImageHashAtEpochs(1, 1, info.osImageHash); + assertTrue(authorize(info, false).authorized); + assertTrue(kms.authorizeApp(epochRequest(info, 0, 0)).authorized); + + kms.removeOsImageHashAtEpochs(0, 1, info.osImageHash); + vm.stopPrank(); + assertFalse(authorize(info, false).authorized); + for (uint256 epoch = 0; epoch < 2; ++epoch) { + assertFalse(kms.allowedOsImagesAtEpoch(epoch, info.osImageHash)); + AuthorizationResult memory result = kms.authorizeApp(epochRequest(info, epoch, 0)); + assertEq(result.rejectionReason, "OS image is not allowed"); + } + } + + function test_PopThenReRegisterIdenticalKeysStartsWithEmptyRows() public { + IAppAuth.AppInfo memory info = authorizationInfo(address(kms)); + vm.startPrank(owner); + registerNextRootEpoch(); + registerNextRootEpoch(); + approveKmsAtEpoch(info, 1); + assertTrue(kms.authorizeKms(kmsEpochRequest(info, 1, 0)).authorized); + (,,, bytes32 popped) = kms.rootEpoch(1); + + kms.popRootEpoch(1, popped); + assertFalse(kms.allowedOsImagesAtEpoch(1, info.osImageHash)); + vm.expectRevert(DstackKms.UnknownRootEpoch.selector); + kms.removeOsImageHashAtEpochs(1, 1, info.osImageHash); + + registerNextRootEpoch(); + (,,, bytes32 again) = kms.rootEpoch(1); + assertEq(again, popped); + assertFalse(kms.allowedOsImagesAtEpoch(1, info.osImageHash)); + assertFalse(kms.kmsAllowedAggregatedMrsAtEpoch(1, info.mrAggregated)); + assertFalse(kms.kmsAllowedDeviceIdsAtEpoch(1, info.deviceId)); + assertFalse(kms.authorizeKms(kmsEpochRequest(info, 1, 0)).authorized); + vm.stopPrank(); + } + + function test_KmsServeIsLimitedToTheCurrentRootEpoch() public { + IAppAuth.AppInfo memory info = authorizationInfo(address(kms)); + vm.startPrank(owner); + registerNextRootEpoch(); + registerNextRootEpoch(); + approveKmsAtEpoch(info, 0); + approveKmsAtEpoch(info, 1); + vm.stopPrank(); + AuthorizationRequest memory request = kmsEpochRequest(info, 1, 0); + assertTrue(kms.authorizeKms(request).authorized); + request.operation = keccak256("kms_export_keys"); + assertTrue(kms.authorizeKms(request).authorized); + request.operation = keccak256("kms_serve"); + assertEq(kms.authorizeKms(request).rejectionReason, "Requested root epoch is not active"); + request.requestedRootEpoch = OptionalUint256(true, 0); + assertTrue(kms.authorizeKms(request).authorized); + request.requestedRootEpoch = OptionalUint256(false, 0); + assertTrue(kms.authorizeKms(request).authorized); + } + + function test_AtEpochSettersChangeOnlyTheirRow() public { + IAppAuth.AppInfo memory info = authorizationInfo(address(kms)); + vm.startPrank(owner); + registerNextRootEpoch(); + registerNextRootEpoch(); + approveKmsAtEpoch(info, 1); + assertFalse(kms.allowedOsImagesAtEpoch(0, info.osImageHash)); + assertFalse(kms.kmsAllowedAggregatedMrsAtEpoch(0, info.mrAggregated)); + assertFalse(kms.kmsAllowedDeviceIdsAtEpoch(0, info.deviceId)); + assertFalse(authorize(info, true).authorized); + assertTrue(kms.authorizeKms(kmsEpochRequest(info, 1, 0)).authorized); + + approveKmsAtEpoch(info, 0); + kms.removeOsImageHashAtEpochs(1, 1, info.osImageHash); + kms.removeKmsAggregatedMrAtEpochs(1, 1, info.mrAggregated); + kms.removeKmsDeviceAtEpochs(1, 1, info.deviceId); + assertTrue(kms.allowedOsImagesAtEpoch(0, info.osImageHash)); + assertTrue(kms.kmsAllowedAggregatedMrsAtEpoch(0, info.mrAggregated)); + assertTrue(kms.kmsAllowedDeviceIdsAtEpoch(0, info.deviceId)); + assertTrue(authorize(info, true).authorized); + assertFalse(kms.authorizeKms(kmsEpochRequest(info, 1, 0)).authorized); + vm.stopPrank(); + } } diff --git a/dstack/kms/auth-eth/test/DstackKmsEpoch.symbolic.t.sol b/dstack/kms/auth-eth/test/DstackKmsEpoch.symbolic.t.sol new file mode 100644 index 0000000000..c7236b4ea8 --- /dev/null +++ b/dstack/kms/auth-eth/test/DstackKmsEpoch.symbolic.t.sol @@ -0,0 +1,638 @@ +/* + * SPDX-FileCopyrightText: © 2026 Phala Network + * + * SPDX-License-Identifier: Apache-2.0 + */ + +pragma solidity ^0.8.24; + +import "forge-std/Test.sol"; +import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol"; +import "../contracts/AuthorizationOperation.sol"; +import "../contracts/DstackApp.sol"; +import "../contracts/DstackKms.sol"; + +function _appAuth( + DstackApp target, + IAppAuth.AppInfo memory info, + uint256 epoch, + bytes32 operation +) + view + returns (bool, string memory) +{ + AuthorizationResult memory result = target.authorizeApp( + AuthorizationRequest( + info, operation, OptionalUint256(true, epoch), OptionalUint256(false, 0), "dstack-tdx", bytes32(0) + ) + ); + return (result.authorized, result.rejectionReason); +} + +/// An app policy predating app epochs: IAppAuth only, one allowed compose hash. +contract LegacyAppPolicy is IAppAuth { + bytes32 internal immutable allowed; + + constructor(bytes32 composeHash) { + allowed = composeHash; + } + + function supportsInterface(bytes4 interfaceId) external pure returns (bool) { + return interfaceId == 0x01ffc9a7 || interfaceId == 0x1e079198; + } + + function isAppAllowed(AppInfo calldata info) external view returns (bool, string memory) { + return info.composeHash == allowed ? (true, "") : (false, "Compose hash not allowed"); + } +} + +/// @notice Halmos symbolic tests for DstackKms root epochs and epoch-scoped +/// authorization. +/// +/// setUp registers root epochs 0, 1 and 2, activates 1 (so 2 is pending), +/// admits one KMS identity and OS image per epoch, and deploys an app at app +/// epoch 1. Halmos has no symbolic storage, so the properties are proved from +/// this state, after one symbolic call where noted. +/// +/// Run with `halmos --contract DstackKmsEpochSymbolicTest`. +contract DstackKmsEpochSymbolicTest is Test { + DstackKms internal kms; + DstackApp internal app; + address internal constant OWNER = address(0xA11CE); + bytes27 internal constant P256_SPKI_PREFIX = 0x3059301306072a8648ce3d020106082a8648ce3d03010703420004; + uint256 internal constant KMS_POLICY_SETTERS = 12; + + /// The AppInfo fields DstackKms and DstackApp read; the app ID is the + /// deployed app and the remaining fields stay zero. + struct Identity { + bytes32 osImageHash; + bytes32 mrAggregated; + bytes32 deviceId; + bytes32 composeHash; + bool upToDate; + } + + function setUp() public { + DstackKms impl = new DstackKms(); + bytes memory initData = abi.encodeCall(DstackKms.initialize, (OWNER, address(new DstackApp()))); + kms = DstackKms(address(new ERC1967Proxy(address(impl), initData))); + + vm.startPrank(OWNER); + for (uint256 epoch = 0; epoch < 3; epoch++) { + kms.registerRootEpoch(_ca(bytes32(epoch + 1), bytes32(0)), _k256(true, bytes32(epoch + 1)), "evidence"); + kms.addOsImageHashAtEpochs(epoch, epoch, _id(0x05, epoch)); + kms.addKmsAggregatedMrAtEpochs(epoch, epoch, _id(0x0a, epoch)); + kms.addKmsDeviceAtEpochs(epoch, epoch, _id(0x0d, epoch)); + } + (, bytes32 hash1) = _entry(1); + kms.activateRootEpoch(1, hash1); + + app = DstackApp(kms.deployAndRegisterApp(OWNER, false, false, true, bytes32(0), _id(0xc0, 0))); + app.advanceAppEpoch(0); + app.addComposeHashAtEpoch(1, _id(0xc0, 1)); + vm.stopPrank(); + } + + function _id(uint256 kind, uint256 epoch) internal pure returns (bytes32) { + return bytes32((kind << 8) | epoch); + } + + function _ca(bytes32 x, bytes32 y) internal pure returns (bytes memory) { + return abi.encodePacked(P256_SPKI_PREFIX, x, y); + } + + function _k256(bool even, bytes32 x) internal pure returns (bytes memory) { + return abi.encodePacked(even ? bytes1(0x02) : bytes1(0x03), x); + } + + function _current() internal view returns (uint256 epoch) { + (epoch,) = kms.currentRootEpoch(); + } + + /// Hash of an epoch's keys, and its chain hash. + function _entry(uint256 epoch) internal view returns (bytes32 keys, bytes32 chainHash) { + (bytes memory ca, bytes memory k256,, bytes32 hash) = kms.rootEpoch(epoch); + return (keccak256(abi.encode(ca, k256)), hash); + } + + function _info(Identity memory id) internal view returns (IAppAuth.AppInfo memory info) { + info.appId = address(app); + info.osImageHash = id.osImageHash; + info.mrAggregated = id.mrAggregated; + info.deviceId = id.deviceId; + info.composeHash = id.composeHash; + info.tcbStatus = id.upToDate ? "UpToDate" : "OutOfDate"; + } + + function _request( + IAppAuth.AppInfo memory info, + bytes32 operation, + bool rootSet, + uint256 root, + bool appSet, + uint256 appEpoch + ) + internal + pure + returns (AuthorizationRequest memory) + { + return AuthorizationRequest( + info, operation, OptionalUint256(appSet, appEpoch), OptionalUint256(rootSet, root), "dstack-tdx", bytes32(0) + ); + } + + /// Calldata of one KMS policy setter: 0-5 write the row of `epoch`, 6-11 + /// every row from `epoch` through `to`. + function _kmsPolicyCall( + uint256 which, + uint256 epoch, + uint256 to, + bytes32 word + ) + internal + pure + returns (bytes memory data) + { + uint256 latest = to; + if (which == 0) data = abi.encodeCall(DstackKms.addKmsAggregatedMrAtEpochs, (epoch, epoch, word)); + else if (which == 1) data = abi.encodeCall(DstackKms.removeKmsAggregatedMrAtEpochs, (epoch, epoch, word)); + else if (which == 2) data = abi.encodeCall(DstackKms.addKmsDeviceAtEpochs, (epoch, epoch, word)); + else if (which == 3) data = abi.encodeCall(DstackKms.removeKmsDeviceAtEpochs, (epoch, epoch, word)); + else if (which == 4) data = abi.encodeCall(DstackKms.addOsImageHashAtEpochs, (epoch, epoch, word)); + else if (which == 5) data = abi.encodeCall(DstackKms.removeOsImageHashAtEpochs, (epoch, epoch, word)); + else if (which == 6) data = abi.encodeCall(DstackKms.addKmsAggregatedMrAtEpochs, (epoch, latest, word)); + else if (which == 7) data = abi.encodeCall(DstackKms.removeKmsAggregatedMrAtEpochs, (epoch, latest, word)); + else if (which == 8) data = abi.encodeCall(DstackKms.addKmsDeviceAtEpochs, (epoch, latest, word)); + else if (which == 9) data = abi.encodeCall(DstackKms.removeKmsDeviceAtEpochs, (epoch, latest, word)); + else if (which == 10) data = abi.encodeCall(DstackKms.addOsImageHashAtEpochs, (epoch, latest, word)); + else data = abi.encodeCall(DstackKms.removeOsImageHashAtEpochs, (epoch, latest, word)); + } + + // --------------------------------------------------------------- + // Root registry step invariant. After any single call to any + // enumerated mutating function, by any caller with symbolic args: + // - the current epoch stays registered and only the owner's + // activation of the next epoch, naming its chain hash, moves it, + // by one; + // - the registry changes by at most one entry at its end, and only + // the owner's pop of a pending epoch, naming its chain hash, + // removes one; + // - existing entries keep their keys and chain hashes; + // - every chain hash commits to its keys and the previous hash; + // - kmsInfo holds the current epoch's keys and no legacy evidence. + // --------------------------------------------------------------- + + /// Calldata of any enumerated mutating function. + function _anyCall( + uint256 which, + uint256 epoch, + bytes32 word, + bytes32 hash, + bool flag, + address addr + ) + internal + view + returns (bytes memory data) + { + if (which < KMS_POLICY_SETTERS) { + data = _kmsPolicyCall(which, epoch, kms.rootEpochCount() - 1, word); + } else if (which == 12) { + data = abi.encodeCall(DstackKms.registerRootEpoch, (_ca(word, hash), _k256(flag, word), "url")); + } else if (which == 13) { + data = abi.encodeCall(DstackKms.activateRootEpoch, (epoch, hash)); + } else if (which == 14) { + data = abi.encodeCall(DstackKms.popRootEpoch, (epoch, hash)); + } else if (which == 15) { + data = abi.encodeCall(DstackKms.setRootEpochEvidenceUrl, (epoch, "url")); + } else if (which == 16) { + data = abi.encodeCall(DstackKms.setGatewayAppId, ("gateway")); + } else if (which == 17) { + data = abi.encodeCall(DstackKms.setAppImplementation, (addr)); + } else if (which == 18) { + data = abi.encodeCall(DstackKms.registerApp, (addr)); + } else if (which == 19) { + data = abi.encodeWithSignature( + "deployAndRegisterApp(address,bool,bool,bool,bytes32,bytes32)", addr, flag, flag, flag, word, hash + ); + } else if (which == 20) { + data = abi.encodeCall(UUPSUpgradeable.upgradeToAndCall, (addr, "")); + } else if (which == 21) { + data = abi.encodeCall(Ownable2StepUpgradeable.transferOwnership, (addr)); + } else if (which == 22) { + data = abi.encodeCall(OwnableUpgradeable.renounceOwnership, ()); + } + } + + function _snapshot() internal view returns (bytes32[] memory entries, bytes32[] memory hashes) { + uint256 count = kms.rootEpochCount(); + entries = new bytes32[](count); + hashes = new bytes32[](count); + for (uint256 i = 0; i < count; i++) { + (entries[i], hashes[i]) = _entry(i); + } + } + + /// Every chain hash commits to its keys and the previous hash, entries + /// that existed before keep their keys and hashes, and kmsInfo holds + /// the current keys without legacy evidence. + function _assertRegistryConsistent(bytes32[] memory entries, bytes32[] memory hashes) internal view { + bytes32 previous; + for (uint256 i = 0; i < kms.rootEpochCount(); i++) { + (bytes memory ca, bytes memory k256,, bytes32 chainHash) = kms.rootEpoch(i); + assert(chainHash == keccak256(abi.encodePacked(previous, keccak256(ca), keccak256(k256)))); + if (i < entries.length) assert(keccak256(abi.encode(ca, k256)) == entries[i] && chainHash == hashes[i]); + previous = chainHash; + } + (bytes memory infoK256, bytes memory infoCa, bytes memory quote, bytes memory eventlog) = kms.kmsInfo(); + (bytes memory currentCa, bytes memory currentK256,,) = kms.rootEpoch(_current()); + assert(keccak256(infoCa) == keccak256(currentCa) && keccak256(infoK256) == keccak256(currentK256)); + assert(quote.length == 0 && eventlog.length == 0); + } + + /// @custom:halmos --loop 4 + function check_RootRegistry_StepInvariant( + address caller, + uint256 which, + uint256 epoch, + bytes32 word, + bytes32 hash, + bool flag, + address addr + ) + external + { + vm.assume(which <= 22); + // Registry functions index the root epoch array, which Halmos cannot + // do symbolically. Only epochs 0-2 exist, so every larger index + // behaves as 3; branching makes each case concrete. + if (which >= 13 && which <= 15) epoch = epoch == 0 ? 0 : epoch == 1 ? 1 : epoch == 2 ? 2 : 3; + uint256 currentBefore = _current(); + (bytes32[] memory entries, bytes32[] memory hashes) = _snapshot(); + + vm.prank(caller); + (bool ok,) = address(kms).call(_anyCall(which, epoch, word, hash, flag, addr)); + ok; + + uint256 count = kms.rootEpochCount(); + uint256 current = _current(); + assert(current < count); + if (current != currentBefore) { + assert(current == currentBefore + 1); + assert(caller == OWNER && which == 13 && epoch == current && hash == hashes[current]); + } + assert(count + 1 >= entries.length && count <= entries.length + 1); + if (count < entries.length) { + assert(caller == OWNER && which == 14 && epoch == count && epoch > currentBefore && hash == hashes[count]); + } + if (count > entries.length) assert(caller == OWNER && which == 12); + _assertRegistryConsistent(entries, hashes); + } + + /// Drop the last byte, keep the bytes, or append a zero byte. + function _resize(bytes memory data, int8 change) internal pure returns (bytes memory) { + if (change < 0) { + assembly { + mstore(data, sub(mload(data), 1)) + } + return data; + } + return change == 0 ? data : abi.encodePacked(data, bytes1(0)); + } + + // --------------------------------------------------------------- + // registerRootEpoch accepts exactly the encodings the KMS + // produces: a 91-byte uncompressed P-256 SubjectPublicKeyInfo and + // a 33-byte compressed secp256k1 key. + // --------------------------------------------------------------- + + function check_RegisterRootEpoch_AcceptsOnlyCanonicalEncodings( + bytes27 prefix, + bytes32 x, + bytes1 tag, + int8 caLength, + int8 k256Length + ) + external + { + bytes memory ca = _resize(abi.encodePacked(prefix, x, x), caLength); + bytes memory k256 = _resize(abi.encodePacked(tag, x), k256Length); + + vm.prank(OWNER); + (bool ok,) = address(kms).call(abi.encodeCall(DstackKms.registerRootEpoch, (ca, k256, "url"))); + + bool canonical = ca.length == 91 && prefix == P256_SPKI_PREFIX && k256.length == 33 + && (tag == bytes1(0x02) || tag == bytes1(0x03)); + assert(ok == canonical); + } + + // --------------------------------------------------------------- + // Authorization bounds: an operation of the wrong kind, an app + // root epoch above the current one, a KMS root epoch above the + // latest registered one, or an app epoch above the app's current + // one is never authorized. Every result reports the current root + // epoch and its chain hash. + // --------------------------------------------------------------- + + function check_Authorize_EnforcesEpochBounds( + bool isKms, + bytes32 operation, + bool rootSet, + uint256 root, + bool appSet, + uint256 appEpoch, + Identity calldata id + ) + external + view + { + AuthorizationRequest memory request = _request(_info(id), operation, rootSet, root, appSet, appEpoch); + AuthorizationResult memory result = isKms ? kms.authorizeKms(request) : kms.authorizeApp(request); + + (uint256 current, bytes32 currentHash) = kms.currentRootEpoch(); + assert(result.currentRootEpoch == current && result.currentRootEpochHash == currentHash); + + bool kindMatches = isKms ? AuthorizationOperation.isKms(operation) : AuthorizationOperation.isApp(operation); + bool issuesKeys = !isKms || operation == AuthorizationOperation.KMS_SERVE; + uint256 rootBound = issuesKeys ? current : kms.rootEpochCount() - 1; + uint256 appBound = isKms ? 0 : app.currentAppEpoch(); + if (!kindMatches || (rootSet && root > rootBound) || (appSet && appEpoch > appBound)) { + assert(!result.authorized); + } + } + + // --------------------------------------------------------------- + // Before any root epoch is registered, only KMS bootstrap can be + // authorized. + // --------------------------------------------------------------- + + function check_Authorize_OnlyBootstrapBeforeRegistration( + bool isKms, + bytes32 operation, + Identity calldata id + ) + external + { + DstackKms impl = new DstackKms(); + bytes memory initData = abi.encodeCall(DstackKms.initialize, (OWNER, address(new DstackApp()))); + DstackKms fresh = DstackKms(address(new ERC1967Proxy(address(impl), initData))); + vm.startPrank(OWNER); + fresh.addOsImageHashAtEpochs(0, 0, id.osImageHash); + fresh.addKmsAggregatedMrAtEpochs(0, 0, id.mrAggregated); + fresh.addKmsDeviceAtEpochs(0, 0, id.deviceId); + vm.stopPrank(); + + AuthorizationRequest memory request = _request(_info(id), operation, false, 0, false, 0); + AuthorizationResult memory result = isKms ? fresh.authorizeKms(request) : fresh.authorizeApp(request); + if (result.authorized) assert(isKms && operation == AuthorizationOperation.KMS_BOOTSTRAP); + } + + // --------------------------------------------------------------- + // KMS authorization matches the policy of the selected root epoch + // (requested, or current when unset), after any one owner write. + // --------------------------------------------------------------- + + /// @custom:halmos --loop 4 + function check_AuthorizeKms_MatchesEpochPolicy( + uint256 which, + uint256 writeEpoch, + uint256 writeTo, + bytes32 word, + bytes32 operation, + bool rootSet, + uint256 root, + Identity calldata id + ) + external + { + if (which < KMS_POLICY_SETTERS) { + bytes memory data = _kmsPolicyCall(which, writeEpoch, writeTo, word); + vm.prank(OWNER); + (bool ok,) = address(kms).call(data); + ok; + } + + AuthorizationResult memory result = kms.authorizeKms(_request(_info(id), operation, rootSet, root, false, 0)); + + uint256 epoch = rootSet ? root : _current(); + uint256 bound = operation == AuthorizationOperation.KMS_SERVE ? _current() : kms.rootEpochCount() - 1; + bool expected = AuthorizationOperation.isKms(operation) && epoch <= bound && id.upToDate + && kms.allowedOsImagesAtEpoch(epoch, id.osImageHash) + && kms.kmsAllowedAggregatedMrsAtEpoch(epoch, id.mrAggregated) + && kms.kmsAllowedDeviceIdsAtEpoch(epoch, id.deviceId); + assert(result.authorized == expected); + } + + // --------------------------------------------------------------- + // App authorization admits exactly a registered app whose OS image + // the selected root epoch allows and whose own policy admits it at + // the selected app epoch. + // --------------------------------------------------------------- + + function check_AuthorizeApp_MatchesKmsAndAppPolicy( + bool getCert, + bool rootSet, + uint256 root, + bool appSet, + uint256 appEpoch, + Identity calldata id + ) + external + view + { + bytes32 operation = getCert ? AuthorizationOperation.APP_GET_CERT : AuthorizationOperation.APP_GET_KEY; + IAppAuth.AppInfo memory info = _info(id); + AuthorizationResult memory result = kms.authorizeApp(_request(info, operation, rootSet, root, appSet, appEpoch)); + + uint256 rootEpoch = rootSet ? root : _current(); + uint256 selectedAppEpoch = appSet ? appEpoch : app.currentAppEpoch(); + bool expected = rootEpoch <= _current() && selectedAppEpoch <= app.currentAppEpoch() + && kms.allowedOsImagesAtEpoch(rootEpoch, id.osImageHash); + if (expected) (expected,) = _appAuth(app, info, selectedAppEpoch, operation); + assert(result.authorized == expected); + } + + // --------------------------------------------------------------- + // Epoch isolation: a KMS policy write never changes a KMS + // authorization decision at a root epoch outside the rows it names. + // --------------------------------------------------------------- + + /// @custom:halmos --loop 4 + function check_KmsPolicyWrite_PreservesOtherEpochDecisions( + uint256 which, + uint256 writeEpoch, + uint256 writeTo, + bytes32 word, + bytes32 operation, + uint256 root, + Identity calldata id + ) + external + { + vm.assume(which < KMS_POLICY_SETTERS); + bytes memory data = _kmsPolicyCall(which, writeEpoch, writeTo, word); + vm.assume(which < 6 ? writeEpoch != root : root < writeEpoch || root > writeTo); + + AuthorizationRequest memory request = _request(_info(id), operation, true, root, false, 0); + AuthorizationResult memory before = kms.authorizeKms(request); + vm.prank(OWNER); + (bool ok,) = address(kms).call(data); + ok; + AuthorizationResult memory afterWrite = kms.authorizeKms(request); + + assert(before.authorized == afterWrite.authorized); + assert(keccak256(bytes(before.rejectionReason)) == keccak256(bytes(afterWrite.rejectionReason))); + } + + // --------------------------------------------------------------- + // Revocation: removing a material from every registered row, 0 + // through the latest, leaves no selectable root epoch at which an + // identity carrying it is authorized, for any KMS or app operation. + // --------------------------------------------------------------- + + /// @custom:halmos --loop 4 + function check_FullRangeRemoval_RevokesAtEveryEpoch( + uint256 kind, + bytes32 operation, + bool rootSet, + uint256 root, + bool appSet, + uint256 appEpoch, + Identity calldata id + ) + external + { + vm.assume(kind < 3); + uint256 latest = kms.rootEpochCount() - 1; + vm.startPrank(OWNER); + if (kind == 0) kms.removeOsImageHashAtEpochs(0, latest, id.osImageHash); + else if (kind == 1) kms.removeKmsAggregatedMrAtEpochs(0, latest, id.mrAggregated); + else kms.removeKmsDeviceAtEpochs(0, latest, id.deviceId); + vm.stopPrank(); + + AuthorizationRequest memory request = _request(_info(id), operation, rootSet, root, appSet, appEpoch); + assert(!kms.authorizeKms(request).authorized); + if (kind == 0) assert(!kms.authorizeApp(request).authorized); + } + + // --------------------------------------------------------------- + // Policy rows belong to a registration: popping the pending epoch + // and registering the number again, with the same keys or others, + // starts with empty rows. + // --------------------------------------------------------------- + + function check_PopThenRegister_StartsWithEmptyRows( + bool sameKeys, + bytes32 x, + bytes32 y, + bool even, + bytes32 word + ) + external + { + (bytes memory ca, bytes memory k256,, bytes32 hash) = kms.rootEpoch(2); + if (!sameKeys) { + ca = _ca(x, y); + k256 = _k256(even, x); + } + vm.startPrank(OWNER); + kms.popRootEpoch(2, hash); + kms.registerRootEpoch(ca, k256, "evidence"); + vm.stopPrank(); + + assert(!kms.allowedOsImagesAtEpoch(2, word)); + assert(!kms.kmsAllowedAggregatedMrsAtEpoch(2, word)); + assert(!kms.kmsAllowedDeviceIdsAtEpoch(2, word)); + } + + // --------------------------------------------------------------- + // Root epoch 0's rows are the v0.5.x mappings: after any one owner + // write, the legacy getters and the epoch 0 getters agree. + // --------------------------------------------------------------- + + /// @custom:halmos --loop 4 + function check_EpochZeroRows_AreTheLegacyMappings( + uint256 which, + uint256 writeEpoch, + uint256 writeTo, + bytes32 word, + bytes32 probe + ) + external + { + vm.assume(which < KMS_POLICY_SETTERS); + vm.prank(OWNER); + (bool ok,) = address(kms).call(_kmsPolicyCall(which, writeEpoch, writeTo, word)); + ok; + assert(kms.allowedOsImages(probe) == kms.allowedOsImagesAtEpoch(0, probe)); + assert(kms.kmsAllowedAggregatedMrs(probe) == kms.kmsAllowedAggregatedMrsAtEpoch(0, probe)); + assert(kms.kmsAllowedDeviceIds(probe) == kms.kmsAllowedDeviceIdsAtEpoch(0, probe)); + } + + // --------------------------------------------------------------- + // An app policy predating app epochs (no IAppEpochAuth) is decided by + // its isAppAllowed and only for app epoch 0: an explicit nonzero app + // epoch is refused, and otherwise the decision is the KMS checks at + // the selected root epoch and the policy's own answer. + // --------------------------------------------------------------- + + function check_AuthorizeApp_LegacyPolicyOnlyAtAppEpochZero( + bool getCert, + bool rootSet, + uint256 root, + bool appSet, + uint256 appEpoch, + Identity calldata id + ) + external + { + LegacyAppPolicy legacy = new LegacyAppPolicy(_id(0xc0, 0)); + kms.registerApp(address(legacy)); + IAppAuth.AppInfo memory info = _info(id); + info.appId = address(legacy); + bytes32 operation = getCert ? AuthorizationOperation.APP_GET_CERT : AuthorizationOperation.APP_GET_KEY; + AuthorizationResult memory result = kms.authorizeApp(_request(info, operation, rootSet, root, appSet, appEpoch)); + + uint256 rootEpoch = rootSet ? root : _current(); + bool expected = rootEpoch <= _current() && (!appSet || appEpoch == 0) + && kms.allowedOsImagesAtEpoch(rootEpoch, id.osImageHash) && id.composeHash == _id(0xc0, 0); + assert(result.authorized == expected); + assert(result.currentAppEpoch == 0); + assert(kms.currentAppEpoch(address(legacy)) == 0); + } + + // --------------------------------------------------------------- + // Legacy entry points serve KMS binaries that only hold root epoch 0: + // before any rotation isKmsAllowed decides as KMS_SERVE at epoch 0, + // and once a later epoch is current both refuse. isAppAllowed never + // authorizes an app whose policy has left app epoch 0. + // --------------------------------------------------------------- + + function check_LegacyEntryPoints_RefuseOnceRotated(Identity calldata id) external view { + IAppAuth.AppInfo memory info = _info(id); + bytes32 rotated = keccak256("Root epoch requires epoch-aware authorization"); + (bool kmsAllowed, string memory kmsReason) = kms.isKmsAllowed(info); + assert(!kmsAllowed && keccak256(bytes(kmsReason)) == rotated); + (bool appAllowed, string memory appReason) = kms.isAppAllowed(info); + assert(!appAllowed && keccak256(bytes(appReason)) == rotated); + } + + function check_LegacyKmsCheck_ReadsEpochZeroBeforeRotation(Identity calldata id) external { + bytes memory initData = abi.encodeCall(DstackKms.initialize, (OWNER, address(new DstackApp()))); + kms = DstackKms(address(new ERC1967Proxy(address(new DstackKms()), initData))); + vm.startPrank(OWNER); + for (uint256 epoch = 0; epoch < 2; epoch++) { + kms.registerRootEpoch(_ca(bytes32(epoch + 1), bytes32(0)), _k256(true, bytes32(epoch + 1)), "evidence"); + kms.addOsImageHashAtEpochs(epoch, epoch, _id(0x05, epoch)); + kms.addKmsAggregatedMrAtEpochs(epoch, epoch, _id(0x0a, epoch)); + kms.addKmsDeviceAtEpochs(epoch, epoch, _id(0x0d, epoch)); + } + vm.stopPrank(); + // Epoch 1 is registered and prepared but pending. + IAppAuth.AppInfo memory info = _info(id); + (bool kmsAllowed,) = kms.isKmsAllowed(info); + AuthorizationResult memory serve = + kms.authorizeKms(_request(info, AuthorizationOperation.KMS_SERVE, true, 0, false, 0)); + assert(kmsAllowed == serve.authorized); + } +} diff --git a/dstack/kms/auth-eth/test/EventAudit.t.sol b/dstack/kms/auth-eth/test/EventAudit.t.sol index 9631b355ac..1fd48a8bbc 100644 --- a/dstack/kms/auth-eth/test/EventAudit.t.sol +++ b/dstack/kms/auth-eth/test/EventAudit.t.sol @@ -54,12 +54,12 @@ contract EventAuditTest is Test { vm.recordLogs(); vm.startPrank(owner); - kms.addKmsAggregatedMr(mr); - kms.addKmsDevice(device); - kms.addOsImageHash(image); + kms.addKmsAggregatedMrAtEpochs(0, 0, mr); + kms.addKmsDeviceAtEpochs(0, 0, device); + kms.addOsImageHashAtEpochs(0, 0, image); kms.setGatewayAppId(gateway); kms.registerApp(address(app)); - kms.removeKmsAggregatedMr(mr); + kms.removeKmsAggregatedMrAtEpochs(0, 0, mr); vm.stopPrank(); Vm.Log[] memory logs = vm.getRecordedLogs(); @@ -83,11 +83,11 @@ contract EventAuditTest is Test { vm.recordLogs(); vm.startPrank(owner); - app.addComposeHash(composeHash); - app.addDevice(device); + app.addComposeHashAtEpoch(0, composeHash); + app.addDeviceAtEpoch(0, device); app.setAllowAnyDevice(true); app.setRequireTcbUpToDate(true); - app.removeDevice(device); + app.removeDeviceAtEpoch(0, device); app.disableUpgrades(); vm.stopPrank(); Vm.Log[] memory logs = vm.getRecordedLogs(); @@ -110,7 +110,7 @@ contract EventAuditTest is Test { vm.recordLogs(); vm.prank(outsider); vm.expectRevert(); - kms.addOsImageHash(image); + kms.addOsImageHashAtEpochs(0, 0, image); Vm.Log[] memory logs = vm.getRecordedLogs(); assertEq(_auditCount(logs), 0); assertFalse(kms.allowedOsImages(image)); @@ -123,7 +123,7 @@ contract EventAuditTest is Test { vm.recordLogs(); vm.prank(owner); - app.addComposeHash(orphaned); + app.addComposeHashAtEpoch(0, orphaned); Vm.Log[] memory orphanLogs = vm.getRecordedLogs(); _assertAudit(orphanLogs, owner, "compose-hash", orphaned, true); assertTrue(app.allowedComposeHashes(orphaned)); @@ -133,7 +133,7 @@ contract EventAuditTest is Test { vm.recordLogs(); vm.prank(owner); - app.addComposeHash(canonical); + app.addComposeHashAtEpoch(0, canonical); Vm.Log[] memory canonicalLogs = vm.getRecordedLogs(); _assertAudit(canonicalLogs, owner, "compose-hash", canonical, true); assertEq(_auditCount(canonicalLogs), 1); diff --git a/dstack/kms/auth-eth/test/LegacyAppCompat.t.sol b/dstack/kms/auth-eth/test/LegacyAppCompat.t.sol new file mode 100644 index 0000000000..18e586455b --- /dev/null +++ b/dstack/kms/auth-eth/test/LegacyAppCompat.t.sol @@ -0,0 +1,220 @@ +/* + * SPDX-FileCopyrightText: © 2026 Phala Network + * + * SPDX-License-Identifier: Apache-2.0 + */ + +pragma solidity ^0.8.24; + +import "forge-std/Test.sol"; +import "openzeppelin-foundry-upgrades/Upgrades.sol"; +import "../contracts/DstackKms.sol"; +import "../contracts/DstackApp.sol"; + +// The epoch-less setters of the released app policies. +interface ILegacyApp { + function addComposeHash(bytes32 composeHash) external; + function removeComposeHash(bytes32 composeHash) external; + function setAllowAnyDevice(bool allowed) external; +} + +/// An upgraded DstackKms with app policies still on the v0.5.9 and v0.6.0 +/// implementations, which app owners upgrade on their own schedule. +contract LegacyAppCompatTest is Test { + DstackKms kms; + address owner = makeAddr("owner"); + address appOwner = makeAddr("appOwner"); + + string[2] internal appReleases = ["DstackAppV059.sol:DstackApp", "DstackAppV060.sol:DstackApp"]; + + bytes32 constant COMPOSE = bytes32(uint256(0xc0)); + bytes32 constant DEVICE = bytes32(uint256(0xd0)); + bytes32 constant IMAGE = bytes32(uint256(0x10)); + + function setUp() public { + vm.startPrank(owner); + kms = DstackKms( + Upgrades.deployUUPSProxy("DstackKms.sol", abi.encodeCall(DstackKms.initialize, (owner, address(0)))) + ); + kms.registerRootEpoch(key(91, 0xa0), key(33, 0xb0), "ipfs://0"); + kms.addOsImageHashAtEpochs(0, 0, IMAGE); + vm.stopPrank(); + } + + function key(uint256 length, uint8 fill) internal pure returns (bytes memory k) { + k = new bytes(length); + for (uint256 i; i < length; ++i) { + k[i] = bytes1(fill); + } + if (length == 91) { + bytes memory prefix = hex"3059301306072a8648ce3d020106082a8648ce3d03010703420004"; + for (uint256 i; i < prefix.length; ++i) { + k[i] = prefix[i]; + } + } else { + k[0] = 0x02; + } + } + + function deployLegacyApp(uint256 release) internal returns (address app) { + vm.prank(appOwner); + app = Upgrades.deployUUPSProxy( + appReleases[release], + abi.encodeWithSignature( + "initialize(address,bool,bool,bytes32,bytes32)", appOwner, false, false, DEVICE, COMPOSE + ) + ); + kms.registerApp(app); + } + + function request(address app, bool appSet, uint256 appEpoch) internal pure returns (AuthorizationRequest memory) { + IAppAuth.AppInfo memory info; + info.appId = app; + info.composeHash = COMPOSE; + info.deviceId = DEVICE; + info.osImageHash = IMAGE; + info.tcbStatus = "UpToDate"; + info.advisoryIds = new string[](0); + return AuthorizationRequest( + info, + keccak256("app_get_key"), + OptionalUint256(appSet, appEpoch), + OptionalUint256(false, 0), + "dstack-tdx", + bytes32(0) + ); + } + + function rotateRoot() internal { + vm.startPrank(owner); + kms.registerRootEpoch(key(91, 0xa1), key(33, 0xb1), "ipfs://1"); + kms.addOsImageHashAtEpochs(1, 1, IMAGE); + (,,, bytes32 hash) = kms.rootEpoch(1); + kms.activateRootEpoch(1, hash); + vm.stopPrank(); + } + + function test_LegacyAppsAreAuthorizedAtAppEpochZeroAcrossRootRotation() public { + for (uint256 release; release < appReleases.length; ++release) { + address app = deployLegacyApp(release); + assertEq(kms.currentAppEpoch(app), 0); + assertTrue(kms.authorizeApp(request(app, false, 0)).authorized); + assertTrue(kms.authorizeApp(request(app, true, 0)).authorized); + AuthorizationResult memory result = kms.authorizeApp(request(app, true, 1)); + assertFalse(result.authorized); + assertEq(result.rejectionReason, "Requested app epoch is not active"); + + // Its epoch-less setters still decide app epoch 0. + vm.prank(appOwner); + ILegacyApp(app).removeComposeHash(COMPOSE); + assertFalse(kms.authorizeApp(request(app, false, 0)).authorized); + vm.prank(appOwner); + ILegacyApp(app).addComposeHash(COMPOSE); + } + rotateRoot(); + for (uint256 release; release < appReleases.length; ++release) { + address app = deployLegacyApp(release); + assertEq(kms.currentAppEpoch(app), 0); + AuthorizationResult memory result = kms.authorizeApp(request(app, false, 0)); + assertTrue(result.authorized, result.rejectionReason); + assertEq(result.currentRootEpoch, 1); + assertEq(result.currentAppEpoch, 0); + assertFalse(kms.authorizeApp(request(app, true, 1)).authorized); + } + } + + function test_RestrictedKmsGatesLegacyAppsByTeeVariant() public { + string[] memory tdx = new string[](1); + tdx[0] = "dstack-tdx"; + vm.startPrank(owner); + kms.setAllowedTeeVariants(tdx); + kms.setAllowAnyTeeVariant(false); + vm.stopPrank(); + for (uint256 release; release < appReleases.length; ++release) { + address app = deployLegacyApp(release); + assertTrue(kms.authorizeApp(request(app, false, 0)).authorized); + AuthorizationRequest memory snp = request(app, false, 0); + snp.teeVariant = "dstack-amd-sev-snp"; + assertEq(kms.authorizeApp(snp).rejectionReason, "TEE variant not allowed"); + } + } + + function test_InterfaceIdsTellLegacyAndEpochAppsApart() public { + bytes4 basicManagement = 0x8fd37527; + for (uint256 release; release < appReleases.length; ++release) { + address app = deployLegacyApp(release); + assertTrue(IERC165(app).supportsInterface(basicManagement)); + assertFalse(IERC165(app).supportsInterface(type(IAppEpochManagement).interfaceId)); + assertFalse(IERC165(app).supportsInterface(type(IAppEpochAuth).interfaceId)); + } + DstackApp current = DstackApp( + Upgrades.deployUUPSProxy( + "DstackApp.sol", + abi.encodeWithSignature( + "initialize(address,bool,bool,bytes32,bytes32)", appOwner, false, false, DEVICE, COMPOSE + ) + ) + ); + assertFalse(current.supportsInterface(basicManagement)); + assertTrue(current.supportsInterface(type(IAppEpochManagement).interfaceId)); + assertTrue(current.supportsInterface(type(IAppEpochAuth).interfaceId)); + } + + function test_UpgradedV059AppKeepsItsPolicyAtAppEpochZero() public { + checkUpgradeKeepsPolicy(0, false); + } + + function test_UpgradedV059AnyDeviceAppKeepsItsPolicyAtAppEpochZero() public { + checkUpgradeKeepsPolicy(0, true); + } + + function test_UpgradedV060AppKeepsItsPolicyAtAppEpochZero() public { + checkUpgradeKeepsPolicy(1, false); + } + + function test_UpgradedV060AnyDeviceAppKeepsItsPolicyAtAppEpochZero() public { + checkUpgradeKeepsPolicy(1, true); + } + + function checkUpgradeKeepsPolicy(uint256 release, bool anyDevice) internal { + address app = deployLegacyApp(release); + if (anyDevice) { + vm.prank(appOwner); + ILegacyApp(app).setAllowAnyDevice(true); + } + Options memory opts; + opts.referenceContract = appReleases[release]; + vm.startPrank(appOwner); + Upgrades.upgradeProxy(app, "DstackApp.sol", "", opts); + vm.stopPrank(); + + DstackApp upgraded = DstackApp(app); + assertEq(upgraded.currentAppEpoch(), 0); + assertTrue(upgraded.allowedComposeHashesAtEpoch(0, COMPOSE)); + assertTrue(upgraded.allowedDeviceIdsAtEpoch(0, DEVICE)); + assertEq(upgraded.allowAnyDevice(), anyDevice); + // Upgraded policies allow any TEE platform. + assertTrue(upgraded.allowAnyTeeVariant()); + assertEq(upgraded.allowedTeeVariants().length, 0); + AuthorizationRequest memory snp = request(app, true, 0); + snp.teeVariant = "dstack-amd-sev-snp"; + assertTrue(kms.authorizeApp(snp).authorized); + assertFalse(upgraded.allowedComposeHashesAtEpoch(1, COMPOSE)); + assertTrue(kms.authorizeApp(request(app, true, 0)).authorized); + + // The epoch-less setters are gone; the rows are written by epoch. + vm.prank(appOwner); + vm.expectRevert(); + ILegacyApp(app).addComposeHash(bytes32(uint256(0xc1))); + // The upgraded allowAnyDevice covers later epochs too: row 1 lists no device. + vm.startPrank(appOwner); + upgraded.advanceAppEpoch(0); + upgraded.addComposeHashAtEpoch(1, COMPOSE); + vm.stopPrank(); + assertEq(kms.authorizeApp(request(app, true, 1)).authorized, anyDevice); + + vm.prank(appOwner); + upgraded.removeComposeHashAtEpochs(0, 1, COMPOSE); + assertFalse(kms.authorizeApp(request(app, true, 0)).authorized); + } +} diff --git a/dstack/kms/auth-eth/test/ManageScript.t.sol b/dstack/kms/auth-eth/test/ManageScript.t.sol new file mode 100644 index 0000000000..1b19bb0fd3 --- /dev/null +++ b/dstack/kms/auth-eth/test/ManageScript.t.sol @@ -0,0 +1,81 @@ +/* + * SPDX-FileCopyrightText: © 2026 Phala Network + * + * SPDX-License-Identifier: Apache-2.0 + */ + +pragma solidity ^0.8.24; + +import "forge-std/Test.sol"; +import "openzeppelin-foundry-upgrades/Upgrades.sol"; +import "../script/Manage.s.sol"; + +contract ManageScriptTest is Test { + function deployApp(string memory release, address owner) internal returns (address) { + return Upgrades.deployUUPSProxy( + release, + abi.encodeWithSignature( + "initialize(address,bool,bool,bytes32,bytes32)", owner, false, false, bytes32(0), bytes32(0) + ) + ); + } + + function addComposeHash(address app) internal returns (AddComposeHash script) { + vm.setEnv("APP_CONTRACT_ADDR", vm.toString(app)); + script = new AddComposeHash(); + script.setUp(); + } + + // Environment variables persist across tests, so the cases run in order. + function test_AppScriptsUseTheSettersTheAppHas() public { + (address owner, uint256 key) = makeAddrAndKey("owner"); + address legacy = deployApp("DstackAppV060.sol:DstackApp", owner); + address current = deployApp("DstackApp.sol", owner); + bytes32 composeHash = bytes32(uint256(0xc0)); + vm.setEnv("KMS_CONTRACT_ADDR", vm.toString(address(1))); + vm.setEnv("PRIVATE_KEY", vm.toString(key)); + vm.setEnv("COMPOSE_HASH", vm.toString(composeHash)); + + // A legacy app takes its epoch-less setter, which writes app epoch 0. + addComposeHash(legacy).run(); + assertTrue(DstackApp(legacy).allowedComposeHashes(composeHash)); + // An epoch-aware app needs its rows named. + AddComposeHash script = addComposeHash(current); + vm.expectRevert(bytes("set APP_EPOCH, or FROM_APP_EPOCH and TO_APP_EPOCH")); + script.run(); + + vm.setEnv("APP_EPOCH", "1"); + addComposeHash(current).run(); + assertFalse(DstackApp(current).allowedComposeHashesAtEpoch(0, composeHash)); + assertTrue(DstackApp(current).allowedComposeHashesAtEpoch(1, composeHash)); + script = addComposeHash(legacy); + vm.expectRevert(bytes("this app predates app epochs: only APP_EPOCH=0 applies")); + script.run(); + + // TEE variant policies take `any` or names, and exist only in current apps. + vm.setEnv("APP_EPOCH", "0"); + vm.setEnv("APP_CONTRACT_ADDR", vm.toString(current)); + vm.setEnv("TEE_VARIANTS", "dstack-tdx,dstack-gcp-tdx"); + SetTeeVariants teeScript = new SetTeeVariants(); + teeScript.setUp(); + teeScript.run(); + assertFalse(DstackApp(current).allowAnyTeeVariant()); + string[] memory names = DstackApp(current).allowedTeeVariants(); + assertEq(names.length, 2); + assertEq(names[1], "dstack-gcp-tdx"); + vm.setEnv("TEE_VARIANTS", "any"); + teeScript.run(); + assertTrue(DstackApp(current).allowAnyTeeVariant()); + // An unset or empty TEE_VARIANTS must not lock everything out. + vm.setEnv("TEE_VARIANTS", ""); + vm.expectRevert(bytes("set TEE_VARIANTS to any or platform names")); + teeScript.run(); + assertTrue(DstackApp(current).allowAnyTeeVariant()); + vm.setEnv("TEE_VARIANTS", "any"); + vm.setEnv("APP_CONTRACT_ADDR", vm.toString(legacy)); + teeScript = new SetTeeVariants(); + teeScript.setUp(); + vm.expectRevert(bytes("this app predates TEE variant policies")); + teeScript.run(); + } +} diff --git a/dstack/kms/auth-eth/test/UpgradesWithPlugin.t.sol b/dstack/kms/auth-eth/test/UpgradesWithPlugin.t.sol index 0cb05013df..a2ab3860a6 100644 --- a/dstack/kms/auth-eth/test/UpgradesWithPlugin.t.sol +++ b/dstack/kms/auth-eth/test/UpgradesWithPlugin.t.sol @@ -24,6 +24,87 @@ contract UpgradesWithPluginTest is Test { Upgrades.upgradeProxy(proxy, "contracts/test-utils/DstackAppV2.sol:DstackAppV2", ""); } + /// Deployed releases; their sources are kept verbatim in contracts/test-utils/reference. + string[2] internal kmsReleases = ["DstackKmsV059.sol:DstackKms", "DstackKmsV060.sol:DstackKms"]; + string[2] internal appReleases = ["DstackAppV059.sol:DstackApp", "DstackAppV060.sol:DstackApp"]; + + function test_ReleasedStorageLayoutsUpgradeToTheCurrentContracts() public { + for (uint256 i = 0; i < kmsReleases.length; ++i) { + Options memory opts; + opts.referenceContract = kmsReleases[i]; + Upgrades.validateUpgrade("DstackKms.sol", opts); + opts.referenceContract = appReleases[i]; + Upgrades.validateUpgrade("DstackApp.sol", opts); + } + } + + function test_ReleasedAppProxyKeepsItsAllowlistAfterUpgrade() public { + bytes32 composeHash = bytes32(uint256(0xc0)); + bytes32 deviceId = bytes32(uint256(0xd0)); + vm.startPrank(owner); + address proxy = Upgrades.deployUUPSProxy( + "DstackAppV059.sol:DstackApp", + abi.encodeWithSignature( + "initialize(address,bool,bool,bool,bytes32,bytes32)", owner, false, true, false, deviceId, composeHash + ) + ); + Options memory opts; + opts.referenceContract = appReleases[0]; + Upgrades.upgradeProxy(proxy, "DstackApp.sol", "", opts); + vm.stopPrank(); + DstackApp app = DstackApp(proxy); + assertEq(app.owner(), owner); + assertTrue(app.requireTcbUpToDate()); + assertTrue(app.allowedComposeHashes(composeHash)); + assertTrue(app.allowedDeviceIds(deviceId)); + assertFalse(app.allowAnyDevice()); + assertEq(app.currentAppEpoch(), 0); + assertTrue(app.allowedComposeHashesAtEpoch(0, composeHash)); + assertTrue(app.allowedDeviceIdsAtEpoch(0, deviceId)); + } + + function test_ReleasedKmsDeploysAppsOnceItsAppImplementationIsCurrent() public { + vm.startPrank(owner); + address releasedApp = deployCode("DstackAppV060.sol:DstackApp"); + address proxy = Upgrades.deployUUPSProxy( + "DstackKmsV060.sol:DstackKms", abi.encodeWithSignature("initialize(address,address)", owner, releasedApp) + ); + Options memory opts; + opts.referenceContract = kmsReleases[1]; + Upgrades.upgradeProxy(proxy, "DstackKms.sol", "", opts); + DstackKms kms = DstackKms(proxy); + + // A released DstackApp has no deployProxy. + vm.expectRevert(bytes("")); + kms.deployAndRegisterApp(owner, false, false, true, bytes32(0), bytes32(0)); + + // UpgradeKms points the upgraded proxy at a current one in the upgrade call. + Upgrades.upgradeProxy( + proxy, "DstackKms.sol", abi.encodeCall(DstackKms.setAppImplementation, (address(new DstackApp()))), opts + ); + vm.recordLogs(); + address appId = + kms.deployAndRegisterApp(owner, false, true, false, bytes32(uint256(0xd0)), bytes32(uint256(0xc0))); + vm.stopPrank(); + assertTrue(kms.registeredApps(appId)); + // The KMS still initializes the app, so its initial policy events name the KMS. + Vm.Log[] memory logs = vm.getRecordedLogs(); + uint256 appPolicyEvents; + for (uint256 i = 0; i < logs.length; ++i) { + if (logs[i].emitter == appId && logs[i].topics[0] == DstackApp.PolicyChanged.selector) { + assertEq(logs[i].topics[1], bytes32(uint256(uint160(proxy)))); + ++appPolicyEvents; + } + } + assertGt(appPolicyEvents, 0); + assertEq(DstackApp(appId).owner(), owner); + assertTrue(DstackApp(appId).requireTcbUpToDate()); + + // An app proxy does not deploy proxies. + vm.expectRevert(UUPSUpgradeable.UUPSUnauthorizedCallContext.selector); + DstackApp(appId).deployProxy(); + } + function attemptKmsUpgrade(address proxy) external { Upgrades.upgradeProxy(proxy, "contracts/test-utils/DstackKmsV2.sol:DstackKmsV2", ""); } @@ -85,7 +166,7 @@ contract UpgradesWithPluginTest is Test { // Set some state to verify it's preserved kms.setGatewayAppId("original-gateway"); bytes32 mrAggregated = bytes32(uint256(123)); - kms.addKmsAggregatedMr(mrAggregated); + kms.addKmsAggregatedMrAtEpochs(0, 0, mrAggregated); // Upgrade to new implementation using plugin Upgrades.upgradeProxy(kmsProxy, "DstackKmsV2.sol", ""); @@ -114,8 +195,8 @@ contract UpgradesWithPluginTest is Test { // Set some state to verify it's preserved bytes32 deviceId = bytes32(uint256(456)); bytes32 composeHash = bytes32(uint256(789)); - app.addDevice(deviceId); - app.addComposeHash(composeHash); + app.addDeviceAtEpoch(0, deviceId); + app.addComposeHashAtEpoch(0, composeHash); app.setAllowAnyDevice(true); // Upgrade to new implementation using plugin @@ -266,8 +347,8 @@ contract UpgradesWithPluginTest is Test { bytes32 osImageHash = bytes32(uint256(0xA1)); bytes32 composeHash = bytes32(uint256(0xA2)); bytes32 mrAggregated = bytes32(uint256(0xA3)); - kms.addOsImageHash(osImageHash); - kms.addKmsAggregatedMr(mrAggregated); + kms.addOsImageHashAtEpochs(0, 0, osImageHash); + kms.addKmsAggregatedMrAtEpochs(0, 0, mrAggregated); address appId = kms.deployAndRegisterApp( owner, @@ -284,7 +365,7 @@ contract UpgradesWithPluginTest is Test { assertTrue(app.allowAnyDevice()); assertTrue(app.allowedComposeHashes(composeHash)); - IAppAuth.AppBootInfo memory bootInfo = IAppAuth.AppBootInfo({ + IAppAuth.AppInfo memory bootInfo = IAppAuth.AppInfo({ appId: appId, composeHash: composeHash, instanceId: address(0), @@ -320,8 +401,8 @@ contract UpgradesWithPluginTest is Test { bytes32 osImageHash = bytes32(uint256(0xB1)); bytes32 composeHash = bytes32(uint256(0xB2)); bytes32 mrAggregated = bytes32(uint256(0xB3)); - kms.addOsImageHash(osImageHash); - kms.addKmsAggregatedMr(mrAggregated); + kms.addOsImageHashAtEpochs(0, 0, osImageHash); + kms.addKmsAggregatedMrAtEpochs(0, 0, mrAggregated); address appId = kms.deployAndRegisterApp( owner, @@ -335,7 +416,7 @@ contract UpgradesWithPluginTest is Test { assertFalse(app.requireTcbUpToDate()); // Outdated TCB still allowed when flag is off - IAppAuth.AppBootInfo memory bootInfo = IAppAuth.AppBootInfo({ + IAppAuth.AppInfo memory bootInfo = IAppAuth.AppInfo({ appId: appId, composeHash: composeHash, instanceId: address(0), @@ -380,8 +461,8 @@ contract UpgradesWithPluginTest is Test { bytes32 osImageHash = bytes32(uint256(789)); bytes32 mrAggregated = bytes32(uint256(101_112)); - kms.addOsImageHash(osImageHash); - kms.addKmsAggregatedMr(mrAggregated); + kms.addOsImageHashAtEpochs(0, 0, osImageHash); + kms.addKmsAggregatedMrAtEpochs(0, 0, mrAggregated); kms.setGatewayAppId("complex-test-gateway"); // Upgrade both contracts @@ -399,7 +480,7 @@ contract UpgradesWithPluginTest is Test { assertEq(app.owner(), owner); // Test the full flow still works - IAppAuth.AppBootInfo memory bootInfo = IAppAuth.AppBootInfo({ + IAppAuth.AppInfo memory bootInfo = IAppAuth.AppInfo({ appId: appId, composeHash: composeHash, instanceId: address(0), diff --git a/dstack/kms/auth-eth/tsconfig.json b/dstack/kms/auth-eth/tsconfig.json deleted file mode 100644 index fc23863cec..0000000000 --- a/dstack/kms/auth-eth/tsconfig.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2020", - "module": "commonjs", - "lib": [ - "es2020" - ], - "strict": true, - "esModuleInterop": true, - "skipLibCheck": true, - "forceConsistentCasingInFileNames": true, - "outDir": "./dist", - "rootDir": "./src", - "resolveJsonModule": true, - "types": [ - "node", - "jest" - ], - "baseUrl": "." - }, - "include": [ - "src/**/*" - ], - "exclude": [ - "node_modules" - ] -} diff --git a/dstack/kms/auth-simple/vitest.config.ts b/dstack/kms/auth-eth/vitest.config.ts similarity index 58% rename from dstack/kms/auth-simple/vitest.config.ts rename to dstack/kms/auth-eth/vitest.config.ts index 17597daca3..3e17ccf51e 100644 --- a/dstack/kms/auth-simple/vitest.config.ts +++ b/dstack/kms/auth-eth/vitest.config.ts @@ -8,5 +8,8 @@ export default defineConfig({ test: { globals: true, environment: 'node', + // The Foundry project shares this directory; keep vitest away from the + // JavaScript under lib/ (contract dependencies) and the build outputs. + include: ['*.test.ts'], }, }); diff --git a/dstack/kms/auth-mock/.oxlintrc.json b/dstack/kms/auth-mock/.oxlintrc.json deleted file mode 100644 index f7d7b8e35e..0000000000 --- a/dstack/kms/auth-mock/.oxlintrc.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "$schema": "https://raw.githubusercontent.com/oxc-project/oxc/main/crates/oxc_linter/src/config/schema.json", - "rules": { - "typescript": "warn", - "unicorn": "warn", - "react": "off", - "jsx-a11y": "off", - "nextjs": "off" - }, - "env": { - "node": true, - "es2022": true - }, - "globals": { - "globalThis": "readonly", - "console": "readonly" - }, - "ignore_patterns": [ - "node_modules/**", - "dist/**", - "build/**", - "coverage/**", - "*.min.js", - "*.d.ts", - "*.test.ts" - ] -} diff --git a/dstack/kms/auth-mock/Dockerfile b/dstack/kms/auth-mock/Dockerfile deleted file mode 100644 index 75207418ae..0000000000 --- a/dstack/kms/auth-mock/Dockerfile +++ /dev/null @@ -1,17 +0,0 @@ -# SPDX-FileCopyrightText: © 2025 Phala Network -# -# SPDX-License-Identifier: Apache-2.0 - -FROM oven/bun:1-alpine -WORKDIR /app - -ARG DSTACK_REV -ARG DSTACK_BRANCH=next - -RUN apk add --no-cache git -RUN git clone --branch ${DSTACK_BRANCH} https://github.com/Dstack-TEE/dstack.git && \ - cd dstack && \ - git checkout ${DSTACK_REV} -WORKDIR /app/dstack/dstack/kms/auth-mock -RUN bun install --frozen-lockfile -CMD ["bun", "index.ts"] diff --git a/dstack/kms/auth-mock/README.md b/dstack/kms/auth-mock/README.md deleted file mode 100644 index c26ed0e19c..0000000000 --- a/dstack/kms/auth-mock/README.md +++ /dev/null @@ -1,168 +0,0 @@ -# dstack KMS auth-mock - -a mock implementation of the dstack KMS backend using bun + hono + zod. **this backend always returns success for all authentication requests** and does not interact with any blockchain. - -## features - -- 🚀 fast and lightweight with bun runtime -- 🔧 modern web framework with hono.js -- ✅ type-safe validation with zod.js -- 📦 single file implementation -- 🎭 **mock behavior**: all authentications succeed -- 🚫 **no blockchain interaction**: no dependencies on ethereum/contracts - -## use cases - -- 🧪 **development & testing**: test applications without blockchain setup -- 🚀 **rapid prototyping**: quickly validate integration workflows -- 🔍 **debugging**: isolate issues by removing blockchain dependencies -- 📚 **demos**: showcase functionality without complex infrastructure - -## installation - -```bash -# install dependencies -bun install -``` - -## usage - -### development -```bash -# run with hot reload -bun run dev -``` - -### production -```bash -# run directly -bun run start - -# or build first -bun run build -``` - -### testing -```bash -# run tests (watch mode) -bun run test - -# run tests once -bun run test:run -``` - -### code quality -```bash -# run linter -bun run lint - -# run linter and fix issues -bun run lint:fix - -# format code -bun run format - -# run full check (lint + tests) -bun run check -``` - -## environment variables - -- `PORT` - server port (default: 3000) -- `MOCK_GATEWAY_APP_ID` - mock gateway app ID (default: 0xmockgateway1234567890123456789012345678) -- `MOCK_CHAIN_ID` - mock blockchain chain ID (default: 1337) -- `MOCK_APP_IMPLEMENTATION` - mock app implementation address (default: 0xmockapp9876543210987654321098765432109) - -## API endpoints - -### GET / -health check and mock system information - -**response includes a `note` field indicating this is a mock backend** - -### POST /bootAuth/app -application boot authentication - **always returns isAllowed=true** - -### POST /bootAuth/kms -KMS boot authentication - **always returns isAllowed=true** - -## request format - -identical to the real backend: - -```json -{ - "mrAggregated": "string", - "osImageHash": "string", - "appId": "string", - "composeHash": "string", - "instanceId": "string", - "deviceId": "string", - "tcbStatus": "string (optional)", - "advisoryIds": ["string (optional)"], - "mrSystem": "string (optional)" -} -``` - -## response format - -```json -{ - "isAllowed": true, - "reason": "mock app always allowed" | "mock KMS always allowed", - "gatewayAppId": "0xmockgateway1234567890123456789012345678" -} -``` - -## mock behavior - -### ✅ always succeeds -- all POST requests return `isAllowed: true` -- no validation against blockchain -- no actual security checks - -### 📝 logs requests -- logs incoming requests with key identifiers -- helps with debugging and monitoring - -### 🎯 consistent responses -- predictable mock values for testing -- same response format as real backend - -## API compatibility - -this implementation is fully API-compatible with the real backend: - -- **request/response schemas**: identical to production API -- **OpenAPI specification**: available in `openapi.json` -- **comprehensive testing**: vitest test suite validates behavior -- **backward compatibility**: supports both minimal and full BootInfo formats - -### differences from real backend - -| aspect | real backend | mock backend | -|--------|-------------|--------------| -| blockchain interaction | ✅ calls smart contracts | ❌ no blockchain | -| authentication logic | ✅ validates against chain | ❌ always allows | -| security | ✅ enforces policies | ❌ bypasses all checks | -| performance | 🐌 depends on network | 🚀 instant responses | -| setup complexity | 🔧 requires ethereum setup | ✅ zero config | - -## warnings - -⚠️ **never use in production** - this backend bypasses all security checks - -⚠️ **development only** - intended for testing and development environments - -⚠️ **no security** - all requests are approved regardless of validity - -## transitioning to real backend - -to switch from mock to real backend: - -1. replace `kms/auth-mock` with `kms/auth-eth-bun` -2. configure ethereum RPC endpoint -3. deploy smart contracts -4. update environment variables - -the API remains identical, so no client code changes are needed. diff --git a/dstack/kms/auth-mock/bun.lock b/dstack/kms/auth-mock/bun.lock deleted file mode 100644 index 955a0dda31..0000000000 --- a/dstack/kms/auth-mock/bun.lock +++ /dev/null @@ -1,297 +0,0 @@ -{ - "lockfileVersion": 1, - "workspaces": { - "": { - "name": "auth-mock", - "dependencies": { - "@hono/zod-validator": "0.2.2", - "hono": "4.13.5", - "zod": "3.25.76", - }, - "devDependencies": { - "@types/bun": "1.2.18", - "@types/node": "22.10.8", - "@vitest/ui": "1.6.1", - "openapi-types": "12.1.3", - "oxlint": "0.9.10", - "typescript": "5.8.3", - "vitest": "4.1.11", - }, - }, - }, - "packages": { - "@emnapi/core": ["@emnapi/core@1.11.1", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.2", "tslib": "^2.4.0" } }, "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ=="], - - "@emnapi/runtime": ["@emnapi/runtime@1.11.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw=="], - - "@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA=="], - - "@hono/zod-validator": ["@hono/zod-validator@0.2.2", "", { "peerDependencies": { "hono": ">=3.9.0", "zod": "^3.19.1" } }, "sha512-dSDxaPV70Py8wuIU2QNpoVEIOSzSXZ/6/B/h4xA7eOMz7+AarKTSGV8E6QwrdcCbBLkpqfJ4Q2TmBO0eP1tCBQ=="], - - "@jest/schemas": ["@jest/schemas@29.6.3", "", { "dependencies": { "@sinclair/typebox": "^0.27.8" } }, "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA=="], - - "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.5.5", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="], - - "@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.1.6", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1" } }, "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg=="], - - "@nodelib/fs.scandir": ["@nodelib/fs.scandir@2.1.5", "", { "dependencies": { "@nodelib/fs.stat": "2.0.5", "run-parallel": "^1.1.9" } }, "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g=="], - - "@nodelib/fs.stat": ["@nodelib/fs.stat@2.0.5", "", {}, "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A=="], - - "@nodelib/fs.walk": ["@nodelib/fs.walk@1.2.8", "", { "dependencies": { "@nodelib/fs.scandir": "2.1.5", "fastq": "^1.6.0" } }, "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg=="], - - "@oxc-project/types": ["@oxc-project/types@0.139.0", "", {}, "sha512-r9gHphtCs+1M7J0pw6Sn/hh/Wpa/iQrOOkrNAlVLF/gHq+/CJmHIWKKUUhdWjcD6CIa8idarspCsASiXCXvFUw=="], - - "@oxlint/darwin-arm64": ["@oxlint/darwin-arm64@0.9.10", "", { "os": "darwin", "cpu": "arm64" }, "sha512-eOXKZYq5bnCSgDefgM5bzAg+4Fc//Rc4yjgKN8iDWUARweCaChiQXb6TXX8MfEfs6qayEMy6yVj0pqoFz0B1aw=="], - - "@oxlint/darwin-x64": ["@oxlint/darwin-x64@0.9.10", "", { "os": "darwin", "cpu": "x64" }, "sha512-UeYICDvLUaUOcY+0ugZUEmBMRLP+x8iTgL7TeY6BlpGw2ahbtUOTbyIIRWtr/0O++TnjZ+v8TzhJ9crw6Ij6dg=="], - - "@oxlint/linux-arm64-gnu": ["@oxlint/linux-arm64-gnu@0.9.10", "", { "os": "linux", "cpu": "arm64" }, "sha512-0Zn+vqHhrZyufFBfq9WOgiIool0gCR14BLsdS+0Dwd9o+kNxPGA5q7erQFkiC4rpkxtfBHeD3iIKMMt7d29Kyw=="], - - "@oxlint/linux-arm64-musl": ["@oxlint/linux-arm64-musl@0.9.10", "", { "os": "linux", "cpu": "arm64" }, "sha512-tkQcWpYwF42bA/uRaV2iMFePHkBjTTgomOgeEaiw6XOSJX4nBEqGIIboqqLBWT4JnKCf/L+IG3y/e1MflhKByw=="], - - "@oxlint/linux-x64-gnu": ["@oxlint/linux-x64-gnu@0.9.10", "", { "os": "linux", "cpu": "x64" }, "sha512-JHbkMUnibqaSMBvLHyqTL5cWxcGW+jw+Ppt2baLISpvo34a6fBR+PI7v/A92sEDWe0W1rPhypzCwA8mKpkQ3DA=="], - - "@oxlint/linux-x64-musl": ["@oxlint/linux-x64-musl@0.9.10", "", { "os": "linux", "cpu": "x64" }, "sha512-aBBwN7bQzidwHwEXr7BAdVvMTLWstCy5gikerjLnGDeCSXX9r+o6+yUzTOqZvOo66E+XBgOJaVbY8rsL1MLE0g=="], - - "@oxlint/win32-arm64": ["@oxlint/win32-arm64@0.9.10", "", { "os": "win32", "cpu": "arm64" }, "sha512-LXDnk7vKHT3IY6G1jq0O7+XMhtcHOYuxLGIx4KP+4xS6vKgBY+Bsq4xV3AtmtKlvnXkP5FxHpfLmcEtm5AWysA=="], - - "@oxlint/win32-x64": ["@oxlint/win32-x64@0.9.10", "", { "os": "win32", "cpu": "x64" }, "sha512-w5XRAV4bhgwenjjpGYZGglqzG9Wv/sI+cjQWJBQsvfDXsr2w4vOBXzt1j3/Z3EcSqf4KtkCa/IIuAhQyeShUbA=="], - - "@polka/url": ["@polka/url@1.0.0-next.29", "", {}, "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww=="], - - "@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.1.5", "", { "os": "android", "cpu": "arm64" }, "sha512-lZg8fqIv2v7FF237bwMgzGZEJvGL79/s5knJ/i6FmsGF4XXlzccZ4jb+TrFIxtSSxFtIpdsgrPZeMk1I9AFcyQ=="], - - "@rolldown/binding-darwin-arm64": ["@rolldown/binding-darwin-arm64@1.1.5", "", { "os": "darwin", "cpu": "arm64" }, "sha512-51Bnx9pNiMRKSUNtBfySkNJ9vMU9Hh3I1ozDd6gyPPYzaXCfnptUcEZxXGYFn+ul2dtcMUiqGR1Yai2K10uoTw=="], - - "@rolldown/binding-darwin-x64": ["@rolldown/binding-darwin-x64@1.1.5", "", { "os": "darwin", "cpu": "x64" }, "sha512-Tm+gbfC0aHu1tBA/JvKQh32S0K6YgCHkiAF4/W6xX0K0RmNuc94VeK419dJoE65R5aRxmo+noZQSWrAMF6yb6g=="], - - "@rolldown/binding-freebsd-x64": ["@rolldown/binding-freebsd-x64@1.1.5", "", { "os": "freebsd", "cpu": "x64" }, "sha512-JMzDKCCXq93YccG5gz3hvOs1oXRKAf0XYpfOS88e+wZrC8Iugj6j68867vrYZkvpDDpKn/KoKORThmchMpF6TA=="], - - "@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/binding-linux-arm-gnueabihf@1.1.5", "", { "os": "linux", "cpu": "arm" }, "sha512-uML21j2K5TfPGutKxub+M+nLjZIrWjXQ5Grx4lCe/nimTj9B4L63zHpjXLl4y0L3mcm2htEQIb06oCG/szerNw=="], - - "@rolldown/binding-linux-arm64-gnu": ["@rolldown/binding-linux-arm64-gnu@1.1.5", "", { "os": "linux", "cpu": "arm64" }, "sha512-navSiuTMogvnQoZoM/v+l3ZWo50/NTwSHSzheABx/RCnmUPaKwq9qSo4Br2OYRs21+Fz8uFqITZM3H4opOB0/Q=="], - - "@rolldown/binding-linux-arm64-musl": ["@rolldown/binding-linux-arm64-musl@1.1.5", "", { "os": "linux", "cpu": "arm64" }, "sha512-lAryqH7IteztmCXQXk0etKj4wBQ7Gx5S6LjKhsgp9zb8I5bsuvU/2llH1hDQcjsFeqIsovMVN339/8pUDDBXxA=="], - - "@rolldown/binding-linux-ppc64-gnu": ["@rolldown/binding-linux-ppc64-gnu@1.1.5", "", { "os": "linux", "cpu": "ppc64" }, "sha512-fsK/sNBnxzBlL4O1JNrZakVQxPspqpED5dLtNsZS9oOKmtSpdNIzxH2kkol5HYTWJN47sE20ztMJPxfZ89qGOg=="], - - "@rolldown/binding-linux-s390x-gnu": ["@rolldown/binding-linux-s390x-gnu@1.1.5", "", { "os": "linux", "cpu": "s390x" }, "sha512-gLYb4BIadlfTOYT5gO503n8zQjXflgzpD0FcyKh0Mzx3rqCZKnHoJWV9xe1KXUJ5lx2JfcSHr/mhzS0PC/McAA=="], - - "@rolldown/binding-linux-x64-gnu": ["@rolldown/binding-linux-x64-gnu@1.1.5", "", { "os": "linux", "cpu": "x64" }, "sha512-FjcpEKUyJygHgs1o50VYNvkt5+7Le/VEdYt0AkRpkL33MnyQfwr8l5mXwMmfmTbyMPr5vJLC+8/Gd9gXnwU1QQ=="], - - "@rolldown/binding-linux-x64-musl": ["@rolldown/binding-linux-x64-musl@1.1.5", "", { "os": "linux", "cpu": "x64" }, "sha512-Me+PfPI2TMeOQk0gYWfLQZtTktrmzbr8cDboqX83XKc7UrgAi55gF+2dUkWdxd19n55Essp2yeca+O9N5rBxHg=="], - - "@rolldown/binding-openharmony-arm64": ["@rolldown/binding-openharmony-arm64@1.1.5", "", { "os": "none", "cpu": "arm64" }, "sha512-yc5WrLzXks6zCQfn9Oxr8pORKyl/pF+QjHmW/Qx3qu0oyrrNC+y2JLTU1E2rcWYAmzlnqngWXHQjy51VzW70Vw=="], - - "@rolldown/binding-wasm32-wasi": ["@rolldown/binding-wasm32-wasi@1.1.5", "", { "dependencies": { "@emnapi/core": "1.11.1", "@emnapi/runtime": "1.11.1", "@napi-rs/wasm-runtime": "^1.1.6" }, "cpu": "none" }, "sha512-VbQGPX2b4r48TAMIM2cjgluIM1HYutm4pcTEJsle7iEP7sB1dFqtPLBVbdLAZCxy1txCcPxf4QFf4v8uvltPqA=="], - - "@rolldown/binding-win32-arm64-msvc": ["@rolldown/binding-win32-arm64-msvc@1.1.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-gHv82k63z4qpV5+Q1y/12KrK0ltWBukVDI8nZcbT7Tt/ZlOIVwppazneq0F93oDxTo3IgAMEDIoQh3E2n6mVsw=="], - - "@rolldown/binding-win32-x64-msvc": ["@rolldown/binding-win32-x64-msvc@1.1.5", "", { "os": "win32", "cpu": "x64" }, "sha512-tTZuDBPw85tEN5PQi1pnEBzDy0Z49HtScLAbD5t6hyeU92A95pRWaSMw1GZZi/RwgSgUIl0xrSlXIT/9QzvYSA=="], - - "@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.1", "", {}, "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw=="], - - "@sinclair/typebox": ["@sinclair/typebox@0.27.8", "", {}, "sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA=="], - - "@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], - - "@tybys/wasm-util": ["@tybys/wasm-util@0.10.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg=="], - - "@types/bun": ["@types/bun@1.2.18", "", { "dependencies": { "bun-types": "1.2.18" } }, "sha512-Xf6RaWVheyemaThV0kUfaAUvCNokFr+bH8Jxp+tTZfx7dAPA8z9ePnP9S9+Vspzuxxx9JRAXhnyccRj3GyCMdQ=="], - - "@types/chai": ["@types/chai@5.2.3", "", { "dependencies": { "@types/deep-eql": "*", "assertion-error": "^2.0.1" } }, "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="], - - "@types/deep-eql": ["@types/deep-eql@4.0.2", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="], - - "@types/estree": ["@types/estree@1.0.8", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="], - - "@types/node": ["@types/node@22.10.8", "", { "dependencies": { "undici-types": "~6.20.0" } }, "sha512-rk+QvAEGsbX/ZPiiyel6hJHNUS9cnSbPWVaZLvE+Er3tLqQFzWMz9JOfWW7XUmKvRPfxJfbl3qYWve+RGXncFw=="], - - "@types/react": ["@types/react@19.1.8", "", { "dependencies": { "csstype": "^3.0.2" } }, "sha512-AwAfQ2Wa5bCx9WP8nZL2uMZWod7J7/JSplxbTmBQ5ms6QpqNYm672H0Vu9ZVKVngQ+ii4R/byguVEUZQyeg44g=="], - - "@vitest/expect": ["@vitest/expect@4.1.11", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "@types/chai": "^5.2.2", "@vitest/spy": "4.1.11", "@vitest/utils": "4.1.11", "chai": "^6.2.2", "tinyrainbow": "^3.1.0" } }, "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw=="], - - "@vitest/mocker": ["@vitest/mocker@4.1.11", "", { "dependencies": { "@vitest/spy": "4.1.11", "estree-walker": "^3.0.3", "magic-string": "^0.30.21" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["msw", "vite"] }, "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ=="], - - "@vitest/pretty-format": ["@vitest/pretty-format@4.1.11", "", { "dependencies": { "tinyrainbow": "^3.1.0" } }, "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw=="], - - "@vitest/runner": ["@vitest/runner@4.1.11", "", { "dependencies": { "@vitest/utils": "4.1.11", "pathe": "^2.0.3" } }, "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw=="], - - "@vitest/snapshot": ["@vitest/snapshot@4.1.11", "", { "dependencies": { "@vitest/pretty-format": "4.1.11", "@vitest/utils": "4.1.11", "magic-string": "^0.30.21", "pathe": "^2.0.3" } }, "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog=="], - - "@vitest/spy": ["@vitest/spy@4.1.11", "", {}, "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA=="], - - "@vitest/ui": ["@vitest/ui@1.6.1", "", { "dependencies": { "@vitest/utils": "1.6.1", "fast-glob": "^3.3.2", "fflate": "^0.8.1", "flatted": "^3.2.9", "pathe": "^1.1.1", "picocolors": "^1.0.0", "sirv": "^2.0.4" }, "peerDependencies": { "vitest": "1.6.1" } }, "sha512-xa57bCPGuzEFqGjPs3vVLyqareG8DX0uMkr5U/v5vLv5/ZUrBrPL7gzxzTJedEyZxFMfsozwTIbbYfEQVo3kgg=="], - - "@vitest/utils": ["@vitest/utils@1.6.1", "", { "dependencies": { "diff-sequences": "^29.6.3", "estree-walker": "^3.0.3", "loupe": "^2.3.7", "pretty-format": "^29.7.0" } }, "sha512-jOrrUvXM4Av9ZWiG1EajNto0u96kWAhJ1LmPmJhXXQx/32MecEKd10pOLYgS2BQx1TgkGhloPU1ArDW2vvaY6g=="], - - "ansi-styles": ["ansi-styles@5.2.0", "", {}, "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA=="], - - "assertion-error": ["assertion-error@2.0.1", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="], - - "braces": ["braces@3.0.3", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="], - - "bun-types": ["bun-types@1.2.18", "", { "dependencies": { "@types/node": "*" }, "peerDependencies": { "@types/react": "^19" } }, "sha512-04+Eha5NP7Z0A9YgDAzMk5PHR16ZuLVa83b26kH5+cp1qZW4F6FmAURngE7INf4tKOvCE69vYvDEwoNl1tGiWw=="], - - "chai": ["chai@6.2.2", "", {}, "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg=="], - - "convert-source-map": ["convert-source-map@2.0.0", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="], - - "csstype": ["csstype@3.1.3", "", {}, "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw=="], - - "detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], - - "diff-sequences": ["diff-sequences@29.6.3", "", {}, "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q=="], - - "es-module-lexer": ["es-module-lexer@2.3.1", "", {}, "sha512-shc1dbU90Yl/xq1QrC7QRtfcwURZuVRfPhZbDoldJ1cn1gzDvBaBWlv0eFolj5+0znnPJz5TXLxsN77X/12KTA=="], - - "estree-walker": ["estree-walker@3.0.3", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="], - - "expect-type": ["expect-type@1.4.0", "", {}, "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA=="], - - "fast-glob": ["fast-glob@3.3.3", "", { "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", "glob-parent": "^5.1.2", "merge2": "^1.3.0", "micromatch": "^4.0.8" } }, "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg=="], - - "fastq": ["fastq@1.19.1", "", { "dependencies": { "reusify": "^1.0.4" } }, "sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ=="], - - "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], - - "fflate": ["fflate@0.8.2", "", {}, "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A=="], - - "fill-range": ["fill-range@7.1.1", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="], - - "flatted": ["flatted@3.3.3", "", {}, "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg=="], - - "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], - - "get-func-name": ["get-func-name@2.0.2", "", {}, "sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ=="], - - "glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="], - - "hono": ["hono@4.13.5", "", {}, "sha512-O6+/eCYRkzzzy0rPWwKLiGBR1nFuUPZynnwjxN1MBA62NNqbT0wQEzQyK2gSO5yDIDB336sXQleAhOHrzlYyKw=="], - - "is-extglob": ["is-extglob@2.1.1", "", {}, "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ=="], - - "is-glob": ["is-glob@4.0.3", "", { "dependencies": { "is-extglob": "^2.1.1" } }, "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg=="], - - "is-number": ["is-number@7.0.0", "", {}, "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng=="], - - "lightningcss": ["lightningcss@1.33.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.33.0", "lightningcss-darwin-arm64": "1.33.0", "lightningcss-darwin-x64": "1.33.0", "lightningcss-freebsd-x64": "1.33.0", "lightningcss-linux-arm-gnueabihf": "1.33.0", "lightningcss-linux-arm64-gnu": "1.33.0", "lightningcss-linux-arm64-musl": "1.33.0", "lightningcss-linux-x64-gnu": "1.33.0", "lightningcss-linux-x64-musl": "1.33.0", "lightningcss-win32-arm64-msvc": "1.33.0", "lightningcss-win32-x64-msvc": "1.33.0" } }, "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA=="], - - "lightningcss-android-arm64": ["lightningcss-android-arm64@1.33.0", "", { "os": "android", "cpu": "arm64" }, "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg=="], - - "lightningcss-darwin-arm64": ["lightningcss-darwin-arm64@1.33.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg=="], - - "lightningcss-darwin-x64": ["lightningcss-darwin-x64@1.33.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ=="], - - "lightningcss-freebsd-x64": ["lightningcss-freebsd-x64@1.33.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg=="], - - "lightningcss-linux-arm-gnueabihf": ["lightningcss-linux-arm-gnueabihf@1.33.0", "", { "os": "linux", "cpu": "arm" }, "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ=="], - - "lightningcss-linux-arm64-gnu": ["lightningcss-linux-arm64-gnu@1.33.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg=="], - - "lightningcss-linux-arm64-musl": ["lightningcss-linux-arm64-musl@1.33.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ=="], - - "lightningcss-linux-x64-gnu": ["lightningcss-linux-x64-gnu@1.33.0", "", { "os": "linux", "cpu": "x64" }, "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg=="], - - "lightningcss-linux-x64-musl": ["lightningcss-linux-x64-musl@1.33.0", "", { "os": "linux", "cpu": "x64" }, "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw=="], - - "lightningcss-win32-arm64-msvc": ["lightningcss-win32-arm64-msvc@1.33.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA=="], - - "lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.33.0", "", { "os": "win32", "cpu": "x64" }, "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA=="], - - "loupe": ["loupe@2.3.7", "", { "dependencies": { "get-func-name": "^2.0.1" } }, "sha512-zSMINGVYkdpYSOBmLi0D1Uo7JU9nVdQKrHxC8eYlV+9YKK9WePqAlL7lSlorG/U2Fw1w0hTBmaa/jrQ3UbPHtA=="], - - "magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], - - "merge2": ["merge2@1.4.1", "", {}, "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg=="], - - "micromatch": ["micromatch@4.0.8", "", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="], - - "mrmime": ["mrmime@2.0.1", "", {}, "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ=="], - - "nanoid": ["nanoid@3.3.16", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q=="], - - "obug": ["obug@2.1.4", "", {}, "sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA=="], - - "openapi-types": ["openapi-types@12.1.3", "", {}, "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw=="], - - "oxlint": ["oxlint@0.9.10", "", { "optionalDependencies": { "@oxlint/darwin-arm64": "0.9.10", "@oxlint/darwin-x64": "0.9.10", "@oxlint/linux-arm64-gnu": "0.9.10", "@oxlint/linux-arm64-musl": "0.9.10", "@oxlint/linux-x64-gnu": "0.9.10", "@oxlint/linux-x64-musl": "0.9.10", "@oxlint/win32-arm64": "0.9.10", "@oxlint/win32-x64": "0.9.10" }, "bin": { "oxlint": "bin/oxlint", "oxc_language_server": "bin/oxc_language_server" } }, "sha512-bKiiFN7Hnoaist/rditTRBXz+GXKYuLd53/NB7Q6zHB/bifELJarSoRLkAUGElIJKl4PSr3lTh1g6zehh+rX0g=="], - - "pathe": ["pathe@1.1.2", "", {}, "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ=="], - - "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], - - "picomatch": ["picomatch@4.0.5", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="], - - "postcss": ["postcss@8.5.23", "", { "dependencies": { "nanoid": "^3.3.16", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg=="], - - "pretty-format": ["pretty-format@29.7.0", "", { "dependencies": { "@jest/schemas": "^29.6.3", "ansi-styles": "^5.0.0", "react-is": "^18.0.0" } }, "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ=="], - - "queue-microtask": ["queue-microtask@1.2.3", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="], - - "react-is": ["react-is@18.3.1", "", {}, "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg=="], - - "reusify": ["reusify@1.1.0", "", {}, "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw=="], - - "rolldown": ["rolldown@1.1.5", "", { "dependencies": { "@oxc-project/types": "=0.139.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm64": "1.1.5", "@rolldown/binding-darwin-arm64": "1.1.5", "@rolldown/binding-darwin-x64": "1.1.5", "@rolldown/binding-freebsd-x64": "1.1.5", "@rolldown/binding-linux-arm-gnueabihf": "1.1.5", "@rolldown/binding-linux-arm64-gnu": "1.1.5", "@rolldown/binding-linux-arm64-musl": "1.1.5", "@rolldown/binding-linux-ppc64-gnu": "1.1.5", "@rolldown/binding-linux-s390x-gnu": "1.1.5", "@rolldown/binding-linux-x64-gnu": "1.1.5", "@rolldown/binding-linux-x64-musl": "1.1.5", "@rolldown/binding-openharmony-arm64": "1.1.5", "@rolldown/binding-wasm32-wasi": "1.1.5", "@rolldown/binding-win32-arm64-msvc": "1.1.5", "@rolldown/binding-win32-x64-msvc": "1.1.5" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-t9z29cJjXf/vxQ8dyhCSpt6H6aSwHTk8cT5I3iy6SMXuFpk5mB6PL6XfC8PCwrPTx93udwKUm9HRteAlTGBLiA=="], - - "run-parallel": ["run-parallel@1.2.0", "", { "dependencies": { "queue-microtask": "^1.2.2" } }, "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA=="], - - "siginfo": ["siginfo@2.0.0", "", {}, "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g=="], - - "sirv": ["sirv@2.0.4", "", { "dependencies": { "@polka/url": "^1.0.0-next.24", "mrmime": "^2.0.0", "totalist": "^3.0.0" } }, "sha512-94Bdh3cC2PKrbgSOUqTiGPWVZeSiXfKOVZNJniWoqrWrRkB1CJzBU3NEbiTsPcYy1lDsANA/THzS+9WBiy5nfQ=="], - - "source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="], - - "stackback": ["stackback@0.0.2", "", {}, "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw=="], - - "std-env": ["std-env@4.2.0", "", {}, "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw=="], - - "tinybench": ["tinybench@2.9.0", "", {}, "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg=="], - - "tinyexec": ["tinyexec@1.2.4", "", {}, "sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg=="], - - "tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="], - - "tinyrainbow": ["tinyrainbow@3.1.0", "", {}, "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw=="], - - "to-regex-range": ["to-regex-range@5.0.1", "", { "dependencies": { "is-number": "^7.0.0" } }, "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ=="], - - "totalist": ["totalist@3.0.1", "", {}, "sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ=="], - - "tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], - - "typescript": ["typescript@5.8.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ=="], - - "undici-types": ["undici-types@6.20.0", "", {}, "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg=="], - - "vite": ["vite@8.1.5", "", { "dependencies": { "lightningcss": "^1.32.0", "picomatch": "^4.0.5", "postcss": "^8.5.17", "rolldown": "~1.1.5", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.3.0", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-7ULLwsCdYx/nRyrpiEwvqb5TFHrMVZyBt+rg/OAXT7rgj/z+DtTDyKFeLAdDkubDVDKD8jOsndmy7m55XcfUsw=="], - - "vitest": ["vitest@4.1.11", "", { "dependencies": { "@vitest/expect": "4.1.11", "@vitest/mocker": "4.1.11", "@vitest/pretty-format": "4.1.11", "@vitest/runner": "4.1.11", "@vitest/snapshot": "4.1.11", "@vitest/spy": "4.1.11", "@vitest/utils": "4.1.11", "es-module-lexer": "^2.0.0", "expect-type": "^1.3.0", "magic-string": "^0.30.21", "obug": "^2.1.1", "pathe": "^2.0.3", "picomatch": "^4.0.3", "std-env": "^4.0.0-rc.1", "tinybench": "^2.9.0", "tinyexec": "^1.0.2", "tinyglobby": "^0.2.15", "tinyrainbow": "^3.1.0", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", "@vitest/browser-playwright": "4.1.11", "@vitest/browser-preview": "4.1.11", "@vitest/browser-webdriverio": "4.1.11", "@vitest/coverage-istanbul": "4.1.11", "@vitest/coverage-v8": "4.1.11", "@vitest/ui": "4.1.11", "happy-dom": "*", "jsdom": "*" }, "optionalPeers": ["@edge-runtime/vm", "@opentelemetry/api", "@types/node", "@vitest/browser-playwright", "@vitest/browser-preview", "@vitest/browser-webdriverio", "@vitest/coverage-istanbul", "@vitest/coverage-v8", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "./vitest.mjs" } }, "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw=="], - - "why-is-node-running": ["why-is-node-running@2.3.0", "", { "dependencies": { "siginfo": "^2.0.0", "stackback": "0.0.2" }, "bin": { "why-is-node-running": "cli.js" } }, "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w=="], - - "zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="], - - "@vitest/expect/@vitest/utils": ["@vitest/utils@4.1.11", "", { "dependencies": { "@vitest/pretty-format": "4.1.11", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" } }, "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ=="], - - "@vitest/runner/@vitest/utils": ["@vitest/utils@4.1.11", "", { "dependencies": { "@vitest/pretty-format": "4.1.11", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" } }, "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ=="], - - "@vitest/runner/pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], - - "@vitest/snapshot/@vitest/utils": ["@vitest/utils@4.1.11", "", { "dependencies": { "@vitest/pretty-format": "4.1.11", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" } }, "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ=="], - - "@vitest/snapshot/pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], - - "bun-types/@types/node": ["@types/node@24.0.14", "", { "dependencies": { "undici-types": "~7.8.0" } }, "sha512-4zXMWD91vBLGRtHK3YbIoFMia+1nqEz72coM42C5ETjnNCa/heoj7NT1G67iAfOqMmcfhuCZ4uNpyz8EjlAejw=="], - - "micromatch/picomatch": ["picomatch@2.3.1", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="], - - "vitest/@vitest/utils": ["@vitest/utils@4.1.11", "", { "dependencies": { "@vitest/pretty-format": "4.1.11", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" } }, "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ=="], - - "vitest/pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], - - "bun-types/@types/node/undici-types": ["undici-types@7.8.0", "", {}, "sha512-9UJ2xGDvQ43tYyVMpuHlsgApydB8ZKfVYTsLDhXkFL/6gfkp+U8xTGdh8pMJv1SpZna0zxG1DwsKZsreLbXBxw=="], - } -} diff --git a/dstack/kms/auth-mock/index.test.ts b/dstack/kms/auth-mock/index.test.ts deleted file mode 100644 index 4937456131..0000000000 --- a/dstack/kms/auth-mock/index.test.ts +++ /dev/null @@ -1,356 +0,0 @@ -// SPDX-FileCopyrightText: © 2025 Phala Network -// -// SPDX-License-Identifier: Apache-2.0 - -import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest'; -import openApiSpec from './openapi.json'; - -// Dynamic import -let appFetch: any; - -beforeAll(async () => { - // Set environment variables for testing - process.env.KMS_CONTRACT_ADDR = '0xmockcontract1234567890123456789012345678'; - process.env.PORT = '3002'; - - // Import the app - const indexModule = await import('./index.ts'); - appFetch = indexModule.default.fetch; -}); - -beforeEach(() => { - // Reset console spy before each test - vi.clearAllMocks(); -}); - -describe('Mock Backend Tests', () => { - describe('GET /', () => { - it('should return mock system info', async () => { - const response = await appFetch(new Request('http://localhost:3002/')); - const data = await response.json(); - - expect(response.status).toBe(200); - expect(data).toMatchObject({ - status: 'ok', - kmsContractAddr: expect.any(String), - gatewayAppId: expect.any(String), - chainId: expect.any(Number), - appAuthImplementation: expect.any(String), - appImplementation: expect.any(String), - note: 'this is a mock backend - all authentications will succeed' - }); - - // Verify mock values (using same defaults as implementation) - expect(data.gatewayAppId).toBe(process.env.MOCK_GATEWAY_APP_ID || '0xmockgateway1234567890123456789012345678'); - expect(data.chainId).toBe(parseInt(process.env.MOCK_CHAIN_ID || '1337')); - expect(data.appImplementation).toBe(process.env.MOCK_APP_IMPLEMENTATION || '0xmockapp9876543210987654321098765432109'); - - // Verify response structure matches OpenAPI spec - const systemInfoSchema = openApiSpec.components.schemas.MockSystemInfo; - const requiredFields = systemInfoSchema.required; - - requiredFields.forEach(field => { - expect(data).toHaveProperty(field); - }); - }); - }); - - describe('POST /bootAuth/app', () => { - const validBootInfo = { - mrAggregated: '0x1234567890123456789012345678901234567890123456789012345678901234', - osImageHash: '0xabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcd', - appId: '0x1111111111111111111111111111111111111111', - composeHash: '0x2222222222222222222222222222222222222222222222222222222222222222', - instanceId: '0x3333333333333333333333333333333333333333', - deviceId: '0x4444444444444444444444444444444444444444444444444444444444444444', - }; - - it('should always return success for app auth', async () => { - const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); - - const response = await appFetch(new Request('http://localhost:3002/bootAuth/app', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(validBootInfo), - })); - - const data = await response.json(); - - expect(response.status).toBe(200); - expect(data).toMatchObject({ - isAllowed: true, - reason: 'mock app always allowed', - gatewayAppId: process.env.MOCK_GATEWAY_APP_ID || '0xmockgateway1234567890123456789012345678', - }); - - // Verify console log was called - expect(consoleSpy).toHaveBeenCalledWith('mock app boot auth request:', { - appId: validBootInfo.appId, - instanceId: validBootInfo.instanceId, - note: 'always returning success' - }); - - // Verify response matches OpenAPI spec - const bootResponseSchema = openApiSpec.components.schemas.BootResponse; - const requiredFields = bootResponseSchema.required; - - requiredFields.forEach(field => { - expect(data).toHaveProperty(field); - }); - - consoleSpy.mockRestore(); - }); - - it('should handle full BootInfo with optional fields', async () => { - const fullBootInfo = { - ...validBootInfo, - tcbStatus: 'OK', - advisoryIds: ['INTEL-SA-00123'], - mrSystem: '0x5555555555555555555555555555555555555555555555555555555555555555', - }; - - const response = await appFetch(new Request('http://localhost:3002/bootAuth/app', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(fullBootInfo), - })); - - const data = await response.json(); - - expect(response.status).toBe(200); - expect(data.isAllowed).toBe(true); - expect(data.reason).toBe('mock app always allowed'); - }); - - it('should reject invalid request body', async () => { - const invalidBootInfo = { - mrAggregated: '0x1234', // missing required fields - }; - - const response = await appFetch(new Request('http://localhost:3002/bootAuth/app', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(invalidBootInfo), - })); - - expect(response.status).toBe(400); - }); - - it('should return success even with minimal data', async () => { - const minimalBootInfo = { - mrAggregated: 'minimal', - osImageHash: 'minimal', - appId: 'minimal', - composeHash: 'minimal', - instanceId: 'minimal', - deviceId: 'minimal', - }; - - const response = await appFetch(new Request('http://localhost:3002/bootAuth/app', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(minimalBootInfo), - })); - - const data = await response.json(); - - expect(response.status).toBe(200); - expect(data.isAllowed).toBe(true); - expect(data.reason).toBe('mock app always allowed'); - }); - }); - - describe('POST /bootAuth/kms', () => { - const validBootInfo = { - mrAggregated: '0x1234567890123456789012345678901234567890123456789012345678901234', - osImageHash: '0xabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcd', - appId: '0x1111111111111111111111111111111111111111', - composeHash: '0x2222222222222222222222222222222222222222222222222222222222222222', - instanceId: '0x3333333333333333333333333333333333333333', - deviceId: '0x4444444444444444444444444444444444444444444444444444444444444444', - }; - - it('should always return success for KMS auth', async () => { - const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); - - const response = await appFetch(new Request('http://localhost:3002/bootAuth/kms', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(validBootInfo), - })); - - const data = await response.json(); - - expect(response.status).toBe(200); - expect(data).toMatchObject({ - isAllowed: true, - reason: 'mock KMS always allowed', - gatewayAppId: process.env.MOCK_GATEWAY_APP_ID || '0xmockgateway1234567890123456789012345678', - }); - - // Verify console log was called - expect(consoleSpy).toHaveBeenCalledWith('mock KMS boot auth request:', { - appId: validBootInfo.appId, - instanceId: validBootInfo.instanceId, - note: 'always returning success' - }); - - consoleSpy.mockRestore(); - }); - - it('should handle different request patterns', async () => { - const randomBootInfo = { - mrAggregated: 'random-mr-value', - osImageHash: 'random-os-hash', - appId: 'random-app-id', - composeHash: 'random-compose-hash', - instanceId: 'random-instance-id', - deviceId: 'random-device-id', - tcbStatus: 'FAIL', // even with fail status - advisoryIds: ['CRITICAL-ADVISORY'], - }; - - const response = await appFetch(new Request('http://localhost:3002/bootAuth/kms', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(randomBootInfo), - })); - - const data = await response.json(); - - expect(response.status).toBe(200); - expect(data.isAllowed).toBe(true); // Always true in mock - expect(data.reason).toBe('mock KMS always allowed'); - }); - - it('should handle "Test backend error" appropriately', async () => { - const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); - - // This shouldn't actually throw an error in mock backend, but test the error handling path - const response = await appFetch(new Request('http://localhost:3002/bootAuth/kms', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(validBootInfo), - })); - - const data = await response.json(); - - expect(response.status).toBe(200); - expect(data.isAllowed).toBe(true); // Still success in mock - - // Verify console.error was not called (no errors in mock) - expect(consoleSpy).not.toHaveBeenCalled(); - - consoleSpy.mockRestore(); - }); - }); -}); - -describe('API Schema Compatibility', () => { - it('should match BootInfo schema requirements', () => { - const bootInfoSchema = openApiSpec.components.schemas.BootInfo; - - // Required fields should match original schema - expect(bootInfoSchema.required).toEqual([ - 'mrAggregated', - 'osImageHash', - 'appId', - 'composeHash', - 'instanceId', - 'deviceId' - ]); - - // Optional fields should be present for full compatibility - expect(bootInfoSchema.properties).toHaveProperty('tcbStatus'); - expect(bootInfoSchema.properties).toHaveProperty('advisoryIds'); - expect(bootInfoSchema.properties).toHaveProperty('mrSystem'); - }); - - it('should match BootResponse schema requirements', () => { - const bootResponseSchema = openApiSpec.components.schemas.BootResponse; - - expect(bootResponseSchema.required).toEqual([ - 'isAllowed', - 'reason', - 'gatewayAppId' - ]); - - // Verify mock-specific examples - expect(bootResponseSchema.properties.isAllowed.example).toBe(true); - expect(bootResponseSchema.properties.reason.example).toBe('mock app always allowed'); - }); - - it('should match MockSystemInfo schema requirements', () => { - const systemInfoSchema = openApiSpec.components.schemas.MockSystemInfo; - - expect(systemInfoSchema.required).toEqual([ - 'status', - 'kmsContractAddr', - 'gatewayAppId', - 'chainId', - 'appAuthImplementation', - 'appImplementation', - 'note' - ]); - - // Verify the note field is required (unique to mock) - expect(systemInfoSchema.properties.note.example).toBe('this is a mock backend - all authentications will succeed'); - }); -}); - -describe('Mock Behavior Verification', () => { - it('should always return success regardless of input validity', async () => { - // Test with completely bogus data - const bogusBootInfo = { - mrAggregated: 'invalid-data', - osImageHash: 'also-invalid', - appId: 'not-a-real-address', - composeHash: 'fake-hash', - instanceId: 'fake-instance', - deviceId: 'fake-device', - tcbStatus: 'COMPROMISED', // even compromised status - advisoryIds: ['CRITICAL-001', 'CRITICAL-002'], - }; - - const appResponse = await appFetch(new Request('http://localhost:3002/bootAuth/app', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(bogusBootInfo), - })); - - const kmsResponse = await appFetch(new Request('http://localhost:3002/bootAuth/kms', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(bogusBootInfo), - })); - - const appData = await appResponse.json(); - const kmsData = await kmsResponse.json(); - - // Both should return success - expect(appData.isAllowed).toBe(true); - expect(kmsData.isAllowed).toBe(true); - expect(appData.reason).toBe('mock app always allowed'); - expect(kmsData.reason).toBe('mock KMS always allowed'); - }); - - it('denies both routes on an unknown MOCK_POLICY', async () => { - process.env.MOCK_POLICY = 'deny_all'; - try { - for (const path of ['app', 'kms']) { - const response = await appFetch(new Request(`http://localhost:3002/bootAuth/${path}`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - mrAggregated: '', osImageHash: '', appId: '', composeHash: '', instanceId: '', deviceId: '', - }), - })); - const data = await response.json(); - expect(data.isAllowed).toBe(false); - expect(data.reason).toBe('unknown MOCK_POLICY "deny_all"'); - } - } finally { - delete process.env.MOCK_POLICY; - } - }); -}); diff --git a/dstack/kms/auth-mock/index.ts b/dstack/kms/auth-mock/index.ts deleted file mode 100644 index 83037c93c0..0000000000 --- a/dstack/kms/auth-mock/index.ts +++ /dev/null @@ -1,222 +0,0 @@ -// SPDX-FileCopyrightText: © 2025 Phala Network -// -// SPDX-License-Identifier: Apache-2.0 - -import { Hono } from 'hono'; -import { zValidator } from '@hono/zod-validator'; -import { z } from 'zod'; - -if (process.env.NODE_ENV === 'production') { - throw new Error('auth-mock must not run with NODE_ENV=production'); -} - -// zod schemas for validation - compatible with original fastify implementation -const BootInfoSchema = z.object({ - // required fields (matching original fastify schema) - mrAggregated: z.string().describe('aggregated MR measurement'), - osImageHash: z.string().describe('OS Image hash'), - appId: z.string().describe('application ID'), - composeHash: z.string().describe('compose hash'), - instanceId: z.string().describe('instance ID'), - deviceId: z.string().describe('device ID'), - // optional fields (for full compatibility with BootInfo interface) - tcbStatus: z.string().optional().default(''), - advisoryIds: z.array(z.string()).optional().default([]), - mrSystem: z.string().optional().default('') -}); - -const BootResponseSchema = z.object({ - isAllowed: z.boolean(), - reason: z.string(), - gatewayAppId: z.string() -}); - -type BootInfo = z.infer; -type BootResponse = z.infer; - -// authorization policy - configurable via environment variables -// MOCK_POLICY: "allow-all" (default), "deny-kms", "deny-app", "deny-all", -// "allowlist-device", "allowlist-mr" -// MOCK_ALLOWED_DEVICE_IDS: comma-separated device IDs (for allowlist-device policy) -// MOCK_ALLOWED_MR_AGGREGATED: comma-separated MR aggregated values (for allowlist-mr policy) - -type MockPolicy = 'allow-all' | 'deny-kms' | 'deny-app' | 'deny-all' | 'allowlist-device' | 'allowlist-mr'; - -function getPolicy(): MockPolicy { - const policy = process.env.MOCK_POLICY || 'allow-all'; - const valid: MockPolicy[] = ['allow-all', 'deny-kms', 'deny-app', 'deny-all', 'allowlist-device', 'allowlist-mr']; - if (!valid.includes(policy as MockPolicy)) { - throw new Error(`unknown MOCK_POLICY "${policy}"`); - } - return policy as MockPolicy; -} - -function parseList(envVar: string): Set { - const raw = process.env[envVar] || ''; - return new Set(raw.split(',').map(s => s.trim().toLowerCase()).filter(Boolean)); -} - -// mock backend class - no blockchain interaction -class MockBackend { - private mockGatewayAppId: string; - private mockChainId: number; - private mockAppImplementation: string; - - constructor() { - // mock values - configurable via environment variables - this.mockGatewayAppId = process.env.MOCK_GATEWAY_APP_ID || '0xmockgateway1234567890123456789012345678'; - this.mockChainId = parseInt(process.env.MOCK_CHAIN_ID || '1337'); - this.mockAppImplementation = process.env.MOCK_APP_IMPLEMENTATION || '0xmockapp9876543210987654321098765432109'; - } - - async checkBoot(bootInfo: BootInfo, isKms: boolean): Promise { - const policy = getPolicy(); - const deny = (reason: string): BootResponse => ({ - isAllowed: false, - reason, - gatewayAppId: '', - }); - const allow = (reason: string): BootResponse => ({ - isAllowed: true, - reason, - gatewayAppId: this.mockGatewayAppId, - }); - - switch (policy) { - case 'deny-all': - return deny(`mock policy: deny-all`); - case 'deny-kms': - if (isKms) return deny(`mock policy: deny-kms`); - return allow('mock app allowed (deny-kms policy)'); - case 'deny-app': - if (!isKms) return deny(`mock policy: deny-app`); - return allow('mock KMS allowed (deny-app policy)'); - case 'allowlist-device': { - const allowed = parseList('MOCK_ALLOWED_DEVICE_IDS'); - const deviceId = bootInfo.deviceId.toLowerCase().replace(/^0x/, ''); - if (allowed.size === 0) return deny('mock policy: allowlist-device with empty list'); - if (!allowed.has(deviceId)) return deny(`mock policy: device ${bootInfo.deviceId} not in allowlist`); - return allow(`mock policy: device ${bootInfo.deviceId} allowed`); - } - case 'allowlist-mr': { - const allowed = parseList('MOCK_ALLOWED_MR_AGGREGATED'); - const mr = bootInfo.mrAggregated.toLowerCase().replace(/^0x/, ''); - if (allowed.size === 0) return deny('mock policy: allowlist-mr with empty list'); - if (!allowed.has(mr)) return deny(`mock policy: mrAggregated ${bootInfo.mrAggregated} not in allowlist`); - return allow(`mock policy: mrAggregated ${bootInfo.mrAggregated} allowed`); - } - case 'allow-all': - default: - return allow(isKms ? 'mock KMS always allowed' : 'mock app always allowed'); - } - } - - async getGatewayAppId(): Promise { - return this.mockGatewayAppId; - } - - async getChainId(): Promise { - return this.mockChainId; - } - - async getAppImplementation(): Promise { - return this.mockAppImplementation; - } -} - -// initialize app -const app = new Hono(); - -// initialize mock backend -const mockBackend = new MockBackend(); - -// health check and info endpoint -app.get('/', async (c) => { - try { - const batch = await Promise.all([ - mockBackend.getGatewayAppId(), - mockBackend.getChainId(), - mockBackend.getAppImplementation(), - ]); - - return c.json({ - status: 'ok', - kmsContractAddr: process.env.KMS_CONTRACT_ADDR || '0xmockcontract1234567890123456789012345678', - ethRpcUrl: process.env.ETH_RPC_URL || '', - gatewayAppId: batch[0], - chainId: batch[1], - appAuthImplementation: batch[2], // NOTE: for backward compatibility - appImplementation: batch[2], - note: 'this is a mock backend - all authentications will succeed' - }); - } catch (error) { - console.error('error in health check:', error); - return c.json({ - status: 'error', - message: error instanceof Error ? error.message : String(error) - }, 500); - } -}); - -// app boot authentication -app.post('/bootAuth/app', - zValidator('json', BootInfoSchema), - async (c) => { - try { - const bootInfo = c.req.valid('json'); - console.log('mock app boot auth request:', { - appId: bootInfo.appId, - instanceId: bootInfo.instanceId, - note: 'always returning success' - }); - - const result = await mockBackend.checkBoot(bootInfo, false); - return c.json(result); - } catch (error) { - console.error('error in app boot auth:', error); - return c.json({ - isAllowed: false, - gatewayAppId: '', - reason: error instanceof Error ? error.message : String(error) - }); - } - } -); - -// KMS boot authentication -app.post('/bootAuth/kms', - zValidator('json', BootInfoSchema), - async (c) => { - try { - const bootInfo = c.req.valid('json'); - console.log('mock KMS boot auth request:', { - appId: bootInfo.appId, - instanceId: bootInfo.instanceId, - note: 'always returning success' - }); - - const result = await mockBackend.checkBoot(bootInfo, true); - return c.json(result); - } catch (error) { - // don't log test backend errors (keeping compatibility with original) - if (!(error instanceof Error && "Test backend error" === error.message)) { - console.error('error in KMS boot auth:', error); - } - return c.json({ - isAllowed: false, - gatewayAppId: '', - reason: error instanceof Error ? error.message : String(error) - }); - } - } -); - -// start server -const port = parseInt(process.env.PORT || '3000'); -const policy = getPolicy(); -console.log(`starting mock auth server on port ${port} (policy: ${policy})`); - -export default { - port, - fetch: app.fetch, -}; diff --git a/dstack/kms/auth-mock/openapi.json b/dstack/kms/auth-mock/openapi.json deleted file mode 100644 index 1689308d05..0000000000 --- a/dstack/kms/auth-mock/openapi.json +++ /dev/null @@ -1,250 +0,0 @@ -{ - "openapi": "3.0.0", - "info": { - "title": "dstack KMS Mock Backend API", - "description": "Mock API for dstack KMS backend - all authentications will succeed (no blockchain interaction)", - "version": "1.0.0" - }, - "servers": [ - { - "url": "http://localhost:3000", - "description": "Development server" - } - ], - "paths": { - "/": { - "get": { - "summary": "Health check and system information", - "description": "Returns mock system status and configuration information", - "operationId": "getSystemInfo", - "responses": { - "200": { - "description": "Mock system information", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/MockSystemInfo" - } - } - } - }, - "500": { - "description": "Internal server error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } - } - } - } - }, - "/bootAuth/app": { - "post": { - "summary": "Application boot authentication (mock - always succeeds)", - "description": "Mock validation that always allows application boot", - "operationId": "authenticateAppBoot", - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/BootInfo" - } - } - } - }, - "responses": { - "200": { - "description": "Authentication result (always success in mock)", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/BootResponse" - } - } - } - } - } - } - }, - "/bootAuth/kms": { - "post": { - "summary": "KMS boot authentication (mock - always succeeds)", - "description": "Mock validation that always allows KMS boot", - "operationId": "authenticateKmsBoot", - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/BootInfo" - } - } - } - }, - "responses": { - "200": { - "description": "Authentication result (always success in mock)", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/BootResponse" - } - } - } - } - } - } - } - }, - "components": { - "schemas": { - "BootInfo": { - "type": "object", - "required": [ - "mrAggregated", - "osImageHash", - "appId", - "composeHash", - "instanceId", - "deviceId" - ], - "properties": { - "mrAggregated": { - "type": "string", - "description": "Aggregated MR measurement" - }, - "osImageHash": { - "type": "string", - "description": "OS Image hash" - }, - "appId": { - "type": "string", - "description": "Application ID" - }, - "composeHash": { - "type": "string", - "description": "Compose hash" - }, - "instanceId": { - "type": "string", - "description": "Instance ID" - }, - "deviceId": { - "type": "string", - "description": "Device ID" - }, - "tcbStatus": { - "type": "string", - "description": "TCB status (optional for compatibility)" - }, - "advisoryIds": { - "type": "array", - "items": { - "type": "string" - }, - "description": "Advisory IDs (optional for compatibility)" - }, - "mrSystem": { - "type": "string", - "description": "MR System measurement (optional for compatibility)" - } - } - }, - "BootResponse": { - "type": "object", - "required": [ - "isAllowed", - "reason", - "gatewayAppId" - ], - "properties": { - "isAllowed": { - "type": "boolean", - "description": "Whether the boot is allowed (always true in mock)", - "example": true - }, - "reason": { - "type": "string", - "description": "Reason for the decision", - "example": "mock app always allowed" - }, - "gatewayAppId": { - "type": "string", - "description": "Mock gateway application ID", - "example": "0xmockgateway1234567890123456789012345678" - } - } - }, - "MockSystemInfo": { - "type": "object", - "required": [ - "status", - "kmsContractAddr", - "gatewayAppId", - "chainId", - "appAuthImplementation", - "appImplementation", - "note" - ], - "properties": { - "status": { - "type": "string", - "enum": ["ok"], - "description": "System status" - }, - "kmsContractAddr": { - "type": "string", - "description": "Mock KMS contract address", - "example": "0xmockcontract1234567890123456789012345678" - }, - "gatewayAppId": { - "type": "string", - "description": "Mock gateway application ID", - "example": "0xmockgateway1234567890123456789012345678" - }, - "chainId": { - "type": "number", - "description": "Mock blockchain chain ID", - "example": 1337 - }, - "appAuthImplementation": { - "type": "string", - "description": "Mock app auth implementation address (deprecated, use appImplementation)", - "example": "0xmockapp9876543210987654321098765432109" - }, - "appImplementation": { - "type": "string", - "description": "Mock app implementation address", - "example": "0xmockapp9876543210987654321098765432109" - }, - "note": { - "type": "string", - "description": "Note about mock backend behavior", - "example": "this is a mock backend - all authentications will succeed" - } - } - }, - "Error": { - "type": "object", - "required": [ - "status", - "message" - ], - "properties": { - "status": { - "type": "string", - "enum": ["error"] - }, - "message": { - "type": "string", - "description": "Error message" - } - } - } - } - } -} diff --git a/dstack/kms/auth-mock/package.json b/dstack/kms/auth-mock/package.json deleted file mode 100644 index 09094da99b..0000000000 --- a/dstack/kms/auth-mock/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "auth-mock", - "version": "1.0.0", - "description": "dstack KMS mock backend with bun + hono + zod", - "main": "index.ts", - "scripts": { - "dev": "bun run --watch index.ts", - "start": "bun run index.ts", - "build": "bun build index.ts --outdir ./dist --target bun", - "test": "vitest", - "test:run": "vitest run", - "lint": "oxlint .", - "lint:fix": "oxlint --fix .", - "fmt": "oxlint --fix .", - "check": "bun run lint && bun run test:run" - }, - "dependencies": { - "hono": "4.13.5", - "@hono/zod-validator": "0.2.2", - "zod": "3.25.76" - }, - "devDependencies": { - "@types/bun": "1.2.18", - "@types/node": "22.10.8", - "@vitest/ui": "1.6.1", - "openapi-types": "12.1.3", - "oxlint": "0.9.10", - "typescript": "5.8.3", - "vitest": "4.1.11" - }, - "type": "module" -} diff --git a/dstack/kms/auth-mock/vitest.config.ts b/dstack/kms/auth-mock/vitest.config.ts deleted file mode 100644 index 17597daca3..0000000000 --- a/dstack/kms/auth-mock/vitest.config.ts +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-FileCopyrightText: © 2025 Phala Network -// -// SPDX-License-Identifier: Apache-2.0 - -import { defineConfig } from 'vitest/config'; - -export default defineConfig({ - test: { - globals: true, - environment: 'node', - }, -}); diff --git a/dstack/kms/auth-simple/.oxlintrc.json b/dstack/kms/auth-simple/.oxlintrc.json deleted file mode 100644 index f7d7b8e35e..0000000000 --- a/dstack/kms/auth-simple/.oxlintrc.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "$schema": "https://raw.githubusercontent.com/oxc-project/oxc/main/crates/oxc_linter/src/config/schema.json", - "rules": { - "typescript": "warn", - "unicorn": "warn", - "react": "off", - "jsx-a11y": "off", - "nextjs": "off" - }, - "env": { - "node": true, - "es2022": true - }, - "globals": { - "globalThis": "readonly", - "console": "readonly" - }, - "ignore_patterns": [ - "node_modules/**", - "dist/**", - "build/**", - "coverage/**", - "*.min.js", - "*.d.ts", - "*.test.ts" - ] -} diff --git a/dstack/kms/auth-simple/README.md b/dstack/kms/auth-simple/README.md deleted file mode 100644 index efd2efcb57..0000000000 --- a/dstack/kms/auth-simple/README.md +++ /dev/null @@ -1,252 +0,0 @@ -# dstack auth-simple - -A config-based auth server for dstack KMS webhook authorization. Validates boot requests against a JSON configuration file. - -## When to Use - -| Auth Server | Use Case | -|-------------|----------| -| **auth-simple** | Production deployments with config-file-based whitelisting | -| auth-eth | Production deployments with on-chain governance | -| auth-mock | Development and testing only | - -## Installation - -```bash -bun install -``` - -## Configuration - -Create `auth-config.json` (see `auth-config.example.json`). - -For KMS deployment, you must allowlist the OS image hash and at least one KMS -identity value via `kms.mrAggregated` (the early/boot-mr-done aggregate MR, -same pinning model as bare TDX). App compose hashes still use -`apps..composeHashes`. - -```json -{ - "osImages": ["0x0b327bcd642788b0517de3ff46d31ebd3847b6c64ea40bacde268bb9f1c8ec83"], - "kms": { - "mrAggregated": ["0x"], - "allowAnyDevice": true - }, - "apps": {} -} -``` - -Add more fields as you deploy Gateway and apps: - -```json -{ - "osImages": ["0x..."], - "allowedTcbStatuses": ["UpToDate"], - "allowedAdvisoryIds": [], - "gatewayAppId": "0x...", - "kms": { - "mrAggregated": ["0x..."], - "devices": [], - "allowAnyDevice": true - }, - "apps": { - "0xYourAppId": { - "composeHashes": ["0xabc...", "0xdef..."], - "devices": [], - "allowAnyDevice": true - } - } -} -``` - -### AWS NitroTPM Example - -AWS NitroTPM has no TDX/SNP-style TCB advisory surface, so the KMS normalizes a -verified NitroTPM attestation to `tcbStatus: "UpToDate"` before calling -auth-simple. Pin KMS via early `mrAggregated` (boot-mr-done snapshot), same as -bare TDX. Prefer a stable AMI/`os_image_hash` and empty TPM key-provider id so -that early MR is precomputable. - -```json -{ - "osImages": ["0x"], - "allowedAdvisoryIds": [], - "kms": { - "mrAggregated": ["0x"], - "devices": [], - "allowAnyDevice": true - }, - "apps": { - "0x": { - "composeHashes": ["0x"], - "devices": [], - "allowAnyDevice": true - } - } -} -``` - -The verifier that calls auth-simple must already have verified the NitroTPM -Attestation Document, AWS NitroTPM PKI chain, boot PCRs, PCR14 launch-event -replay, and OS image binding. PCR8 is an optional third-party shortcut, not a -required dstack check; see `docs/aws-ec2-production-verifier-runbook.md`. -auth-simple authorizes the resulting canonical `BootInfo`; it does not verify -raw NitroTPM evidence by itself. - -### Configuration Fields - -| Field | Required | Description | -|-------|----------|-------------| -| `osImages` | Yes | Allowed OS image hashes (from `digest.txt`) | -| `gatewayAppId` | No | Gateway app ID (add after Gateway deployment) | -| `allowedTcbStatuses` | No | Allowed verifier-derived TCB status strings. Defaults to `["UpToDate"]`; non-up-to-date SNP/TDX statuses remain fail-closed unless explicitly allowlisted for testing. | -| `allowedAdvisoryIds` | No | Advisory IDs permitted in `advisoryIds`. Defaults to `[]`, which rejects any advisory. | -| `kms.mrAggregated` | Yes | Allowed KMS early aggregate MR values (boot-mr-done). | -| `kms.devices` | No | Allowed KMS device IDs. Empty denies all unless `kms.allowAnyDevice` is true. | -| `kms.allowAnyDevice` | No | If true, skip device ID check for KMS | -| `apps..composeHashes` | No | Allowed compose hashes for this app | -| `apps..devices` | No | Allowed device IDs for this app. Empty denies all unless `allowAnyDevice` is true. | -| `apps..allowAnyDevice` | No | If true, skip device ID check for this app | - -For experimental AMD SEV-SNP dry-run authorization, keep the default fail-closed TCB policy unless you intentionally want the auth webhook to accept non-up-to-date verifier-derived SNP `BootInfo`. To exercise the dry-run path without enabling key release, allowlist the recomputed SNP `mrAggregated`, `osImageHash`, app/compose identity, device/chip identity, and any non-default `allowedTcbStatuses`/`allowedAdvisoryIds` values explicitly. KMS still rejects SNP before returning app keys, KMS keys, or app certificates. - -### Getting Hash Values - -**OS Image Hash:** -```bash -# From meta-dstack build output -cat images/digest.txt -``` - -**Compose Hash:** -```bash -sha256sum .app-compose.json | awk '{print "0x"$1}' -``` - -## Usage - -### Development - -```bash -# Run with hot reload -bun run dev -``` - -### Production - -```bash -# Run directly -bun run start - -# Or build first -bun run build -``` - -## Environment Variables - -| Variable | Default | Description | -|----------|---------|-------------| -| `PORT` | 3000 | Server port | -| `AUTH_CONFIG_PATH` | ./auth-config.json | Path to config file | - -## API Endpoints - -### GET / - -Health check and server info. - -**Response:** -```json -{ - "status": "ok", - "configPath": "./auth-config.json", - "gatewayAppId": "0x..." -} -``` - -### POST /bootAuth/app - -App boot authorization. - -**Request:** -```json -{ - "teeVariant": "dstack-tdx", - "mrAggregated": "0x...", - "osImageHash": "0x...", - "appId": "0x...", - "composeHash": "0x...", - "instanceId": "0x...", - "deviceId": "0x...", - "tcbStatus": "UpToDate", - "advisoryIds": [] -} -``` - -**Response:** -```json -{ - "isAllowed": true, - "reason": "", - "gatewayAppId": "0x..." -} -``` - -### POST /bootAuth/kms - -KMS boot authorization. - -**Request:** Same as `/bootAuth/app` - -**Response:** Same as `/bootAuth/app` - -## Validation Logic - -### KMS Boot Validation - -1. `tcbStatus` must be listed in `allowedTcbStatuses` (default: only `"UpToDate"`). AWS NitroTPM is normalized to `"UpToDate"` by the KMS before it reaches auth-simple. -2. Every `advisoryIds` entry must be listed in `allowedAdvisoryIds` (default: none allowed) -3. `osImageHash` must be in `osImages` array -4. `mrAggregated` must be in the `kms.mrAggregated` early/boot-mr-done allowlist -5. `deviceId` must be in `kms.devices` unless `allowAnyDevice` is true - -### App Boot Validation - -1. `tcbStatus` must be listed in `allowedTcbStatuses` (default: only `"UpToDate"`). AWS NitroTPM is normalized to `"UpToDate"` by the KMS before it reaches auth-simple. -2. Every `advisoryIds` entry must be listed in `allowedAdvisoryIds` (default: none allowed) -3. `osImageHash` must be in `osImages` array -4. `appId` must exist in `apps` object -5. `composeHash` must be in app's `composeHashes` array -6. `deviceId` must be in app's `devices` (unless `allowAnyDevice` is true) - -## Hot Reload - -The config file is re-read on every request. No restart required after config changes. - -## Integration with KMS - -Configure KMS to use webhook auth pointing to this server: - -```toml -[core.auth_api] -type = "webhook" - -[core.auth_api.webhook] -url = "http://localhost:3000" -``` - -## Testing - -```bash -# Run tests -bun run test - -# Run once -bun run test:run -``` - -## See Also - -- [auth-eth](../auth-eth/) - On-chain governance auth server -- [auth-mock](../auth-mock/) - Development/testing auth server (always allows) -- [Deployment Guide](../../../docs/deployment.md) - Full deployment instructions diff --git a/dstack/kms/auth-simple/auth-config.example.json b/dstack/kms/auth-simple/auth-config.example.json deleted file mode 100644 index b93e4e987a..0000000000 --- a/dstack/kms/auth-simple/auth-config.example.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "osImages": [ - "0x0b327bcd642788b0517de3ff46d31ebd3847b6c64ea40bacde268bb9f1c8ec83" - ], - "kms": { - "mrAggregated": [ - "0x" - ], - "devices": [], - "allowAnyDevice": true - }, - "apps": { - "0xYourAppId": { - "composeHashes": [ - "0xYourComposeHash" - ], - "devices": [], - "allowAnyDevice": true - } - } -} diff --git a/dstack/kms/auth-simple/bun.lock b/dstack/kms/auth-simple/bun.lock deleted file mode 100644 index 211959aa66..0000000000 --- a/dstack/kms/auth-simple/bun.lock +++ /dev/null @@ -1,345 +0,0 @@ -{ - "lockfileVersion": 1, - "workspaces": { - "": { - "name": "auth-simple", - "dependencies": { - "@hono/zod-validator": "0.2.2", - "hono": "4.13.5", - "zod": "3.25.76", - }, - "devDependencies": { - "@types/bun": "1.2.18", - "@types/node": "22.10.8", - "@vitest/ui": "1.6.1", - "openapi-types": "12.1.3", - "oxlint": "0.9.10", - "typescript": "5.8.3", - "vitest": "3.2.6", - }, - }, - }, - "packages": { - "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.21.5", "", { "os": "aix", "cpu": "ppc64" }, "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ=="], - - "@esbuild/android-arm": ["@esbuild/android-arm@0.21.5", "", { "os": "android", "cpu": "arm" }, "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg=="], - - "@esbuild/android-arm64": ["@esbuild/android-arm64@0.21.5", "", { "os": "android", "cpu": "arm64" }, "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A=="], - - "@esbuild/android-x64": ["@esbuild/android-x64@0.21.5", "", { "os": "android", "cpu": "x64" }, "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA=="], - - "@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.21.5", "", { "os": "darwin", "cpu": "arm64" }, "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ=="], - - "@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.21.5", "", { "os": "darwin", "cpu": "x64" }, "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw=="], - - "@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.21.5", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g=="], - - "@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.21.5", "", { "os": "freebsd", "cpu": "x64" }, "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ=="], - - "@esbuild/linux-arm": ["@esbuild/linux-arm@0.21.5", "", { "os": "linux", "cpu": "arm" }, "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA=="], - - "@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.21.5", "", { "os": "linux", "cpu": "arm64" }, "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q=="], - - "@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.21.5", "", { "os": "linux", "cpu": "ia32" }, "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg=="], - - "@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.21.5", "", { "os": "linux", "cpu": "none" }, "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg=="], - - "@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.21.5", "", { "os": "linux", "cpu": "none" }, "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg=="], - - "@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.21.5", "", { "os": "linux", "cpu": "ppc64" }, "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w=="], - - "@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.21.5", "", { "os": "linux", "cpu": "none" }, "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA=="], - - "@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.21.5", "", { "os": "linux", "cpu": "s390x" }, "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A=="], - - "@esbuild/linux-x64": ["@esbuild/linux-x64@0.21.5", "", { "os": "linux", "cpu": "x64" }, "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ=="], - - "@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.21.5", "", { "os": "none", "cpu": "x64" }, "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg=="], - - "@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.21.5", "", { "os": "openbsd", "cpu": "x64" }, "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow=="], - - "@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.21.5", "", { "os": "sunos", "cpu": "x64" }, "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg=="], - - "@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.21.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A=="], - - "@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.21.5", "", { "os": "win32", "cpu": "ia32" }, "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA=="], - - "@esbuild/win32-x64": ["@esbuild/win32-x64@0.21.5", "", { "os": "win32", "cpu": "x64" }, "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw=="], - - "@hono/zod-validator": ["@hono/zod-validator@0.2.2", "", { "peerDependencies": { "hono": ">=3.9.0", "zod": "^3.19.1" } }, "sha512-dSDxaPV70Py8wuIU2QNpoVEIOSzSXZ/6/B/h4xA7eOMz7+AarKTSGV8E6QwrdcCbBLkpqfJ4Q2TmBO0eP1tCBQ=="], - - "@jest/schemas": ["@jest/schemas@29.6.3", "", { "dependencies": { "@sinclair/typebox": "^0.27.8" } }, "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA=="], - - "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.5.5", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="], - - "@nodelib/fs.scandir": ["@nodelib/fs.scandir@2.1.5", "", { "dependencies": { "@nodelib/fs.stat": "2.0.5", "run-parallel": "^1.1.9" } }, "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g=="], - - "@nodelib/fs.stat": ["@nodelib/fs.stat@2.0.5", "", {}, "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A=="], - - "@nodelib/fs.walk": ["@nodelib/fs.walk@1.2.8", "", { "dependencies": { "@nodelib/fs.scandir": "2.1.5", "fastq": "^1.6.0" } }, "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg=="], - - "@oxlint/darwin-arm64": ["@oxlint/darwin-arm64@0.9.10", "", { "os": "darwin", "cpu": "arm64" }, "sha512-eOXKZYq5bnCSgDefgM5bzAg+4Fc//Rc4yjgKN8iDWUARweCaChiQXb6TXX8MfEfs6qayEMy6yVj0pqoFz0B1aw=="], - - "@oxlint/darwin-x64": ["@oxlint/darwin-x64@0.9.10", "", { "os": "darwin", "cpu": "x64" }, "sha512-UeYICDvLUaUOcY+0ugZUEmBMRLP+x8iTgL7TeY6BlpGw2ahbtUOTbyIIRWtr/0O++TnjZ+v8TzhJ9crw6Ij6dg=="], - - "@oxlint/linux-arm64-gnu": ["@oxlint/linux-arm64-gnu@0.9.10", "", { "os": "linux", "cpu": "arm64" }, "sha512-0Zn+vqHhrZyufFBfq9WOgiIool0gCR14BLsdS+0Dwd9o+kNxPGA5q7erQFkiC4rpkxtfBHeD3iIKMMt7d29Kyw=="], - - "@oxlint/linux-arm64-musl": ["@oxlint/linux-arm64-musl@0.9.10", "", { "os": "linux", "cpu": "arm64" }, "sha512-tkQcWpYwF42bA/uRaV2iMFePHkBjTTgomOgeEaiw6XOSJX4nBEqGIIboqqLBWT4JnKCf/L+IG3y/e1MflhKByw=="], - - "@oxlint/linux-x64-gnu": ["@oxlint/linux-x64-gnu@0.9.10", "", { "os": "linux", "cpu": "x64" }, "sha512-JHbkMUnibqaSMBvLHyqTL5cWxcGW+jw+Ppt2baLISpvo34a6fBR+PI7v/A92sEDWe0W1rPhypzCwA8mKpkQ3DA=="], - - "@oxlint/linux-x64-musl": ["@oxlint/linux-x64-musl@0.9.10", "", { "os": "linux", "cpu": "x64" }, "sha512-aBBwN7bQzidwHwEXr7BAdVvMTLWstCy5gikerjLnGDeCSXX9r+o6+yUzTOqZvOo66E+XBgOJaVbY8rsL1MLE0g=="], - - "@oxlint/win32-arm64": ["@oxlint/win32-arm64@0.9.10", "", { "os": "win32", "cpu": "arm64" }, "sha512-LXDnk7vKHT3IY6G1jq0O7+XMhtcHOYuxLGIx4KP+4xS6vKgBY+Bsq4xV3AtmtKlvnXkP5FxHpfLmcEtm5AWysA=="], - - "@oxlint/win32-x64": ["@oxlint/win32-x64@0.9.10", "", { "os": "win32", "cpu": "x64" }, "sha512-w5XRAV4bhgwenjjpGYZGglqzG9Wv/sI+cjQWJBQsvfDXsr2w4vOBXzt1j3/Z3EcSqf4KtkCa/IIuAhQyeShUbA=="], - - "@polka/url": ["@polka/url@1.0.0-next.29", "", {}, "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww=="], - - "@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.54.0", "", { "os": "android", "cpu": "arm" }, "sha512-OywsdRHrFvCdvsewAInDKCNyR3laPA2mc9bRYJ6LBp5IyvF3fvXbbNR0bSzHlZVFtn6E0xw2oZlyjg4rKCVcng=="], - - "@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.54.0", "", { "os": "android", "cpu": "arm64" }, "sha512-Skx39Uv+u7H224Af+bDgNinitlmHyQX1K/atIA32JP3JQw6hVODX5tkbi2zof/E69M1qH2UoN3Xdxgs90mmNYw=="], - - "@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.54.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-k43D4qta/+6Fq+nCDhhv9yP2HdeKeP56QrUUTW7E6PhZP1US6NDqpJj4MY0jBHlJivVJD5P8NxrjuobZBJTCRw=="], - - "@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.54.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-cOo7biqwkpawslEfox5Vs8/qj83M/aZCSSNIWpVzfU2CYHa2G3P1UN5WF01RdTHSgCkri7XOlTdtk17BezlV3A=="], - - "@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.54.0", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-miSvuFkmvFbgJ1BevMa4CPCFt5MPGw094knM64W9I0giUIMMmRYcGW/JWZDriaw/k1kOBtsWh1z6nIFV1vPNtA=="], - - "@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.54.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-KGXIs55+b/ZfZsq9aR026tmr/+7tq6VG6MsnrvF4H8VhwflTIuYh+LFUlIsRdQSgrgmtM3fVATzEAj4hBQlaqQ=="], - - "@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.54.0", "", { "os": "linux", "cpu": "arm" }, "sha512-EHMUcDwhtdRGlXZsGSIuXSYwD5kOT9NVnx9sqzYiwAc91wfYOE1g1djOEDseZJKKqtHAHGwnGPQu3kytmfaXLQ=="], - - "@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.54.0", "", { "os": "linux", "cpu": "arm" }, "sha512-+pBrqEjaakN2ySv5RVrj/qLytYhPKEUwk+e3SFU5jTLHIcAtqh2rLrd/OkbNuHJpsBgxsD8ccJt5ga/SeG0JmA=="], - - "@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.54.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-NSqc7rE9wuUaRBsBp5ckQ5CVz5aIRKCwsoa6WMF7G01sX3/qHUw/z4pv+D+ahL1EIKy6Enpcnz1RY8pf7bjwng=="], - - "@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.54.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-gr5vDbg3Bakga5kbdpqx81m2n9IX8M6gIMlQQIXiLTNeQW6CucvuInJ91EuCJ/JYvc+rcLLsDFcfAD1K7fMofg=="], - - "@rollup/rollup-linux-loong64-gnu": ["@rollup/rollup-linux-loong64-gnu@4.54.0", "", { "os": "linux", "cpu": "none" }, "sha512-gsrtB1NA3ZYj2vq0Rzkylo9ylCtW/PhpLEivlgWe0bpgtX5+9j9EZa0wtZiCjgu6zmSeZWyI/e2YRX1URozpIw=="], - - "@rollup/rollup-linux-ppc64-gnu": ["@rollup/rollup-linux-ppc64-gnu@4.54.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-y3qNOfTBStmFNq+t4s7Tmc9hW2ENtPg8FeUD/VShI7rKxNW7O4fFeaYbMsd3tpFlIg1Q8IapFgy7Q9i2BqeBvA=="], - - "@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.54.0", "", { "os": "linux", "cpu": "none" }, "sha512-89sepv7h2lIVPsFma8iwmccN7Yjjtgz0Rj/Ou6fEqg3HDhpCa+Et+YSufy27i6b0Wav69Qv4WBNl3Rs6pwhebQ=="], - - "@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.54.0", "", { "os": "linux", "cpu": "none" }, "sha512-ZcU77ieh0M2Q8Ur7D5X7KvK+UxbXeDHwiOt/CPSBTI1fBmeDMivW0dPkdqkT4rOgDjrDDBUed9x4EgraIKoR2A=="], - - "@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.54.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-2AdWy5RdDF5+4YfG/YesGDDtbyJlC9LHmL6rZw6FurBJ5n4vFGupsOBGfwMRjBYH7qRQowT8D/U4LoSvVwOhSQ=="], - - "@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.54.0", "", { "os": "linux", "cpu": "x64" }, "sha512-WGt5J8Ij/rvyqpFexxk3ffKqqbLf9AqrTBbWDk7ApGUzaIs6V+s2s84kAxklFwmMF/vBNGrVdYgbblCOFFezMQ=="], - - "@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.54.0", "", { "os": "linux", "cpu": "x64" }, "sha512-JzQmb38ATzHjxlPHuTH6tE7ojnMKM2kYNzt44LO/jJi8BpceEC8QuXYA908n8r3CNuG/B3BV8VR3Hi1rYtmPiw=="], - - "@rollup/rollup-openharmony-arm64": ["@rollup/rollup-openharmony-arm64@4.54.0", "", { "os": "none", "cpu": "arm64" }, "sha512-huT3fd0iC7jigGh7n3q/+lfPcXxBi+om/Rs3yiFxjvSxbSB6aohDFXbWvlspaqjeOh+hx7DDHS+5Es5qRkWkZg=="], - - "@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.54.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-c2V0W1bsKIKfbLMBu/WGBz6Yci8nJ/ZJdheE0EwB73N3MvHYKiKGs3mVilX4Gs70eGeDaMqEob25Tw2Gb9Nqyw=="], - - "@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.54.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-woEHgqQqDCkAzrDhvDipnSirm5vxUXtSKDYTVpZG3nUdW/VVB5VdCYA2iReSj/u3yCZzXID4kuKG7OynPnB3WQ=="], - - "@rollup/rollup-win32-x64-gnu": ["@rollup/rollup-win32-x64-gnu@4.54.0", "", { "os": "win32", "cpu": "x64" }, "sha512-dzAc53LOuFvHwbCEOS0rPbXp6SIhAf2txMP5p6mGyOXXw5mWY8NGGbPMPrs4P1WItkfApDathBj/NzMLUZ9rtQ=="], - - "@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.54.0", "", { "os": "win32", "cpu": "x64" }, "sha512-hYT5d3YNdSh3mbCU1gwQyPgQd3T2ne0A3KG8KSBdav5TiBg6eInVmV+TeR5uHufiIgSFg0XsOWGW5/RhNcSvPg=="], - - "@sinclair/typebox": ["@sinclair/typebox@0.27.8", "", {}, "sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA=="], - - "@types/bun": ["@types/bun@1.2.18", "", { "dependencies": { "bun-types": "1.2.18" } }, "sha512-Xf6RaWVheyemaThV0kUfaAUvCNokFr+bH8Jxp+tTZfx7dAPA8z9ePnP9S9+Vspzuxxx9JRAXhnyccRj3GyCMdQ=="], - - "@types/chai": ["@types/chai@5.2.3", "", { "dependencies": { "@types/deep-eql": "*", "assertion-error": "^2.0.1" } }, "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="], - - "@types/deep-eql": ["@types/deep-eql@4.0.2", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="], - - "@types/estree": ["@types/estree@1.0.8", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="], - - "@types/node": ["@types/node@22.10.8", "", { "dependencies": { "undici-types": "~6.20.0" } }, "sha512-rk+QvAEGsbX/ZPiiyel6hJHNUS9cnSbPWVaZLvE+Er3tLqQFzWMz9JOfWW7XUmKvRPfxJfbl3qYWve+RGXncFw=="], - - "@types/react": ["@types/react@19.2.7", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-MWtvHrGZLFttgeEj28VXHxpmwYbor/ATPYbBfSFZEIRK0ecCFLl2Qo55z52Hss+UV9CRN7trSeq1zbgx7YDWWg=="], - - "@vitest/expect": ["@vitest/expect@3.2.6", "", { "dependencies": { "@types/chai": "^5.2.2", "@vitest/spy": "3.2.6", "@vitest/utils": "3.2.6", "chai": "^5.2.0", "tinyrainbow": "^2.0.0" } }, "sha512-1+7q9BtaKzEmO+fmNT3kYvoNn5Y71XWAx2Q5HRim4tTVRQVRv4uJFAQ5FbK0OPUeNP/WmVCpxYxoJdvuHVjzBQ=="], - - "@vitest/mocker": ["@vitest/mocker@3.2.6", "", { "dependencies": { "@vitest/spy": "3.2.6", "estree-walker": "^3.0.3", "magic-string": "^0.30.17" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" }, "optionalPeers": ["msw", "vite"] }, "sha512-EZOrpDbkKotFAP7wPAQV1UIyoGOk4oX7ynWhBhLB7v+meMHbQhU16oPpIYGTTe4oFlhpryGpgpcZP/sin3hYuw=="], - - "@vitest/pretty-format": ["@vitest/pretty-format@3.2.7", "", { "dependencies": { "tinyrainbow": "^2.0.0" } }, "sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA=="], - - "@vitest/runner": ["@vitest/runner@3.2.6", "", { "dependencies": { "@vitest/utils": "3.2.6", "pathe": "^2.0.3", "strip-literal": "^3.0.0" } }, "sha512-HYcoSj1w5tcgUnzoF0HcyaAQjpA1gj9ftUJ7iSJSuipc02jW9gKkigwZbjFldAfYHA1fa8UZVRftdMY5msWM9Q=="], - - "@vitest/snapshot": ["@vitest/snapshot@3.2.6", "", { "dependencies": { "@vitest/pretty-format": "3.2.6", "magic-string": "^0.30.17", "pathe": "^2.0.3" } }, "sha512-H+ZjNTWGpObenh0YnlBctAPnJSI20P81PL8BPzWpx54YXLLTm8hEsWawtcYLMrwvpK48hGxLLbCS+1KRXhsKhw=="], - - "@vitest/spy": ["@vitest/spy@3.2.6", "", { "dependencies": { "tinyspy": "^4.0.3" } }, "sha512-oq6BbH68WzcWmwtBrU9nqLeaXTR4XwJF7FSLkKEZo4i6eoXcrxjcwSuTvWBIRUTC6VC72nXYunzqgZA+IKdtxg=="], - - "@vitest/ui": ["@vitest/ui@1.6.1", "", { "dependencies": { "@vitest/utils": "1.6.1", "fast-glob": "^3.3.2", "fflate": "^0.8.1", "flatted": "^3.2.9", "pathe": "^1.1.1", "picocolors": "^1.0.0", "sirv": "^2.0.4" }, "peerDependencies": { "vitest": "1.6.1" } }, "sha512-xa57bCPGuzEFqGjPs3vVLyqareG8DX0uMkr5U/v5vLv5/ZUrBrPL7gzxzTJedEyZxFMfsozwTIbbYfEQVo3kgg=="], - - "@vitest/utils": ["@vitest/utils@1.6.1", "", { "dependencies": { "diff-sequences": "^29.6.3", "estree-walker": "^3.0.3", "loupe": "^2.3.7", "pretty-format": "^29.7.0" } }, "sha512-jOrrUvXM4Av9ZWiG1EajNto0u96kWAhJ1LmPmJhXXQx/32MecEKd10pOLYgS2BQx1TgkGhloPU1ArDW2vvaY6g=="], - - "ansi-styles": ["ansi-styles@5.2.0", "", {}, "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA=="], - - "assertion-error": ["assertion-error@2.0.1", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="], - - "braces": ["braces@3.0.3", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="], - - "bun-types": ["bun-types@1.2.18", "", { "dependencies": { "@types/node": "*" }, "peerDependencies": { "@types/react": "^19" } }, "sha512-04+Eha5NP7Z0A9YgDAzMk5PHR16ZuLVa83b26kH5+cp1qZW4F6FmAURngE7INf4tKOvCE69vYvDEwoNl1tGiWw=="], - - "cac": ["cac@6.7.14", "", {}, "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ=="], - - "chai": ["chai@5.3.3", "", { "dependencies": { "assertion-error": "^2.0.1", "check-error": "^2.1.1", "deep-eql": "^5.0.1", "loupe": "^3.1.0", "pathval": "^2.0.0" } }, "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw=="], - - "check-error": ["check-error@2.1.3", "", {}, "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA=="], - - "csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="], - - "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], - - "deep-eql": ["deep-eql@5.0.2", "", {}, "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q=="], - - "diff-sequences": ["diff-sequences@29.6.3", "", {}, "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q=="], - - "es-module-lexer": ["es-module-lexer@1.7.0", "", {}, "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA=="], - - "esbuild": ["esbuild@0.21.5", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.21.5", "@esbuild/android-arm": "0.21.5", "@esbuild/android-arm64": "0.21.5", "@esbuild/android-x64": "0.21.5", "@esbuild/darwin-arm64": "0.21.5", "@esbuild/darwin-x64": "0.21.5", "@esbuild/freebsd-arm64": "0.21.5", "@esbuild/freebsd-x64": "0.21.5", "@esbuild/linux-arm": "0.21.5", "@esbuild/linux-arm64": "0.21.5", "@esbuild/linux-ia32": "0.21.5", "@esbuild/linux-loong64": "0.21.5", "@esbuild/linux-mips64el": "0.21.5", "@esbuild/linux-ppc64": "0.21.5", "@esbuild/linux-riscv64": "0.21.5", "@esbuild/linux-s390x": "0.21.5", "@esbuild/linux-x64": "0.21.5", "@esbuild/netbsd-x64": "0.21.5", "@esbuild/openbsd-x64": "0.21.5", "@esbuild/sunos-x64": "0.21.5", "@esbuild/win32-arm64": "0.21.5", "@esbuild/win32-ia32": "0.21.5", "@esbuild/win32-x64": "0.21.5" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw=="], - - "estree-walker": ["estree-walker@3.0.3", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="], - - "expect-type": ["expect-type@1.4.0", "", {}, "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA=="], - - "fast-glob": ["fast-glob@3.3.3", "", { "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", "glob-parent": "^5.1.2", "merge2": "^1.3.0", "micromatch": "^4.0.8" } }, "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg=="], - - "fastq": ["fastq@1.20.1", "", { "dependencies": { "reusify": "^1.0.4" } }, "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw=="], - - "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], - - "fflate": ["fflate@0.8.2", "", {}, "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A=="], - - "fill-range": ["fill-range@7.1.1", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="], - - "flatted": ["flatted@3.3.3", "", {}, "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg=="], - - "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], - - "get-func-name": ["get-func-name@2.0.2", "", {}, "sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ=="], - - "glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="], - - "hono": ["hono@4.13.5", "", {}, "sha512-O6+/eCYRkzzzy0rPWwKLiGBR1nFuUPZynnwjxN1MBA62NNqbT0wQEzQyK2gSO5yDIDB336sXQleAhOHrzlYyKw=="], - - "is-extglob": ["is-extglob@2.1.1", "", {}, "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ=="], - - "is-glob": ["is-glob@4.0.3", "", { "dependencies": { "is-extglob": "^2.1.1" } }, "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg=="], - - "is-number": ["is-number@7.0.0", "", {}, "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng=="], - - "js-tokens": ["js-tokens@9.0.1", "", {}, "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ=="], - - "loupe": ["loupe@2.3.7", "", { "dependencies": { "get-func-name": "^2.0.1" } }, "sha512-zSMINGVYkdpYSOBmLi0D1Uo7JU9nVdQKrHxC8eYlV+9YKK9WePqAlL7lSlorG/U2Fw1w0hTBmaa/jrQ3UbPHtA=="], - - "magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], - - "merge2": ["merge2@1.4.1", "", {}, "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg=="], - - "micromatch": ["micromatch@4.0.8", "", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="], - - "mrmime": ["mrmime@2.0.1", "", {}, "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ=="], - - "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], - - "nanoid": ["nanoid@3.3.11", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="], - - "openapi-types": ["openapi-types@12.1.3", "", {}, "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw=="], - - "oxlint": ["oxlint@0.9.10", "", { "optionalDependencies": { "@oxlint/darwin-arm64": "0.9.10", "@oxlint/darwin-x64": "0.9.10", "@oxlint/linux-arm64-gnu": "0.9.10", "@oxlint/linux-arm64-musl": "0.9.10", "@oxlint/linux-x64-gnu": "0.9.10", "@oxlint/linux-x64-musl": "0.9.10", "@oxlint/win32-arm64": "0.9.10", "@oxlint/win32-x64": "0.9.10" }, "bin": { "oxlint": "bin/oxlint", "oxc_language_server": "bin/oxc_language_server" } }, "sha512-bKiiFN7Hnoaist/rditTRBXz+GXKYuLd53/NB7Q6zHB/bifELJarSoRLkAUGElIJKl4PSr3lTh1g6zehh+rX0g=="], - - "pathe": ["pathe@1.1.2", "", {}, "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ=="], - - "pathval": ["pathval@2.0.1", "", {}, "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ=="], - - "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], - - "picomatch": ["picomatch@4.0.5", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="], - - "postcss": ["postcss@8.5.6", "", { "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg=="], - - "pretty-format": ["pretty-format@29.7.0", "", { "dependencies": { "@jest/schemas": "^29.6.3", "ansi-styles": "^5.0.0", "react-is": "^18.0.0" } }, "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ=="], - - "queue-microtask": ["queue-microtask@1.2.3", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="], - - "react-is": ["react-is@18.3.1", "", {}, "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg=="], - - "reusify": ["reusify@1.1.0", "", {}, "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw=="], - - "rollup": ["rollup@4.54.0", "", { "dependencies": { "@types/estree": "1.0.8" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.54.0", "@rollup/rollup-android-arm64": "4.54.0", "@rollup/rollup-darwin-arm64": "4.54.0", "@rollup/rollup-darwin-x64": "4.54.0", "@rollup/rollup-freebsd-arm64": "4.54.0", "@rollup/rollup-freebsd-x64": "4.54.0", "@rollup/rollup-linux-arm-gnueabihf": "4.54.0", "@rollup/rollup-linux-arm-musleabihf": "4.54.0", "@rollup/rollup-linux-arm64-gnu": "4.54.0", "@rollup/rollup-linux-arm64-musl": "4.54.0", "@rollup/rollup-linux-loong64-gnu": "4.54.0", "@rollup/rollup-linux-ppc64-gnu": "4.54.0", "@rollup/rollup-linux-riscv64-gnu": "4.54.0", "@rollup/rollup-linux-riscv64-musl": "4.54.0", "@rollup/rollup-linux-s390x-gnu": "4.54.0", "@rollup/rollup-linux-x64-gnu": "4.54.0", "@rollup/rollup-linux-x64-musl": "4.54.0", "@rollup/rollup-openharmony-arm64": "4.54.0", "@rollup/rollup-win32-arm64-msvc": "4.54.0", "@rollup/rollup-win32-ia32-msvc": "4.54.0", "@rollup/rollup-win32-x64-gnu": "4.54.0", "@rollup/rollup-win32-x64-msvc": "4.54.0", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-3nk8Y3a9Ea8szgKhinMlGMhGMw89mqule3KWczxhIzqudyHdCIOHw8WJlj/r329fACjKLEh13ZSk7oE22kyeIw=="], - - "run-parallel": ["run-parallel@1.2.0", "", { "dependencies": { "queue-microtask": "^1.2.2" } }, "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA=="], - - "siginfo": ["siginfo@2.0.0", "", {}, "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g=="], - - "sirv": ["sirv@2.0.4", "", { "dependencies": { "@polka/url": "^1.0.0-next.24", "mrmime": "^2.0.0", "totalist": "^3.0.0" } }, "sha512-94Bdh3cC2PKrbgSOUqTiGPWVZeSiXfKOVZNJniWoqrWrRkB1CJzBU3NEbiTsPcYy1lDsANA/THzS+9WBiy5nfQ=="], - - "source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="], - - "stackback": ["stackback@0.0.2", "", {}, "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw=="], - - "std-env": ["std-env@3.10.0", "", {}, "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg=="], - - "strip-literal": ["strip-literal@3.1.0", "", { "dependencies": { "js-tokens": "^9.0.1" } }, "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg=="], - - "tinybench": ["tinybench@2.9.0", "", {}, "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg=="], - - "tinyexec": ["tinyexec@0.3.2", "", {}, "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA=="], - - "tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="], - - "tinypool": ["tinypool@1.1.1", "", {}, "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg=="], - - "tinyrainbow": ["tinyrainbow@2.0.0", "", {}, "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw=="], - - "tinyspy": ["tinyspy@4.0.4", "", {}, "sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q=="], - - "to-regex-range": ["to-regex-range@5.0.1", "", { "dependencies": { "is-number": "^7.0.0" } }, "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ=="], - - "totalist": ["totalist@3.0.1", "", {}, "sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ=="], - - "typescript": ["typescript@5.8.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ=="], - - "undici-types": ["undici-types@6.20.0", "", {}, "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg=="], - - "vite": ["vite@5.4.21", "", { "dependencies": { "esbuild": "^0.21.3", "postcss": "^8.4.43", "rollup": "^4.20.0" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^18.0.0 || >=20.0.0", "less": "*", "lightningcss": "^1.21.0", "sass": "*", "sass-embedded": "*", "stylus": "*", "sugarss": "*", "terser": "^5.4.0" }, "optionalPeers": ["@types/node", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser"], "bin": { "vite": "bin/vite.js" } }, "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw=="], - - "vite-node": ["vite-node@3.2.4", "", { "dependencies": { "cac": "^6.7.14", "debug": "^4.4.1", "es-module-lexer": "^1.7.0", "pathe": "^2.0.3", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" }, "bin": { "vite-node": "vite-node.mjs" } }, "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg=="], - - "vitest": ["vitest@3.2.6", "", { "dependencies": { "@types/chai": "^5.2.2", "@vitest/expect": "3.2.6", "@vitest/mocker": "3.2.6", "@vitest/pretty-format": "^3.2.6", "@vitest/runner": "3.2.6", "@vitest/snapshot": "3.2.6", "@vitest/spy": "3.2.6", "@vitest/utils": "3.2.6", "chai": "^5.2.0", "debug": "^4.4.1", "expect-type": "^1.2.1", "magic-string": "^0.30.17", "pathe": "^2.0.3", "picomatch": "^4.0.2", "std-env": "^3.9.0", "tinybench": "^2.9.0", "tinyexec": "^0.3.2", "tinyglobby": "^0.2.14", "tinypool": "^1.1.1", "tinyrainbow": "^2.0.0", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0", "vite-node": "3.2.4", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@types/debug": "^4.1.12", "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", "@vitest/browser": "3.2.6", "@vitest/ui": "3.2.6", "happy-dom": "*", "jsdom": "*" }, "optionalPeers": ["@edge-runtime/vm", "@types/debug", "@types/node", "@vitest/browser", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "vitest.mjs" } }, "sha512-xejya+bT/j/+R/AGa1XOfRxLmNUlLtlwjRsFUILF+xHfzElmGcmFydy2gqqIrd62ptIEfwVMofd19uNWD9L7Nw=="], - - "why-is-node-running": ["why-is-node-running@2.3.0", "", { "dependencies": { "siginfo": "^2.0.0", "stackback": "0.0.2" }, "bin": { "why-is-node-running": "cli.js" } }, "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w=="], - - "zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="], - - "@vitest/expect/@vitest/utils": ["@vitest/utils@3.2.6", "", { "dependencies": { "@vitest/pretty-format": "3.2.6", "loupe": "^3.1.4", "tinyrainbow": "^2.0.0" } }, "sha512-lI23nIs4bnT3T8NIoh+vFaz5s2/DdP0Jgt2jxwgWljvwn82cLJtyi/If+fjFyoLMGIOz0U/fKvWE0d4jsNQEfg=="], - - "@vitest/runner/@vitest/utils": ["@vitest/utils@3.2.6", "", { "dependencies": { "@vitest/pretty-format": "3.2.6", "loupe": "^3.1.4", "tinyrainbow": "^2.0.0" } }, "sha512-lI23nIs4bnT3T8NIoh+vFaz5s2/DdP0Jgt2jxwgWljvwn82cLJtyi/If+fjFyoLMGIOz0U/fKvWE0d4jsNQEfg=="], - - "@vitest/runner/pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], - - "@vitest/snapshot/@vitest/pretty-format": ["@vitest/pretty-format@3.2.6", "", { "dependencies": { "tinyrainbow": "^2.0.0" } }, "sha512-lb7XXXzmm2h2ASzFnRvQpDo6onT1NmMJA3tkGTWiBFtRJ9lxGY3d3mm/Apt36gej2bkkOVLL/yTOtufDaFa/jA=="], - - "@vitest/snapshot/pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], - - "chai/loupe": ["loupe@3.2.1", "", {}, "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ=="], - - "micromatch/picomatch": ["picomatch@2.3.1", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="], - - "vite-node/pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], - - "vitest/@vitest/utils": ["@vitest/utils@3.2.6", "", { "dependencies": { "@vitest/pretty-format": "3.2.6", "loupe": "^3.1.4", "tinyrainbow": "^2.0.0" } }, "sha512-lI23nIs4bnT3T8NIoh+vFaz5s2/DdP0Jgt2jxwgWljvwn82cLJtyi/If+fjFyoLMGIOz0U/fKvWE0d4jsNQEfg=="], - - "vitest/pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], - - "@vitest/expect/@vitest/utils/@vitest/pretty-format": ["@vitest/pretty-format@3.2.6", "", { "dependencies": { "tinyrainbow": "^2.0.0" } }, "sha512-lb7XXXzmm2h2ASzFnRvQpDo6onT1NmMJA3tkGTWiBFtRJ9lxGY3d3mm/Apt36gej2bkkOVLL/yTOtufDaFa/jA=="], - - "@vitest/expect/@vitest/utils/loupe": ["loupe@3.2.1", "", {}, "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ=="], - - "@vitest/runner/@vitest/utils/@vitest/pretty-format": ["@vitest/pretty-format@3.2.6", "", { "dependencies": { "tinyrainbow": "^2.0.0" } }, "sha512-lb7XXXzmm2h2ASzFnRvQpDo6onT1NmMJA3tkGTWiBFtRJ9lxGY3d3mm/Apt36gej2bkkOVLL/yTOtufDaFa/jA=="], - - "@vitest/runner/@vitest/utils/loupe": ["loupe@3.2.1", "", {}, "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ=="], - - "vitest/@vitest/utils/@vitest/pretty-format": ["@vitest/pretty-format@3.2.6", "", { "dependencies": { "tinyrainbow": "^2.0.0" } }, "sha512-lb7XXXzmm2h2ASzFnRvQpDo6onT1NmMJA3tkGTWiBFtRJ9lxGY3d3mm/Apt36gej2bkkOVLL/yTOtufDaFa/jA=="], - - "vitest/@vitest/utils/loupe": ["loupe@3.2.1", "", {}, "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ=="], - } -} diff --git a/dstack/kms/auth-simple/index.test.ts b/dstack/kms/auth-simple/index.test.ts deleted file mode 100644 index fee441712b..0000000000 --- a/dstack/kms/auth-simple/index.test.ts +++ /dev/null @@ -1,494 +0,0 @@ -// SPDX-FileCopyrightText: © 2025 Phala Network -// -// SPDX-License-Identifier: Apache-2.0 - -import { describe, it, expect, beforeAll, afterAll } from 'vitest'; -import { writeFileSync, unlinkSync, existsSync } from 'fs'; -import app from './index'; - -const TEST_CONFIG_PATH = './test-auth-config.json'; - -const baseBootInfo = { - teeVariant: 'dstack-tdx', - mrAggregated: '0xabc123', - osImageHash: '0x1fbb0cf9cc6cfbf23d6b779776fabad2c5403d643badb9e5e238615e4960a78a', - appId: '0xapp123', - composeHash: '0xcompose456', - instanceId: '0xinstance789', - deviceId: '0xdevice999', - tcbStatus: 'UpToDate', - advisoryIds: [], - mrSystem: '' -}; - -function writeTestConfig(config: object) { - writeFileSync(TEST_CONFIG_PATH, JSON.stringify(config, null, 2)); -} - -describe('auth-simple', () => { - beforeAll(() => { - process.env.AUTH_CONFIG_PATH = TEST_CONFIG_PATH; - }); - - afterAll(() => { - if (existsSync(TEST_CONFIG_PATH)) { - unlinkSync(TEST_CONFIG_PATH); - } - }); - - describe('GET /', () => { - it('returns health check info', async () => { - writeTestConfig({ gatewayAppId: '0xgateway' }); - - const res = await app.fetch(new Request('http://localhost/', { method: 'GET' })); - const json = await res.json(); - - expect(res.status).toBe(200); - expect(json.status).toBe('ok'); - expect(json.gatewayAppId).toBe('0xgateway'); - }); - }); - - describe('POST /bootAuth/kms', () => { - it('allows KMS boot with valid config', async () => { - writeTestConfig({ - gatewayAppId: '0xgateway', - osImages: ['0x1fbb0cf9cc6cfbf23d6b779776fabad2c5403d643badb9e5e238615e4960a78a'], - kms: { - mrAggregated: ['0xabc123'], - devices: ['0xdevice999'], - allowAnyDevice: false - } - }); - - const res = await app.fetch(new Request('http://localhost/bootAuth/kms', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(baseBootInfo) - })); - const json = await res.json(); - - expect(json.isAllowed).toBe(true); - expect(json.reason).toBe(''); - }); - - it('rejects KMS boot with invalid TCB status', async () => { - writeTestConfig({ - gatewayAppId: '0xgateway', - osImages: ['0x1fbb0cf9cc6cfbf23d6b779776fabad2c5403d643badb9e5e238615e4960a78a'], - kms: { - mrAggregated: ['0xabc123'], - allowAnyDevice: true - } - }); - - const res = await app.fetch(new Request('http://localhost/bootAuth/kms', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ ...baseBootInfo, tcbStatus: 'OutOfDate' }) - })); - const json = await res.json(); - - expect(json.isAllowed).toBe(false); - expect(json.reason).toContain('TCB status'); - }); - - it('requires explicit opt-in for non-UpToDate SEV-SNP TCB status', async () => { - writeTestConfig({ - gatewayAppId: '0xgateway', - osImages: ['0x1fbb0cf9cc6cfbf23d6b779776fabad2c5403d643badb9e5e238615e4960a78a'], - kms: { - mrAggregated: ['0xabc123'], - devices: ['0xdevice999'], - allowAnyDevice: false - } - }); - - const sevSnpBootInfo = { - ...baseBootInfo, - teeVariant: 'dstack-amd-sev-snp', - tcbStatus: 'OutOfDate' - }; - const denied = await app.fetch(new Request('http://localhost/bootAuth/kms', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(sevSnpBootInfo) - })); - expect((await denied.json()).isAllowed).toBe(false); - - writeTestConfig({ - gatewayAppId: '0xgateway', - osImages: ['0x1fbb0cf9cc6cfbf23d6b779776fabad2c5403d643badb9e5e238615e4960a78a'], - allowedTcbStatuses: ['OutOfDate'], - kms: { - mrAggregated: ['0xabc123'], - devices: ['0xdevice999'], - allowAnyDevice: false - } - }); - - const allowed = await app.fetch(new Request('http://localhost/bootAuth/kms', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(sevSnpBootInfo) - })); - const allowedJson = await allowed.json(); - - expect(allowedJson.isAllowed).toBe(true); - expect(allowedJson.reason).toBe(''); - }); - - it('rejects unallowlisted advisory IDs by default', async () => { - writeTestConfig({ - gatewayAppId: '0xgateway', - osImages: ['0x1fbb0cf9cc6cfbf23d6b779776fabad2c5403d643badb9e5e238615e4960a78a'], - kms: { - mrAggregated: ['0xabc123'], - allowAnyDevice: true - } - }); - - const denied = await app.fetch(new Request('http://localhost/bootAuth/kms', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ ...baseBootInfo, advisoryIds: ['INTEL-SA-TEST'] }) - })); - const deniedJson = await denied.json(); - - expect(deniedJson.isAllowed).toBe(false); - expect(deniedJson.reason).toContain('advisory'); - - writeTestConfig({ - gatewayAppId: '0xgateway', - osImages: ['0x1fbb0cf9cc6cfbf23d6b779776fabad2c5403d643badb9e5e238615e4960a78a'], - allowedAdvisoryIds: ['INTEL-SA-TEST'], - kms: { - mrAggregated: ['0xabc123'], - allowAnyDevice: true - } - }); - - const allowed = await app.fetch(new Request('http://localhost/bootAuth/kms', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ ...baseBootInfo, advisoryIds: ['INTEL-SA-TEST'] }) - })); - const allowedJson = await allowed.json(); - - expect(allowedJson.isAllowed).toBe(true); - }); - - it('rejects KMS boot with invalid OS image', async () => { - writeTestConfig({ - gatewayAppId: '0xgateway', - osImages: ['0xdifferentimage'], - kms: { - mrAggregated: ['0xabc123'], - allowAnyDevice: true - } - }); - - const res = await app.fetch(new Request('http://localhost/bootAuth/kms', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(baseBootInfo) - })); - const json = await res.json(); - - expect(json.isAllowed).toBe(false); - expect(json.reason).toContain('OS image'); - }); - - it('rejects KMS boot with invalid mrAggregated', async () => { - writeTestConfig({ - gatewayAppId: '0xgateway', - osImages: ['0x1fbb0cf9cc6cfbf23d6b779776fabad2c5403d643badb9e5e238615e4960a78a'], - kms: { - mrAggregated: ['0xdifferentmr'], - allowAnyDevice: true - } - }); - - const res = await app.fetch(new Request('http://localhost/bootAuth/kms', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(baseBootInfo) - })); - const json = await res.json(); - - expect(json.isAllowed).toBe(false); - expect(json.reason).toContain('MR'); - }); - - it('rejects KMS boot when the identity allowlist is empty', async () => { - writeTestConfig({ - gatewayAppId: '0xgateway', - osImages: ['0x1fbb0cf9cc6cfbf23d6b779776fabad2c5403d643badb9e5e238615e4960a78a'], - kms: { - mrAggregated: [], - allowAnyDevice: true - } - }); - - const res = await app.fetch(new Request('http://localhost/bootAuth/kms', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(baseBootInfo) - })); - const json = await res.json(); - - expect(json.isAllowed).toBe(false); - expect(json.reason).toContain('MR'); - }); - it('rejects KMS boot with an empty device allowlist', async () => { - writeTestConfig({ - gatewayAppId: '0xgateway', - osImages: ['0x1fbb0cf9cc6cfbf23d6b779776fabad2c5403d643badb9e5e238615e4960a78a'], - kms: { - mrAggregated: ['0xabc123'], - devices: [], - allowAnyDevice: false - } - }); - - const res = await app.fetch(new Request('http://localhost/bootAuth/kms', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(baseBootInfo) - })); - const json = await res.json(); - - expect(json.isAllowed).toBe(false); - expect(json.reason).toContain('device'); - }); - - it('allows KMS boot with allowAnyDevice', async () => { - writeTestConfig({ - gatewayAppId: '0xgateway', - osImages: ['0x1fbb0cf9cc6cfbf23d6b779776fabad2c5403d643badb9e5e238615e4960a78a'], - kms: { - mrAggregated: ['0xabc123'], - devices: ['0xotherdevice'], - allowAnyDevice: true - } - }); - - const res = await app.fetch(new Request('http://localhost/bootAuth/kms', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(baseBootInfo) - })); - const json = await res.json(); - - expect(json.isAllowed).toBe(true); - }); - }); - - describe('POST /bootAuth/app', () => { - it('allows app boot with valid config', async () => { - writeTestConfig({ - gatewayAppId: '0xgateway', - osImages: ['0x1fbb0cf9cc6cfbf23d6b779776fabad2c5403d643badb9e5e238615e4960a78a'], - apps: { - '0xapp123': { - composeHashes: ['0xcompose456'], - devices: ['0xdevice999'], - allowAnyDevice: false - } - } - }); - - const res = await app.fetch(new Request('http://localhost/bootAuth/app', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(baseBootInfo) - })); - const json = await res.json(); - - expect(json.isAllowed).toBe(true); - expect(json.reason).toBe(''); - }); - - it('rejects app boot with unregistered app', async () => { - writeTestConfig({ - gatewayAppId: '0xgateway', - osImages: ['0x1fbb0cf9cc6cfbf23d6b779776fabad2c5403d643badb9e5e238615e4960a78a'], - apps: {} - }); - - const res = await app.fetch(new Request('http://localhost/bootAuth/app', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(baseBootInfo) - })); - const json = await res.json(); - - expect(json.isAllowed).toBe(false); - expect(json.reason).toContain('not registered'); - }); - - it('rejects app boot with invalid compose hash', async () => { - writeTestConfig({ - gatewayAppId: '0xgateway', - osImages: ['0x1fbb0cf9cc6cfbf23d6b779776fabad2c5403d643badb9e5e238615e4960a78a'], - apps: { - '0xapp123': { - composeHashes: ['0xdifferenthash'], - allowAnyDevice: true - } - } - }); - - const res = await app.fetch(new Request('http://localhost/bootAuth/app', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(baseBootInfo) - })); - const json = await res.json(); - - expect(json.isAllowed).toBe(false); - expect(json.reason).toContain('compose hash'); - }); - - it('rejects app boot with invalid device', async () => { - writeTestConfig({ - gatewayAppId: '0xgateway', - osImages: ['0x1fbb0cf9cc6cfbf23d6b779776fabad2c5403d643badb9e5e238615e4960a78a'], - apps: { - '0xapp123': { - composeHashes: ['0xcompose456'], - devices: ['0xotherdevice'], - allowAnyDevice: false - } - } - }); - - const res = await app.fetch(new Request('http://localhost/bootAuth/app', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(baseBootInfo) - })); - const json = await res.json(); - - expect(json.isAllowed).toBe(false); - expect(json.reason).toContain('device'); - }); - - it('rejects app boot with an empty device allowlist', async () => { - writeTestConfig({ - gatewayAppId: '0xgateway', - osImages: ['0x1fbb0cf9cc6cfbf23d6b779776fabad2c5403d643badb9e5e238615e4960a78a'], - apps: { - '0xapp123': { - composeHashes: ['0xcompose456'], - devices: [], - allowAnyDevice: false - } - } - }); - - const res = await app.fetch(new Request('http://localhost/bootAuth/app', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(baseBootInfo) - })); - const json = await res.json(); - - expect(json.isAllowed).toBe(false); - expect(json.reason).toContain('device'); - }); - - it('allows app boot with allowAnyDevice', async () => { - writeTestConfig({ - gatewayAppId: '0xgateway', - osImages: ['0x1fbb0cf9cc6cfbf23d6b779776fabad2c5403d643badb9e5e238615e4960a78a'], - apps: { - '0xapp123': { - composeHashes: ['0xcompose456'], - devices: [], - allowAnyDevice: true - } - } - }); - - const res = await app.fetch(new Request('http://localhost/bootAuth/app', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(baseBootInfo) - })); - const json = await res.json(); - - expect(json.isAllowed).toBe(true); - }); - - // Stricter than a legacy DstackApp by design; see DstackApp.t.sol - // test_IsAppAllowed_RejectsOutdatedTcbWhenRequired. - it('rejects app boot with out-of-date TCB or unallowlisted advisory ID', async () => { - writeTestConfig({ - gatewayAppId: '0xgateway', - osImages: [baseBootInfo.osImageHash], - apps: { '0xapp123': { composeHashes: ['0xcompose456'], allowAnyDevice: true } } - }); - - for (const [patch, reason] of [ - [{ tcbStatus: 'OutOfDate' }, 'TCB status is not allowed'], - [{ advisoryIds: ['INTEL-SA-00614'] }, 'advisory ID is not allowed'], - ] as const) { - const res = await app.fetch(new Request('http://localhost/bootAuth/app', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ ...baseBootInfo, ...patch }) - })); - const json = await res.json(); - expect(json.isAllowed).toBe(false); - expect(json.reason).toBe(reason); - } - }); - }); - - describe('hex normalization', () => { - it('handles uppercase hex', async () => { - writeTestConfig({ - gatewayAppId: '0xgateway', - osImages: ['0x1FBB0CF9CC6CFBF23D6B779776FABAD2C5403D643BADB9E5E238615E4960A78A'], - apps: { - '0xAPP123': { - composeHashes: ['0xCOMPOSE456'], - allowAnyDevice: true - } - } - }); - - const res = await app.fetch(new Request('http://localhost/bootAuth/app', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(baseBootInfo) - })); - const json = await res.json(); - - expect(json.isAllowed).toBe(true); - }); - - it('handles hex without 0x prefix', async () => { - writeTestConfig({ - gatewayAppId: '0xgateway', - osImages: ['1fbb0cf9cc6cfbf23d6b779776fabad2c5403d643badb9e5e238615e4960a78a'], - apps: { - 'app123': { - composeHashes: ['compose456'], - allowAnyDevice: true - } - } - }); - - const res = await app.fetch(new Request('http://localhost/bootAuth/app', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(baseBootInfo) - })); - const json = await res.json(); - - expect(json.isAllowed).toBe(true); - }); - }); -}); diff --git a/dstack/kms/auth-simple/index.ts b/dstack/kms/auth-simple/index.ts deleted file mode 100644 index 7f9a7f036c..0000000000 --- a/dstack/kms/auth-simple/index.ts +++ /dev/null @@ -1,322 +0,0 @@ -// SPDX-FileCopyrightText: © 2025 Phala Network -// -// SPDX-License-Identifier: Apache-2.0 - -import { Hono } from 'hono'; -import { zValidator } from '@hono/zod-validator'; -import { z } from 'zod'; -import { readFileSync, existsSync } from 'fs'; - -// zod schemas for validation - compatible with auth-eth implementation -const BootInfoSchema = z.object({ - teeVariant: z.string().optional().default(''), - mrAggregated: z.string().describe('aggregated MR measurement'), - osImageHash: z.string().describe('OS Image hash'), - appId: z.string().describe('application ID'), - composeHash: z.string().describe('compose hash'), - instanceId: z.string().describe('instance ID'), - deviceId: z.string().describe('device ID'), - tcbStatus: z.string().optional().default(''), - advisoryIds: z.array(z.string()).optional().default([]), - mrSystem: z.string().optional().default('') -}); - -const BootResponseSchema = z.object({ - isAllowed: z.boolean(), - reason: z.string(), - gatewayAppId: z.string() -}); - -// config schema -const AppConfigSchema = z.object({ - composeHashes: z.array(z.string()).default([]), - devices: z.array(z.string()).default([]), - allowAnyDevice: z.boolean().default(false) -}); - -const KmsConfigSchema = z.object({ - mrAggregated: z.array(z.string()).default([]), - devices: z.array(z.string()).default([]), - allowAnyDevice: z.boolean().default(false) -}); - -const AuthConfigSchema = z.object({ - gatewayAppId: z.string().default(''), - // KMS expects these fields in the health check response - kmsContractAddr: z.string().default('0x0000000000000000000000000000000000000000'), - chainId: z.number().default(0), - appImplementation: z.string().default('0x0000000000000000000000000000000000000000'), - osImages: z.array(z.string()).default([]), - // TDX and SEV-SNP production defaults remain strict: only UpToDate is - // accepted unless operators explicitly allow another verifier-derived status. - allowedTcbStatuses: z.array(z.string()).default(['UpToDate']), - allowedAdvisoryIds: z.array(z.string()).default([]), - kms: KmsConfigSchema.default({}), - apps: z.record(z.string(), AppConfigSchema).default({}) -}); - -type BootInfo = z.infer; -type BootResponse = z.infer; -type AuthConfig = z.infer; - -// normalize hex string to lowercase with 0x prefix -function normalizeHex(hex: string): string { - hex = hex.toLowerCase(); - if (!hex.startsWith('0x')) { - hex = '0x' + hex; - } - return hex; -} - -// config-based backend -class ConfigBackend { - private getConfigPath(): string { - return process.env.AUTH_CONFIG_PATH || './auth-config.json'; - } - - private loadConfig(): AuthConfig { - const configPath = this.getConfigPath(); - if (!existsSync(configPath)) { - console.error(`config file not found: ${configPath}`); - return AuthConfigSchema.parse({}); - } - - try { - const content = readFileSync(configPath, 'utf-8'); - const parsed = JSON.parse(content); - return AuthConfigSchema.parse(parsed); - } catch (error) { - console.error(`failed to load config: ${error}`); - return AuthConfigSchema.parse({}); - } - } - - async checkBoot(bootInfo: BootInfo, isKms: boolean): Promise { - const config = this.loadConfig(); - const osImageHash = normalizeHex(bootInfo.osImageHash); - const deviceId = normalizeHex(bootInfo.deviceId); - - // check TCB status - const allowedTcbStatuses = config.allowedTcbStatuses; - if (!allowedTcbStatuses.includes(bootInfo.tcbStatus)) { - return { - isAllowed: false, - reason: 'TCB status is not allowed', - gatewayAppId: config.gatewayAppId - }; - } - - for (const advisoryId of bootInfo.advisoryIds) { - if (!config.allowedAdvisoryIds.includes(advisoryId)) { - return { - isAllowed: false, - reason: 'advisory ID is not allowed', - gatewayAppId: config.gatewayAppId - }; - } - } - - // check OS image - const allowedOsImages = config.osImages.map(normalizeHex); - if (!allowedOsImages.includes(osImageHash)) { - return { - isAllowed: false, - reason: 'OS image is not allowed', - gatewayAppId: config.gatewayAppId - }; - } - - if (isKms) { - return this.checkKmsBoot(bootInfo, config, deviceId); - } else { - return this.checkAppBoot(bootInfo, config, deviceId); - } - } - - private checkKmsBoot(bootInfo: BootInfo, config: AuthConfig, deviceId: string): BootResponse { - const mrAggregated = normalizeHex(bootInfo.mrAggregated); - - // check aggregated MR - const allowedMrs = config.kms.mrAggregated.map(normalizeHex); - if (!allowedMrs.includes(mrAggregated)) { - return { - isAllowed: false, - reason: 'aggregated MR not allowed', - gatewayAppId: config.gatewayAppId - }; - } - - // check device ID - if (!config.kms.allowAnyDevice) { - const allowedDevices = config.kms.devices.map(normalizeHex); - if (!allowedDevices.includes(deviceId)) { - return { - isAllowed: false, - reason: 'KMS is not allowed to boot on this device', - gatewayAppId: config.gatewayAppId - }; - } - } - - return { - isAllowed: true, - reason: '', - gatewayAppId: config.gatewayAppId - }; - } - - private checkAppBoot(bootInfo: BootInfo, config: AuthConfig, deviceId: string): BootResponse { - const appId = normalizeHex(bootInfo.appId); - const composeHash = normalizeHex(bootInfo.composeHash); - - // check app exists - const appConfig = Object.entries(config.apps).find( - ([id]) => normalizeHex(id) === appId - )?.[1]; - - if (!appConfig) { - return { - isAllowed: false, - reason: 'app not registered', - gatewayAppId: config.gatewayAppId - }; - } - - // check compose hash - const allowedHashes = appConfig.composeHashes.map(normalizeHex); - if (!allowedHashes.includes(composeHash)) { - return { - isAllowed: false, - reason: 'compose hash not allowed', - gatewayAppId: config.gatewayAppId - }; - } - - // check device ID - if (!appConfig.allowAnyDevice) { - const allowedDevices = appConfig.devices.map(normalizeHex); - if (!allowedDevices.includes(deviceId)) { - return { - isAllowed: false, - reason: 'app is not allowed to boot on this device', - gatewayAppId: config.gatewayAppId - }; - } - } - - return { - isAllowed: true, - reason: '', - gatewayAppId: config.gatewayAppId - }; - } - - async getGatewayAppId(): Promise { - return this.loadConfig().gatewayAppId; - } - - async getInfo(): Promise<{ - gatewayAppId: string; - kmsContractAddr: string; - chainId: number; - appImplementation: string; - }> { - const config = this.loadConfig(); - return { - gatewayAppId: config.gatewayAppId, - kmsContractAddr: config.kmsContractAddr, - chainId: config.chainId, - appImplementation: config.appImplementation, - }; - } -} - -// initialize app -const app = new Hono(); - -// initialize backend -const backend = new ConfigBackend(); - -// health check and info endpoint -app.get('/', async (c) => { - try { - const info = await backend.getInfo(); - return c.json({ - status: 'ok', - kmsContractAddr: info.kmsContractAddr, - gatewayAppId: info.gatewayAppId, - chainId: info.chainId, - appAuthImplementation: info.appImplementation, // backward compat - appImplementation: info.appImplementation, - }); - } catch (error) { - console.error('error in health check:', error); - return c.json({ - status: 'error', - message: error instanceof Error ? error.message : String(error) - }, 500); - } -}); - -// app boot authentication -app.post('/bootAuth/app', - zValidator('json', BootInfoSchema), - async (c) => { - try { - const bootInfo = c.req.valid('json'); - console.log('app boot auth request:', { - appId: bootInfo.appId, - composeHash: bootInfo.composeHash, - instanceId: bootInfo.instanceId, - }); - - const result = await backend.checkBoot(bootInfo, false); - console.log('app boot auth result:', result); - return c.json(result); - } catch (error) { - console.error('error in app boot auth:', error); - return c.json({ - isAllowed: false, - gatewayAppId: '', - reason: error instanceof Error ? error.message : String(error) - }); - } - } -); - -// KMS boot authentication -app.post('/bootAuth/kms', - zValidator('json', BootInfoSchema), - async (c) => { - try { - const bootInfo = c.req.valid('json'); - console.log('KMS boot auth request:', { - osImageHash: bootInfo.osImageHash, - mrAggregated: bootInfo.mrAggregated, - instanceId: bootInfo.instanceId, - }); - - const result = await backend.checkBoot(bootInfo, true); - console.log('KMS boot auth result:', result); - return c.json(result); - } catch (error) { - console.error('error in KMS boot auth:', error); - return c.json({ - isAllowed: false, - gatewayAppId: '', - reason: error instanceof Error ? error.message : String(error) - }); - } - } -); - -// start server -const port = parseInt(process.env.PORT || '3000'); -const defaultConfigPath = process.env.AUTH_CONFIG_PATH || './auth-config.json'; -console.log(`starting auth-simple server on port ${port}`); -console.log(`config path: ${defaultConfigPath}`); - -export default { - port, - fetch: app.fetch, -}; diff --git a/dstack/kms/auth-simple/package.json b/dstack/kms/auth-simple/package.json deleted file mode 100644 index b7d86003e2..0000000000 --- a/dstack/kms/auth-simple/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "auth-simple", - "version": "1.0.0", - "description": "dstack KMS config-based auth server with bun + hono + zod", - "main": "index.ts", - "scripts": { - "dev": "bun run --watch index.ts", - "start": "bun run index.ts", - "build": "bun build index.ts --outdir ./dist --target bun", - "test": "vitest", - "test:run": "vitest run", - "lint": "oxlint .", - "lint:fix": "oxlint --fix .", - "fmt": "oxlint --fix .", - "check": "bun run lint && bun run test:run" - }, - "dependencies": { - "hono": "4.13.5", - "@hono/zod-validator": "0.2.2", - "zod": "3.25.76" - }, - "devDependencies": { - "@types/bun": "1.2.18", - "@types/node": "22.10.8", - "@vitest/ui": "1.6.1", - "openapi-types": "12.1.3", - "oxlint": "0.9.10", - "typescript": "5.8.3", - "vitest": "3.2.6" - }, - "type": "module" -} diff --git a/dstack/kms/dstack-app/.gitignore b/dstack/kms/dstack-app/.gitignore index 09a73e5627..6d376df96e 100644 --- a/dstack/kms/dstack-app/.gitignore +++ b/dstack/kms/dstack-app/.gitignore @@ -1,3 +1,4 @@ .app-compose.json .env .GIT_REV +rpc.json diff --git a/dstack/kms/dstack-app/builder/Dockerfile b/dstack/kms/dstack-app/builder/Dockerfile index 426dd6ab96..7b6a19507c 100644 --- a/dstack/kms/dstack-app/builder/Dockerfile +++ b/dstack/kms/dstack-app/builder/Dockerfile @@ -3,8 +3,8 @@ # SPDX-License-Identifier: Apache-2.0 FROM rust:1.92.0@sha256:48851a839d6a67370c9dbe0e709bedc138e3e404b161c5233aedcf2b717366e4 AS kms-builder -COPY --from=build-shared /pin-packages.sh /build/ -COPY ./shared/*-pinned-packages.txt /build/ +COPY --chmod=0755 --from=build-shared /pin-packages.sh /build/ +COPY --chmod=0644 ./shared/*-pinned-packages.txt /build/ ARG DSTACK_REV ARG DSTACK_SRC_URL=https://github.com/Dstack-TEE/dstack.git WORKDIR /build @@ -27,8 +27,8 @@ RUN cd repo/dstack && cargo build --release --locked -p dstack-kms --target x86_ RUN echo "${DSTACK_REV}" > /build/.GIT_REV FROM debian:bookworm@sha256:0d8498a0e9e6a60011df39aab78534cfe940785e7c59d19dfae1eb53ea59babe -COPY --from=build-shared /pin-packages.sh /build/ -COPY ./shared/pinned-packages.txt /build/ +COPY --chmod=0755 --from=build-shared /pin-packages.sh /build/ +COPY --chmod=0644 ./shared/pinned-packages.txt /build/ WORKDIR /build # reqwest is built against rustls-platform-verifier, which reads the system # trust store and errors out when it finds none. The KMS builds its collateral diff --git a/dstack/kms/dstack-app/builder/README.md b/dstack/kms/dstack-app/builder/README.md index 39815e762f..239343c25c 100644 --- a/dstack/kms/dstack-app/builder/README.md +++ b/dstack/kms/dstack-app/builder/README.md @@ -45,6 +45,11 @@ that tag, rather than building the branch selected in the workflow UI. ## Reproducing a released image +Files copied from the checkout have explicit permissions in the Dockerfile, +so the caller's clone-time umask does not affect their image layers. For older +release tags without these permissions, set `umask 0022` before cloning to +match the release checkout. + Release CI runs this same script, so a published image can be rebuilt and checked digest-for-digest. Use a clean checkout of the release commit so the Dockerfile, package lists, shared scripts and copied files also match the release. diff --git a/dstack/kms/dstack-app/builder/shared/builder-pinned-packages.txt b/dstack/kms/dstack-app/builder/shared/builder-pinned-packages.txt index e390e80bcc..568d740a48 100644 --- a/dstack/kms/dstack-app/builder/shared/builder-pinned-packages.txt +++ b/dstack/kms/dstack-app/builder/shared/builder-pinned-packages.txt @@ -309,10 +309,10 @@ libpng16-16t64:amd64=1.6.48-1 libpq-dev=17.6-0+deb13u1 libpq5:amd64=17.6-0+deb13u1 libproc2-0:amd64=2:4.0.4-9 -libprotobuf-dev:amd64=3.21.12-11 -libprotobuf-lite32t64:amd64=3.21.12-11 -libprotobuf32t64:amd64=3.21.12-11 -libprotoc32t64:amd64=3.21.12-11 +libprotobuf-dev:amd64=3.21.12-11+deb13u1 +libprotobuf-lite32t64:amd64=3.21.12-11+deb13u1 +libprotobuf32t64:amd64=3.21.12-11+deb13u1 +libprotoc32t64:amd64=3.21.12-11+deb13u1 libpsl-dev:amd64=0.21.2-1.1+b1 libpsl5t64:amd64=0.21.2-1.1+b1 libpython3-stdlib:amd64=3.13.5-1 @@ -347,8 +347,8 @@ libsqlite3-0:amd64=3.46.1-7 libsqlite3-dev:amd64=3.46.1-7 libssh2-1-dev:amd64=1.11.1-1 libssh2-1t64:amd64=1.11.1-1 -libssl-dev:amd64=3.5.5-1~deb13u1 -libssl3t64:amd64=3.5.5-1~deb13u1 +libssl-dev:amd64=3.5.7-1~deb13u3 +libssl3t64:amd64=3.5.7-1~deb13u3 libstdc++-14-dev:amd64=14.2.0-19 libstdc++6:amd64=14.2.0-19 libsvn1:amd64=1.14.5-3 @@ -424,9 +424,9 @@ media-types=13.0.0 mercurial-common=7.0.1-2 mercurial=7.0.1-2 mount=2.41-5 -musl-dev:amd64=1.2.5-3 -musl-tools=1.2.5-3 -musl:amd64=1.2.5-3 +musl-dev:amd64=1.2.5-3.1~deb13u1 +musl-tools=1.2.5-3.1~deb13u1 +musl:amd64=1.2.5-3.1~deb13u1 mysql-common=5.8+1.1.1 native-architecture=0.2.6 ncurses-base=6.5+20250216-2 @@ -434,8 +434,8 @@ ncurses-bin=6.5+20250216-2 netbase=6.5 nettle-dev:amd64=3.10.1-1 openssh-client=1:10.0p1-7 -openssl-provider-legacy=3.5.5-1~deb13u1 -openssl=3.5.5-1~deb13u1 +openssl-provider-legacy=3.5.7-1~deb13u3 +openssl=3.5.7-1~deb13u3 pango1.0-tools=1.56.3-1 passwd=1:4.17.4-2 patch=2.8-2 @@ -446,7 +446,7 @@ pinentry-curses=1.3.1-2 pkgconf-bin=1.8.1-4 pkgconf:amd64=1.8.1-4 procps=2:4.0.4-9 -protobuf-compiler=3.21.12-11 +protobuf-compiler=3.21.12-11+deb13u1 python3-minimal=3.13.5-1 python3-packaging=25.0-1 python3.13-minimal=3.13.5-2 diff --git a/dstack/kms/dstack-app/builder/shared/pinned-packages.txt b/dstack/kms/dstack-app/builder/shared/pinned-packages.txt index e966045f90..34659193c2 100644 --- a/dstack/kms/dstack-app/builder/shared/pinned-packages.txt +++ b/dstack/kms/dstack-app/builder/shared/pinned-packages.txt @@ -4,7 +4,7 @@ base-files=12.4+deb12u11 base-passwd=3.6.1 bash=5.2.15-2+b8 bsdutils=1:2.38.1-5+deb12u3 -ca-certificates=20230311+deb12u1 +ca-certificates=20250419~deb12u2 coreutils=9.1-1 dash=0.5.12-2 debconf=1.5.82 @@ -62,7 +62,7 @@ libsemanage2:amd64=3.4-1+b5 libsepol2:amd64=3.4-2.1 libsmartcols1:amd64=2.38.1-5+deb12u3 libss2:amd64=1.47.0-2 -libssl3:amd64=3.0.18-1~deb12u2 +libssl3:amd64=3.0.22-1~deb12u1 libstdc++6:amd64=12.2.0-14+deb12u1 libsystemd0:amd64=252.38-1~deb12u1 libtasn1-6:amd64=4.19.0-2+deb12u1 @@ -78,7 +78,7 @@ mawk=1.3.4.20200120-3.1 mount=2.38.1-5+deb12u3 ncurses-base=6.4-4 ncurses-bin=6.4-4 -openssl=3.0.18-1~deb12u2 +openssl=3.0.22-1~deb12u1 passwd=1:4.13+dfsg1-1+deb12u1 perl-base=5.36.0-7+deb12u2 sed=4.9-1 diff --git a/dstack/kms/dstack-app/compose-dev.yaml b/dstack/kms/dstack-app/compose-dev.yaml index a642b32187..401473b7de 100644 --- a/dstack/kms/dstack-app/compose-dev.yaml +++ b/dstack/kms/dstack-app/compose-dev.yaml @@ -8,22 +8,36 @@ services: build: context: . dockerfile_inline: | - FROM node:20-bookworm-slim@sha256:2cf067cfed83d5ea958367df9f966191a942351a2df77d6f0193e162b5febfc0 + FROM oven/bun:1.4.4-alpine@sha256:4cf82f5686b196504fe119db3fcd9185b191f82ece82c40680e597228ec6070a WORKDIR /app - RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates && rm -rf /var/lib/apt/lists/* + RUN apk add --no-cache git ca-certificates RUN git clone ${GIT_REPOSITORY} && \ cd dstack && \ git checkout ${GIT_REV} WORKDIR /app/dstack/dstack/kms/auth-eth - RUN npm ci - RUN npm run build - CMD node dist/main.js + RUN bun install --frozen-lockfile --production --ignore-scripts + ENV NODE_ENV=production + CMD ["bun", "index.ts"] environment: - - HOST=0.0.0.0 - - PORT=8000 - - ETH_RPC_URL=${ETH_RPC_URL} - - KMS_CONTRACT_ADDR=${KMS_CONTRACT_ADDR} + PORT: 8000 + # One endpoint per line. Every read must be answered alike by n of the m + # endpoints, with ETH_RPC_QUORUM as n/m. A ${NAME} is an API key from + # env in the unmeasured .user-config; its allowed_envs spec keeps it + # to one path segment, so it cannot change an endpoint or add one. + ETH_RPC_URLS: | + ${ETH_RPC_URLS} + ETH_RPC_QUORUM: ${ETH_RPC_QUORUM} + # finalized on L1; an OP-stack chain read through Helios requires latest. + ETH_BLOCK_TAG: ${ETH_BLOCK_TAG} + ETH_FINALITY_CONFIRMATIONS: ${ETH_FINALITY_CONFIRMATIONS} + # Empty disables the block age check. + ETH_MAX_BLOCK_AGE: "${ETH_MAX_BLOCK_AGE}" + # Empty disables the chain ID check. + ETH_CHAIN_ID: "${ETH_CHAIN_ID}" + # Empty keeps app authorization on the DstackKms/DstackApp contracts. + APP_AUTH_URL: ${APP_AUTH_URL} + KMS_CONTRACT_ADDR: "${KMS_CONTRACT_ADDR}" restart: unless-stopped ports: - 8001:8000 @@ -35,6 +49,7 @@ services: - /var/run/dstack.sock:/var/run/dstack.sock ports: - 8000:8000 + - 8002:8001 depends_on: - auth-api restart: unless-stopped @@ -59,9 +74,9 @@ configs: [core] cert_dir = "/kms/certs" + keyring_dir = "/kms/keyring" [core.image] - verify = true cache_dir = "/kms/images" download_url = "${IMAGE_DOWNLOAD_URL}" download_timeout = "2m" @@ -72,6 +87,18 @@ configs: [core.auth_api.webhook] url = "http://auth-api:8000" + [core.admin] + enabled = true + # The onboarding KMS reaches it through the CVM port 8002. + address = "0.0.0.0" + port = 8001 + # SHA-256 of the admin token, which stays with the operator. + auth_token_hash = "${ADMIN_TOKEN_HASH}" + + [core.admin.tls] + key = "/kms/certs/rpc.key" + certs = "/kms/certs/rpc.crt" + [core.onboard] enabled = true auto_bootstrap_domain = "" diff --git a/dstack/kms/dstack-app/compose-simple.yaml b/dstack/kms/dstack-app/compose-simple.yaml index 711b06cad5..ba27e2be7d 100644 --- a/dstack/kms/dstack-app/compose-simple.yaml +++ b/dstack/kms/dstack-app/compose-simple.yaml @@ -2,8 +2,9 @@ # # SPDX-License-Identifier: Apache-2.0 -# KMS deployment with external auth-simple webhook -# auth-simple runs outside the CVM (operator infrastructure) +# KMS deployment with an external dstack-auth webhook. +# dstack-auth runs outside the CVM, on the operator host; see +# docs/dstack-auth-operations.md. services: kms: @@ -13,6 +14,7 @@ services: - /var/run/dstack.sock:/var/run/dstack.sock ports: - 8000:8000 + - 8002:8001 restart: unless-stopped configs: - source: kms_config @@ -35,9 +37,9 @@ configs: [core] cert_dir = "/kms/certs" + keyring_dir = "/kms/keyring" [core.image] - verify = true cache_dir = "/kms/images" download_url = "${IMAGE_DOWNLOAD_URL}" download_timeout = "2m" @@ -48,6 +50,18 @@ configs: [core.auth_api.webhook] url = "${AUTH_WEBHOOK_URL}" + [core.admin] + enabled = true + # The onboarding KMS reaches it through the CVM port 8002. + address = "0.0.0.0" + port = 8001 + # SHA-256 of the admin token, which stays with the operator. + auth_token_hash = "${ADMIN_TOKEN_HASH}" + + [core.admin.tls] + key = "/kms/certs/rpc.key" + certs = "/kms/certs/rpc.crt" + [core.onboard] enabled = true auto_bootstrap_domain = "" diff --git a/dstack/kms/dstack-app/deploy-simple.sh b/dstack/kms/dstack-app/deploy-simple.sh index c24b37715e..3e36b17a36 100755 --- a/dstack/kms/dstack-app/deploy-simple.sh +++ b/dstack/kms/dstack-app/deploy-simple.sh @@ -4,8 +4,11 @@ # # SPDX-License-Identifier: Apache-2.0 -# Deploy KMS with external auth-simple webhook -# auth-simple runs outside the CVM (operator infrastructure) +# Deploy KMS with an external dstack-auth webhook. +# dstack-auth runs outside the CVM, on the operator host. Start it first: +# cargo build --release -p dstack-auth +# dstack-auth --config auth-config.json --port 3001 +# See docs/dstack-auth-operations.md. set -e @@ -20,27 +23,30 @@ else # Create a template .env.simple file echo "Creating template .env.simple file..." cat >.env.simple <rpc.json +} + # Check if .env exists if [ -f ".env" ]; then # Load variables from .env @@ -32,17 +41,59 @@ else # The address of the KMS service listening on Host machine # KMS_RPC_ADDR=0.0.0.0:9201 +# Optional: the address of the KMS admin listener on the Host machine, which +# other KMS nodes onboard from with ADMIN_TOKEN; firewall it to KMS nodes only +# KMS_ADMIN_ADDR=127.0.0.1:9203 + # The address of the guest agent service listening on Host machine # GUEST_AGENT_ADDR=127.0.0.1:9205 # The URL of the dstack app image download URL # IMAGE_DOWNLOAD_URL=https://download.dstack.org/os-images/mr_{OS_IMAGE_HASH}.tar.gz -# Image hash verification feature flag -VERIFY_IMAGE=true +# rpc.json lists the Ethereum RPC endpoints and how many of them must answer +# every read alike, as n/m. All of it is measured and public. Write an API key +# as \${NAME} in an endpoint, give NAME an allowed_envs spec under keys, and set +# its value here: values reach the CVM through its unmeasured user config and +# stay out of the measurement. For example: +# { +# "quorum": "2/3", +# "endpoints": [ +# "https://eth-mainnet.g.alchemy.com/v2/\${ALCHEMY_KEY}", +# "https://mainnet.infura.io/v3/\${INFURA_KEY}", +# "https://ethereum-rpc.publicnode.com" +# ], +# "keys": { +# "ALCHEMY_KEY": "/[A-Za-z0-9_-]{32}/", +# "INFURA_KEY": "/[0-9a-f]{32}/" +# } +# } +# A spec must keep its key to one URL path segment, so that the key cannot +# change an endpoint or add one. Keys need dstack OS 0.6.7 or later. +# ALCHEMY_KEY= +# INFURA_KEY= + +# The block the auth-api reads policy at: latest, safe or finalized (default). +# Use finalized on L1; an OP-stack chain read through Helios requires latest. +# ETH_BLOCK_TAG=finalized -# The URL of the Ethereum RPC service -ETH_RPC_URL=https://rpc.phala.network +# Reject decisions if the RPC reports a different chain ID (empty: no check). +# ETH_CHAIN_ID= + +# Read this many blocks behind the block ETH_BLOCK_TAG resolves to (default: 0). +# ETH_FINALITY_CONFIRMATIONS=0 + +# Reject decisions if the block read is older than this many seconds (empty: no +# check). Required when rpc.json lists more than one endpoint; leave room for +# ETH_BLOCK_TAG, as finalized on Ethereum mainnet is about 13 minutes old. +# ETH_MAX_BLOCK_AGE= + +# Delegate app authorization to this service instead of the on-chain app +# contract (empty: app policy stays on chain). Requires a KMS that calls +# /authorizeApp (v0.6.4+). The default KMS_IMAGE uses /bootAuth/app, which +# does not delegate app key release. Before setting APP_AUTH_URL, replace +# KMS_IMAGE with a compatible image pinned by digest. +# APP_AUTH_URL='https://auth.example' # The Git repository to deploy GIT_REPOSITORY=https://github.com/Dstack-TEE/dstack.git @@ -54,25 +105,51 @@ GIT_REV=HEAD OS_IMAGE=dstack-0.5.5 # The dstack KMS image name to use for the KMS app -KMS_IMAGE=dstacktee/dstack-kms@sha256:11ac59f524a22462ccd2152219b0bec48a28ceb734e32500152d4abefab7a62a +KMS_IMAGE=dstacktee/dstack-kms@$LEGACY_KMS_IMAGE_DIGEST # The admin token for the KMS app ADMIN_TOKEN=$(tr -dc 'a-zA-Z0-9' < /dev/urandom | fold -w 32 | head -n 1) EOF + init_rpc_json https://rpc.phala.network echo "Please edit the .env file and set the required variables, then run this script again." exit 1 fi +# The generated default image uses /bootAuth/app, which is never delegated. +if [[ ${APP_AUTH_URL:-} =~ [^[:space:]] && ${KMS_IMAGE:-} == *"@$LEGACY_KMS_IMAGE_DIGEST" ]]; then + echo 'error: APP_AUTH_URL requires a KMS that calls /authorizeApp (v0.6.4+); set KMS_IMAGE to a compatible image pinned by digest' >&2 + exit 1 +fi + +# An .env that predates rpc.json names its one endpoint in ETH_RPC_URL. +init_rpc_json "${ETH_RPC_URL:-https://rpc.phala.network}" +if [ -n "${ETH_RPC_URL:-}" ] && ! jq -e --arg url "$ETH_RPC_URL" '.endpoints == [$url]' rpc.json >/dev/null; then + echo "Warning: ETH_RPC_URL in .env is ignored, as rpc.json names the RPC endpoints." +fi +if ! UNDECLARED=$(jq -r '[.endpoints[] | scan("\\$\\{(\\w+)\\}")[]] - (.keys | keys) | join(" ")' rpc.json); then + echo "Error: rpc.json is invalid." + exit 1 +fi +if [ -n "$UNDECLARED" ]; then + echo "Error: rpc.json gives no spec under keys for: $UNDECLARED" + exit 1 +fi +if [ -z "${ETH_MAX_BLOCK_AGE:-}" ] && jq -e '.endpoints | length > 1' rpc.json >/dev/null; then + echo "Error: set ETH_MAX_BLOCK_AGE in .env: the auth-api requires it with several RPC endpoints." + exit 1 +fi +mapfile -t RPC_KEYS < <(jq -r '.keys | keys[]' rpc.json) +mapfile -t ENV_SPECS < <(jq -r '.keys | to_entries[] | "--env-spec", "\(.key): \(.value)"' rpc.json) + required_env_vars=( "VMM_RPC" "KMS_RPC_ADDR" "AUTH_API_RPC_ADDR" "GUEST_AGENT_ADDR" "KMS_CONTRACT_ADDR" - "ETH_RPC_URL" "IMAGE_DOWNLOAD_URL" - "VERIFY_IMAGE" "GIT_REPOSITORY" + "${RPC_KEYS[@]}" ) for var in "${required_env_vars[@]}"; do @@ -95,17 +172,40 @@ ADMIN_TOKEN_HASH=$(echo -n "$ADMIN_TOKEN" | sha256sum | cut -d' ' -f1) cp compose-dev.yaml "$COMPOSE_TMP" subvar() { - sed -i "s|\${$1}|${!1}|g" "$COMPOSE_TMP" + local value=${!1} + # Escape sed replacement syntax, including literal newlines in block scalars. + value=${value//\\/\\\\} + value=${value//&/\\&} + value=${value//|/\\|} + value=${value//$'\n'/$'\\\n'} + sed -i "s|\${$1}|$value|g" "$COMPOSE_TMP" } -subvar ETH_RPC_URL +ETH_BLOCK_TAG=${ETH_BLOCK_TAG:-finalized} +ETH_CHAIN_ID=${ETH_CHAIN_ID:-} +ETH_FINALITY_CONFIRMATIONS=${ETH_FINALITY_CONFIRMATIONS:-0} +ETH_MAX_BLOCK_AGE=${ETH_MAX_BLOCK_AGE:-} +# Quote the YAML scalar and protect literal dollars from Compose interpolation. +APP_AUTH_URL=$(jq -nr --arg url "${APP_AUTH_URL:-}" '$url | gsub("\\$"; "$$") | @json') +# One endpoint per line of the block scalar in compose-dev.yaml. +# shellcheck disable=SC2034 # consumed via `subvar` into compose-*.yaml +ETH_RPC_URLS=$(jq -r '.endpoints | join("\n ")' rpc.json) +# shellcheck disable=SC2034 +ETH_RPC_QUORUM=$(jq -r .quorum rpc.json) +subvar ETH_RPC_URLS +subvar ETH_RPC_QUORUM +subvar ETH_BLOCK_TAG +subvar ETH_CHAIN_ID +subvar ETH_FINALITY_CONFIRMATIONS +subvar ETH_MAX_BLOCK_AGE subvar KMS_CONTRACT_ADDR subvar GIT_REV subvar IMAGE_DOWNLOAD_URL subvar ADMIN_TOKEN_HASH -subvar VERIFY_IMAGE subvar GIT_REPOSITORY subvar KMS_IMAGE +# Insert the URL last so any placeholder-like path segments stay literal. +subvar APP_AUTH_URL echo "Docker compose file:" cat "$COMPOSE_TMP" @@ -129,11 +229,21 @@ $CLI compose \ --public-sysinfo \ --secure-time \ --no-instance-id \ + "${ENV_SPECS[@]}" \ + ${RPC_KEYS:+--init-script <(echo "dstack-util import-env ${RPC_KEYS[*]}")} \ --output .app-compose.json # Remove the temporary file as it is no longer needed rm "$COMPOSE_TMP" +# The user config holds the keys under env, apart from the fields dstack +# defines. The import-env init script copies them into the env file and refuses +# one that breaks its allowed_envs spec. mktemp keeps the keys readable by this +# user only. +USER_CONFIG=$(mktemp) +trap 'rm -f "$USER_CONFIG"' EXIT +jq '{env: .keys | with_entries(.value = env[.key])}' rpc.json >"$USER_CONFIG" + echo "Deploying KMS to dstack-vmm..." $CLI deploy \ @@ -141,8 +251,10 @@ $CLI deploy \ --compose .app-compose.json \ --image "$OS_IMAGE" \ --port tcp:"$KMS_RPC_ADDR":8000 \ + ${KMS_ADMIN_ADDR:+--port "tcp:$KMS_ADMIN_ADDR:8002"} \ --port tcp:"$AUTH_API_RPC_ADDR":8001 \ --port tcp:"$GUEST_AGENT_ADDR":8090 \ + ${RPC_KEYS:+--user-config "$USER_CONFIG"} \ --vcpu 8 \ --memory 8G \ --disk 50G diff --git a/dstack/kms/dstack-app/docker-compose.yaml b/dstack/kms/dstack-app/docker-compose.yaml deleted file mode 100644 index a83d5f3342..0000000000 --- a/dstack/kms/dstack-app/docker-compose.yaml +++ /dev/null @@ -1,85 +0,0 @@ -# SPDX-FileCopyrightText: © 2025 Phala Network -# -# SPDX-License-Identifier: Apache-2.0 - -services: - # Helios is a Ethereum light client - helios: - build: - context: . - dockerfile_inline: | - FROM rust:1.92.0@sha256:48851a839d6a67370c9dbe0e709bedc138e3e404b161c5233aedcf2b717366e4 - WORKDIR /app - RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates && rm -rf /var/lib/apt/lists/* build-base openssl-dev protobuf protobuf-dev perl - RUN git clone https://github.com/a16z/helios && \ - cd helios && \ - git checkout 5c61864a167c16141a9a12b976c0e9398b332f07 - WORKDIR /app/helios - RUN cargo build --release - command: [ - "./target/release/helios", - "ethereum", - "--network", "mainnet", - "--checkpoint", "0xbee4f32f91e62060d2aa41c652f6c69431829cfb09b02ea3cad92f65bd15dcce", - "--rpc-bind-ip", "0.0.0.0", - "--rpc-port", "8545", - "--consensus-rpc", "https://ethereum.operationsolarstorm.org", - "--execution-rpc", "https://ethereum-rpc.publicnode.com" - ] - - # Auth API is a webhook server that authenticates KMS instances and Apps launches - auth-api: - build: - context: . - dockerfile_inline: | - FROM node:20-bookworm-slim@sha256:2cf067cfed83d5ea958367df9f966191a942351a2df77d6f0193e162b5febfc0 - WORKDIR /app - - RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates && rm -rf /var/lib/apt/lists/* - RUN git clone https://github.com/Dstack-TEE/dstack.git && \ - cd dstack && \ - git checkout 78057c975fe4b9e21f557fb888d72eeecfb21178 - WORKDIR /app/dstack/kms/auth-eth - RUN npm ci && npm run build - CMD node dist/main.js - environment: - - HOST=0.0.0.0 - - PORT=8000 - - ETH_RPC_URL=http://helios:8545 - - KMS_CONTRACT_ADDR=0x515cd0dd984Adc75EE8625131FcC3d2D91f7F140 - depends_on: - - helios - - # KMS handles the TEE Remote Attestation - kms: - build: - context: . - dockerfile_inline: | - FROM rust:1.92.0@sha256:48851a839d6a67370c9dbe0e709bedc138e3e404b161c5233aedcf2b717366e4 - WORKDIR /app - RUN apt-get update && apt-get install -y \ - git \ - build-essential \ - libssl-dev \ - protobuf-compiler \ - libprotobuf-dev \ - clang \ - libclang-dev \ - --no-install-recommends \ - && rm -rf /var/lib/apt/lists/* - RUN git clone https://github.com/Dstack-TEE/dstack.git && \ - cd dstack && \ - git checkout 78057c975fe4b9e21f557fb888d72eeecfb21178 - WORKDIR /app/dstack - RUN cargo build --release --locked -p dstack-kms - CMD ["./target/release/dstack-kms"] - volumes: - - kms-volume:/etc/kms - - /var/run/dstack.sock:/var/run/dstack.sock - ports: - - 8000:8000 - depends_on: - - auth-api - -volumes: - kms-volume: diff --git a/dstack/kms/dstack-app/entrypoint.sh b/dstack/kms/dstack-app/entrypoint.sh index 52d14b8c66..ae48080bfc 100755 --- a/dstack/kms/dstack-app/entrypoint.sh +++ b/dstack/kms/dstack-app/entrypoint.sh @@ -9,10 +9,12 @@ set -e cat < ./kms.toml [core.image] -verify = ${VERIFY_IMAGE} cache_dir = "./images" download_url = "${IMAGE_DOWNLOAD_URL}" download_timeout = "2m" + +[listeners.admin] +auth_token_hash = "${ADMIN_TOKEN_HASH}" EOF exec dstack-kms -c ./kms.toml diff --git a/dstack/kms/kms.toml b/dstack/kms/kms.toml index 03aabbd990..835ac80e2e 100644 --- a/dstack/kms/kms.toml +++ b/dstack/kms/kms.toml @@ -2,28 +2,76 @@ # # SPDX-License-Identifier: Apache-2.0 -[default] -workers = 8 -max_blocking = 64 +# Listeners. `[listeners.default]` applies to every listener unless the +# listener's own section overrides it; it also takes Rocket settings such as +# `workers` or `keep_alive`. The KMS refuses the older locations of these +# settings (`[rpc]`, `[core.admin]`, `[core.onboard]`, `[default]`). +[listeners.default] +# Sent as the `Server` header. ident = "DStack KMS" -temp_dir = "/tmp" -keep_alive = 10 -log_level = "info" - -[rpc] +# Require a PROXY protocol (v1 or v2) header on every connection and log its +# source address as the client. Enable only behind a proxy that sends one, such +# as HAProxy with `send-proxy-v2`; connections without it are dropped. Not +# supported on the onboard listener. +proxy_protocol = false + +# No `mutual` section: client certificates are verified by the attestation they +# carry, not by an issuer CA (see ra-rpc's ratls_client_verifier). +[listeners.default.tls] +key = "/var/lib/kms/certs/rpc.key" +certs = "/var/lib/kms/certs/rpc.crt" + +# For CVMs: all KMS RPCs, including those that release keys. +[listeners.guest] address = "0.0.0.0" port = 8000 -[rpc.tls] -key = "/etc/kms/certs/rpc.key" -certs = "/etc/kms/certs/rpc.crt" +# Operator RPCs (e.g. ClearImageCache) and the key handover to onboarding KMS +# nodes, behind the admin credential below. It fails closed: the KMS does not +# start until auth_token (or DSTACK_KMS_ADMIN_TOKEN), auth_token_hash or +# htpasswd_file is set. Unless core.onboard.public_key_handover = true, the KMS +# requires this listener with TLS, so that other KMS nodes can onboard. Keep it +# off the public network; to serve KMS onboarding, bind to an address the new +# KMS can reach. +[listeners.admin] +enabled = true +address = "127.0.0.1" +port = 8001 +# Shared admin token required by every admin RPC. Can also be supplied via the +# `DSTACK_KMS_ADMIN_TOKEN` or `ADMIN_API_TOKEN` env vars. Clients send it as +# `Authorization: Bearer ` or the `X-Admin-Token: ` header. +# Required unless insecure_no_auth = true. Generate with: openssl rand -hex 32 +auth_token = "" +# Or the token's hex SHA-256, for a config that is not secret (an app compose). +# The hash is public there, so the token must be high-entropy random, or it can +# be brute-forced offline: TOKEN=$(openssl rand -hex 32) +# printf '%s' "$TOKEN" | sha256sum +auth_token_hash = "" +# Optional Apache bcrypt htpasswd file (create with `htpasswd -B -c file admin`). +htpasswd_file = "" +# Development/testing escape hatch only. Never enable this on an admin +# interface that is reachable from the network. +insecure_no_auth = false + +# For deployers and verifiers: only the read-only RPCs (GetMeta, +# GetAppEnvEncryptPubKey, GetSealedEnvPubKey) at the same paths, so the guest +# listener can be restricted to the CVMs. +[listeners.public] +enabled = false +address = "0.0.0.0" +port = 8002 -# No `[rpc.tls.mutual]`: client certificates are verified by the attestation they -# carry, not by an issuer CA (see ra-rpc's ratls_client_verifier). Leaving a -# `mutual` section here is harmless — it is no longer the trust anchor. +# The setup page, while [core.onboard] enabled = true and the KMS has no keys. +# Plain HTTP: it does not inherit the default `tls`. +[listeners.onboard] +address = "0.0.0.0" +port = 8000 [core] -cert_dir = "/etc/kms/certs" +cert_dir = "/var/lib/kms/certs" +# Root keys of every epoch, the only state the KMS cannot regenerate. Keep it on +# persistent storage. +keyring_dir = "/var/lib/kms/keyring" subject_postfix = ".dstack" site_name = "" # Whether trusted RPCs require the KMS to first attest itself to its own @@ -63,6 +111,9 @@ insecure_allow_external_trust_anchors = false # Hosts the GCP TPM AK issuer certificates and CRLs may be fetched from; `*` # matches within one DNS label. Unset keeps Google's Private CA hosts. # allowed_collateral_hosts = ["privateca-content-*.storage.googleapis.com"] +# Minimum SEV-SNP TCBs for CPUs the auth API publishes none for, as the same +# JSON list; see docs/amd-sev-snp.md. A published minimum takes precedence. +# sev_snp_tcb_requirements_file = "/etc/dstack/sev-snp-tcb-requirements.json" [core.attestation.urls] # pccs = "https://pccs.phala.network" @@ -78,41 +129,13 @@ insecure_allow_external_trust_anchors = false # sev_snp_turin = "/etc/dstack/roots/amd-turin-ark.pem" [core.image] -# Verify os_image_hash against the booted image. If false, os_image_hash is -# caller-supplied, so allowedOsImages is not enforced. Never disable in production. -verify = true cache_dir = "/usr/share/dstack/images" download_url = "http://localhost:8000/{OS_IMAGE_HASH}.tar.gz" download_timeout = "2m" -# Admin API: serves operator RPCs (e.g. ClearImageCache) on a dedicated -# listener behind the shared HTTP authenticator. Disabled by default; when -# enabled it fails closed unless auth_token or htpasswd_file is set. -[core.admin] -enabled = false -# Bind address/port for the admin listener (keep it off the public network). -address = "127.0.0.1" -port = 8001 -# Shared admin token required by every admin RPC. Can also be supplied via the -# `DSTACK_KMS_ADMIN_TOKEN` or `ADMIN_API_TOKEN` env vars. Clients send it as -# `Authorization: Bearer ` or the `X-Admin-Token: ` header. -# Required unless insecure_no_auth = true. Generate with: openssl rand -hex 32 -auth_token = "" -# Optional Apache bcrypt htpasswd file (create with `htpasswd -B -c file admin`). -htpasswd_file = "" -# Development/testing escape hatch only. Never enable this on an admin -# interface that is reachable from the network. -insecure_no_auth = false - -# Optional TLS for the admin listener. When configured, clients may present an -# RA-TLS certificate. GetKmsKey requires it; other admin RPCs do not. -# [core.admin.tls] -# key = "/etc/kms/certs/rpc.key" -# certs = "/etc/kms/certs/rpc.crt" - [core.metrics] # Expose unauthenticated Prometheus metrics on /metrics. -# Disable this if the KMS RPC listener is not protected by network policy +# Disable this if the rpc listener is not protected by network policy # or another access-control layer. enabled = true @@ -130,8 +153,6 @@ gateway_app_id = "any" [core.onboard] enabled = true auto_bootstrap_domain = "" -# Keep KMS.GetKmsKey on the public RPC listener for older onboarding clients. -# New deployments should point onboarding at the admin listener instead. -public_key_handover = true -address = "0.0.0.0" -port = 8000 +# Also serve KMS.GetKmsKey on the public RPC listener, for onboarding clients +# that cannot reach the admin listener (KMS 0.5.x, or no source admin token). +public_key_handover = false diff --git a/dstack/kms/rpc/proto/kms_rpc.proto b/dstack/kms/rpc/proto/kms_rpc.proto index 36da0254fa..886d352a52 100644 --- a/dstack/kms/rpc/proto/kms_rpc.proto +++ b/dstack/kms/rpc/proto/kms_rpc.proto @@ -11,12 +11,27 @@ package kms; message GetAppKeyRequest { uint32 api_version = 1; string vm_config = 2; + // Root key epoch to derive from; unset means the current epoch. Epoch 0 is + // the original root keys. Older epochs remain available so CVMs can migrate. + optional uint32 root_epoch = 3; + optional uint32 app_epoch = 4; + // The launch ticket from the CVM's sys-config; empty when it has none. Its + // hash is checked against the app's allowlist. + string launch_ticket = 5; } message AppId { bytes app_id = 1; } +message SealedEnvPubKeyResponse { + bytes public_key = 1; + uint32 root_epoch = 2; + uint64 timestamp = 3; + bytes signature = 4; + uint32 app_epoch = 5; +} + message PublicKeyResponse { bytes public_key = 1; // Legacy signature without timestamp (for backward compatibility). @@ -46,6 +61,11 @@ message AppKeyResponse { string gateway_app_id = 7; // OS Image hash bytes os_image_hash = 8; + // Root key epoch all epoch-dependent fields above were derived from. + uint32 root_epoch = 9; + // X25519 private key for the SealedEnv HPKE receiver, derived for this epoch. + bytes sealed_env_key = 10; + uint32 app_epoch = 11; } message GetMetaResponse { @@ -55,33 +75,44 @@ message GetMetaResponse { BootstrapResponse bootstrap_info = 4; bool is_dev = 5; optional string gateway_app_id = 6; + // Deprecated: read `kmsContractAddr` from `auth_api_info` instead. optional string kms_contract_address = 7; + // Deprecated: read `chainId` from `auth_api_info` instead. optional uint64 chain_id = 8; + // Deprecated: read `appImplementation` from `auth_api_info` instead. optional string app_auth_implementation = 9; - // `[core.image] verify`: whether `os_image_hash` is checked against the - // booted image. Unset on older KMS; do not treat unset as true. + // Whether `os_image_hash` is checked against the booted image; always true + // now. Unset on older KMS; do not treat unset as true. optional bool os_image_verification = 10; + // Public metadata the auth backend reports as `authApiInfo` in its GET / + // response, forwarded verbatim and opaque to KMS; its format is defined by + // the backend (a JSON object for auth-eth). Unset when the backend reports + // none. + optional string auth_api_info = 11; } message GetKmsKeyRequest { string vm_config = 1; + // The joining instance's launch ticket; empty when it has none. Its hash is + // checked against the KMS allowlist. + string launch_ticket = 2; } message KmsKeys { string ca_key = 1; bytes k256_key = 2; + // Attestation produced when this epoch's keys were generated, as registered + // with governance; empty if none. Archived by the receiver, not verified. + bytes attestation = 3; } message KmsKeyResponse { + // Retained for legacy KMS onboarding. This public CA authenticates no caller. string temp_ca_key = 1; + // Root keys of every epoch the KMS holds; the index is the epoch. repeated KmsKeys keys = 2; } -// See the note on `GetTempCaCert`. -// -// `temp_ca_key` is a CA private key handed to any caller, so it authenticates -// nobody. It exists because the KMS pinned this CA for mutual TLS, which left a -// self-issued RA-TLS certificate with nothing to chain to. message GetTempCaCertResponse { string temp_ca_cert = 1; string temp_ca_key = 2; @@ -93,6 +124,8 @@ message SignCertRequest { bytes csr = 2; bytes signature = 3; string vm_config = 4; + // As in GetAppKeyRequest. + string launch_ticket = 5; } message SignCertResponse { @@ -107,28 +140,26 @@ service KMS { rpc GetKmsKey(GetKmsKeyRequest) returns (KmsKeyResponse); // Request the app environment encryption public key given the app id rpc GetAppEnvEncryptPubKey(AppId) returns (PublicKeyResponse); + rpc GetSealedEnvPubKey(AppId) returns (SealedEnvPubKeyResponse); // Request the KMS instance metadata for use as a probe and health check. rpc GetMeta(google.protobuf.Empty) returns (GetMetaResponse); - // Request the temporary CA certificate and key. - // - // Both current callers - guests at boot, and KMS-to-KMS onboarding - fetch this CA - // and mint their client certificate from it, because the KMS used to pin the CA for - // mutual TLS and a self-issued certificate had nothing to chain to. - // - // That pin is gone: the KMS now verifies client certificates by the attestation - // they carry and ignores the issuer, so a self-issued certificate would be accepted - // on the same terms. Neither caller has been migrated yet, so this RPC still has to - // work; it is scheduled for removal once both are. - // - // Do not build new callers on it. A caller that only needs the KMS root CA can read - // `ca_cert` from `GetMeta` instead. + // Compatibility for existing OS images and tokenless legacy onboarding. rpc GetTempCaCert(google.protobuf.Empty) returns (GetTempCaCertResponse); // Sign a certificate rpc SignCert(SignCertRequest) returns (SignCertResponse); } +// The read-only subset of the KMS service, served on the optional +// `[listeners.public]` listener. None of these release secrets or need a client +// certificate. +service ReadOnly { + rpc GetMeta(google.protobuf.Empty) returns (GetMetaResponse); + rpc GetAppEnvEncryptPubKey(AppId) returns (PublicKeyResponse); + rpc GetSealedEnvPubKey(AppId) returns (SealedEnvPubKeyResponse); +} + // The KMS admin RPC service. Served on a separate admin listener -// (`[core.admin]`) behind the shared HTTP authenticator, so the credential +// (`[listeners.admin]`) behind the shared HTTP authenticator, so the credential // travels in the `Authorization`/`X-Admin-Token` header rather than the // request body. service Admin { @@ -158,11 +189,21 @@ message OnboardRequest { string domain = 2; // Optional bearer token for the source KMS admin listener. string source_token = 3; + // Import the source's epochs 0..N-1 and generate epoch N locally. The source + // must be at the current epoch N-1. + bool rotate = 4; + // This instance's launch ticket, presented to the source; empty when the + // KMS policy requires none. + string launch_ticket = 5; } message OnboardResponse { - // k256 public key (secp256k1) inherited from source KMS + // k256 public key (secp256k1) of the current epoch bytes k256_pubkey = 1; + // Set only by a rotation: the generated CA public key and the attestation + // binding the new epoch's public keys. + bytes ca_pubkey = 2; + bytes attestation = 3; } // Attestation info needed for on-chain KMS authorization. @@ -185,6 +226,18 @@ message AttestationInfoResponse { bytes ppid = 8; } +// Public material already written by Bootstrap or Onboard, so the setup page +// can resume after a refresh without repeating those RPCs. +message SetupStatusResponse { + bool provisioned = 1; + bytes k256_pubkey = 2; + bytes ca_pubkey = 3; + bytes attestation = 4; + // All key and certificate files are present, so Finish can start the KMS. + // If ready is true, provisioned is also true. + bool ready = 5; +} + // The Onboard RPC service. service Onboard { // Bootstrap a new KMS @@ -193,6 +246,8 @@ service Onboard { rpc Onboard(OnboardRequest) returns (OnboardResponse); // Get attestation info for on-chain KMS authorization rpc GetAttestationInfo(google.protobuf.Empty) returns (AttestationInfoResponse); + // Public keys already stored for this KMS, if any + rpc GetSetupStatus(google.protobuf.Empty) returns (SetupStatusResponse); // Finish onboarding rpc Finish(google.protobuf.Empty) returns (google.protobuf.Empty); } diff --git a/dstack/kms/src/admin_auth.rs b/dstack/kms/src/admin_auth.rs index 22fe33bd6d..6ff23af54e 100644 --- a/dstack/kms/src/admin_auth.rs +++ b/dstack/kms/src/admin_auth.rs @@ -7,12 +7,14 @@ //! Unlike the KMS public RPC surface (which authenticates callers by RA-TLS //! attestation), the admin API is reached by operators/tooling, so it uses the //! same shared-token/htpasswd HTTP mechanism as the VMM and gateway. The token -//! is configured via `core.admin.auth_token`, or the `DSTACK_KMS_ADMIN_TOKEN` / -//! `ADMIN_API_TOKEN` environment variables. +//! is configured via `listeners.admin.auth_token`, or the `DSTACK_KMS_ADMIN_TOKEN` / +//! `ADMIN_API_TOKEN` environment variables, or as its SHA-256 in +//! `listeners.admin.auth_token_hash`. -use anyhow::{bail, Result}; +use anyhow::{bail, Context, Result}; use dstack_api_auth::{Authenticator, HttpAuthConfig, HttpAuthFairing}; use rocket::Route; +use sha2::{Digest, Sha256}; use crate::config::AdminConfig; @@ -29,28 +31,47 @@ impl AdminAuthFairing { http_config(), ))); } - let token = if !config.auth_token.is_empty() { - config.auth_token.trim().to_owned() - } else { - std::env::var(ENV_ADMIN_TOKEN) - .or_else(|_| std::env::var(ENV_ADMIN_TOKEN_COMPAT)) - .unwrap_or_default() - .trim() - .to_owned() - }; - if token.is_empty() && config.htpasswd_file.as_os_str().is_empty() { - bail!( - "admin API is enabled but neither auth_token nor htpasswd_file is configured; \ - set core.admin.auth_token, {ENV_ADMIN_TOKEN}, {ENV_ADMIN_TOKEN_COMPAT}, \ - core.admin.htpasswd_file, or insecure_no_auth = true (testing only)" - ); - } - let mut auth = Authenticator::from_tokens([token]); - if !config.htpasswd_file.as_os_str().is_empty() { - auth = auth.with_htpasswd_file(&config.htpasswd_file)?; - } - Ok(Self(HttpAuthFairing::new(auth, http_config()))) + Ok(Self(HttpAuthFairing::new( + authenticator(config)?, + http_config(), + ))) + } +} + +fn authenticator(config: &AdminConfig) -> Result { + let token = if !config.auth_token.is_empty() { + config.auth_token.trim().to_owned() + } else { + std::env::var(ENV_ADMIN_TOKEN) + .or_else(|_| std::env::var(ENV_ADMIN_TOKEN_COMPAT)) + .unwrap_or_default() + .trim() + .to_owned() + }; + let mut hashes = Vec::new(); + if !token.is_empty() { + hashes.push(Sha256::digest(token.as_bytes()).into()); + } + let hash = config.auth_token_hash.trim(); + if !hash.is_empty() { + let hash = hex::decode(hash) + .ok() + .and_then(|hash| <[u8; 32]>::try_from(hash).ok()) + .context("listeners.admin.auth_token_hash must be a hex SHA-256 digest")?; + hashes.push(hash); + } + if hashes.is_empty() && config.htpasswd_file.as_os_str().is_empty() { + bail!( + "admin API is enabled but no credential is configured; set listeners.admin.auth_token, \ + {ENV_ADMIN_TOKEN}, {ENV_ADMIN_TOKEN_COMPAT}, listeners.admin.auth_token_hash, \ + listeners.admin.htpasswd_file, or insecure_no_auth = true (testing only)" + ); } + let mut auth = Authenticator::from_token_hashes(hashes); + if !config.htpasswd_file.as_os_str().is_empty() { + auth = auth.with_htpasswd_file(&config.htpasswd_file)?; + } + Ok(auth) } fn http_config() -> HttpAuthConfig { @@ -86,7 +107,6 @@ mod tests { std::env::remove_var(ENV_ADMIN_TOKEN); std::env::remove_var(ENV_ADMIN_TOKEN_COMPAT); let cfg = AdminConfig { - enabled: true, ..Default::default() }; assert!(AdminAuthFairing::from_config(&cfg).is_err()); @@ -95,17 +115,31 @@ mod tests { #[test] fn insecure_no_auth_is_allowed() { let cfg = AdminConfig { - enabled: true, insecure_no_auth: true, ..Default::default() }; assert!(AdminAuthFairing::from_config(&cfg).is_ok()); } + #[test] + fn a_token_hash_admits_its_token() { + let cfg = AdminConfig { + auth_token_hash: hex::encode(Sha256::digest(b"secret")), + ..Default::default() + }; + let auth = authenticator(&cfg).unwrap(); + assert!(auth.verify_token("secret")); + assert!(!auth.verify_token("other")); + let bad = AdminConfig { + auth_token_hash: "00".into(), + ..cfg + }; + assert!(authenticator(&bad).is_err()); + } + #[test] fn configured_token_builds() { let cfg = AdminConfig { - enabled: true, auth_token: "secret".into(), ..Default::default() }; diff --git a/dstack/kms/src/admin_service.rs b/dstack/kms/src/admin_service.rs index 181ff4dea0..f4f6780e90 100644 --- a/dstack/kms/src/admin_service.rs +++ b/dstack/kms/src/admin_service.rs @@ -2,7 +2,7 @@ // // SPDX-License-Identifier: Apache-2.0 -//! KMS admin RPC service, served on the `[core.admin]` listener behind the +//! KMS admin RPC service, served on the `[listeners.admin]` listener behind the //! shared HTTP authenticator. Callers are authenticated by the admin token / //! htpasswd via `Authorization`/`X-Admin-Token`, so the handlers do no token //! checks of their own. @@ -14,7 +14,7 @@ use dstack_kms_rpc::{ }; use ra_rpc::{CallContext, RpcCall}; -use crate::main_service::{KmsState, RpcHandler}; +use crate::main_service::{KeyRelease, KmsState, RpcHandler}; pub struct AdminRpcHandler { state: KmsState, @@ -28,7 +28,9 @@ impl AdminRpc for AdminRpcHandler { } async fn get_kms_key(self, request: GetKmsKeyRequest) -> Result { - self.rpc.handover_keys(request).await + self.rpc + .handover_keys(KeyRelease::AdminHandover, request) + .await } } diff --git a/dstack/kms/src/config.rs b/dstack/kms/src/config.rs index 0ae47d65c2..80f5943263 100644 --- a/dstack/kms/src/config.rs +++ b/dstack/kms/src/config.rs @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: Apache-2.0 +use anyhow::{bail, Result}; use dstack_attest::attestation::AttestationVerifierConfig; use load_config::load_config; use rocket::figment::Figment; @@ -13,6 +14,54 @@ pub fn load_config_figment(config_file: Option<&str>) -> Figment { load_config("kms", DEFAULT_CONFIG, config_file, false) } +/// Settings that moved to `[listeners.*]`. The defaults (`kms.toml`) have none +/// of them, so one present was set by the operator and would otherwise be +/// silently ignored. +const MOVED_SETTINGS: [(&str, &str); 6] = [ + ("rpc", "listeners.guest"), + ("core.admin", "listeners.admin"), + ("core.onboard.address", "listeners.onboard.address"), + ("core.onboard.port", "listeners.onboard.port"), + ("core.onboard.tls", "listeners.onboard.tls"), + ("default", "listeners.default"), +]; + +/// Refuse a config that sets a moved setting, including a Rocket setting at the +/// top level of a config file, which the old guest and onboard listeners read. +pub(crate) fn reject_moved_settings(figment: &Figment) -> Result<()> { + load_config::reject_moved_settings(figment, &MOVED_SETTINGS) +} + +/// The `enabled` switches of the optional listeners. Their bind settings +/// (`address`, `port`, `tls`, `proxy_protocol`) are read by Rocket, see +/// [`listener_figment`]. +#[derive(Debug, Clone, Default, Deserialize)] +pub(crate) struct ListenersConfig { + #[serde(default)] + pub admin: AdminConfig, + #[serde(default)] + pub public: ListenerSwitch, +} + +#[derive(Debug, Clone, Default, Deserialize)] +pub(crate) struct ListenerSwitch { + #[serde(default)] + pub enabled: bool, +} + +impl ListenersConfig { + pub fn load(figment: &Figment) -> Result { + Ok(figment.extract_inner("listeners")?) + } +} + +/// The Rocket config of listener `name`. The onboard listener does not inherit +/// the default `tls`, since it runs before the KMS has certificates. +pub(crate) fn listener_figment(figment: &Figment, name: &str) -> Result { + let uninherited: &[&str] = if name == "onboard" { &["tls"] } else { &[] }; + load_config::listener_figment(figment, name, uninherited) +} + const TEMP_CA_CERT: &str = "tmp-ca.crt"; const TEMP_CA_KEY: &str = "tmp-ca.key"; const ROOT_CA_CERT: &str = "root-ca.crt"; @@ -21,11 +70,12 @@ const RPC_CERT: &str = "rpc.crt"; const RPC_KEY: &str = "rpc.key"; const RPC_DOMAIN: &str = "rpc-domain"; const K256_KEY: &str = "root-k256.key"; -const BOOTSTRAP_INFO: &str = "bootstrap-info.json"; +const ROOT_ATTESTATION: &str = "root-attestation"; +const ROOT_EPOCH: &str = "root-epoch"; +const EPOCHS_DIR: &str = "epochs"; #[derive(Debug, Clone, Deserialize)] pub(crate) struct ImageConfig { - pub verify: bool, pub cache_dir: PathBuf, pub download_url: String, #[serde(with = "serde_duration")] @@ -35,6 +85,8 @@ pub(crate) struct ImageConfig { #[derive(Debug, Clone, Deserialize)] pub(crate) struct KmsConfig { pub cert_dir: PathBuf, + /// Root keys of every epoch. + pub keyring_dir: PathBuf, #[serde(default)] pub attestation: AttestationVerifierConfig, pub auth_api: AuthApi, @@ -83,10 +135,6 @@ pub(crate) struct KmsConfig { #[serde(default = "default_true")] pub enforce_self_authorization: bool, pub metrics: MetricsConfig, - /// Admin API listener + authentication. The admin RPCs (e.g. - /// `ClearImageCache`) are served here, behind the shared HTTP authenticator. - #[serde(default)] - pub admin: AdminConfig, } #[derive(Debug, Clone, Deserialize)] @@ -95,13 +143,11 @@ pub(crate) struct MetricsConfig { pub enabled: bool, } -/// Admin API listener + authentication, mirroring the gateway `[core.admin]` -/// section. The listen `address`/`port` are read from the same `[core.admin]` -/// section by Rocket. The token travels in the `Authorization`/`X-Admin-Token` +/// The admin listener, `[listeners.admin]`: whether it is served and its +/// authentication. The token travels in the `Authorization`/`X-Admin-Token` /// header. #[derive(Debug, Clone, Default, Deserialize)] pub(crate) struct AdminConfig { - /// Whether to serve the admin API at all. #[serde(default)] pub enabled: bool, /// Shared admin token required to call any admin RPC. Can also be supplied @@ -109,6 +155,10 @@ pub(crate) struct AdminConfig { /// `insecure_no_auth = true`. #[serde(default)] pub auth_token: String, + /// Hex SHA-256 of the admin token, for configs that are not secret, such + /// as an app compose, so the token itself stays out of them. + #[serde(default)] + pub auth_token_hash: String, /// Optional Apache bcrypt htpasswd file, accepted in addition to the token. #[serde(default)] pub htpasswd_file: PathBuf, @@ -122,22 +172,52 @@ fn default_true() -> bool { true } +/// Without the public handover, other KMS nodes can get the keys only from the +/// admin listener over TLS. A KMS without either would strand them, so it +/// refuses to start, in any mode. +pub(crate) fn check_key_handover( + config: &KmsConfig, + listeners: &ListenersConfig, + figment: &Figment, +) -> Result<()> { + if config.onboard.public_key_handover { + return Ok(()); + } + let admin = listener_figment(figment, "admin")?; + let set = |key: &str| { + admin + .find_value(key) + .ok() + .and_then(|value| value.into_string()) + .is_some_and(|value| !value.is_empty()) + }; + let missing = if !listeners.admin.enabled { + "[listeners.admin] enabled = true" + } else if !set("tls.key") { + "the admin listener's tls key" + } else if !set("tls.certs") { + "the admin listener's tls certs" + } else { + return Ok(()); + }; + bail!( + "no key handover path for onboarding other KMS nodes: {missing} is not set. \ + Configure the admin listener with TLS ([listeners.admin] enabled = true with an \ + admin credential, and tls key and certs in [listeners.admin.tls] or \ + [listeners.default.tls]), or set core.onboard.public_key_handover = true" + ) +} + impl KmsConfig { - /// The root keys are the last files a bootstrap writes, so both existing - /// marks a completed one. Anything short of that is left over from an - /// interrupted bootstrap and may be overwritten. + /// The root epoch marker is the last file a bootstrap or onboarding writes, + /// so its presence marks a completed one. Anything short of that is left + /// over from an interrupted attempt and may be overwritten. pub fn root_keys_exist(&self) -> bool { - self.root_ca_key().exists() && self.k256_key().exists() + self.root_epoch().exists() } pub fn keys_exists(&self) -> bool { - self.tmp_ca_cert().exists() - && self.tmp_ca_key().exists() - && self.root_ca_cert().exists() - && self.root_ca_key().exists() - && self.rpc_cert().exists() - && self.rpc_key().exists() - && self.k256_key().exists() + self.root_keys_exist() && self.rpc_cert().exists() && self.rpc_key().exists() } pub fn tmp_ca_cert(&self) -> PathBuf { @@ -148,14 +228,6 @@ impl KmsConfig { self.cert_dir.join(TEMP_CA_KEY) } - pub fn root_ca_cert(&self) -> PathBuf { - self.cert_dir.join(ROOT_CA_CERT) - } - - pub fn root_ca_key(&self) -> PathBuf { - self.cert_dir.join(ROOT_CA_KEY) - } - pub fn rpc_cert(&self) -> PathBuf { self.cert_dir.join(RPC_CERT) } @@ -168,12 +240,20 @@ impl KmsConfig { self.cert_dir.join(RPC_DOMAIN) } - pub fn k256_key(&self) -> PathBuf { - self.cert_dir.join(K256_KEY) + /// Records the newest epoch this KMS holds. + pub fn root_epoch(&self) -> PathBuf { + self.keyring_dir.join(ROOT_EPOCH) } - pub fn bootstrap_info(&self) -> PathBuf { - self.cert_dir.join(BOOTSTRAP_INFO) + /// Root key paths of `epoch`, under `epochs//`. + pub fn root_key_paths(&self, epoch: u32) -> RootKeyPaths { + let dir = self.keyring_dir.join(EPOCHS_DIR).join(epoch.to_string()); + RootKeyPaths { + ca_cert: dir.join(ROOT_CA_CERT), + ca_key: dir.join(ROOT_CA_KEY), + k256_key: dir.join(K256_KEY), + attestation: dir.join(ROOT_ATTESTATION), + } } } @@ -210,12 +290,19 @@ pub(crate) struct Dev { pub gateway_app_id: String, } +pub(crate) struct RootKeyPaths { + pub ca_cert: PathBuf, + pub ca_key: PathBuf, + pub k256_key: PathBuf, + pub attestation: PathBuf, +} + #[derive(Debug, Clone, Deserialize)] pub(crate) struct OnboardConfig { pub enabled: bool, pub auto_bootstrap_domain: String, - /// Keep GetKmsKey available on the public RPC listener for compatibility. - #[serde(default = "default_true")] + /// Also serve GetKmsKey on the public RPC listener, for legacy onboarding clients. + #[serde(default)] pub public_key_handover: bool, } @@ -225,18 +312,96 @@ mod tests { use rocket::figment::providers::{Format, Toml}; #[test] - fn default_config_parses_with_admin_disabled_and_no_hash() { + fn default_config_serves_the_handover_on_the_admin_listener() { let figment = load_config_figment(None); let config: KmsConfig = figment .focus("core") .extract() .expect("kms.toml must parse into KmsConfig"); - assert!(!config.admin.enabled, "admin must be off by default"); + let listeners = ListenersConfig::load(&figment).unwrap(); + assert!(listeners.admin.enabled); + assert!(!listeners.public.enabled); + check_key_handover(&config, &listeners, &figment) + .expect("the default config has a handover path"); assert!( - config.admin.auth_token.is_empty(), + listeners.admin.auth_token.is_empty(), "default admin token must be empty (fail-closed)" ); - assert!(!config.admin.insecure_no_auth); + assert!(!listeners.admin.insecure_no_auth); + assert!( + !config.onboard.public_key_handover, + "public key handover must be off by default" + ); + } + + fn handover_check(toml: &str) -> Result<()> { + let figment = load_config_figment(None).merge(Toml::string(toml)); + let config: KmsConfig = figment.focus("core").extract().unwrap(); + check_key_handover(&config, &ListenersConfig::load(&figment).unwrap(), &figment) + } + + #[test] + fn moved_listener_settings_are_refused() { + reject_moved_settings(&load_config_figment(None)).expect("kms.toml uses the new names"); + for (toml, old) in [ + ("[rpc]\nport = 9100\n", "rpc -> listeners.guest"), + ( + "[core.admin]\nport = 9101\n", + "core.admin -> listeners.admin", + ), + ( + "[core.admin]\nauth_token = \"t\"\n", + "core.admin -> listeners.admin", + ), + ("[core.onboard]\nport = 9102\n", "core.onboard.port -> "), + ("[default]\nworkers = 8\n", "default -> listeners.default"), + ] { + let figment = load_config_figment(None).merge(Toml::string(toml)); + let err = reject_moved_settings(&figment).unwrap_err().to_string(); + assert!(err.contains(old), "{err}"); + } + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("kms.toml"); + fs_err::write( + &file, + "log_level = \"debug\"\n[core.onboard]\nenabled = false\n", + ) + .unwrap(); + let err = reject_moved_settings(&load_config_figment(file.to_str())) + .unwrap_err() + .to_string(); + assert!( + err.contains("log_level -> listeners.default.log_level"), + "{err}" + ); + let onboarding = "[core.onboard]\nenabled = false\n"; + reject_moved_settings(&load_config_figment(None).merge(Toml::string(onboarding))) + .expect("onboarding options stay in core"); + } + + #[test] + fn a_serving_kms_needs_a_key_handover_path() { + let public = "[core.onboard]\npublic_key_handover = true\n"; + let no_admin = "[listeners.admin]\nenabled = false\n"; + let no_key = "[listeners.admin.tls]\nkey = \"\"\n"; + let no_certs = "[listeners.admin.tls]\ncerts = \"\"\n"; + assert!(handover_check("").is_ok()); + // onboarding and bootstrap modes are checked alike. + let onboarding = "[core.onboard]\nenabled = true\nauto_bootstrap_domain = \"kms.test\"\n"; + assert!(handover_check(onboarding).is_ok()); + assert!(handover_check(&format!("{onboarding}{no_admin}")).is_err()); + for missing in [no_admin, no_key, no_certs] { + assert!(handover_check(&format!("{public}{missing}")).is_ok()); + } + for (toml, setting) in [ + (no_admin, "[listeners.admin] enabled = true"), + (no_key, "the admin listener's tls key"), + (no_certs, "the admin listener's tls certs"), + ] { + let err = handover_check(toml).unwrap_err().to_string(); + assert!(err.contains(setting), "{err}"); + assert!(err.contains("public_key_handover = true"), "{err}"); + } } #[test] diff --git a/dstack/kms/src/crypto.rs b/dstack/kms/src/crypto.rs index faa8e01f89..93a5c5054b 100644 --- a/dstack/kms/src/crypto.rs +++ b/dstack/kms/src/crypto.rs @@ -8,11 +8,21 @@ use k256::ecdsa::SigningKey; use ra_tls::api_v1::sign_recoverable_keccak256; use ra_tls::kdf; +pub(crate) fn app_epoch_context(epoch: u32) -> Vec { + if epoch == 0 { + Vec::new() + } else { + [b"app-epoch-v1:".as_slice(), &epoch.to_be_bytes()].concat() + } +} + pub(crate) fn derive_k256_key( parent_key: &SigningKey, app_id: &[u8], + app_epoch: u32, ) -> Result<(SigningKey, Vec)> { - let context_data = [app_id, b"app-key"]; + let epoch_context = app_epoch_context(app_epoch); + let context_data = [app_id, b"app-key", epoch_context.as_slice()]; let derived_key_bytes: [u8; 32] = kdf::derive_key(&parent_key.to_bytes(), &context_data, 32)? .try_into() .ok() @@ -20,12 +30,21 @@ pub(crate) fn derive_k256_key( let derived_signing_key = SigningKey::from_bytes(&derived_key_bytes.into())?; let pubkey = derived_signing_key.verifying_key(); - let signature = sign_message( - parent_key, - b"dstack-kms-issued", - app_id, - &pubkey.to_sec1_bytes(), - )?; + let signature = if app_epoch == 0 { + sign_message( + parent_key, + b"dstack-kms-issued", + app_id, + &pubkey.to_sec1_bytes(), + )? + } else { + sign_message( + parent_key, + b"dstack-kms-issued-v2", + app_id, + &[app_epoch.to_be_bytes().as_slice(), &pubkey.to_sec1_bytes()].concat(), + )? + }; Ok((derived_signing_key, signature)) } @@ -141,7 +160,7 @@ mod tests { #[test] fn issued_app_key_signatures_match_their_golden_vectors() { let root = SigningKey::from_slice(&[7_u8; 32]).unwrap(); - let (derived, signature) = derive_k256_key(&root, b"app-a").unwrap(); + let (derived, signature) = derive_k256_key(&root, b"app-a", 0).unwrap(); assert_eq!( hex::encode(derived.to_bytes()), diff --git a/dstack/kms/src/main.rs b/dstack/kms/src/main.rs index f4bf428a85..3525ebd6b3 100644 --- a/dstack/kms/src/main.rs +++ b/dstack/kms/src/main.rs @@ -3,19 +3,21 @@ // SPDX-License-Identifier: Apache-2.0 use anyhow::{anyhow, bail, Context, Result}; -use clap::Parser; +use clap::{Parser, Subcommand}; use config::KmsConfig; +use futures::FutureExt; use main_service::{KmsState, RpcHandler}; use ra_rpc::ratls_client_verifier::RaTlsClientAuth; use ra_rpc::rocket_helper::QuoteVerifier; use ra_tls::attestation::AttestationVerifier; use rocket::{ fairing::AdHoc, - figment::{providers::Serialized, Figment}, + figment::Figment, response::content::{RawHtml, RawText}, tls::Resolver as _, Shutdown, State, }; +use rocket_proxy_listener::launch; use tracing::{info, warn}; mod admin_auth; @@ -24,17 +26,52 @@ mod config; mod crypto; mod main_service; mod onboard_service; +mod readonly_service; fn app_version() -> String { dstack_build_info::app_version!() } +fn app_version_header() -> AdHoc { + AdHoc::on_response("Add app version header", |_req, res| { + Box::pin(async move { + res.set_raw_header("X-App-Version", app_version()); + }) + }) +} + #[derive(Parser)] #[command(author, version, about, long_version = app_version())] struct Args { /// Path to the configuration file #[arg(short, long)] config: Option, + #[command(subcommand)] + command: Option, +} + +#[derive(Subcommand)] +enum Command { + /// Print, as hex, the attestation `registerRootEpoch` takes for epoch 0, + /// converted from the legacy `kmsInfo` quote and event log + LegacyAttestation { + /// TDX quote, hex + #[arg(long)] + quote: String, + /// Event log JSON, hex-encoded as `kmsInfo()` returns it + #[arg(long)] + eventlog: String, + }, +} + +fn legacy_attestation(quote: &str, eventlog: &str) -> Result { + let decode = |hex_str: &str| hex::decode(hex_str.trim().trim_start_matches("0x")); + let quote = decode(quote).context("invalid quote hex")?; + let eventlog = decode(eventlog).context("invalid event log hex")?; + let attestation = dstack_attest::attestation::Attestation::from_tdx_quote(quote, &eventlog)? + .into_versioned() + .to_bytes()?; + Ok(format!("0x{}", hex::encode(attestation))) } async fn run_onboard_service(kms_config: KmsConfig, figment: Figment) -> Result<()> { @@ -58,11 +95,7 @@ async fn run_onboard_service(kms_config: KmsConfig, figment: Figment) -> Result< } let state = OnboardState::new(kms_config)?; - let figment = figment - .clone() - .merge(Serialized::defaults(figment.find_value("core.onboard")?)); - - // Remove section tls + let figment = config::listener_figment(&figment, "onboard")?; let rocket = rocket::custom(figment) .mount("/", rocket::routes![index, finish, health]) @@ -123,8 +156,13 @@ async fn main() -> Result<()> { fmt().with_env_filter(filter).with_ansi(false).init(); } let args = Args::parse(); + if let Some(Command::LegacyAttestation { quote, eventlog }) = args.command { + println!("{}", legacy_attestation("e, &eventlog)?); + return Ok(()); + } let figment = config::load_config_figment(args.config.as_deref()); + config::reject_moved_settings(&figment)?; let config: KmsConfig = figment.focus("core").extract()?; if !config.attest_rpc_cert { @@ -135,6 +173,24 @@ async fn main() -> Result<()> { ); } + // before onboarding or bootstrap, so a misconfigured node fails before it + // gets or generates root keys: the handover path, and the admin listener + // serving it (enabled with no credential fails here). + let listeners = config::ListenersConfig::load(&figment)?; + config::check_key_handover(&config, &listeners, &figment)?; + let admin_config = listeners.admin.clone(); + let admin_setup = if listeners.admin.enabled { + let admin_fairing = admin_auth::AdminAuthFairing::from_config(&admin_config)?; + Some((config::listener_figment(&figment, "admin")?, admin_fairing)) + } else { + None + }; + let public_figment = if listeners.public.enabled { + Some(config::listener_figment(&figment, "public")?) + } else { + None + }; + if config.onboard.enabled && !config.keys_exists() { info!("Onboarding"); run_onboard_service(config.clone(), figment.clone()).await?; @@ -143,8 +199,12 @@ async fn main() -> Result<()> { } } + let keyring = main_service::Keyring::load(&config).context("Failed to load the root keys")?; + let rpc_epoch = main_service::wait_for_servable_epoch(&config, &keyring).await; + info!("Issuing RPC certificate under root epoch {rpc_epoch}"); + info!("Updating certs"); - if let Err(err) = onboard_service::update_certs(&config).await { + if let Err(err) = onboard_service::update_certs(&config, rpc_epoch).await { if config.attest_rpc_cert { return Err(err).context( "Failed to reissue the attested KMS RPC certificate; refusing to start with a \ @@ -161,38 +221,20 @@ async fn main() -> Result<()> { } let metrics_enabled = config.metrics.enabled; - let admin_config = config.admin.clone(); - // build the admin listener figment from `[core.admin]` before `config` is - // moved into the state; the fairing is built now so a misconfigured admin - // (enabled but no credential) fails fast before we start serving. - let admin_setup = if admin_config.enabled { - let admin_value = figment - .find_value("core.admin") - .context("core.admin section not found")?; - let admin_figment = - Figment::from(rocket::Config::default()).merge(Serialized::defaults(admin_value)); - let admin_fairing = admin_auth::AdminAuthFairing::from_config(&admin_config)?; - Some((admin_figment, admin_fairing)) - } else { - None - }; - let state = main_service::KmsState::new(config).context("Failed to initialize KMS state")?; + // Reload certificates after renewal before exposing them through RPCs. + let rpc_ca_cert = fs_err::read_to_string(config.root_key_paths(rpc_epoch).ca_cert)?; + let keyring = main_service::Keyring::load(&config).context("Failed to reload the root keys")?; + let state = main_service::KmsState::new(config, keyring, rpc_ca_cert) + .context("Failed to initialize KMS state")?; let quote_verifier = QuoteVerifier::new(state.attestation_verifier()); let admin_quote_verifier = QuoteVerifier::new(state.attestation_verifier()); - let figment = figment - .clone() - .merge(Serialized::defaults(figment.find_value("rpc")?)); - let mut rocket = rocket::custom(figment) + let mut rocket = rocket::custom(config::listener_figment(&figment, "guest")?) // Verify client certificates by their attestation rather than by issuer. The // certificates guests and onboarding mint from the temp CA today keep working // unchanged - they are now accepted for the attestation they carry rather than // for who signed them - and a self-issued certificate would be accepted too. .attach(RaTlsClientAuth::fairing()) - .attach(AdHoc::on_response("Add app version header", |_req, res| { - Box::pin(async move { - res.set_raw_header("X-App-Version", app_version()); - }) - })) + .attach(app_version_header()) .mount( "/prpc", ra_rpc::prpc_routes!(KmsState, RpcHandler, trim: "KMS."), @@ -212,35 +254,75 @@ async fn main() -> Result<()> { rocket = rocket.manage(quote_verifier); - let main_srv = rocket.launch(); - match admin_setup { - Some((admin_figment, admin_fairing)) => { - if admin_config.insecure_no_auth { - warn!( - "admin API is served with insecure_no_auth = true; the admin RPCs are exposed without authentication" - ); - } else { - info!("admin API authentication enabled"); - } - let admin_srv = rocket::custom(admin_figment) - .attach(admin_fairing) - .attach(RaTlsClientAuth::fairing()) - .mount("/", admin_auth::routes()) - .mount( - "/prpc", - ra_rpc::prpc_routes!(KmsState, admin_service::AdminRpcHandler, trim: "Admin."), - ) - .manage(state) - .manage(admin_quote_verifier) - .launch(); - tokio::try_join!( - async { main_srv.await.map_err(|err| anyhow!(err.to_string())) }, - async { admin_srv.await.map_err(|err| anyhow!(err.to_string())) }, - )?; + let mut servers = vec![launch(rocket).boxed()]; + if let Some(public_figment) = public_figment { + info!("serving the read-only RPCs on the public listener"); + let public = rocket::custom(public_figment) + .attach(app_version_header()) + .mount("/", rocket::routes![health]) + .mount( + "/prpc", + ra_rpc::prpc_routes!( + KmsState, + readonly_service::ReadOnlyRpcHandler, + trim: "ReadOnly." + ), + ) + .manage(state.clone()); + servers.push(launch(public).boxed()); + } + if let Some((admin_figment, admin_fairing)) = admin_setup { + if admin_config.insecure_no_auth { + warn!( + "admin API is served with insecure_no_auth = true; the admin RPCs are exposed without authentication" + ); + } else { + info!("admin API authentication enabled"); } - None => { - main_srv.await.map_err(|err| anyhow!(err.to_string()))?; + let admin = rocket::custom(admin_figment) + .attach(admin_fairing) + .attach(RaTlsClientAuth::fairing()) + .mount("/", admin_auth::routes()) + .mount( + "/prpc", + ra_rpc::prpc_routes!(KmsState, admin_service::AdminRpcHandler, trim: "Admin."), + ) + .manage(state.clone()) + .manage(admin_quote_verifier); + servers.push(launch(admin).boxed()); + } + // Refresh the TLS listeners when the authorized root CA changes. + tokio::select! { + result = futures::future::try_join_all(servers) => { + result.map_err(|err| anyhow!(err.to_string()))?; + } + () = state.restart_requested() => { + bail!("the RPC root CA changed; restarting to refresh the TLS certificate") } } Ok(()) } + +#[cfg(test)] +mod tests { + use dstack_attest::attestation::VersionedAttestation; + + #[test] + fn legacy_attestation_converts_a_get_quote_response() { + let fixture: serde_json::Value = serde_json::from_str(include_str!( + "../../verifier/fixtures/tdx-lite-getquote.json" + )) + .unwrap(); + let quote = fixture["quote"].as_str().unwrap(); + let eventlog = hex::encode(fixture["event_log"].as_str().unwrap()); + + let attestation = super::legacy_attestation(quote, &format!("0x{eventlog}")).unwrap(); + let attestation = + VersionedAttestation::from_bytes(&hex::decode(&attestation[2..]).unwrap()).unwrap(); + let attestation = attestation.into_v1(); + assert_eq!( + hex::encode(attestation.report_data().unwrap()), + fixture["report_data"].as_str().unwrap() + ); + } +} diff --git a/dstack/kms/src/main_service.rs b/dstack/kms/src/main_service.rs index 6a5af39413..8295d20d8b 100644 --- a/dstack/kms/src/main_service.rs +++ b/dstack/kms/src/main_service.rs @@ -3,7 +3,6 @@ // SPDX-License-Identifier: Apache-2.0 use std::{ - path::Path, sync::{ atomic::{AtomicU64, Ordering}, Arc, @@ -14,29 +13,32 @@ use std::{ use anyhow::{anyhow, bail, Context, Result}; use dstack_kms_rpc::{ kms_server::{KmsRpc, KmsServer}, - AppId, AppKeyResponse, GetAppKeyRequest, GetKmsKeyRequest, GetMetaResponse, - GetTempCaCertResponse, KmsKeyResponse, KmsKeys, PublicKeyResponse, SignCertRequest, - SignCertResponse, + AppId, AppKeyResponse, BootstrapResponse, GetAppKeyRequest, GetKmsKeyRequest, GetMetaResponse, + GetTempCaCertResponse, KmsKeyResponse, KmsKeys, PublicKeyResponse, SealedEnvPubKeyResponse, + SignCertRequest, SignCertResponse, }; use dstack_verifier::{CvmVerifier, VerificationDetails}; use fs_err as fs; use k256::ecdsa::SigningKey; use moka::future::Cache; -use ra_rpc::{CallContext, RpcCall}; +use p256::pkcs8::DecodePrivateKey; +use ra_rpc::{CallContext, RemoteEndpoint, RpcCall}; use ra_tls::{ attestation::{resolve_vm_config, AttestationVerifier, TeeVariant, VerifiedAttestation}, cert::{CaCert, CertRequest, CertSigningRequestV1, CertSigningRequestV2, Csr}, kdf, + rcgen::KeyPair, }; use scale::Decode; -use tracing::{debug, warn}; +use tracing::{info, warn}; use upgrade_authority::{ - build_boot_info, ensure_app_id_len, local_kms_boot_info, BootInfo, GetInfoResponse, + build_boot_info, ensure_app_id_len, local_kms_boot_info, AuthorizationResult, BootInfo, + GetInfoResponse, Operation, RootEpochRegistry, }; use crate::{ - config::KmsConfig, - crypto::{derive_k256_key, sign_message, sign_message_with_timestamp}, + config::{KmsConfig, RootKeyPaths}, + crypto::{app_epoch_context, derive_k256_key, sign_message, sign_message_with_timestamp}, }; pub(crate) mod amd_attest; @@ -44,15 +46,21 @@ pub(crate) mod upgrade_authority; /// How long the auth API's info and this KMS's own authorization are reused. /// -/// `GetMeta`, `GetAppEnvEncryptPubKey` and `GetTempCaCert` need no client certificate, and each +/// `GetMeta` and `GetAppEnvEncryptPubKey` need no client certificate, and each /// would otherwise cost the auth API a round of chain RPC calls. Concurrent callers share one /// in-flight request. App authorization is never cached. const AUTH_API_CACHE_TTL: Duration = Duration::from_secs(1); +/// Apps whose epoch is cached at once. Floods of random app IDs still reach the +/// auth API; limit them per source in a proxy in front of the KMS. +const APP_EPOCH_CACHE_CAPACITY: u64 = 10_000; + /// How long this KMS's own verified boot info is reused. /// /// Its measurements do not change while the KMS runs, but the TCB status and advisories do when -/// the platform's collateral is updated, and the auth API judges them on every self check. +/// the platform's collateral is updated. Self checks judge the cached copy, so a change to this +/// KMS's TCB status takes effect up to this long later. Callers' attestations are verified on +/// every request and are not affected. const SELF_BOOT_INFO_TTL: Duration = Duration::from_secs(60 * 60); #[derive(Clone)] @@ -68,17 +76,124 @@ impl std::ops::Deref for KmsState { } } +/// The root key pair of one epoch. +struct RootKeys { + ca: CaCert, + k256: SigningKey, + /// Evidence produced when the keys were generated; empty if there is none. + attestation: Vec, +} + +impl RootKeys { + fn load(paths: &RootKeyPaths) -> Result { + let ca = CaCert::load(&paths.ca_cert, &paths.ca_key) + .context("failed to load root CA certificate")?; + let key_bytes = fs::read(&paths.k256_key).context("failed to read ECDSA root key")?; + let k256 = SigningKey::from_slice(&key_bytes).context("failed to load ECDSA root key")?; + let attestation = read_root_attestation(paths)?; + Ok(Self { + ca, + k256, + attestation, + }) + } +} + +/// The root keys of epochs 0..=latest this KMS holds, and their chain hashes. +pub(crate) struct Keyring { + roots: Vec, + chain_hashes: Vec<[u8; 32]>, +} + +impl Keyring { + pub(crate) fn load(config: &KmsConfig) -> Result { + let latest = read_root_epoch(config)?; + let roots = (0..=latest) + .map(|epoch| { + RootKeys::load(&config.root_key_paths(epoch)) + .with_context(|| format!("failed to load root keys of epoch {epoch}")) + }) + .collect::>>()?; + let chain_hashes = root_chain_hashes(roots.iter().map(|root| (&root.ca.key, &root.k256))); + Ok(Self { + roots, + chain_hashes, + }) + } + + /// Never empty: [`Self::load`] reads epochs `0..=latest`. + pub(crate) fn latest(&self) -> u32 { + self.roots.len() as u32 - 1 + } + + pub(crate) fn servable_epoch(&self, registry: RootEpochRegistry) -> Result { + servable_epoch(&self.chain_hashes, registry) + } +} + +/// Chain hashes of the root keys of epochs 0, 1, ... +pub(crate) fn root_chain_hashes<'a>( + roots: impl Iterator, +) -> Vec<[u8; 32]> { + let pubkeys: Vec<_> = roots + .map(|(ca, k256)| { + ( + ca.public_key_der(), + k256.verifying_key().to_sec1_bytes().to_vec(), + ) + }) + .collect(); + dstack_types::root_epoch::chain_hashes(pubkeys.iter().map(|(ca, k256)| (&ca[..], &k256[..]))) +} + +/// The epoch a keyring with `chain_hashes` serves under `registry`: the +/// current epoch, which the keyring must hold with a matching chain hash. A +/// keyring nobody registered is servable only at epoch 0, as before root +/// epochs existed. +pub(crate) fn servable_epoch( + chain_hashes: &[[u8; 32]], + registry: RootEpochRegistry, +) -> Result { + let latest = u32::try_from(chain_hashes.len()) + .ok() + .and_then(|len| len.checked_sub(1)) + .context("the keyring holds no root epoch")?; + let current = match registry { + RootEpochRegistry::Unchecked => return Ok(latest), + RootEpochRegistry::Empty if latest == 0 => return Ok(0), + RootEpochRegistry::Empty => { + bail!("the keyring holds root epoch {latest}, but no root epoch is registered") + } + RootEpochRegistry::Current(current) => current, + }; + match chain_hashes.get(current.epoch as usize) { + Some(hash) if *hash == current.chain_hash => Ok(current.epoch), + Some(_) => bail!( + "the root keys up to epoch {} are not the registered ones", + current.epoch + ), + None => bail!( + "root epoch {} is current, but the keyring holds only up to {latest}", + current.epoch + ), + } +} + pub struct KmsStateInner { config: KmsConfig, - root_ca: CaCert, - k256_key: SigningKey, - temp_ca_cert: String, - temp_ca_key: String, + keyring: Keyring, + temp_ca: CaCert, + /// The CA of the running TLS listener, independent of key selection. + rpc_ca_pubkey: Vec, + restart: tokio::sync::Notify, verifier: CvmVerifier, attestation_verifier: Arc, self_boot_info: Cache<(), BootInfo>, - self_allowed: Cache<(), ()>, + self_allowed: Cache, auth_api_info: Cache<(), GetInfoResponse>, + /// App epochs read for the unauthenticated env public key RPCs, so repeated + /// requests for one app do not each reach the auth API. + app_epochs: Cache, u32>, metrics: KmsMetrics, } @@ -86,6 +201,35 @@ pub struct KmsStateInner { pub(crate) struct KmsMetrics { attestation_requests_total: AtomicU64, attestation_failures_total: AtomicU64, + key_releases_total: [AtomicU64; KeyRelease::ALL.len()], +} + +/// A listener and operation that hands out key material. +#[derive(Debug, Clone, Copy)] +pub(crate) enum KeyRelease { + RpcHandover, + AdminHandover, + AppKey, + AppCert, +} + +impl KeyRelease { + const ALL: [Self; 4] = [ + Self::RpcHandover, + Self::AdminHandover, + Self::AppKey, + Self::AppCert, + ]; + + /// The listener and operation labels. + fn labels(self) -> (&'static str, &'static str) { + match self { + Self::RpcHandover => ("rpc", "kms_export_keys"), + Self::AdminHandover => ("admin", "kms_export_keys"), + Self::AppKey => ("rpc", "app_get_key"), + Self::AppCert => ("rpc", "app_get_cert"), + } + } } impl KmsMetrics { @@ -98,9 +242,24 @@ impl KmsMetrics { } } + fn record_key_release(&self, release: KeyRelease) { + self.key_releases_total[release as usize].fetch_add(1, Ordering::Relaxed); + } + pub(crate) fn render_prometheus(&self) -> String { let attestation_requests_total = self.attestation_requests_total.load(Ordering::Relaxed); let attestation_failures_total = self.attestation_failures_total.load(Ordering::Relaxed); + let mut key_releases = String::from( + "# HELP dstack_kms_key_releases_total Total number of key material releases.\n\ + # TYPE dstack_kms_key_releases_total counter\n", + ); + for release in KeyRelease::ALL { + let count = self.key_releases_total[release as usize].load(Ordering::Relaxed); + let (listener, operation) = release.labels(); + key_releases.push_str(&format!( + "dstack_kms_key_releases_total{{listener=\"{listener}\",operation=\"{operation}\"}} {count}\n" + )); + } format!( "# HELP dstack_kms_attestation_requests_total Total number of KMS attestation requests.\n\ @@ -108,66 +267,40 @@ impl KmsMetrics { dstack_kms_attestation_requests_total {attestation_requests_total}\n\ # HELP dstack_kms_attestation_failures_total Total number of failed KMS attestation requests.\n\ # TYPE dstack_kms_attestation_failures_total counter\n\ - dstack_kms_attestation_failures_total {attestation_failures_total}\n" + dstack_kms_attestation_failures_total {attestation_failures_total}\n\ + {key_releases}" ) } } -fn short_lived_cache() -> Cache<(), V> { +fn short_lived_cache(capacity: u64) -> Cache +where + K: Eq + std::hash::Hash + Send + Sync + 'static, + V: Clone + Send + Sync + 'static, +{ Cache::builder() - .max_capacity(1) + .max_capacity(capacity) .time_to_live(AUTH_API_CACHE_TTL) .build() } -/// remove a single cache entry (a hex-named subdir/file) under `parent_dir`, or -/// everything when `sub_dir == "all"`. A non-hex key is rejected to keep the -/// deletion confined to the cache. -fn remove_cache(parent_dir: &Path, sub_dir: &str) -> Result<()> { - if sub_dir.is_empty() { - return Ok(()); - } - if sub_dir == "all" { - if parent_dir.exists() { - fs::remove_dir_all(parent_dir)?; - } - return Ok(()); - } - if !sub_dir.chars().all(|c| c.is_ascii_hexdigit()) { - bail!("invalid cache key"); - } - let path = parent_dir.join(sub_dir); - if path.is_dir() { - fs::remove_dir_all(path)?; - } else if path.is_file() { - fs::remove_file(path)?; - } - Ok(()) -} - impl KmsState { /// clear cached image and measurement material for the given hashes. Used by /// the admin `ClearImageCache` RPC; authorization is enforced by the admin /// listener's HTTP authenticator, not here. pub(crate) fn clear_image_cache(&self, image_hash: &str, config_hash: &str) -> Result<()> { - let images_dir = self.config.image.cache_dir.join("images"); - remove_cache(&images_dir, image_hash).context("failed to clear image cache")?; - // measurement cache is kept by the verifier under measurements/. - let mr_cache_dir = self.config.image.cache_dir.join("measurements"); - remove_cache(&mr_cache_dir, config_hash).context("failed to clear measurement cache")?; - Ok(()) - } - - pub fn new(config: KmsConfig) -> Result { - let root_ca = CaCert::load(config.root_ca_cert(), config.root_ca_key()) - .context("Failed to load root CA certificate")?; - let key_bytes = fs::read(config.k256_key()).context("Failed to read ECDSA root key")?; - let k256_key = - SigningKey::from_slice(&key_bytes).context("Failed to load ECDSA root key")?; - let temp_ca_key = - fs::read_to_string(config.tmp_ca_key()).context("Faeild to read temp ca key")?; - let temp_ca_cert = - fs::read_to_string(config.tmp_ca_cert()).context("Faeild to read temp ca cert")?; + self.verifier.clear_cache(image_hash, config_hash) + } + + pub fn new(config: KmsConfig, keyring: Keyring, rpc_ca_cert: String) -> Result { + let (_, pem) = x509_parser::pem::parse_x509_pem(rpc_ca_cert.as_bytes()) + .context("invalid RPC CA certificate")?; + let rpc_ca_pubkey = pem + .parse_x509() + .context("invalid RPC CA certificate")? + .public_key() + .raw + .to_vec(); let attestation_verifier = Arc::new( AttestationVerifier::load(&config.attestation) .context("failed to load attestation verifier")?, @@ -183,31 +316,36 @@ impl KmsState { "self-authorization is disabled; trusted RPCs will not be gated by KMS self-attestation - do not use in production TEE deployments" ); } - if !config.image.verify { - warn!( - "os image verification is disabled; os_image_hash is caller-supplied and unverified - do not use in production TEE deployments" - ); - } Ok(Self { inner: Arc::new(KmsStateInner { + temp_ca: crate::onboard_service::ensure_temp_ca(&config)?, config, - root_ca, - k256_key, - temp_ca_cert, - temp_ca_key, + keyring, + rpc_ca_pubkey, + restart: tokio::sync::Notify::new(), verifier, attestation_verifier, self_boot_info: Cache::builder() .max_capacity(1) .time_to_live(SELF_BOOT_INFO_TTL) .build(), - self_allowed: short_lived_cache(), - auth_api_info: short_lived_cache(), + self_allowed: short_lived_cache(4), + auth_api_info: short_lived_cache(1), + app_epochs: short_lived_cache(APP_EPOCH_CACHE_CAPACITY), metrics: KmsMetrics::default(), }), }) } + /// The current epoch of an app, cached for [`AUTH_API_CACHE_TTL`]. Failures + /// are not cached. + async fn app_epoch(&self, app_id: &[u8]) -> Result { + self.app_epochs + .try_get_with(app_id.to_vec(), self.config.auth_api.app_epoch(app_id)) + .await + .map_err(|err| anyhow!("{err:#}")) + } + pub(crate) fn metrics(&self) -> &KmsMetrics { &self.inner.metrics } @@ -215,11 +353,164 @@ impl KmsState { pub(crate) fn attestation_verifier(&self) -> Arc { self.inner.attestation_verifier.clone() } + + fn epoch_root(&self, epoch: u32) -> Result<&RootKeys> { + self.keyring + .roots + .get(epoch as usize) + .with_context(|| format!("root epoch {epoch} is not held by this KMS")) + } + + pub async fn restart_requested(&self) { + self.restart.notified().await + } + + async fn current_epoch_from_info(&self) -> Result { + let info = self + .auth_api_info + .try_get_with((), self.config.auth_api.get_info()) + .await + .map_err(|err| anyhow!("{err:#}"))?; + self.keyring.servable_epoch(info.root_epochs) + } + + /// Resolve this request from its authorization result; no serving epoch is cached. + fn authorized_epoch( + &self, + result: &AuthorizationResult, + requested: Option, + ) -> Result { + if !result.authorized { + bail!("Authorization denied: {}", result.rejection_reason); + } + let current = if self.config.auth_api.is_dev() { + self.keyring.latest() + } else { + let current = result + .current_root()? + .context("Root epoch not registered")?; + self.keyring + .servable_epoch(RootEpochRegistry::Current(current))? + }; + let epoch = requested.unwrap_or(current); + if epoch > current { + bail!("root epoch {epoch} is not active; the current one is {current}"); + } + self.epoch_root(epoch)?; + Ok(epoch) + } + + /// Keep the running TLS issuer consistent with default key responses until reload. + fn ensure_rpc_ca(&self, current_epoch: u32) -> Result<()> { + if self.epoch_root(current_epoch)?.ca.key.public_key_der() != self.rpc_ca_pubkey { + self.restart.notify_one(); + bail!("the RPC root CA changed; retry after the TLS certificate is refreshed"); + } + Ok(()) + } +} + +/// Wait for the registered current roots to issue the RPC certificate at startup. +/// An epoch-0 keyring may start while the info endpoint is unreachable, but +/// key release still requires an authorization result with registered roots. +pub(crate) async fn wait_for_servable_epoch(config: &KmsConfig, keyring: &Keyring) -> u32 { + const RETRY: Duration = Duration::from_secs(10); + loop { + let result = match config.auth_api.get_info().await { + Ok(info) => keyring.servable_epoch(info.root_epochs), + Err(err) if keyring.latest() == 0 => { + warn!("skipping the root epoch check: {err:#}"); + return 0; + } + Err(err) => Err(err.context("failed to read the current root epoch")), + }; + match result { + Ok(epoch) => return epoch, + Err(err) => { + warn!("not serving yet: {err:#}; retrying in {}s", RETRY.as_secs()); + tokio::time::sleep(RETRY).await; + } + } + } +} + +struct AppKeys { + disk_crypt_key: Vec, + env_crypt_key: Vec, + k256_key: Vec, + k256_signature: Vec, + sealed_env_key: Vec, +} + +fn derive_sealed_env_key(root: &RootKeys, app_id: &[u8], app_epoch: u32) -> Result<[u8; 32]> { + ensure_app_id_len(app_id)?; + let ca_secret = p256::SecretKey::from_pkcs8_der(root.ca.key.serialized_der())?; + kdf::derive_key_with_salt( + b"dstack-sealed-env-v1", + &ca_secret.to_bytes(), + &[app_id, &app_epoch_context(app_epoch)], + 32, + ) + .map_err(|_| anyhow!("failed to derive sealed env key"))? + .try_into() + .map_err(|_| anyhow!("invalid sealed env key length")) +} + +fn derive_app_keys( + root: &RootKeys, + app_id: &[u8], + instance_id: &[u8], + app_epoch: u32, +) -> Result { + let disk_crypt_key = kdf::derive_dh_secret( + &root.ca.key, + &[ + app_id, + instance_id, + b"app-disk-crypt-key", + &app_epoch_context(app_epoch), + ], + ) + .context("Failed to derive app disk key")?; + let env_crypt_key = kdf::derive_dh_secret( + &root.ca.key, + &[app_id, b"env-encrypt-key", &app_epoch_context(app_epoch)], + ) + .context("Failed to derive env encrypt key")?; + let env_crypt_key = x25519_dalek::StaticSecret::from(env_crypt_key).to_bytes(); + let (k256_key, k256_signature) = + derive_k256_key(&root.k256, app_id, app_epoch).context("Failed to derive app ecdsa key")?; + let sealed_env_key = derive_sealed_env_key(root, app_id, app_epoch)?.to_vec(); + Ok(AppKeys { + disk_crypt_key: disk_crypt_key.to_vec(), + env_crypt_key: env_crypt_key.to_vec(), + k256_key: k256_key.to_bytes().to_vec(), + k256_signature, + sealed_env_key, + }) +} + +/// The attestation of an epoch's root keys; empty if it has none. +pub(crate) fn read_root_attestation(paths: &RootKeyPaths) -> Result> { + match fs::read(&paths.attestation) { + Ok(attestation) => Ok(attestation), + Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()), + Err(err) => Err(err).context("failed to read root key attestation"), + } +} + +pub(crate) fn read_root_epoch(config: &KmsConfig) -> Result { + fs::read_to_string(config.root_epoch()) + .context("failed to read root epoch file")? + .trim() + .parse() + .context("invalid root epoch file") } pub struct RpcHandler { state: KmsState, attestation: Option, + remote_endpoint: Option, } impl RpcHandler { @@ -227,28 +518,133 @@ impl RpcHandler { Self { state: context.state.clone(), attestation: context.attestation, + remote_endpoint: context.remote_endpoint, + } + } + + /// Count a key release and log it, regardless of the metrics setting. + fn audit_key_release( + &self, + release: KeyRelease, + boot_info: &BootInfo, + requested: &str, + returned: &str, + cached: bool, + ) { + self.state.metrics().record_key_release(release); + let (listener, operation) = release.labels(); + info!( + target: "dstack_kms::audit", + listener, + operation, + app_id = %hex::encode(&boot_info.app_id), + instance_id = %instance_id_text(boot_info), + remote = ?self.remote_endpoint, + requested_epoch = requested, + returned_epoch = returned, + cached, + "key release" + ); + } + + /// Log a key request refused after the caller was identified. + fn audit_denial( + &self, + release: KeyRelease, + boot_info: &BootInfo, + result: Result, + ) -> Result { + if let Err(err) = &result { + let (listener, operation) = release.labels(); + warn!( + target: "dstack_kms::audit", + listener, + operation, + app_id = %hex::encode(&boot_info.app_id), + instance_id = %instance_id_text(boot_info), + remote = ?self.remote_endpoint, + error = %ra_rpc::log_text(&format_args!("{err:#}")), + "key release denied" + ); + } + result + } + + fn audit_env_pubkey(&self, operation: &str, app_id: &[u8], result: &Result) { + let app_id = tracing::field::display(hex::encode(app_id)); + match result { + Ok(_) => info!( + target: "dstack_kms::audit", + operation, + app_id, + remote = ?self.remote_endpoint, + "env public key served" + ), + Err(err) => warn!( + target: "dstack_kms::audit", + operation, + app_id, + remote = ?self.remote_endpoint, + error = %ra_rpc::log_text(&format_args!("{err:#}")), + "env public key refused" + ), } } - pub(crate) async fn handover_keys(self, request: GetKmsKeyRequest) -> Result { - self.ensure_self_allowed() + fn self_allowed_cached(&self, operation: Operation) -> bool { + self.state.self_allowed.contains_key(&operation) + } + + pub(crate) async fn handover_keys( + self, + release: KeyRelease, + request: GetKmsKeyRequest, + ) -> Result { + // reject anonymous callers before the self check reaches the backend + let att = self.ensure_attested()?; + let cached = self.self_allowed_cached(Operation::KmsExportKeys); + self.ensure_self_allowed(Operation::KmsExportKeys) .await .context("KMS self authorization failed")?; - let info = self.ensure_kms_allowed(&request.vm_config).await?; - ensure_key_release_allowed(&info, (&self.state.config).into())?; + let auth_api = &self.state.config.auth_api; + let info = auth_api.boot_info(att, false, &request.vm_config).await?; + let result = async { + self.ensure_kms_allowed(att, &info, &request.vm_config, &request.launch_ticket) + .await?; + ensure_key_release_allowed(&info, (&self.state.config).into()) + } + .await; + self.audit_denial(release, &info, result)?; + let returned = format!("root 0..={}", self.state.keyring.latest()); + self.audit_key_release(release, &info, "all", &returned, cached); Ok(KmsKeyResponse { - temp_ca_key: self.state.inner.temp_ca_key.clone(), - keys: vec![KmsKeys { - ca_key: self.state.inner.root_ca.key.serialize_pem(), - k256_key: self.state.inner.k256_key.to_bytes().to_vec(), - }], + temp_ca_key: self.state.temp_ca.key.serialize_pem(), + keys: self + .state + .keyring + .roots + .iter() + .map(|root| KmsKeys { + ca_key: root.ca.key.serialize_pem(), + k256_key: root.k256.to_bytes().to_vec(), + attestation: root.attestation.clone(), + }) + .collect(), }) } } +#[derive(Default)] +struct RequestedAppEpochs { + root: Option, + app: Option, +} + struct BootConfig { boot_info: BootInfo, gateway_app_id: String, + root_epoch: u32, + app_epoch: u32, } pub(crate) fn build_boot_info_for_attestation( @@ -268,6 +664,13 @@ pub(crate) fn build_boot_info_for_attestation( Ok(boot_info) } +fn instance_id_text(boot_info: &BootInfo) -> String { + match &boot_info.instance_id[..] { + [] => "UNKNOWN".to_string(), + id => hex::encode(id), + } +} + /// The per-platform local key-release opt-ins, read from `KmsConfig`. /// /// Carried as a named struct rather than positional bools so that adding a @@ -289,6 +692,27 @@ impl From<&KmsConfig> for KeyReleasePolicy { } } +/// A missing ticket is denied like an unknown one; say which, since an older +/// VMM or guest drops the ticket silently. +fn ensure_ticket_presented( + response: &AuthorizationResult, + launch_ticket: &str, + hint: &str, +) -> Result<()> { + if !response.authorized + && launch_ticket.is_empty() + && response + .rejection_reason + .eq_ignore_ascii_case("invalid launch ticket") + { + bail!( + "Authorization denied: {}: no launch ticket was presented; {hint}", + response.rejection_reason + ); + } + Ok(()) +} + fn ensure_key_release_allowed(boot_info: &BootInfo, policy: KeyReleasePolicy) -> Result<()> { match boot_info.tee_variant { TeeVariant::DstackAmdSevSnp if !policy.snp => { @@ -304,46 +728,45 @@ fn ensure_key_release_allowed(boot_info: &BootInfo, policy: KeyReleasePolicy) -> } } -fn ensure_self_key_release_allowed( - self_boot_info: Option<&BootInfo>, - policy: KeyReleasePolicy, -) -> Result<()> { - if let Some(boot_info) = self_boot_info { - ensure_key_release_allowed(boot_info, policy)?; - } - Ok(()) -} - impl RpcHandler { - async fn ensure_self_allowed(&self) -> Result> { + async fn ensure_self_allowed(&self, operation: Operation) -> Result { if !self.state.config.enforce_self_authorization { - return Ok(None); + let epoch = self.state.current_epoch_from_info().await?; + self.state.ensure_rpc_ca(epoch)?; + return Ok(epoch); } let boot_info = self .state .self_boot_info - .try_get_with((), local_kms_boot_info(&self.state.attestation_verifier)) + .try_get_with( + (), + local_kms_boot_info( + &self.state.config.auth_api, + &self.state.attestation_verifier, + ), + ) .await .map_err(|err| anyhow!("{err:#}")) .context("Failed to load cached self boot info")?; - self.state + let response = self + .state .self_allowed - .try_get_with((), async { + .try_get_with(operation, async { let response = self .state .config .auth_api - .is_app_allowed(&boot_info, true) + .authorize_kms(&boot_info, operation, None, "") .await .context("Failed to call self KMS auth check")?; - if !response.is_allowed { - bail!("KMS is not allowed: {}", response.reason); - } - Ok(()) + let epoch = self.state.authorized_epoch(&response, None)?; + self.state.ensure_rpc_ca(epoch)?; + Ok::<_, anyhow::Error>(response) }) .await .map_err(|err| anyhow!("{err:#}"))?; - Ok(Some(boot_info)) + let epoch = self.state.authorized_epoch(&response, None)?; + Ok(epoch) } fn ensure_attested(&self) -> Result<&VerifiedAttestation> { @@ -353,71 +776,106 @@ impl RpcHandler { Ok(attestation) } - async fn ensure_kms_allowed(&self, vm_config: &str) -> Result { - let att = self.ensure_attested()?; - self.ensure_app_attestation_allowed(att, true, false, vm_config) - .await - .map(|c| c.boot_info) - } - - async fn ensure_app_boot_allowed(&self, vm_config: &str) -> Result { - let att = self.ensure_attested()?; - self.ensure_app_attestation_allowed(att, false, false, vm_config) - .await - } - - async fn verify_os_image_hash( + async fn ensure_kms_allowed( &self, - vm_config: String, - report: &VerifiedAttestation, + att: &VerifiedAttestation, + boot_info: &BootInfo, + vm_config: &str, + launch_ticket: &str, ) -> Result<()> { - if !self.state.config.image.verify { - debug!("os image verification is disabled"); - return Ok(()); - } - let mut detail = VerificationDetails::default(); - self.state - .verifier - .verify_os_image_hash(vm_config, report, &mut detail) + // Handover approval covers the highest exported epoch and all older roots. + let response = self + .state + .config + .auth_api + .authorize_kms( + boot_info, + Operation::KmsImportKeys, + Some(self.state.keyring.latest()), + launch_ticket, + ) + .await?; + ensure_ticket_presented( + &response, + launch_ticket, + "pass this instance's ticket in the Onboard request", + )?; + self.state.authorized_epoch(&response, None)?; + self.ensure_attestation_policy(att, vm_config, boot_info, &response) .await - .context("Failed to verify os image hash")?; - Ok(()) } async fn ensure_app_attestation_allowed( &self, att: &VerifiedAttestation, - is_kms: bool, - use_boottime_mr: bool, - vm_config_str: &str, + boot_info: BootInfo, + vm_config: &str, + launch_ticket: &str, + operation: Operation, + epochs: RequestedAppEpochs, ) -> Result { - let boot_info = build_boot_info_for_attestation(att, use_boottime_mr, vm_config_str)?; let response = self .state .config .auth_api - .is_app_allowed(&boot_info, is_kms) + .authorize_app( + &boot_info, + operation, + epochs.root, + epochs.app, + launch_ticket, + ) .await?; - if !response.is_allowed { - bail!("Boot denied: {}", response.reason); + ensure_ticket_presented( + &response, + launch_ticket, + "check that the VMM and the guest OS support launch tickets", + )?; + let root_epoch = self.state.authorized_epoch(&response, epochs.root)?; + let app_epoch = epochs.app.unwrap_or(response.current_app_epoch); + if app_epoch > response.current_app_epoch { + bail!("requested app epoch is not active"); } + self.ensure_attestation_policy(att, vm_config, &boot_info, &response) + .await?; + Ok(BootConfig { + boot_info, + gateway_app_id: response.gateway_app_id, + root_epoch, + app_epoch, + }) + } + + async fn ensure_attestation_policy( + &self, + att: &VerifiedAttestation, + vm_config: &str, + boot_info: &BootInfo, + response: &AuthorizationResult, + ) -> Result<()> { + let current_epoch = if self.state.config.auth_api.is_dev() { + self.state.keyring.latest() + } else { + response.current_root_epoch + }; + self.state.ensure_rpc_ca(current_epoch)?; // SNP rootfs/app/config binding is handled by the SNP launch-measurement // helper above. The legacy OS-image verifier is TDX-oriented and still // rejects SNP quotes; keep SNP on the explicit fail-closed helper path. if boot_info.tee_variant != TeeVariant::DstackAmdSevSnp { - self.verify_os_image_hash(vm_config_str.into(), att) + self.state + .verifier + .verify_os_image_hash(vm_config.into(), att, &mut VerificationDetails::default()) .await .context("Failed to verify os image hash")?; } - Ok(BootConfig { - boot_info, - gateway_app_id: response.gateway_app_id, - }) + Ok(()) } - fn derive_app_ca(&self, app_id: &[u8]) -> Result { - let context_data = vec![app_id, b"app-ca"]; - let app_key = kdf::derive_p256_key_pair(&self.state.root_ca.key, &context_data) + fn derive_app_ca(&self, app_id: &[u8], root: &RootKeys, app_epoch: u32) -> Result { + let epoch_context = app_epoch_context(app_epoch); + let context_data = vec![app_id, b"app-ca", epoch_context.as_slice()]; + let app_key = kdf::derive_p256_key_pair(&root.ca.key, &context_data) .context("Failed to derive app disk key")?; let req = CertRequest::builder() .key(&app_key) @@ -427,11 +885,7 @@ impl RpcHandler { .app_id(app_id) .special_usage("app:ca") .build(); - let app_ca = self - .state - .root_ca - .sign(req) - .context("Failed to sign App CA")?; + let app_ca = root.ca.sign(req).context("Failed to sign App CA")?; Ok(CaCert::from_parts(app_key, app_ca)) } } @@ -441,162 +895,221 @@ impl KmsRpc for RpcHandler { if request.api_version > 1 { bail!("Unsupported API version: {}", request.api_version); } - self.ensure_self_allowed() + // reject anonymous callers before the self check reaches the backend + let att = self.ensure_attested()?; + let cached = self.self_allowed_cached(Operation::KmsServe); + self.ensure_self_allowed(Operation::KmsServe) .await .context("KMS self authorization failed")?; - let BootConfig { - boot_info, - gateway_app_id, - } = self - .ensure_app_boot_allowed(&request.vm_config) - .await - .context("App not allowed")?; - ensure_key_release_allowed(&boot_info, (&self.state.config).into())?; - let app_id = boot_info.app_id; - let instance_id = boot_info.instance_id; - let os_image_hash = boot_info.os_image_hash; - - let context_data = vec![&app_id[..], &instance_id[..], b"app-disk-crypt-key"]; - let app_disk_key = kdf::derive_dh_secret(&self.state.root_ca.key, &context_data) - .context("Failed to derive app disk key")?; - let env_crypt_key = { - let secret = - kdf::derive_dh_secret(&self.state.root_ca.key, &[&app_id[..], b"env-encrypt-key"]) - .context("Failed to derive env encrypt key")?; - let secret = x25519_dalek::StaticSecret::from(secret); - secret.to_bytes() - }; - - let (k256_key, k256_signature) = { - let (k256_app_key, signature) = derive_k256_key(&self.state.k256_key, &app_id) - .context("Failed to derive app ecdsa key")?; - (k256_app_key.to_bytes().to_vec(), signature) - }; + let auth_api = &self.state.config.auth_api; + let boot_info = auth_api.boot_info(att, false, &request.vm_config).await?; + let result = async { + let BootConfig { + boot_info, + gateway_app_id, + root_epoch, + app_epoch, + } = self + .ensure_app_attestation_allowed( + att, + boot_info.clone(), + &request.vm_config, + &request.launch_ticket, + Operation::AppGetKey, + RequestedAppEpochs { + root: request.root_epoch, + app: request.app_epoch, + }, + ) + .await + .context("App not allowed")?; + ensure_key_release_allowed(&boot_info, (&self.state.config).into())?; + let root = self.state.epoch_root(root_epoch)?; + let keys = derive_app_keys(root, &boot_info.app_id, &boot_info.instance_id, app_epoch)?; + let epoch = |epoch: Option| epoch.map_or("current".into(), |e| e.to_string()); + self.audit_key_release( + KeyRelease::AppKey, + &boot_info, + &format!( + "root {} app {}", + epoch(request.root_epoch), + epoch(request.app_epoch) + ), + &format!("root {root_epoch} app {app_epoch}"), + cached, + ); - Ok(AppKeyResponse { - ca_cert: self.state.root_ca.pem_cert.clone(), - disk_crypt_key: app_disk_key.to_vec(), - env_crypt_key: env_crypt_key.to_vec(), - k256_key, - k256_signature, - tproxy_app_id: gateway_app_id.clone(), - gateway_app_id, - os_image_hash, - }) + Ok(AppKeyResponse { + ca_cert: root.ca.pem_cert.clone(), + disk_crypt_key: keys.disk_crypt_key, + env_crypt_key: keys.env_crypt_key, + k256_key: keys.k256_key, + k256_signature: keys.k256_signature, + tproxy_app_id: gateway_app_id.clone(), + gateway_app_id, + os_image_hash: boot_info.os_image_hash, + root_epoch, + sealed_env_key: keys.sealed_env_key, + app_epoch, + }) + } + .await; + self.audit_denial(KeyRelease::AppKey, &boot_info, result) } async fn get_app_env_encrypt_pub_key(self, request: AppId) -> Result { - self.ensure_self_allowed() - .await - .context("KMS self authorization failed")?; ensure_app_id_len(&request.app_id)?; - let secret = kdf::derive_dh_secret( - &self.state.root_ca.key, - &[&request.app_id[..], "env-encrypt-key".as_bytes()], - ) - .context("Failed to derive env encrypt key")?; - let secret = x25519_dalek::StaticSecret::from(secret); - let pubkey = x25519_dalek::PublicKey::from(&secret); - - let public_key = pubkey.to_bytes().to_vec(); - let timestamp = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .context("System time before UNIX epoch")? - .as_secs(); - - // Legacy signature (without timestamp) for backward compatibility - let signature = sign_message( - &self.state.k256_key, - b"dstack-env-encrypt-pubkey", - &request.app_id, - &public_key, - ) - .context("Failed to sign the public key")?; - - // New signature with timestamp to prevent replay attacks - let signature_v1 = sign_message_with_timestamp( - &self.state.k256_key, - b"dstack-env-encrypt-pubkey", - &request.app_id, - timestamp, - &public_key, - ) - .context("Failed to sign the public key with timestamp")?; + let result = async { + let epoch = self + .ensure_self_allowed(Operation::KmsServe) + .await + .context("KMS self authorization failed")?; + let root = self.state.epoch_root(epoch)?; + let app_epoch = self.state.app_epoch(&request.app_id).await?; + if app_epoch != 0 { + bail!("epoch-aware applications must use GetSealedEnvPubKey"); + } + let secret = + kdf::derive_dh_secret(&root.ca.key, &[&request.app_id[..], b"env-encrypt-key"]) + .context("Failed to derive env encrypt key")?; + let secret = x25519_dalek::StaticSecret::from(secret); + let pubkey = x25519_dalek::PublicKey::from(&secret); + + let public_key = pubkey.to_bytes().to_vec(); + let timestamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .context("System time before UNIX epoch")? + .as_secs(); + + // Legacy signature (without timestamp) for backward compatibility + let signature = sign_message( + &root.k256, + b"dstack-env-encrypt-pubkey", + &request.app_id, + &public_key, + ) + .context("Failed to sign the public key")?; + + // New signature with timestamp to prevent replay attacks + let signature_v1 = sign_message_with_timestamp( + &root.k256, + b"dstack-env-encrypt-pubkey", + &request.app_id, + timestamp, + &public_key, + ) + .context("Failed to sign the public key with timestamp")?; + + Ok(PublicKeyResponse { + public_key, + signature, + timestamp, + signature_v1, + }) + } + .await; + self.audit_env_pubkey("app_env_encrypt_pubkey", &request.app_id, &result); + result + } - Ok(PublicKeyResponse { - public_key, - signature, - timestamp, - signature_v1, - }) + async fn get_sealed_env_pub_key(self, request: AppId) -> Result { + ensure_app_id_len(&request.app_id)?; + let result = async { + let epoch = self.ensure_self_allowed(Operation::KmsServe).await?; + let root = self.state.epoch_root(epoch)?; + let app_epoch = self.state.app_epoch(&request.app_id).await?; + let secret = derive_sealed_env_key(root, &request.app_id, app_epoch)?; + let public_key = + x25519_dalek::PublicKey::from(&x25519_dalek::StaticSecret::from(secret)).to_bytes(); + let timestamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .context("system time before UNIX epoch")? + .as_secs(); + let mut message = Vec::with_capacity(8 + 32 + 8); + message.extend_from_slice(&epoch.to_be_bytes()); + message.extend_from_slice(&app_epoch.to_be_bytes()); + message.extend_from_slice(&public_key); + message.extend_from_slice(×tamp.to_be_bytes()); + let signature = sign_message( + &root.k256, + b"dstack-sealed-env-pubkey-v1", + &request.app_id, + &message, + )?; + Ok(SealedEnvPubKeyResponse { + public_key: public_key.to_vec(), + root_epoch: epoch, + app_epoch, + timestamp, + signature, + }) + } + .await; + self.audit_env_pubkey("app_sealed_env_pubkey", &request.app_id, &result); + result } async fn get_meta(self) -> Result { - let bootstrap_info = fs::read_to_string(self.state.config.bootstrap_info()) - .ok() - .and_then(|s| serde_json::from_str(&s).ok()); let info = self .state .auth_api_info .try_get_with((), self.state.config.auth_api.get_info()) .await .map_err(|err| anyhow!("{err:#}"))?; + let epoch = self.state.keyring.servable_epoch(info.root_epochs)?; + let root = self.state.epoch_root(epoch)?; + let k256_pubkey = root.k256.verifying_key().to_sec1_bytes().to_vec(); + let bootstrap_info = (!root.attestation.is_empty()).then(|| BootstrapResponse { + ca_pubkey: root.ca.key.public_key_der(), + k256_pubkey: k256_pubkey.clone(), + attestation: root.attestation.clone(), + }); Ok(GetMetaResponse { - ca_cert: self.state.inner.root_ca.pem_cert.clone(), + ca_cert: root.ca.pem_cert.clone(), allow_any_upgrade: self.state.inner.config.auth_api.is_dev(), - k256_pubkey: self - .state - .inner - .k256_key - .verifying_key() - .to_sec1_bytes() - .to_vec(), + k256_pubkey, bootstrap_info, is_dev: self.state.config.auth_api.is_dev(), kms_contract_address: info.kms_contract_address, chain_id: info.chain_id, gateway_app_id: info.gateway_app_id, app_auth_implementation: info.app_implementation, - os_image_verification: Some(self.state.config.image.verify), + os_image_verification: Some(true), + auth_api_info: info.auth_api_info, }) } async fn get_kms_key(self, request: GetKmsKeyRequest) -> Result { if !self.state.config.onboard.public_key_handover { - bail!("public KMS key handover is disabled; use the admin listener"); + bail!( + "public KMS key handover is disabled; onboard through the admin listener with \ + the source admin token, or set core.onboard.public_key_handover = true" + ); } - self.handover_keys(request).await - } - - /// Serve the temp CA certificate and key. - /// - /// Both current callers - guests at boot, and KMS-to-KMS onboarding - /// ([`crate::onboard_service`]) - fetch this CA and mint their client certificate - /// from it, because the KMS used to pin the CA for mutual TLS and a self-issued - /// certificate had nothing to chain to. - /// - /// That pin is gone: client certificates are now verified by the attestation they - /// carry (`ra_rpc::ratls_client_verifier`), so a self-issued certificate would be - /// accepted on the same terms. Neither caller has been migrated yet, so this RPC - /// still has to work. - /// - /// The key it returns authenticates nobody: it is handed to any caller. Removing - /// this RPC needs both callers migrated first. + self.handover_keys(KeyRelease::RpcHandover, request).await + } + async fn get_temp_ca_cert(self) -> Result { - let self_boot_info = self - .ensure_self_allowed() - .await - .context("KMS self authorization failed")?; - ensure_self_key_release_allowed(self_boot_info.as_ref(), (&self.state.config).into())?; + let epoch = self.ensure_self_allowed(Operation::KmsServe).await?; + if self.state.config.enforce_self_authorization { + let boot_info = self + .state + .self_boot_info + .get(&()) + .await + .context("missing authorized KMS boot info")?; + ensure_key_release_allowed(&boot_info, (&self.state.config).into())?; + } Ok(GetTempCaCertResponse { - temp_ca_cert: self.state.inner.temp_ca_cert.clone(), - temp_ca_key: self.state.inner.temp_ca_key.clone(), - ca_cert: self.state.inner.root_ca.pem_cert.clone(), + temp_ca_cert: self.state.temp_ca.pem_cert.clone(), + temp_ca_key: self.state.temp_ca.key.serialize_pem(), + ca_cert: self.state.epoch_root(epoch)?.ca.pem_cert.clone(), }) } async fn sign_cert(self, request: SignCertRequest) -> Result { - self.ensure_self_allowed() + let cached = self.self_allowed_cached(Operation::KmsServe); + self.ensure_self_allowed(Operation::KmsServe) .await .context("KMS self authorization failed")?; let csr = match request.api_version { @@ -623,26 +1136,50 @@ impl KmsRpc for RpcHandler { .verify_with_ra_pubkey(&csr.pubkey, &self.state.attestation_verifier) .await .context("Quote verification failed")?; - let app_info = self - .ensure_app_attestation_allowed(&attestation, false, true, &request.vm_config) + let auth_api = &self.state.config.auth_api; + let boot_info = auth_api + .boot_info(&attestation, true, &request.vm_config) .await?; - ensure_key_release_allowed(&app_info.boot_info, (&self.state.config).into())?; - let app_ca = self.derive_app_ca(&app_info.boot_info.app_id)?; - // Stamp the identity verified above, not the requester's own claims. - // Runtime measurements (`false`) are what certificates have always carried. - let cert_app_info = attestation - .decode_app_info_ex(false, &request.vm_config) - .context("Failed to decode the verified app info")?; - let cert = app_ca - .sign_csr(&csr, Some(&cert_app_info), "app:custom") - .context("Failed to sign certificate")?; - Ok(SignCertResponse { - certificate_chain: vec![ - cert.pem(), - app_ca.pem_cert.clone(), - self.state.root_ca.pem_cert.clone(), - ], - }) + let result = async { + let app_info = self + .ensure_app_attestation_allowed( + &attestation, + boot_info.clone(), + &request.vm_config, + &request.launch_ticket, + Operation::AppGetCert, + RequestedAppEpochs::default(), + ) + .await?; + ensure_key_release_allowed(&app_info.boot_info, (&self.state.config).into())?; + let root = self.state.epoch_root(app_info.root_epoch)?; + let app_ca = + self.derive_app_ca(&app_info.boot_info.app_id, root, app_info.app_epoch)?; + // Stamp the identity verified above, not the requester's own claims. + // Runtime measurements (`false`) are what certificates have always carried. + let cert_app_info = attestation + .decode_app_info_ex(false, &request.vm_config) + .context("Failed to decode the verified app info")?; + let cert = app_ca + .sign_csr(&csr, Some(&cert_app_info), "app:custom") + .context("Failed to sign certificate")?; + self.audit_key_release( + KeyRelease::AppCert, + &app_info.boot_info, + "current", + &format!("root {} app {}", app_info.root_epoch, app_info.app_epoch), + cached, + ); + Ok(SignCertResponse { + certificate_chain: vec![ + cert.pem(), + app_ca.pem_cert.clone(), + root.ca.pem_cert.clone(), + ], + }) + } + .await; + self.audit_denial(KeyRelease::AppCert, &boot_info, result) } } @@ -666,7 +1203,14 @@ mod tests { }; use cc_eventlog::RuntimeEvent; use sha2::{Digest, Sha256, Sha384}; - use std::time::Duration; + use std::{path::Path, time::Duration}; + + #[test] + fn an_empty_keyring_serves_no_epoch() { + for registry in [RootEpochRegistry::Unchecked, RootEpochRegistry::Empty] { + assert!(servable_epoch(&[], registry).is_err()); + } + } const SNP_ENABLED: KeyReleasePolicy = KeyReleasePolicy { snp: true, @@ -679,28 +1223,6 @@ mod tests { nitro_enclave: true, }; - #[test] - fn remove_cache_only_deletes_the_named_hex_entry() { - let dir = tempfile::tempdir().unwrap(); - let root = dir.path(); - let keep = root.join("cafe"); - let drop = root.join("beef"); - fs::create_dir_all(&keep).unwrap(); - fs::create_dir_all(&drop).unwrap(); - - remove_cache(root, "beef").unwrap(); - assert!(!drop.exists(), "named entry must be removed"); - assert!(keep.exists(), "other entries must be kept"); - - // empty key is a no-op; a non-hex key is rejected before touching disk. - remove_cache(root, "").unwrap(); - assert!(remove_cache(root, "../escape").is_err()); - assert!(keep.exists()); - - // "all" clears the whole cache dir. - remove_cache(root, "all").unwrap(); - assert!(!root.exists()); - } use std::collections::BTreeMap; fn hex_of(byte: u8, len: usize) -> String { @@ -779,12 +1301,16 @@ mod tests { config, report: ra_tls::attestation::DstackVerifiedReport::DstackAmdSevSnp( dstack_attest::amd_sev_snp::VerifiedAmdSnpReport { + cpuid: Some(dstack_attest::amd_sev_snp::AmdSnpCpuid::from_eax( + 0x00a0_0f11, + )), measurement, report_data: [0x42; 64], host_data: mr_config.to_snp_host_data(), chip_id, tcb_info: dstack_attest::amd_sev_snp::AmdSnpTcbInfo::default(), - advisory_ids: Vec::new(), + // This KMS lists no minimum of its own. + tcb_status: String::new(), }, ), } @@ -961,6 +1487,29 @@ mod tests { } } + #[test] + fn a_denial_for_a_missing_ticket_says_none_was_presented() { + let denied = |reason: &str| AuthorizationResult { + authorized: false, + rejection_reason: reason.into(), + gateway_app_id: String::new(), + current_root_epoch: 0, + current_app_epoch: 0, + current_root_epoch_hash: String::new(), + latest_root_epoch: 0, + latest_root_epoch_hash: String::new(), + }; + let err = ensure_ticket_presented(&denied("Invalid launch ticket"), "", "hint") + .unwrap_err() + .to_string(); + assert!( + err.contains("no launch ticket was presented; hint"), + "{err}" + ); + // A presented ticket, or another denial, keeps the backend's reason alone. + assert!(ensure_ticket_presented(&denied("invalid launch ticket"), "t", "hint").is_ok()); + assert!(ensure_ticket_presented(&denied("Compose hash not allowed"), "", "hint").is_ok()); + } #[test] fn build_boot_info_for_attestation_binds_aws_nitro_tpm_app_measurement() { let (attestation, vm_config, os_image_hash, key_provider_info) = @@ -1219,6 +1768,78 @@ mod tests { build_boot_info_for_attestation(&attestation, false, &vm_config).unwrap() } + #[rocket::async_test] + async fn sev_snp_tcb_is_judged_against_governances_requirements() { + use ra_tls::attestation::DstackVerifiedReport; + use serde_json::json; + use upgrade_authority::tests::{serve_with_status, webhook}; + + let input = valid_snp_measurement_input(); + let measurement = compute_expected_measurement(&input).unwrap(); + // A Milan (`00a00f11`) whose TCB is all zeros, with the verdict of this + // KMS's own list: none, met or unmet. + let attestation = |own: &str| { + let mut attestation = verified_snp_attestation(measurement, [0xab; 64]); + let DstackVerifiedReport::DstackAmdSevSnp(report) = &mut attestation.report else { + panic!("not an SEV-SNP attestation"); + }; + report.tcb_status = own.into(); + attestation + }; + let vm_config = snp_vm_config(&input, &valid_snp_mr_config()); + let published = |cpuid: &str, bootloader: u8| { + let requirements = json!([{ + "cpuid": cpuid, "bootloader": bootloader, "tee": 0, "snp": 0, "microcode": 0, + }]); + let body = json!({ "requirements": requirements.to_string() }); + (200, body.to_string()) + }; + let none = || (200, json!({ "requirements": "" }).to_string()); + let unparsable = (200, json!({ "requirements": "[{}]" }).to_string()); + let unlisted = Err("no minimum TCB is listed for CPUID 00a00f11"); + // Each case has its own backend: the list is cached per backend. + for (own, response, expected) in [ + ("", published("00a00f11", 0), Ok("UpToDate")), + ("", published("00a00f11", 1), Ok("OutOfDate")), + // A report nothing can judge is refused, not called out of date. + ("", published("00a00f12", 0), unlisted), + ("", none(), unlisted), + // This KMS's list covers a CPU governance does not name, and + // gives way where it does. + ("UpToDate", none(), Ok("UpToDate")), + ("OutOfDate", published("00a00f12", 0), Ok("OutOfDate")), + ("UpToDate", published("00a00f11", 1), Ok("OutOfDate")), + ("OutOfDate", published("00a00f11", 0), Ok("UpToDate")), + // The auth API must answer, whatever this KMS lists. + ("UpToDate", (404, String::new()), Err("returned 404")), + ("UpToDate", (503, String::new()), Err("returned 503")), + ("UpToDate", unparsable, Err("missing field")), + ] { + let (url, server) = serve_with_status(vec![response]); + let judged = webhook(url) + .boot_info(&attestation(own), false, &vm_config) + .await; + match (judged, expected) { + (Ok(info), Ok(status)) => assert_eq!(info.tcb_status, status), + (Err(err), Err(reason)) => { + let err = format!("{err:#}"); + assert!(err.contains(reason), "{err}"); + } + (judged, expected) => panic!("expected {expected:?}, got {judged:?}"), + } + assert_eq!(server.join().unwrap()[0].0, "/sevSnpTcbRequirements"); + } + + // The dev backend publishes none and leaves the verifier's status. + let dev = crate::config::Dev { + gateway_app_id: String::new(), + }; + let dev = crate::config::AuthApi::Dev { dev }; + let attestation = attestation("UpToDate"); + let info = dev.boot_info(&attestation, false, &vm_config).await; + assert_eq!(info.unwrap().tcb_status, "UpToDate"); + } + #[test] fn snp_key_release_requires_explicit_enablement() { let boot_info = snp_boot_info(); @@ -1250,16 +1871,6 @@ mod tests { .expect("TCB/advisory policy should be decided by the auth API, not this local gate"); } - #[test] - fn snp_self_boot_info_uses_same_release_policy_for_temp_ca() { - let boot_info = snp_boot_info(); - - ensure_self_key_release_allowed(Some(&boot_info), KeyReleasePolicy::default()) - .expect_err("disabled SNP self boot info must not receive temp CA key material"); - ensure_self_key_release_allowed(Some(&boot_info), SNP_ENABLED) - .expect("enabled clean SNP self boot info should pass the temp CA release gate"); - } - #[test] fn nitro_enclave_key_release_requires_explicit_enablement() { let mut boot_info = snp_boot_info(); @@ -1277,13 +1888,6 @@ mod tests { // explicitly enabled permits it ensure_key_release_allowed(&boot_info, NITRO_ENCLAVE_ENABLED) .expect("explicitly enabled nitro enclave key release should allow the boot info"); - - // the temp CA path uses the same gate - ensure_self_key_release_allowed(Some(&boot_info), KeyReleasePolicy::default()).expect_err( - "disabled nitro enclave self boot info must not receive temp CA key material", - ); - ensure_self_key_release_allowed(Some(&boot_info), NITRO_ENCLAVE_ENABLED) - .expect("enabled nitro enclave self boot info should pass the temp CA release gate"); } #[test] @@ -1359,29 +1963,23 @@ mod tests { .build() .self_signed() .unwrap(); - let tmp_ca_key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap(); - let tmp_ca_cert = CertRequest::builder() - .org_name("Dstack") - .subject("Dstack Client Temp CA") - .ca_level(0) - .key(&tmp_ca_key) - .build() - .self_signed() - .unwrap(); - fs::write(cert_dir.join("root-ca.key"), ca_key.serialize_pem()).unwrap(); - fs::write(cert_dir.join("root-ca.crt"), ca_cert.pem()).unwrap(); - fs::write(cert_dir.join("tmp-ca.key"), tmp_ca_key.serialize_pem()).unwrap(); - fs::write(cert_dir.join("tmp-ca.crt"), tmp_ca_cert.pem()).unwrap(); + let keyring_dir = cert_dir.join("keyring"); + let root_dir = keyring_dir.join("epochs/0"); + fs::create_dir_all(&root_dir).unwrap(); + fs::write(root_dir.join("root-ca.key"), ca_key.serialize_pem()).unwrap(); + fs::write(root_dir.join("root-ca.crt"), ca_cert.pem()).unwrap(); fs::write( - cert_dir.join("root-k256.key"), + root_dir.join("root-k256.key"), SigningKey::random(&mut rand::rngs::OsRng).to_bytes(), ) .unwrap(); + fs::write(keyring_dir.join("root-epoch"), "0").unwrap(); let overrides = format!( r#" [core] cert_dir = "{}" + keyring_dir = "{}" attest_rpc_cert = false enforce_self_authorization = false @@ -1395,6 +1993,7 @@ mod tests { url = "{webhook_url}" "#, cert_dir.display(), + keyring_dir.display(), cert_dir.display(), ); let config: KmsConfig = Figment::from(rocket::Config::default()) @@ -1403,11 +2002,803 @@ mod tests { .focus("core") .extract() .unwrap(); - KmsState::new(config).unwrap() + let keyring = Keyring::load(&config).unwrap(); + KmsState::new(config, keyring, ca_cert.pem()).unwrap() + } + + #[test] + fn sealed_env_derivation_is_separate_and_shared_with_app_keys() { + let dir = tempfile::tempdir().unwrap(); + let state = kms_state(dir.path(), "http://127.0.0.1:1"); + let root = state.epoch_root(0).unwrap(); + let app = [1; 20]; + let sealed = derive_sealed_env_key(root, &app, 0).unwrap(); + let app_keys = derive_app_keys(root, &app, &[2; 20], 0).unwrap(); + assert_eq!(sealed.as_slice(), app_keys.sealed_env_key); + assert_ne!(sealed.as_slice(), app_keys.env_crypt_key); + assert_ne!(sealed.as_slice(), app_keys.disk_crypt_key); + assert_ne!(sealed, derive_sealed_env_key(root, &[3; 20], 0).unwrap()); + assert!(derive_sealed_env_key(root, &[1; 19], 0).is_err()); + } + + #[test] + fn app_epoch_derivation_is_separate_and_epoch_zero_is_unchanged() { + let dir = tempfile::tempdir().unwrap(); + let state = kms_state(dir.path(), "http://127.0.0.1:1"); + let root = state.epoch_root(0).unwrap(); + let app = [1; 20]; + let instance = [2; 20]; + let zero = derive_app_keys(root, &app, &instance, 0).unwrap(); + assert_eq!( + zero.disk_crypt_key, + kdf::derive_dh_secret(&root.ca.key, &[&app, &instance, b"app-disk-crypt-key"]).unwrap() + ); + assert_eq!( + zero.env_crypt_key, + x25519_dalek::StaticSecret::from( + kdf::derive_dh_secret(&root.ca.key, &[&app, b"env-encrypt-key"]).unwrap() + ) + .to_bytes() + ); + for epoch in [1, 2, u32::MAX] { + let rotated = derive_app_keys(root, &app, &instance, epoch).unwrap(); + let again = derive_app_keys(root, &app, &instance, epoch).unwrap(); + assert_eq!(rotated.disk_crypt_key, again.disk_crypt_key); + assert_ne!(zero.disk_crypt_key, rotated.disk_crypt_key); + assert_ne!(zero.env_crypt_key, rotated.env_crypt_key); + assert_ne!(zero.sealed_env_key, rotated.sealed_env_key); + assert_ne!(zero.k256_key, rotated.k256_key); + } + assert_ne!( + derive_app_keys(root, &app, &instance, 1).unwrap().k256_key, + derive_app_keys(root, &app, &instance, 2).unwrap().k256_key + ); + } + + /// The keyring in `config.keyring_dir` with a second root epoch appended. + fn rotated_keyring(config: &KmsConfig) -> Keyring { + let mut keyring = Keyring::load(config).unwrap(); + let key = KeyPair::generate_for(&ra_tls::rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); + let cert = CertRequest::builder() + .key(&key) + .subject("Root epoch 1") + .ca_level(1) + .build() + .self_signed() + .unwrap(); + keyring.roots.push(RootKeys { + ca: CaCert::from_parts(key, cert), + k256: SigningKey::random(&mut rand::rngs::OsRng), + attestation: Vec::new(), + }); + keyring.chain_hashes = + root_chain_hashes(keyring.roots.iter().map(|root| (&root.ca.key, &root.k256))); + keyring + } + + #[rocket::async_test] + async fn authorization_selects_epochs_without_a_serving_epoch_snapshot() { + let dir = tempfile::tempdir().unwrap(); + let initial = kms_state(dir.path(), "http://127.0.0.1:1"); + let keyring = rotated_keyring(&initial.config); + let state = KmsState::new( + initial.config.clone(), + keyring, + initial.keyring.roots[0].ca.pem_cert.clone(), + ) + .unwrap(); + let result = |epoch: u32| AuthorizationResult { + authorized: true, + rejection_reason: String::new(), + gateway_app_id: String::new(), + current_root_epoch: epoch, + current_app_epoch: 0, + current_root_epoch_hash: hex::encode(state.keyring.chain_hashes[epoch as usize]), + latest_root_epoch: epoch, + latest_root_epoch_hash: hex::encode(state.keyring.chain_hashes[epoch as usize]), + }; + assert_eq!(state.authorized_epoch(&result(0), None).unwrap(), 0); + assert!(state.authorized_epoch(&result(0), Some(1)).is_err()); + assert_eq!(state.authorized_epoch(&result(1), None).unwrap(), 1); + assert_eq!(state.authorized_epoch(&result(1), Some(0)).unwrap(), 0); + assert_eq!(state.authorized_epoch(&result(1), Some(1)).unwrap(), 1); + assert!(state.authorized_epoch(&result(1), Some(u32::MAX)).is_err()); + // Key selection already follows epoch 1; only the TLS listener needs refreshing. + assert!(state.ensure_rpc_ca(1).is_err()); + assert!( + tokio::time::timeout(Duration::from_millis(10), state.restart_requested()) + .await + .is_ok() + ); + assert_eq!(state.rpc_ca_pubkey, initial.rpc_ca_pubkey); + + let mut rejected = result(1); + rejected.authorized = false; + rejected.rejection_reason = "Policy denied".into(); + assert!(state.authorized_epoch(&rejected, Some(0)).is_err()); + rejected.authorized = true; + for hash in [ + "invalid".into(), + hex::encode([0; 32]), + hex::encode([0x55; 32]), + ] { + rejected.current_root_epoch_hash = hash; + assert!(state.authorized_epoch(&rejected, None).is_err()); + } + // A rejection is reported even when the epoch fields do not match. + rejected.authorized = false; + let err = state.authorized_epoch(&rejected, None).unwrap_err(); + assert!(err.to_string().contains("Policy denied"), "{err}"); + let mut missing = result(1); + missing.current_root_epoch = u32::MAX; + assert!(state.authorized_epoch(&missing, Some(0)).is_err()); + assert!(state.epoch_root(u32::MAX).is_err()); } const AUTH_API_INFO: &str = r#"{"status":"ok","kmsContractAddr":"0xkms","ethRpcUrl":"https://rpc.example","gatewayAppId":"0xgateway","chainId":1,"appImplementation":"0ximpl"}"#; + #[rocket::async_test] + async fn self_authorization_cache_cannot_authorize_a_different_operation() { + use upgrade_authority::tests::{boot_info, serve}; + let dir = tempfile::tempdir().unwrap(); + let initial = kms_state(dir.path(), "http://127.0.0.1:1"); + let response = |allowed| { + serde_json::json!({ + "authorized": allowed, "rejectionReason": "export denied", "gatewayAppId": "", + "currentRootEpoch": 0, "currentAppEpoch": 0, + "currentRootEpochHash": hex::encode(initial.keyring.chain_hashes[0]), + "latestRootEpoch": 0, + "latestRootEpochHash": hex::encode(initial.keyring.chain_hashes[0]), + }) + .to_string() + }; + let (url, server) = serve(vec![response(true), response(false)]); + let mut config = initial.config.clone(); + config.enforce_self_authorization = true; + config.auth_api = upgrade_authority::tests::webhook(url); + let keyring = Keyring::load(&config).unwrap(); + let state = KmsState::new( + config, + keyring, + initial.epoch_root(0).unwrap().ca.pem_cert.clone(), + ) + .unwrap(); + state.self_boot_info.insert((), boot_info(1)).await; + let handler = RpcHandler { + state, + attestation: None, + remote_endpoint: None, + }; + assert_eq!( + handler + .ensure_self_allowed(Operation::KmsServe) + .await + .unwrap(), + 0 + ); + assert!(handler + .ensure_self_allowed(Operation::KmsExportKeys) + .await + .is_err()); + assert_eq!( + handler + .ensure_self_allowed(Operation::KmsServe) + .await + .unwrap(), + 0 + ); + let requests = server.join().unwrap(); + assert_eq!(requests[0].1["operation"], "kms_serve"); + assert_eq!(requests[1].1["operation"], "kms_export_keys"); + } + + /// An SNP caller, which skips the OS image download in the attestation policy. + fn snp_caller() -> (VerifiedAttestation, String) { + let input = valid_snp_measurement_input(); + let measurement = compute_expected_measurement(&input).unwrap(); + let mr_config = valid_snp_mr_config(); + let vm_config = snp_vm_config(&input, &mr_config); + let attestation = verified_snp_attestation_with_config( + measurement, + [0xab; 64], + vm_config.clone(), + &mr_config, + ); + (attestation, vm_config) + } + + fn auth_answer(state: &KmsState, allowed: bool) -> String { + epoch_answer(&state.keyring, allowed, 0, 0) + } + + fn epoch_answer(keyring: &Keyring, allowed: bool, root_epoch: u32, app_epoch: u32) -> String { + let hash = hex::encode(keyring.chain_hashes[root_epoch as usize]); + serde_json::json!({ + "authorized": allowed, "rejectionReason": "denied", "gatewayAppId": "", + "currentRootEpoch": root_epoch, "currentAppEpoch": app_epoch, + "currentRootEpochHash": hash, + "latestRootEpoch": root_epoch, "latestRootEpochHash": hash, + }) + .to_string() + } + + /// Wait for the auth API requests; a missing request fails instead of hanging. + fn auth_requests( + server: std::thread::JoinHandle>, + ) -> Vec<(String, serde_json::Value)> { + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || tx.send(server.join().unwrap())); + rx.recv_timeout(Duration::from_secs(5)) + .expect("an expected auth API request was not made") + } + + #[derive(Clone, Copy)] + struct HandoverCase { + snp_key_release: bool, + public_key_handover: bool, + admin: bool, + } + + const ALLOWED_HANDOVER: HandoverCase = HandoverCase { + snp_key_release: true, + public_key_handover: true, + admin: false, + }; + + /// Run one handover with the auth API answering `answers` (self check, then + /// caller check), and return its + /// result with the requests the auth API received. + async fn handover( + case: HandoverCase, + answers: &[bool], + ) -> ( + Result, + Vec<(String, serde_json::Value)>, + String, + ) { + use upgrade_authority::tests::{boot_info, serve, webhook}; + let dir = tempfile::tempdir().unwrap(); + let initial = kms_state(dir.path(), "http://127.0.0.1:1"); + let answers: Vec<_> = answers + .iter() + .map(|allowed| auth_answer(&initial, *allowed)) + .collect(); + let (url, server) = serve(answers); + let mut config = initial.config.clone(); + config.enforce_self_authorization = true; + config.auth_api = webhook(url); + config.sev_snp_key_release = case.snp_key_release; + config.onboard.public_key_handover = case.public_key_handover; + let keyring = Keyring::load(&config).unwrap(); + let state = KmsState::new( + config, + keyring, + initial.epoch_root(0).unwrap().ca.pem_cert.clone(), + ) + .unwrap(); + state.self_boot_info.insert((), boot_info(1)).await; + let (attestation, vm_config) = snp_caller(); + let handler = RpcHandler { + state: state.clone(), + attestation: Some(attestation), + remote_endpoint: None, + }; + let request = GetKmsKeyRequest { + vm_config, + ..Default::default() + }; + let result = if case.admin { + handler + .handover_keys(KeyRelease::AdminHandover, request) + .await + } else { + handler.get_kms_key(request).await + }; + ( + result, + auth_requests(server), + state.metrics().render_prometheus(), + ) + } + + #[rocket::async_test] + async fn handover_runs_every_authorization_check() { + let (result, requests, metrics) = handover(ALLOWED_HANDOVER, &[true, true]).await; + assert_eq!(result.unwrap().keys.len(), 1); + let [(self_route, self_check), (caller_route, caller_check)] = &requests[..] else { + panic!("unexpected auth API requests: {requests:?}"); + }; + assert_eq!(self_route, "/authorizeKms"); + assert_eq!(self_check["operation"], "kms_export_keys"); + assert!(self_check.get("requestedRootEpoch").is_none()); + assert_eq!(self_check["appId"], hex::encode([4; 20])); + assert_eq!(caller_route, "/authorizeKms"); + assert_eq!(caller_check["operation"], "kms_import_keys"); + assert_eq!(caller_check["requestedRootEpoch"], 0); + assert_eq!(caller_check["appId"], hex::encode([0x11; 20])); + // Judged against the list the auth API publishes: the verifier's own status is empty. + assert_eq!(caller_check["tcbStatus"], "UpToDate"); + assert!(metrics.contains(&key_releases("rpc", 1)), "{metrics}"); + assert!(metrics.contains(&key_releases("admin", 0)), "{metrics}"); + + let admin = HandoverCase { + admin: true, + public_key_handover: false, + ..ALLOWED_HANDOVER + }; + let (result, requests, metrics) = handover(admin, &[true, true]).await; + assert!(result.is_ok()); + assert_eq!(requests.len(), 2); + assert!(metrics.contains(&key_releases("admin", 1)), "{metrics}"); + assert!(metrics.contains(&key_releases("rpc", 0)), "{metrics}"); + } + + fn key_releases(listener: &str, count: u64) -> String { + format!( + "dstack_kms_key_releases_total{{listener=\"{listener}\",operation=\"kms_export_keys\"}} {count}\n" + ) + } + + #[rocket::async_test] + async fn handover_is_refused_when_any_check_denies() { + let (result, requests, metrics) = handover(ALLOWED_HANDOVER, &[false]).await; + assert!(format!("{:#}", result.unwrap_err()).contains("KMS self authorization failed")); + assert_eq!(requests[0].1["operation"], "kms_export_keys"); + // A refused handover releases nothing and is not counted. + assert!(metrics.contains(&key_releases("rpc", 0)), "{metrics}"); + + for admin in [false, true] { + let case = HandoverCase { + admin, + ..ALLOWED_HANDOVER + }; + let (result, requests, metrics) = handover(case, &[true, false]).await; + assert!(result.is_err()); + assert_eq!(requests[1].1["operation"], "kms_import_keys"); + let listener = if admin { "admin" } else { "rpc" }; + assert!(metrics.contains(&key_releases(listener, 0)), "{metrics}"); + + let case = HandoverCase { + snp_key_release: false, + admin, + ..ALLOWED_HANDOVER + }; + let (result, _, _) = handover(case, &[true, true]).await; + let err = format!("{:#}", result.unwrap_err()); + assert!(err.contains("sev-snp key release is not enabled"), "{err}"); + } + + let public_disabled = HandoverCase { + public_key_handover: false, + ..ALLOWED_HANDOVER + }; + let (result, requests, _) = handover(public_disabled, &[]).await; + let err = format!("{:#}", result.unwrap_err()); + assert!(err.contains("public KMS key handover is disabled"), "{err}"); + assert!(requests.is_empty()); + } + + #[rocket::async_test] + async fn handover_recipient_requires_the_source_to_be_allowed_to_export() { + use upgrade_authority::tests::{serve, webhook}; + let dir = tempfile::tempdir().unwrap(); + let state = kms_state(dir.path(), "http://127.0.0.1:1"); + let (attestation, _) = snp_caller(); + for allowed in [true, false] { + let (url, server) = serve(vec![auth_answer(&state, allowed)]); + let mut config = state.config.clone(); + config.auth_api = webhook(url); + let result = upgrade_authority::ensure_kms_allowed(&config, &attestation, 2).await; + assert_eq!(result.is_ok(), allowed); + let requests = auth_requests(server); + let [(route, check)] = &requests[..] else { + panic!("unexpected auth API requests: {requests:?}"); + }; + assert_eq!(route, "/authorizeKms"); + assert_eq!(check["operation"], "kms_export_keys"); + assert_eq!(check["requestedRootEpoch"], 2); + } + } + + type AuthRequests = std::thread::JoinHandle>; + + /// A KMS holding root epochs 0 and 1 and serving 1, with self authorization + /// enforced. Its auth API reports root epoch 1 and app epoch 1 as current + /// and answers `allowed` to each request in turn (self check first). + async fn rotated_kms( + dir: &Path, + allowed: &[bool], + configure: impl FnOnce(&mut KmsConfig), + ) -> (KmsState, AuthRequests) { + use upgrade_authority::tests::{boot_info, serve, webhook}; + let initial = kms_state(dir, "http://127.0.0.1:1"); + let keyring = rotated_keyring(&initial.config); + let answers = allowed + .iter() + .map(|allowed| epoch_answer(&keyring, *allowed, 1, 1)) + .collect(); + let (url, server) = serve(answers); + let mut config = initial.config.clone(); + config.enforce_self_authorization = true; + config.auth_api = webhook(url); + configure(&mut config); + let rpc_ca = keyring.roots[1].ca.pem_cert.clone(); + let state = KmsState::new(config, keyring, rpc_ca).unwrap(); + state.self_boot_info.insert((), boot_info(1)).await; + (state, server) + } + + fn released(metrics: &str, operation: &str, count: u64) -> bool { + metrics.contains(&format!( + "dstack_kms_key_releases_total{{listener=\"rpc\",operation=\"{operation}\"}} {count}\n" + )) + } + + /// Request an app key from a [`rotated_kms`] as an SNP caller, or anonymously. + async fn rotated_app_key( + allowed: &[bool], + attested: bool, + root_epoch: Option, + app_epoch: Option, + ) -> ( + Result, + Vec<(String, serde_json::Value)>, + KmsState, + BootInfo, + ) { + let dir = tempfile::tempdir().unwrap(); + let (state, server) = rotated_kms(dir.path(), allowed, |config| { + config.sev_snp_key_release = true + }) + .await; + let (attestation, vm_config) = snp_caller(); + let boot_info = build_boot_info_for_attestation(&attestation, false, &vm_config).unwrap(); + let handler = RpcHandler { + state: state.clone(), + attestation: attested.then_some(attestation), + remote_endpoint: None, + }; + let result = handler + .get_app_key(GetAppKeyRequest { + api_version: 1, + vm_config, + root_epoch, + app_epoch, + ..Default::default() + }) + .await; + (result, auth_requests(server), state, boot_info) + } + + #[rocket::async_test] + async fn get_app_key_derives_from_the_requested_epochs_after_rotation() { + for (requested_root, requested_app, root_epoch, app_epoch) in [ + (None, None, 1, 1), + (Some(0), Some(0), 0, 0), + (Some(0), Some(1), 0, 1), + (Some(1), Some(0), 1, 0), + ] { + let (result, requests, state, caller) = + rotated_app_key(&[true, true], true, requested_root, requested_app).await; + let response = result.unwrap(); + assert_eq!( + (response.root_epoch, response.app_epoch), + (root_epoch, app_epoch) + ); + let root = state.epoch_root(root_epoch).unwrap(); + assert_eq!(response.ca_cert, root.ca.pem_cert); + let expected = + derive_app_keys(root, &caller.app_id, &caller.instance_id, app_epoch).unwrap(); + assert_eq!(response.disk_crypt_key, expected.disk_crypt_key); + assert_eq!(response.sealed_env_key, expected.sealed_env_key); + assert_eq!(response.k256_key, expected.k256_key); + + let [(_, self_check), (route, check)] = &requests[..] else { + panic!("unexpected auth API requests: {requests:?}"); + }; + assert_eq!(self_check["operation"], "kms_serve"); + assert_eq!(route, "/authorizeApp"); + assert_eq!(check["operation"], "app_get_key"); + assert_eq!(check["tcbStatus"], "UpToDate"); + assert_eq!( + check.get("requestedRootEpoch"), + requested_root.map(Into::into).as_ref() + ); + assert_eq!( + check.get("requestedAppEpoch"), + requested_app.map(Into::into).as_ref() + ); + let metrics = state.metrics().render_prometheus(); + assert!(released(&metrics, "app_get_key", 1), "{metrics}"); + } + } + + #[rocket::async_test] + async fn get_app_key_fails_unless_the_request_is_authorized() { + let (result, requests, state, _) = rotated_app_key(&[true, false], true, None, None).await; + let err = format!("{:#}", result.unwrap_err()); + assert!( + err.contains("App not allowed") && err.contains("denied"), + "{err}" + ); + assert_eq!(requests.len(), 2); + let metrics = state.metrics().render_prometheus(); + assert!(released(&metrics, "app_get_key", 0), "{metrics}"); + + // A backend that authorizes an epoch it reports as inactive is not trusted. + let (result, _, _, _) = rotated_app_key(&[true, true], true, None, Some(2)).await; + let err = format!("{:#}", result.unwrap_err()); + assert!(err.contains("requested app epoch is not active"), "{err}"); + let (result, _, _, _) = rotated_app_key(&[true, true], true, Some(2), None).await; + let err = format!("{:#}", result.unwrap_err()); + assert!(err.contains("root epoch 2 is not active"), "{err}"); + + // An anonymous caller is refused before the KMS reaches its backend. + let (result, requests, _, _) = rotated_app_key(&[], false, None, None).await; + let err = format!("{:#}", result.unwrap_err()); + assert!(err.contains("No attestation provided"), "{err}"); + assert!(requests.is_empty()); + } + + fn pem_public_key(pem: &str) -> Vec { + let (_, pem) = x509_parser::pem::parse_x509_pem(pem.as_bytes()).unwrap(); + pem.parse_x509().unwrap().public_key().raw.to_vec() + } + + /// Sign a certificate on a [`rotated_kms`] for a mock nitro enclave app. + async fn rotated_sign_cert( + allowed: &[bool], + ) -> ( + Result, + Vec<(String, serde_json::Value)>, + KmsState, + ) { + use ra_tls::{ + attestation::{ + Attestation, AttestationQuote, AttestationVerifierConfig, DstackNitroQuote, + QuoteContentType, RootCaPaths, + }, + cert::{CertConfigV2, Csr}, + }; + let dir = tempfile::tempdir().unwrap(); + let attester = mock_attestation::nsm::NsmGenerator::new().unwrap(); + let attestation_root = dir.path().join("nitro-root.pem"); + fs::write(&attestation_root, attester.root_ca_pem()).unwrap(); + let (state, server) = rotated_kms(dir.path(), allowed, |config| { + config.nitro_enclave_key_release = true; + config.attestation = AttestationVerifierConfig { + insecure_allow_external_trust_anchors: true, + root_ca: RootCaPaths { + aws_nitro_enclave: Some(attestation_root), + ..Default::default() + }, + ..Default::default() + }; + }) + .await; + + let key = KeyPair::generate_for(&ra_tls::rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); + let pubkey = key.public_key_der(); + let report_data = QuoteContentType::RaTlsCert.to_report_data(&pubkey); + let pcrs: BTreeMap> = [0, 1, 2, 4] + .into_iter() + .map(|i| (i, vec![i as u8 + 1; 48])) + .collect(); + let os_image_hash = sha256_chunks(&[&pcrs[&0], &pcrs[&1], &pcrs[&2]]); + let attestation = Attestation { + quote: AttestationQuote::DstackNitroEnclave(DstackNitroQuote { + nsm_quote: attester.attest_with_pcrs(&report_data, pcrs).unwrap(), + }), + runtime_events: vec![runtime_event("app-id", vec![0x22; 20])], + report_data, + config: String::new(), + report: (), + } + .into_versioned(); + let csr = CertSigningRequestV2 { + confirm: "please sign cert:".into(), + pubkey, + config: CertConfigV2 { + org_name: None, + subject: "app.test".into(), + subject_alt_names: vec![], + usage_server_auth: true, + usage_client_auth: false, + ext_quote: false, + ext_app_info: false, + not_before: None, + not_after: None, + }, + attestation, + }; + let request = SignCertRequest { + api_version: 2, + signature: csr.signed_by(&key).unwrap(), + csr: csr.to_vec(), + vm_config: serde_json::json!({ "os_image_hash": hex::encode(os_image_hash) }) + .to_string(), + ..Default::default() + }; + let result = RpcHandler { + state: state.clone(), + attestation: None, + remote_endpoint: None, + } + .sign_cert(request) + .await; + (result, auth_requests(server), state) + } + + #[rocket::async_test] + async fn sign_cert_issues_from_the_current_epochs_after_rotation() { + let (result, requests, state) = rotated_sign_cert(&[true, true]).await; + let chain = result.unwrap().certificate_chain; + let root = state.epoch_root(1).unwrap(); + assert_eq!(chain[2], root.ca.pem_cert); + let app_ca_key = kdf::derive_p256_key_pair( + &root.ca.key, + &[&[0x22; 20][..], b"app-ca", &app_epoch_context(1)], + ) + .unwrap(); + assert_eq!(pem_public_key(&chain[1]), app_ca_key.public_key_der()); + + let [(_, self_check), (route, check)] = &requests[..] else { + panic!("unexpected auth API requests: {requests:?}"); + }; + assert_eq!(self_check["operation"], "kms_serve"); + assert_eq!(route, "/authorizeApp"); + assert_eq!(check["operation"], "app_get_cert"); + assert!(check.get("requestedRootEpoch").is_none()); + assert!(check.get("requestedAppEpoch").is_none()); + let metrics = state.metrics().render_prometheus(); + assert!(released(&metrics, "app_get_cert", 1), "{metrics}"); + } + + #[rocket::async_test] + async fn sign_cert_fails_when_the_backend_rejects_the_app() { + let (result, requests, state) = rotated_sign_cert(&[true, false]).await; + let err = format!("{:#}", result.unwrap_err()); + assert!(err.contains("Authorization denied: denied"), "{err}"); + assert_eq!(requests.len(), 2); + let metrics = state.metrics().render_prometheus(); + assert!(released(&metrics, "app_get_cert", 0), "{metrics}"); + + let (result, requests, _) = rotated_sign_cert(&[false]).await; + let err = format!("{:#}", result.unwrap_err()); + assert!(err.contains("KMS self authorization failed"), "{err}"); + assert_eq!(requests.len(), 1); + } + + /// Fetch an env public key while the auth API answers the app epoch query + /// with `status` and `body`. + async fn env_pub_key(sealed: bool, status: u16, body: &'static str) -> Result<()> { + let (url, server) = + upgrade_authority::tests::serve_with_status(vec![(200, AUTH_API_INFO), (status, body)]); + let dir = tempfile::tempdir().unwrap(); + let handler = RpcHandler { + state: kms_state(dir.path(), &url), + attestation: None, + remote_endpoint: None, + }; + let request = AppId { + app_id: vec![0x11; 20], + }; + let result = if sealed { + handler.get_sealed_env_pub_key(request).await.map(drop) + } else { + handler.get_app_env_encrypt_pub_key(request).await.map(drop) + }; + let requests = auth_requests(server); + assert_eq!(requests[1].0, format!("/app/0x{}", "11".repeat(20))); + result + } + + #[rocket::async_test] + async fn env_public_keys_require_the_backend_to_report_the_app_epoch() { + for sealed in [false, true] { + for (status, body) in [ + (404, r#"{"error":"unknown app"}"#), + (503, r#"{"error":"authorization backend unavailable"}"#), + (500, r#"{"status":"error"}"#), + ] { + let err = env_pub_key(sealed, status, body).await.unwrap_err(); + assert!(format!("{err:#}").contains(&status.to_string()), "{err:#}"); + } + // A legacy app at epoch zero still gets its key. + env_pub_key(sealed, 200, r#"{"currentAppEpoch":0}"#) + .await + .unwrap(); + } + } + + #[rocket::async_test] + async fn env_public_keys_at_a_rotated_app_epoch() { + let err = env_pub_key(false, 200, r#"{"currentAppEpoch":1}"#) + .await + .unwrap_err(); + assert!( + format!("{err:#}").contains("must use GetSealedEnvPubKey"), + "{err:#}" + ); + + let (url, server) = + upgrade_authority::tests::serve(vec![AUTH_API_INFO, r#"{"currentAppEpoch":1}"#]); + let dir = tempfile::tempdir().unwrap(); + let state = kms_state(dir.path(), &url); + let app_id = [0x11; 20]; + let response = RpcHandler { + state: state.clone(), + attestation: None, + remote_endpoint: None, + } + .get_sealed_env_pub_key(AppId { + app_id: app_id.to_vec(), + }) + .await + .unwrap(); + auth_requests(server); + assert_eq!((response.root_epoch, response.app_epoch), (0, 1)); + let root = state.epoch_root(0).unwrap(); + let secret = derive_sealed_env_key(root, &app_id, 1).unwrap(); + assert_ne!(secret, derive_sealed_env_key(root, &app_id, 0).unwrap()); + let public_key = + x25519_dalek::PublicKey::from(&x25519_dalek::StaticSecret::from(secret)).to_bytes(); + assert_eq!(response.public_key, public_key); + let message = [ + &0u32.to_be_bytes()[..], + &1u32.to_be_bytes(), + &public_key, + &response.timestamp.to_be_bytes(), + ] + .concat(); + let signature = sign_message( + &root.k256, + b"dstack-sealed-env-pubkey-v1", + &app_id, + &message, + ) + .unwrap(); + // The recoverable signature is deterministic (RFC 6979). + assert_eq!(response.signature, signature); + } + + #[rocket::async_test] + async fn legacy_temp_ca_rpc_returns_a_separate_ca_and_the_served_root() { + assert!(dstack_kms_rpc::kms_server::KMSMethod::from_str("GetTempCaCert").is_some()); + let dir = tempfile::tempdir().unwrap(); + let (url, _) = serve_concurrent_auth_api(AUTH_API_INFO); + let state = kms_state(dir.path(), &url); + let response = RpcHandler { + state: state.clone(), + attestation: None, + remote_endpoint: None, + } + .get_temp_ca_cert() + .await + .unwrap(); + let temp_ca = CaCert::new(response.temp_ca_cert, response.temp_ca_key).unwrap(); + assert_ne!(temp_ca.key.public_key_der(), state.rpc_ca_pubkey); + assert_eq!(response.ca_cert, state.epoch_root(0).unwrap().ca.pem_cert); + } + + #[rocket::async_test] + async fn app_epoch_lookups_are_cached_per_app_for_one_second() { + use std::sync::atomic::Ordering; + let dir = tempfile::tempdir().unwrap(); + let (url, requests) = serve_concurrent_auth_api(r#"{"currentAppEpoch":2}"#); + let state = kms_state(dir.path(), &url); + for _ in 0..3 { + assert_eq!(state.app_epoch(&[0x11; 20]).await.unwrap(), 2); + } + assert_eq!(requests.load(Ordering::SeqCst), 1); + // Another app is looked up separately. + state.app_epoch(&[0x22; 20]).await.unwrap(); + assert_eq!(requests.load(Ordering::SeqCst), 2); + tokio::time::sleep(AUTH_API_CACHE_TTL + Duration::from_millis(100)).await; + state.app_epoch(&[0x11; 20]).await.unwrap(); + assert_eq!(requests.load(Ordering::SeqCst), 3); + } + #[rocket::async_test] async fn concurrent_get_meta_calls_share_one_auth_api_request() { let dir = tempfile::tempdir().unwrap(); @@ -1421,6 +2812,7 @@ mod tests { RpcHandler { state, attestation: None, + remote_endpoint: None, } .get_meta() .await diff --git a/dstack/kms/src/main_service/amd_attest.rs b/dstack/kms/src/main_service/amd_attest.rs index 10b6517f41..b8e0ea879a 100644 --- a/dstack/kms/src/main_service/amd_attest.rs +++ b/dstack/kms/src/main_service/amd_attest.rs @@ -85,7 +85,6 @@ pub(crate) fn build_amd_snp_boot_info( &host_data, verified_chip_id, "UpToDate", - &[], input, &os_image_hash, &mr_config_document, @@ -98,7 +97,6 @@ fn build_amd_snp_boot_info_with_tcb_status( verified_host_data: &[u8; 32], verified_chip_id: &[u8; 64], tcb_status: &str, - advisory_ids: &[String], input: &MeasurementInput, os_image_hash: &[u8], mr_config_document: &str, @@ -121,7 +119,7 @@ fn build_amd_snp_boot_info_with_tcb_status( device_id: Sha256::digest(verified_chip_id).to_vec(), key_provider_info, tcb_status: tcb_status.to_string(), - advisory_ids: advisory_ids.to_vec(), + advisory_ids: Vec::new(), }) } @@ -146,8 +144,7 @@ pub(crate) fn build_amd_snp_boot_info_from_verified_attestation( &verified.measurement, &verified.host_data, &verified.chip_id, - verified.tcb_info.tcb_status(), - &verified.advisory_ids, + &verified.tcb_status, input, os_image_hash, mr_config_document, @@ -318,6 +315,7 @@ mod tests { config: String::new(), report: ra_tls::attestation::DstackVerifiedReport::DstackAmdSevSnp( dstack_attest::amd_sev_snp::VerifiedAmdSnpReport { + cpuid: None, measurement, report_data: [0x42; 64], host_data: MrConfigV3::snp_host_data_from_document( @@ -325,7 +323,7 @@ mod tests { ), chip_id, tcb_info: dstack_attest::amd_sev_snp::AmdSnpTcbInfo::default(), - advisory_ids: Vec::new(), + tcb_status: "UpToDate".into(), }, ), } @@ -419,17 +417,6 @@ mod tests { let chip_id = [0xbc; 64]; let mr_config = valid_mr_config(&input)?; let mr_config_document = mr_config.to_canonical_json(); - let tcb = dstack_attest::amd_sev_snp::AmdSnpTcbVersion { - fmc: None, - bootloader: 1, - tee: 2, - snp: 3, - microcode: 4, - }; - let stale_tcb = dstack_attest::amd_sev_snp::AmdSnpTcbVersion { - microcode: 3, - ..tcb - }; let attestation = ra_tls::attestation::VerifiedAttestation { quote: ra_tls::attestation::AttestationQuote::DstackAmdSevSnp( ra_tls::attestation::SnpQuote { @@ -443,17 +430,13 @@ mod tests { config: String::new(), report: ra_tls::attestation::DstackVerifiedReport::DstackAmdSevSnp( dstack_attest::amd_sev_snp::VerifiedAmdSnpReport { + cpuid: None, measurement: verified, report_data: [0x42; 64], host_data: MrConfigV3::snp_host_data_from_document(&mr_config_document), chip_id, - tcb_info: dstack_attest::amd_sev_snp::AmdSnpTcbInfo { - current: tcb, - reported: tcb, - committed: tcb, - launch: stale_tcb, - }, - advisory_ids: vec!["SNP-TEST-ADVISORY".to_string()], + tcb_info: dstack_attest::amd_sev_snp::AmdSnpTcbInfo::default(), + tcb_status: "OutOfDate".into(), }, ), }; @@ -467,7 +450,7 @@ mod tests { .expect("verified snp attestation should feed boot info helper"); assert_eq!(boot_info.tcb_status, "OutOfDate"); - assert_eq!(boot_info.advisory_ids, vec!["SNP-TEST-ADVISORY"]); + assert!(boot_info.advisory_ids.is_empty()); assert_ne!(boot_info.tcb_status, "snp-verified-basic-policy"); Ok(()) } @@ -633,7 +616,6 @@ mod tests { &host_data, &chip_id, "UpToDate", - &[], &input, &os_image_hash, &mr_config_document, @@ -653,7 +635,6 @@ mod tests { &changed_host_data, &chip_id, "UpToDate", - &[], &input, &os_image_hash, &changed_mr_config_document, diff --git a/dstack/kms/src/main_service/upgrade_authority.rs b/dstack/kms/src/main_service/upgrade_authority.rs index 79f4a7c23d..3b742548ce 100644 --- a/dstack/kms/src/main_service/upgrade_authority.rs +++ b/dstack/kms/src/main_service/upgrade_authority.rs @@ -2,19 +2,23 @@ // // SPDX-License-Identifier: Apache-2.0 -use super::build_boot_info_for_attestation; +use super::{build_boot_info_for_attestation, short_lived_cache}; use crate::config::{AuthApi, KmsConfig}; -use anyhow::{bail, Context, Result}; +use anyhow::{anyhow, bail, Context, Result}; +use dstack_attest::amd_sev_snp::AmdSnpTcbRequirement; +use dstack_attest::attestation::sev_snp_tcb_requirements_from_json; use dstack_guest_agent_rpc::v0::{ dstack_guest_client::DstackGuestClient, AttestResponse, RawQuoteArgs, }; +use dstack_types::authorization; +pub(crate) use dstack_types::authorization::AuthorizationOperation as Operation; use http_client::prpc::PrpcClient; +use moka::future::Cache; use ra_tls::attestation::{AttestationVerifier, VerifiedAttestation, VersionedAttestation}; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; -use std::sync::OnceLock; +use std::sync::{Arc, OnceLock}; use std::time::Duration; -use tracing::warn; /// The KMS `bootAuth` payload. This is the verifier's `PolicyBootInfo` — the one /// canonical struct shared by the producer (KMS) and the policy input the @@ -64,7 +68,10 @@ fn ensure_identity_widths(boot_info: &BootInfo) -> Result<()> { Ok(()) } -pub(crate) async fn local_kms_boot_info(verifier: &AttestationVerifier) -> Result { +pub(crate) async fn local_kms_boot_info( + auth_api: &AuthApi, + verifier: &AttestationVerifier, +) -> Result { let response = app_attest(pad64([0u8; 32])) .await .context("Failed to get local KMS attestation")?; @@ -75,9 +82,10 @@ pub(crate) async fn local_kms_boot_info(verifier: &AttestationVerifier) -> Resul .verify(verifier) .await .context("Failed to verify local KMS attestation")?; - build_boot_info_for_attestation(&verified, false, "") + auth_api.boot_info(&verified, false, "").await } +#[cfg(test)] #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub(crate) struct BootResponse { @@ -86,6 +94,109 @@ pub(crate) struct BootResponse { pub reason: String, } +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct AuthorizationResult { + pub authorized: bool, + pub rejection_reason: String, + pub gateway_app_id: String, + pub current_root_epoch: u32, + pub current_app_epoch: u32, + pub current_root_epoch_hash: String, + pub latest_root_epoch: u32, + pub latest_root_epoch_hash: String, +} + +impl AuthorizationResult { + pub fn current_root(&self) -> Result> { + root_epoch(self.current_root_epoch, &self.current_root_epoch_hash) + } + + /// The latest registered root epoch, which may be pending activation. + pub fn latest_root(&self) -> Result> { + root_epoch(self.latest_root_epoch, &self.latest_root_epoch_hash) + } +} + +/// A zero chain hash means no epoch is registered. +fn root_epoch(epoch: u32, hash: &str) -> Result> { + let chain_hash: [u8; 32] = hex::decode(hash.trim_start_matches("0x")) + .ok() + .and_then(|hash| hash.try_into().ok()) + .context("invalid authorization root epoch chain hash")?; + if chain_hash == [0; 32] { + return Ok(None); + } + Ok(Some(CurrentRootEpoch { epoch, chain_hash })) +} + +/// The root epoch fields: the KMS sends the epoch it serves in boot checks, +/// and auth backends report the current one in info responses. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct RootEpochFields { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub root_epoch: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub root_epoch_hash: Option, +} + +impl From for RootEpochFields { + fn from(current: CurrentRootEpoch) -> Self { + Self { + root_epoch: Some(current.epoch), + root_epoch_hash: Some(format!("0x{}", hex::encode(current.chain_hash))), + } + } +} + +impl RootEpochFields { + pub fn registry(&self) -> Result { + match (self.root_epoch, &self.root_epoch_hash) { + (None, None) => Ok(RootEpochRegistry::Empty), + (Some(epoch), Some(hash)) => { + let chain_hash = hex::decode(hash.trim_start_matches("0x")) + .ok() + .and_then(|hash| hash.try_into().ok()) + .context("invalid root epoch chain hash")?; + Ok(RootEpochRegistry::Current(CurrentRootEpoch { + epoch, + chain_hash, + })) + } + _ => bail!("the auth API reports a root epoch without its chain hash"), + } + } +} + +/// A root epoch governance registered, with the chain hash committing to the +/// root public keys of epochs 0..=epoch. Usually the current epoch. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct CurrentRootEpoch { + pub epoch: u32, + pub chain_hash: [u8; 32], +} + +/// What governance says about root epochs. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) enum RootEpochRegistry { + /// The dev backend: there is nothing to check against. + Unchecked, + /// No epoch is registered, or the backend predates root epochs. + Empty, + Current(CurrentRootEpoch), +} + +/// What governance says about root epochs at a key handover: the current epoch +/// and the latest registered one. Chain hashes are cumulative, so the latest +/// binds every registered epoch, including those pending activation. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct RootEpochRegistration { + pub registry: RootEpochRegistry, + /// Absent for the dev backend and when nothing is registered. + pub latest: Option, +} + #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub(crate) struct AuthApiInfoResponse { @@ -96,6 +207,9 @@ pub(crate) struct AuthApiInfoResponse { pub gateway_app_id: String, pub chain_id: u64, pub app_implementation: String, + pub auth_api_info: Option, + #[serde(flatten)] + pub root_epoch: RootEpochFields, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -107,6 +221,8 @@ pub(crate) struct GetInfoResponse { pub eth_rpc_url: Option, pub chain_id: Option, pub app_implementation: Option, + pub root_epochs: RootEpochRegistry, + pub auth_api_info: Option, } const AUTH_API_CONNECT_TIMEOUT: Duration = Duration::from_secs(5); @@ -122,6 +238,30 @@ fn auth_api_client() -> &'static reqwest::Client { }) } +/// Reused for [`AUTH_API_CACHE_TTL`]; failures are not cached. +async fn sev_snp_tcb_requirements( + url: &str, + timeout: Duration, +) -> Result> { + #[derive(Deserialize)] + struct Response { + requirements: String, + } + static CACHE: OnceLock>> = OnceLock::new(); + let fetch = async { + let Response { requirements } = http_get(url, timeout).await?; + if requirements.is_empty() { + return Ok(Vec::new()); + } + sev_snp_tcb_requirements_from_json(&requirements) + }; + CACHE + .get_or_init(|| short_lived_cache(1)) + .try_get_with(url.to_string(), fetch) + .await + .map_err(|err: Arc| anyhow!("{err:#}")) +} + async fn http_get(url: &str, timeout: Duration) -> Result { send_request(auth_api_client().get(url).timeout(timeout), url).await } @@ -167,7 +307,165 @@ async fn send_request(req: reqwest::RequestBuilder, url: &s } impl AuthApi { - pub async fn is_app_allowed(&self, boot_info: &BootInfo, is_kms: bool) -> Result { + /// The boot info an authorization judges. An SEV-SNP TCB is judged against + /// the minimums governance publishes, and against the verifier's own for + /// a CPU governance does not list; the dev backend publishes none. + pub async fn boot_info( + &self, + att: &VerifiedAttestation, + use_boottime_mr: bool, + vm_config: &str, + ) -> Result { + let mut boot_info = build_boot_info_for_attestation(att, use_boottime_mr, vm_config)?; + if let (Some(report), AuthApi::Webhook { webhook }) = (att.report.amd_snp_report(), self) { + let url = url_join(&webhook.url, "sevSnpTcbRequirements"); + let requirements = sev_snp_tcb_requirements(&url, webhook.timeout) + .await + .context("failed to read the SEV-SNP TCB requirements from the auth API")?; + boot_info.tcb_status = report + .assess(&requirements) + .context("the SEV-SNP TCB requirements cannot judge this report")? + .to_string(); + } + Ok(boot_info) + } + + pub async fn authorize_kms( + &self, + app_info: &BootInfo, + operation: Operation, + requested_root_epoch: Option, + launch_ticket: &str, + ) -> Result { + if !operation.is_kms() { + bail!("invalid KMS authorization operation"); + } + self.check_authorization( + app_info, + "authorizeKms", + operation, + requested_root_epoch, + None, + launch_ticket, + ) + .await + } + + pub async fn authorize_app( + &self, + app_info: &BootInfo, + operation: Operation, + requested_root_epoch: Option, + requested_app_epoch: Option, + launch_ticket: &str, + ) -> Result { + if operation.is_kms() { + bail!("invalid app authorization operation"); + } + self.check_authorization( + app_info, + "authorizeApp", + operation, + requested_root_epoch, + requested_app_epoch, + launch_ticket, + ) + .await + } + + async fn check_authorization( + &self, + app_info: &BootInfo, + method: &str, + operation: Operation, + requested_root_epoch: Option, + requested_app_epoch: Option, + launch_ticket: &str, + ) -> Result { + #[derive(Serialize)] + #[serde(rename_all = "camelCase")] + struct AuthorizationRequest<'a> { + #[serde(flatten)] + app_info: &'a BootInfo, + operation: Operation, + #[serde(skip_serializing_if = "Option::is_none")] + requested_app_epoch: Option, + #[serde(skip_serializing_if = "Option::is_none")] + requested_root_epoch: Option, + #[serde(skip_serializing_if = "Option::is_none")] + launch_ticket_hash: Option, + } + ensure_identity_widths(app_info)?; + // An empty ticket is none. + let launch_ticket_hash = if launch_ticket.is_empty() { + None + } else { + authorization::check_launch_ticket(launch_ticket).map_err(anyhow::Error::msg)?; + Some(hex::encode(authorization::launch_ticket_hash( + launch_ticket, + ))) + }; + match self { + AuthApi::Dev { dev } => Ok(AuthorizationResult { + authorized: true, + rejection_reason: String::new(), + gateway_app_id: dev.gateway_app_id.clone(), + current_root_epoch: 0, + current_app_epoch: 0, + current_root_epoch_hash: hex::encode([0; 32]), + latest_root_epoch: 0, + latest_root_epoch_hash: hex::encode([0; 32]), + }), + AuthApi::Webhook { webhook } => { + let url = url_join(&webhook.url, method); + http_post( + &url, + &AuthorizationRequest { + app_info, + operation, + requested_app_epoch, + requested_root_epoch, + launch_ticket_hash, + }, + webhook.timeout, + ) + .await + } + } + } + + pub async fn app_epoch(&self, app_id: &[u8]) -> Result { + ensure_app_id_len(app_id)?; + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + struct AppEpoch { + current_app_epoch: u32, + } + match self { + AuthApi::Dev { .. } => Ok(0), + AuthApi::Webhook { webhook } => { + let url = url_join(&webhook.url, &format!("app/0x{}", hex::encode(app_id))); + let response: AppEpoch = http_get(&url, webhook.timeout).await?; + Ok(response.current_app_epoch) + } + } + } + + #[cfg(test)] + pub async fn is_app_allowed( + &self, + boot_info: &BootInfo, + is_kms: bool, + root_epoch: Option, + ) -> Result { + #[derive(Serialize)] + struct BootAuthRequest<'a> { + #[serde(flatten)] + boot_info: &'a BootInfo, + #[serde(flatten)] + root_epoch: RootEpochFields, + } + ensure_identity_widths(boot_info)?; match self { AuthApi::Dev { dev } => Ok(BootResponse { @@ -182,11 +480,36 @@ impl AuthApi { "bootAuth/app" }; let url = url_join(&webhook.url, path); - http_post(&url, &boot_info, webhook.timeout).await + let request = BootAuthRequest { + boot_info, + root_epoch: root_epoch.map(Into::into).unwrap_or_default(), + }; + http_post(&url, &request, webhook.timeout).await } } } + /// The root CA public key (SPKI DER) of the current root epoch, which + /// signs the RPC certificate of every KMS serving it; `None` in dev mode, + /// which registers none. + pub async fn root_ca_pubkey(&self) -> Result>> { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + struct Info { + root_ca_pubkey: Option, + } + let AuthApi::Webhook { webhook } = self else { + return Ok(None); + }; + let info: Info = http_get(&webhook.url, webhook.timeout).await?; + let key = info.root_ca_pubkey.context( + "the auth API reports no root CA key: register a root epoch, or upgrade the auth API", + )?; + let key = + hex::decode(key.trim_start_matches("0x")).context("invalid root CA public key")?; + Ok(Some(key)) + } + pub async fn get_info(&self) -> Result { match self { AuthApi::Dev { dev } => Ok(GetInfoResponse { @@ -196,6 +519,8 @@ impl AuthApi { gateway_app_id: Some(dev.gateway_app_id.clone()), chain_id: None, app_implementation: None, + root_epochs: RootEpochRegistry::Unchecked, + auth_api_info: None, }), AuthApi::Webhook { webhook } => { let info: AuthApiInfoResponse = http_get(&webhook.url, webhook.timeout).await?; @@ -211,6 +536,8 @@ impl AuthApi { chain_id: Some(info.chain_id), gateway_app_id: Some(info.gateway_app_id.clone()), app_implementation: Some(info.app_implementation.clone()), + root_epochs: info.root_epoch.registry()?, + auth_api_info: info.auth_api_info, }) } } @@ -250,16 +577,26 @@ pub(crate) async fn ensure_self_kms_allowed( if !cfg.enforce_self_authorization { return Ok(()); } - let boot_info = local_kms_boot_info(verifier) + let boot_info = local_kms_boot_info(&cfg.auth_api, verifier) .await .context("failed to build local KMS boot info")?; let response = cfg .auth_api - .is_app_allowed(&boot_info, true) + .authorize_kms(&boot_info, Operation::KmsBootstrap, None, "") .await - .context("failed to call KMS auth check")?; - if !response.is_allowed { - bail!("boot denied: {}", response.reason); + .context("failed to call KMS bootstrap authorization")?; + if !response.authorized { + bail!("boot denied: {}", response.rejection_reason); + } + Ok(()) +} + +/// A source must present its OS image hash. KMS releases before 0.6 issue +/// certificates without a vm_config, and so without one; they cannot be joined +/// directly. Upgrade such a cluster to 0.6 first. +fn ensure_source_os_image(boot_info: &BootInfo) -> Result<()> { + if boot_info.os_image_hash.is_empty() { + bail!("the source KMS certificate does not carry its OS image hash; onboard from a v0.6+ source"); } Ok(()) } @@ -267,44 +604,53 @@ pub(crate) async fn ensure_self_kms_allowed( pub(crate) async fn ensure_kms_allowed( cfg: &KmsConfig, attestation: &VerifiedAttestation, - verifier: &AttestationVerifier, -) -> Result<()> { - let mut boot_info = build_boot_info_for_attestation(attestation, false, "") + root_epoch: u32, +) -> Result { + let boot_info = cfg + .auth_api + .boot_info(attestation, false, "") + .await .context("failed to build KMS boot info from attestation")?; - // Workaround: old source KMS instances use the legacy cert format (separate TDX_QUOTE + - // EVENT_LOG OIDs) which lacks vm_config, resulting in an empty os_image_hash. - // Fill it from the local KMS's own value, so only mrAggregated gates the source image here. - // A source that presents a config but no os_image_hash is not legacy and gets no fallback. - // TODO: remove once all source KMS instances use the unified PHALA_RATLS_ATTESTATION format. - if boot_info.os_image_hash.is_empty() && attestation.config.is_empty() { - warn!("source KMS uses the legacy cert format, falling back to the local os_image_hash"); - let local_info = local_kms_boot_info(verifier) - .await - .context("failed to get local KMS boot info for os_image_hash fallback")?; - boot_info.os_image_hash = local_info.os_image_hash; - } + ensure_source_os_image(&boot_info)?; let response = cfg .auth_api - .is_app_allowed(&boot_info, true) + .authorize_kms(&boot_info, Operation::KmsExportKeys, Some(root_epoch), "") .await - .context("failed to call KMS auth check")?; - if !response.is_allowed { - bail!("boot denied: {}", response.reason); + .context("failed to authorize source KMS key export")?; + if !response.authorized { + bail!("boot denied: {}", response.rejection_reason); } - Ok(()) + if cfg.auth_api.is_dev() { + return Ok(RootEpochRegistration { + registry: RootEpochRegistry::Unchecked, + latest: None, + }); + } + let current = response + .current_root()? + .context("root epoch not registered")?; + let latest = response + .latest_root()? + .filter(|latest| latest.epoch >= current.epoch) + .context("the auth API reports no latest root epoch at or after the current one")?; + Ok(RootEpochRegistration { + registry: RootEpochRegistry::Current(current), + latest: Some(latest), + }) } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; use crate::config::Webhook; use ra_tls::attestation::TeeVariant; use serde_json::Value; + use sha2::{Digest, Sha256}; use std::io::{Read, Write}; use std::net::TcpListener; use std::thread; - fn boot_info(identity: u8) -> BootInfo { + pub(crate) fn boot_info(identity: u8) -> BootInfo { BootInfo { tee_variant: TeeVariant::DstackTdx, mr_aggregated: vec![identity; 32], @@ -320,15 +666,43 @@ mod tests { } } - fn serve>( + /// What [`serve`] publishes: a minimum every TCB of the SEV-SNP fixtures' + /// CPU, a Milan, meets. + const MET_TCB_REQUIREMENTS: &str = r#"{"requirements":"[{\"cpuid\":\"00a00f11\",\"bootloader\":0,\"tee\":0,\"snp\":0,\"microcode\":0}]"}"#; + + /// Answers each authorization request in turn, and publishes + /// [`MET_TCB_REQUIREMENTS`] without counting those requests. + pub(crate) fn serve>( responses: Vec, ) -> (String, thread::JoinHandle>) { - let responses: Vec = responses.into_iter().map(Into::into).collect(); + serve_routes( + responses.into_iter().map(|body| (200, body)).collect(), + false, + ) + } + + /// Like [`serve`], answering every request in turn with its own HTTP status. + pub(crate) fn serve_with_status>( + responses: Vec<(u16, S)>, + ) -> (String, thread::JoinHandle>) { + serve_routes(responses, true) + } + + fn serve_routes>( + responses: Vec<(u16, S)>, + serves_tcb_requirements: bool, + ) -> (String, thread::JoinHandle>) { + let mut responses = responses + .into_iter() + .map(|(status, body)| (status, body.into())) + .collect::>() + .into_iter() + .peekable(); let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let address = listener.local_addr().unwrap(); let handle = thread::spawn(move || { let mut requests = Vec::new(); - for response in responses { + while responses.peek().is_some() { let (mut stream, _) = listener.accept().unwrap(); let mut request = Vec::new(); let mut chunk = [0u8; 4096]; @@ -364,13 +738,22 @@ mod tests { .nth(1) .unwrap() .to_string(); - let body = - serde_json::from_slice(&request[header_end..header_end + content_length]) - .unwrap(); - requests.push((path, body)); + let body = &request[header_end..header_end + content_length]; + let body = if body.is_empty() { + Value::Null + } else { + serde_json::from_slice(body).unwrap() + }; + let (status, response) = + if path == "/sevSnpTcbRequirements" && !serves_tcb_requirements { + (200, MET_TCB_REQUIREMENTS.to_string()) + } else { + requests.push((path, body)); + responses.next().unwrap() + }; write!( stream, - "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + "HTTP/1.1 {status} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", response.len(), response ) @@ -381,7 +764,22 @@ mod tests { (format!("http://{address}"), handle) } - fn webhook(url: String) -> AuthApi { + /// Joins and rotations share this check, so both refuse such a source. + #[test] + fn a_source_certificate_without_an_os_image_hash_is_refused() { + let legacy = BootInfo { + os_image_hash: vec![], + ..boot_info(1) + }; + let err = ensure_source_os_image(&legacy).unwrap_err(); + assert!( + err.to_string().contains("onboard from a v0.6+ source"), + "{err:#}" + ); + ensure_source_os_image(&boot_info(1)).unwrap(); + } + + pub(crate) fn webhook(url: String) -> AuthApi { AuthApi::Webhook { webhook: Webhook { url, @@ -436,7 +834,7 @@ mod tests { let mut aliasing_compose_hash = boot_info(1); aliasing_compose_hash.compose_hash.truncate(31); let err = auth - .is_app_allowed(&aliasing_compose_hash, false) + .is_app_allowed(&aliasing_compose_hash, false, None) .await .unwrap_err(); assert!(err.to_string().contains("compose_hash must be 32 bytes")); @@ -444,7 +842,7 @@ mod tests { let mut aliasing_instance_id = boot_info(1); aliasing_instance_id.instance_id.truncate(19); let err = auth - .is_app_allowed(&aliasing_instance_id, false) + .is_app_allowed(&aliasing_instance_id, false, None) .await .unwrap_err(); assert!(err @@ -455,7 +853,7 @@ mod tests { let mut no_instance_id = boot_info(1); no_instance_id.instance_id.clear(); assert!( - auth.is_app_allowed(&no_instance_id, false) + auth.is_app_allowed(&no_instance_id, false, None) .await .unwrap() .is_allowed @@ -472,8 +870,8 @@ mod tests { let auth = webhook(url); let info = boot_info(1); - let first = auth.is_app_allowed(&info, false).await.unwrap(); - let repeated = auth.is_app_allowed(&info, false).await.unwrap(); + let first = auth.is_app_allowed(&info, false, None).await.unwrap(); + let repeated = auth.is_app_allowed(&info, false, None).await.unwrap(); assert!(first.is_allowed); assert!(!repeated.is_allowed); assert_eq!(repeated.reason, "revoked"); @@ -495,8 +893,18 @@ mod tests { let app = boot_info(10); let kms = boot_info(20); - assert!(auth.is_app_allowed(&app, false).await.unwrap().is_allowed); - assert!(auth.is_app_allowed(&kms, true).await.unwrap().is_allowed); + assert!( + auth.is_app_allowed(&app, false, None) + .await + .unwrap() + .is_allowed + ); + assert!( + auth.is_app_allowed(&kms, true, None) + .await + .unwrap() + .is_allowed + ); let requests = server.join().unwrap(); assert_eq!(requests[0].0, "/bootAuth/app"); @@ -509,6 +917,244 @@ mod tests { assert_ne!(requests[0].1["mrAggregated"], requests[1].1["mrAggregated"]); } + #[rocket::async_test] + async fn authorization_operations_are_typed_and_sent_without_legacy_fallback() { + let operations = [ + Operation::KmsBootstrap, + Operation::KmsServe, + Operation::KmsExportKeys, + Operation::KmsImportKeys, + Operation::AppGetKey, + Operation::AppGetCert, + ]; + let response = r#"{"authorized":true,"rejectionReason":"","gatewayAppId":"","currentRootEpoch":0,"currentAppEpoch":0,"currentRootEpochHash":"0000000000000000000000000000000000000000000000000000000000000000","latestRootEpoch":0,"latestRootEpochHash":"0000000000000000000000000000000000000000000000000000000000000000"}"#; + let (url, server) = serve(vec![response; operations.len()]); + let auth = webhook(url); + for operation in operations { + if operation.is_kms() { + auth.authorize_kms(&boot_info(1), operation, Some(0), "") + .await + .unwrap(); + } else { + auth.authorize_app(&boot_info(1), operation, None, None, "") + .await + .unwrap(); + } + } + let wire_names = [ + "kms_bootstrap", + "kms_serve", + "kms_export_keys", + "kms_import_keys", + "app_get_key", + "app_get_cert", + ]; + for (((route, body), operation), name) in server + .join() + .unwrap() + .into_iter() + .zip(operations) + .zip(wire_names) + { + assert_eq!(body["operation"], name); + assert_eq!( + route, + if operation.is_kms() { + "/authorizeKms" + } else { + "/authorizeApp" + } + ); + assert_eq!( + serde_json::from_value::(body["operation"].clone()).unwrap(), + operation + ); + } + assert!(serde_json::from_str::(r#""unknown""#).is_err()); + } + + #[rocket::async_test] + async fn onboarding_pins_the_registered_root_ca_keys() { + let (url, server) = serve(vec![r#"{"rootCaPubkey":"0x3059"}"#, r#"{"status":"ok"}"#]); + let auth = webhook(url); + assert_eq!(auth.root_ca_pubkey().await.unwrap(), Some(vec![0x30, 0x59])); + // Nothing to pin fails closed: a registry without roots and an auth + // API that predates the field both omit it. + assert!(auth.root_ca_pubkey().await.is_err()); + server.join().unwrap(); + let dev = AuthApi::Dev { + dev: crate::config::Dev { + gateway_app_id: String::new(), + }, + }; + assert_eq!(dev.root_ca_pubkey().await.unwrap(), None); + } + + #[rocket::async_test] + async fn launch_tickets_are_sent_as_hashes() { + let response = r#"{"authorized":true,"rejectionReason":"","gatewayAppId":"","currentRootEpoch":0,"currentAppEpoch":0,"currentRootEpochHash":"0000000000000000000000000000000000000000000000000000000000000000","latestRootEpoch":0,"latestRootEpochHash":"0000000000000000000000000000000000000000000000000000000000000000"}"#; + let (url, server) = serve(vec![response; 3]); + let auth = webhook(url); + let ticket = "t".repeat(32); + let info = boot_info(1); + auth.authorize_app(&info, Operation::AppGetKey, None, None, &ticket) + .await + .unwrap(); + auth.authorize_kms(&info, Operation::KmsImportKeys, Some(0), &ticket) + .await + .unwrap(); + auth.authorize_app(&info, Operation::AppGetCert, None, None, "") + .await + .unwrap(); + // A short ticket is refused before it reaches the backend. + let err = auth + .authorize_app(&info, Operation::AppGetKey, None, None, "short") + .await + .unwrap_err(); + assert!(err.to_string().contains("32 to 1024 bytes"), "{err:#}"); + + let requests = server.join().unwrap(); + let sent = |i: usize| requests[i].1.get("launchTicketHash").cloned(); + let expected = + Some(hex::encode(Sha256::digest(format!("dstack-launch-ticket/v1:{ticket}"))).into()); + assert_eq!(sent(0), expected); + assert_eq!(sent(1), expected); + assert_eq!(sent(2), None); + } + + #[rocket::async_test] + async fn authorization_returns_the_epoch_with_each_decision() { + let response = |allowed: bool, epoch: u32| { + format!( + r#"{{"authorized":{allowed},"rejectionReason":"","gatewayAppId":"gw", "currentRootEpoch":{epoch},"currentAppEpoch":0,"currentRootEpochHash":"0x{}","latestRootEpoch":{latest},"latestRootEpochHash":"0x{}"}}"#, + "11".repeat(32), + "22".repeat(32), + latest = epoch + 1, + ) + }; + let (url, server) = serve(vec![ + response(true, 0), + response(false, 1), + response(true, 1), + response(true, 1), + response(false, 1), + ]); + let auth = webhook(url); + let info = boot_info(50); + let first = auth + .authorize_app(&info, Operation::AppGetKey, None, None, "") + .await + .unwrap(); + let second = auth + .authorize_app(&info, Operation::AppGetKey, None, None, "") + .await + .unwrap(); + assert!(first.authorized); + assert!(!second.authorized); + assert_eq!(first.current_root().unwrap().unwrap().epoch, 0); + assert_eq!(second.current_root().unwrap().unwrap().epoch, 1); + let latest = second.latest_root().unwrap().unwrap(); + assert_eq!((latest.epoch, latest.chain_hash), (2, [0x22; 32])); + auth.authorize_app(&info, Operation::AppGetKey, Some(0), Some(0), "") + .await + .unwrap(); + auth.authorize_kms(&info, Operation::KmsServe, None, "") + .await + .unwrap(); + assert!( + !auth + .authorize_kms(&info, Operation::KmsImportKeys, Some(2), "") + .await + .unwrap() + .authorized + ); + let requests = server.join().unwrap(); + assert_eq!(requests.len(), 5); + assert!(requests[..3] + .iter() + .all(|(path, _)| path == "/authorizeApp")); + assert_eq!(requests[3].0, "/authorizeKms"); + assert_eq!(requests[4].0, "/authorizeKms"); + assert_eq!(requests[4].1["requestedRootEpoch"], 2); + assert!(requests[4].1.get("requestedAppEpoch").is_none()); + let mut expected = serde_json::to_value(info).unwrap(); + expected["operation"] = "app_get_key".into(); + assert_eq!(requests[0].1, expected); + assert_eq!(requests[2].1["requestedAppEpoch"], 0); + assert!(requests[0].1.get("requestedRootEpoch").is_none()); + assert_eq!(requests[2].1["requestedRootEpoch"], 0); + } + + #[test] + fn authorization_requires_the_latest_root_epoch_fields() { + let base = serde_json::json!({ + "authorized": true, "rejectionReason": "", "gatewayAppId": "", + "currentRootEpoch": 0, "currentAppEpoch": 0, + "currentRootEpochHash": format!("0x{}", "11".repeat(32)), + }); + assert!(serde_json::from_value::(base.clone()).is_err()); + let mut unregistered = base.clone(); + unregistered["latestRootEpoch"] = 0.into(); + unregistered["latestRootEpochHash"] = format!("0x{}", "00".repeat(32)).into(); + let result: AuthorizationResult = serde_json::from_value(unregistered).unwrap(); + assert_eq!(result.latest_root().unwrap(), None); + let mut invalid = base; + invalid["latestRootEpoch"] = 0.into(); + invalid["latestRootEpochHash"] = "0x11".into(); + let result: AuthorizationResult = serde_json::from_value(invalid).unwrap(); + assert!(result.latest_root().is_err()); + } + + #[rocket::async_test] + async fn authorization_without_epoch_fields_is_not_accepted_as_legacy() { + let (url, server) = serve(vec![ + r#"{"isAllowed":true,"reason":"","gatewayAppId":"gw"}"#, + ]); + assert!(webhook(url) + .authorize_app(&boot_info(50), Operation::AppGetKey, None, None, "") + .await + .is_err()); + assert_eq!(server.join().unwrap().len(), 1); + } + + #[rocket::async_test] + async fn root_epochs_are_read_from_info_and_sent_in_boot_checks() { + let hash = "0x".to_string() + &"11".repeat(32); + let (url, server) = serve(vec![ + format!( + r#"{{"status":"ok","kmsContractAddr":"0x00","gatewayAppId":"gw","chainId":1, + "appImplementation":"0x00","rootEpoch":3,"rootEpochHash":"{hash}"}}"# + ), + r#"{"status":"ok","kmsContractAddr":"0x00","gatewayAppId":"gw","chainId":1, + "appImplementation":"0x00","rootEpoch":3}"# + .into(), + r#"{"isAllowed":true,"gatewayAppId":"gw","reason":""}"#.into(), + r#"{"isAllowed":true,"gatewayAppId":"gw","reason":""}"#.into(), + ]); + let auth = webhook(url); + let current = CurrentRootEpoch { + epoch: 3, + chain_hash: [0x11; 32], + }; + + assert_eq!( + auth.get_info().await.unwrap().root_epochs, + RootEpochRegistry::Current(current) + ); + assert!(auth.get_info().await.is_err()); + let info = boot_info(50); + auth.is_app_allowed(&info, false, Some(current)) + .await + .unwrap(); + auth.is_app_allowed(&info, true, None).await.unwrap(); + + let requests = server.join().unwrap(); + assert_eq!(requests[2].1["rootEpoch"], 3); + assert_eq!(requests[2].1["rootEpochHash"], hash); + assert_eq!(requests[2].1["appId"], requests[3].1["appId"]); + assert!(requests[3].1.get("rootEpoch").is_none()); + } + #[rocket::async_test] async fn malformed_backend_response_fails_closed_and_next_request_recovers() { let (url, server) = serve(vec![ @@ -518,9 +1164,9 @@ mod tests { let auth = webhook(url); let info = boot_info(30); - let error = auth.is_app_allowed(&info, false).await.unwrap_err(); + let error = auth.is_app_allowed(&info, false, None).await.unwrap_err(); assert!(error.to_string().contains("failed to decode response")); - let recovered = auth.is_app_allowed(&info, false).await.unwrap(); + let recovered = auth.is_app_allowed(&info, false, None).await.unwrap(); assert!(recovered.is_allowed); assert_eq!(recovered.reason, "recovered"); assert_eq!(server.join().unwrap().len(), 2); @@ -537,7 +1183,7 @@ mod tests { let (url, server) = serve(vec![body]); let error = webhook(url) - .is_app_allowed(&boot_info(40), false) + .is_app_allowed(&boot_info(40), false, None) .await .unwrap_err(); diff --git a/dstack/kms/src/onboard_service.rs b/dstack/kms/src/onboard_service.rs index 0476e60de4..45b39be932 100644 --- a/dstack/kms/src/onboard_service.rs +++ b/dstack/kms/src/onboard_service.rs @@ -13,12 +13,12 @@ use dstack_kms_rpc::{ kms_client::KmsClient, onboard_server::{OnboardRpc, OnboardServer}, AttestationInfoResponse, BootstrapRequest, BootstrapResponse, GetKmsKeyRequest, KmsKeyResponse, - OnboardRequest, OnboardResponse, + OnboardRequest, OnboardResponse, SetupStatusResponse, }; use fs_err as fs; use k256::ecdsa::SigningKey; use ra_rpc::{ - client::{CertInfo, RaClient, RaClientConfig}, + client::{CertInfo, PinnedIssuer, RaClientConfig}, CallContext, RpcCall, }; use ra_tls::{ @@ -34,11 +34,13 @@ use tokio::sync::Mutex as AsyncMutex; use tracing::info; use crate::{ - config::KmsConfig, + config::{KmsConfig, RootKeyPaths}, main_service::{ - build_boot_info_for_attestation, + build_boot_info_for_attestation, read_root_attestation, read_root_epoch, root_chain_hashes, + servable_epoch, upgrade_authority::{ app_attest, dstack_client, ensure_kms_allowed, ensure_self_kms_allowed, pad64, + RootEpochRegistration, RootEpochRegistry, }, }, }; @@ -107,6 +109,25 @@ fn validate_onboarding_domain(domain: &str) -> Result<()> { Ok(()) } +fn setup_status(cfg: &KmsConfig) -> Result { + if !cfg.root_keys_exist() { + return Ok(SetupStatusResponse::default()); + } + let root = cfg.root_key_paths(read_root_epoch(cfg)?); + let ca_key = + KeyPair::from_pem(&fs::read_to_string(&root.ca_key)?).context("failed to parse CA key")?; + let k256_key = + SigningKey::from_slice(&fs::read(&root.k256_key)?).context("failed to parse k256 key")?; + let attestation = read_root_attestation(&root)?; + Ok(SetupStatusResponse { + provisioned: true, + ready: cfg.keys_exists(), + k256_pubkey: k256_key.verifying_key().to_sec1_bytes().to_vec(), + ca_pubkey: ca_key.public_key_der(), + attestation, + }) +} + impl OnboardRpc for OnboardHandler { async fn bootstrap(self, request: BootstrapRequest) -> Result { validate_onboarding_domain(&request.domain)?; @@ -118,21 +139,10 @@ impl OnboardRpc for OnboardHandler { ensure_self_kms_allowed(cfg, &self.state.attestation_verifier) .await .context("KMS is not allowed to bootstrap")?; - let keys = Keys::generate(&request.domain, self.state.config.attest_rpc_cert) + let mut keys = Keys::generate(&request.domain, self.state.config.attest_rpc_cert) .await .context("Failed to generate keys")?; - - let k256_pubkey = keys.k256_key.verifying_key().to_sec1_bytes().to_vec(); - let ca_pubkey = keys.ca_key.public_key_der(); - let attestation = attest_keys(&ca_pubkey, &k256_pubkey).await?; - - let response = BootstrapResponse { - ca_pubkey, - k256_pubkey, - attestation, - }; - // Store the bootstrap info - safe_write(cfg.bootstrap_info(), serde_json::to_vec(&response)?)?; + let response = keys.latest.attest().await?; keys.store(cfg)?; Ok(response) } @@ -150,18 +160,34 @@ impl OnboardRpc for OnboardHandler { } else { format!("{source_url}/prpc") }; - let keys = Keys::onboard( + let mut keys = Keys::onboard( cfg, &source_url, &request.source_token, + &request.launch_ticket, &request.domain, + request.rotate, self.state.attestation_verifier.clone(), ) .await .context("Failed to onboard")?; - let k256_pubkey = keys.k256_key.verifying_key().to_sec1_bytes().to_vec(); + if !request.rotate { + let k256_pubkey = keys.latest.k256_pubkey(); + keys.store(cfg).context("Failed to store keys")?; + return Ok(OnboardResponse { + k256_pubkey, + ..Default::default() + }); + } + // The attestation over the new epoch is what governance registers, so + // it is persisted with the keys and stays readable via GetSetupStatus. + let info = keys.latest.attest().await?; keys.store(cfg).context("Failed to store keys")?; - Ok(OnboardResponse { k256_pubkey }) + Ok(OnboardResponse { + k256_pubkey: info.k256_pubkey, + ca_pubkey: info.ca_pubkey, + attestation: info.attestation, + }) } async fn get_attestation_info(self) -> Result { @@ -216,6 +242,11 @@ impl OnboardRpc for OnboardHandler { ) } + async fn get_setup_status(self) -> Result { + let _bootstrap_guard = self.state.bootstrap_lock.lock().await; + setup_status(&self.state.config) + } + async fn finish(self) -> anyhow::Result<()> { let shutdown = self .state @@ -257,6 +288,8 @@ mod tests { use crate::main_service::amd_attest::{ compute_expected_measurement, MeasurementInput, OvmfSectionParam, }; + use crate::main_service::upgrade_authority::CurrentRootEpoch; + use dstack_kms_rpc::KmsKeys; use sha2::Digest; fn hex_of(byte: u8, len: usize) -> String { @@ -326,12 +359,15 @@ mod tests { config: String::new(), report: ra_tls::attestation::DstackVerifiedReport::DstackAmdSevSnp( dstack_attest::amd_sev_snp::VerifiedAmdSnpReport { + cpuid: Some(dstack_attest::amd_sev_snp::AmdSnpCpuid::from_eax( + 0x00a0_0f11, + )), measurement, report_data: [0x42; 64], host_data: mr_config.to_snp_host_data(), chip_id, tcb_info: dstack_attest::amd_sev_snp::AmdSnpTcbInfo::default(), - advisory_ids: Vec::new(), + tcb_status: "UpToDate".into(), }, ), } @@ -438,7 +474,8 @@ mod tests { let overrides = format!( r#" [core] - cert_dir = "{}" + cert_dir = "{0}" + keyring_dir = "{0}/keyring" attest_rpc_cert = false enforce_self_authorization = false @@ -462,8 +499,9 @@ mod tests { let verifier = AttestationVerifier::load(&cfg.attestation).unwrap(); bootstrap_keys(&cfg, &verifier).await.unwrap(); - let root_ca_key = fs::read(cfg.root_ca_key()).unwrap(); - let k256_key = fs::read(cfg.k256_key()).unwrap(); + let root = cfg.root_key_paths(0); + let root_ca_key = fs::read(&root.ca_key).unwrap(); + let k256_key = fs::read(&root.k256_key).unwrap(); // A single missing certificate is enough to make `keys_exists()` false, // which is what sends the KMS back into onboarding on the next start. @@ -475,8 +513,8 @@ mod tests { format!("{err:#}").contains("already been bootstrapped"), "unexpected error: {err:#}" ); - assert_eq!(fs::read(cfg.root_ca_key()).unwrap(), root_ca_key); - assert_eq!(fs::read(cfg.k256_key()).unwrap(), k256_key); + assert_eq!(fs::read(&root.ca_key).unwrap(), root_ca_key); + assert_eq!(fs::read(&root.k256_key).unwrap(), k256_key); } #[rocket::async_test] @@ -485,13 +523,393 @@ mod tests { let cfg = auto_bootstrap_config(cert_dir.path()); let verifier = AttestationVerifier::load(&cfg.attestation).unwrap(); - // A crash between the two root key writes. - fs::write(cfg.root_ca_key(), "stale").unwrap(); + // A crash before the root epoch marker was written. + let root = cfg.root_key_paths(0); + fs::create_dir_all(root.ca_key.parent().unwrap()).unwrap(); + fs::write(&root.ca_key, "stale").unwrap(); assert!(!cfg.root_keys_exist()); bootstrap_keys(&cfg, &verifier).await.unwrap(); assert!(cfg.keys_exists()); - assert_ne!(fs::read(cfg.root_ca_key()).unwrap(), b"stale"); + assert_ne!(fs::read(&root.ca_key).unwrap(), b"stale"); + } + + #[test] + fn setup_status_is_empty_before_root_keys_exist() { + let cert_dir = tempfile::tempdir().unwrap(); + let cfg = auto_bootstrap_config(cert_dir.path()); + let status = setup_status(&cfg).unwrap(); + assert!(!status.provisioned); + assert!(!status.ready); + assert!(status.k256_pubkey.is_empty()); + assert!(status.ca_pubkey.is_empty()); + assert!(status.attestation.is_empty()); + } + + fn handover(epochs: u32) -> KmsKeyResponse { + KmsKeyResponse { + temp_ca_key: String::new(), + keys: (0..epochs) + .map(|epoch| KmsKeys { + ca_key: KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256) + .unwrap() + .serialize_pem(), + k256_key: SigningKey::random(&mut rand::rngs::OsRng) + .to_bytes() + .to_vec(), + attestation: vec![epoch as u8; 4], + }) + .collect(), + } + } + + /// Epoch `epoch` of `res` as governance would register it. + fn epoch_of(res: &KmsKeyResponse, epoch: u32) -> CurrentRootEpoch { + let roots: Vec<_> = res + .keys + .iter() + .map(|k| { + ( + KeyPair::from_pem(&k.ca_key).unwrap().public_key_der(), + SigningKey::from_slice(&k.k256_key) + .unwrap() + .verifying_key() + .to_sec1_bytes() + .to_vec(), + ) + }) + .collect(); + let hashes = dstack_types::root_epoch::chain_hashes( + roots.iter().map(|(ca, k256)| (&ca[..], &k256[..])), + ); + CurrentRootEpoch { + epoch, + chain_hash: hashes[epoch as usize], + } + } + + /// The registry a correct handover of `res` would be checked against. + fn current_of(res: &KmsKeyResponse, epoch: u32) -> RootEpochRegistry { + RootEpochRegistry::Current(epoch_of(res, epoch)) + } + + /// Governance with `current` active and every epoch `res` holds registered. + fn registered(res: &KmsKeyResponse, current: u32) -> RootEpochRegistration { + registered_up_to(res, current, res.keys.len() as u32 - 1) + } + + fn registered_up_to(res: &KmsKeyResponse, current: u32, latest: u32) -> RootEpochRegistration { + RootEpochRegistration { + registry: current_of(res, current), + latest: Some(epoch_of(res, latest)), + } + } + + fn unregistered(registry: RootEpochRegistry) -> RootEpochRegistration { + RootEpochRegistration { + registry, + latest: None, + } + } + + async fn onboard( + cfg: &KmsConfig, + res: KmsKeyResponse, + rotate: bool, + registration: RootEpochRegistration, + ) -> Result { + Keys::from_key_response(cfg, res, "kms.example.com", rotate, registration).await + } + + #[test] + fn generated_keys_report_data_matches_the_published_format() { + let report_data = generated_keys_report_data(&[0xa0; 3], &[0xb0; 3]); + // keccak256("dstack-kms-genereted-keys-v1:a0a0a0;b0b0b0;"), zero-padded to 64 bytes. + assert_eq!( + hex::encode(&report_data), + format!( + "01597f74286b5a55b295f839d5b63946462681c7b07ab93b679262fc10946580{}", + "00".repeat(32) + ) + ); + assert_ne!(generated_keys_report_data(&[], &[0xb0; 3]), report_data); + assert_ne!(generated_keys_report_data(&[0xa0; 3], &[]), report_data); + } + + #[test] + fn compatibility_ca_survives_restart_and_recovers_a_missing_certificate() { + let dir = tempfile::tempdir().unwrap(); + let cfg = auto_bootstrap_config(dir.path()); + let first = ensure_temp_ca(&cfg).unwrap(); + let second = ensure_temp_ca(&cfg).unwrap(); + assert_eq!(first.key.public_key_der(), second.key.public_key_der()); + assert_eq!(first.pem_cert, second.pem_cert); + fs::remove_file(cfg.tmp_ca_cert()).unwrap(); + let recovered = ensure_temp_ca(&cfg).unwrap(); + assert_eq!(first.key.public_key_der(), recovered.key.public_key_der()); + assert!(!cfg.root_keys_exist()); + } + + #[rocket::async_test] + async fn join_imports_and_stores_every_epoch() { + let cert_dir = tempfile::tempdir().unwrap(); + let cfg = auto_bootstrap_config(cert_dir.path()); + let res = handover(3); + let sent = res.keys.clone(); + + let keys = onboard(&cfg, res, false, unregistered(RootEpochRegistry::Unchecked)) + .await + .unwrap(); + keys.store(&cfg).unwrap(); + assert!(cfg.tmp_ca_key().exists()); + assert!(cfg.tmp_ca_cert().exists()); + + assert_eq!(read_root_epoch(&cfg).unwrap(), 2); + for (epoch, sent) in (0..).zip(&sent) { + let root = cfg.root_key_paths(epoch); + assert_eq!(fs::read(&root.k256_key).unwrap(), sent.k256_key); + assert_eq!(fs::read(&root.attestation).unwrap(), sent.attestation); + } + } + + #[rocket::async_test] + async fn rotation_imports_the_keyring_and_generates_the_next_epoch() { + let cert_dir = tempfile::tempdir().unwrap(); + let cfg = auto_bootstrap_config(cert_dir.path()); + let res = handover(2); + let registration = registered(&res, 1); + let sent: Vec<_> = res.keys.iter().map(|k| k.k256_key.clone()).collect(); + + let keys = onboard(&cfg, res, true, registration).await.unwrap(); + assert_eq!(keys.epoch(), 2); + keys.store(&cfg).unwrap(); + + assert_eq!(fs::read(cfg.root_key_paths(1).k256_key).unwrap(), sent[1]); + let current = fs::read(cfg.root_key_paths(2).k256_key).unwrap(); + assert!(!sent.contains(¤t)); + } + + #[rocket::async_test] + async fn onboarding_checks_the_handover_against_the_current_epoch() { + let cert_dir = tempfile::tempdir().unwrap(); + let cfg = auto_bootstrap_config(cert_dir.path()); + let res = handover(2); + let other = handover(2); + + // A join may hold an epoch pending activation beyond the current one. + assert!(onboard(&cfg, res.clone(), false, registered(&res, 1)) + .await + .is_ok()); + assert!(onboard(&cfg, res.clone(), false, registered(&res, 0)) + .await + .is_ok()); + // A rotation must start at the current epoch. + assert!(onboard(&cfg, res.clone(), true, registered(&res, 0)) + .await + .is_err()); + // A keyring other than the registered one. + assert!(onboard(&cfg, res.clone(), false, registered(&other, 1)) + .await + .is_err()); + assert!(onboard(&cfg, res.clone(), true, registered(&other, 1)) + .await + .is_err()); + // A source behind the current epoch. + assert!(onboard(&cfg, handover(1), false, registered(&res, 1)) + .await + .is_err()); + // A missing epoch shifts the rest, so the chain hash no longer matches. + let mut gap = res.clone(); + gap.keys.remove(0); + assert!(onboard(&cfg, gap, false, registered(&res, 0)) + .await + .is_err()); + assert!(onboard( + &cfg, + handover(0), + false, + unregistered(RootEpochRegistry::Unchecked) + ) + .await + .is_err()); + } + + #[rocket::async_test] + async fn onboarding_binds_the_pending_tail_to_the_latest_registered_epoch() { + let cert_dir = tempfile::tempdir().unwrap(); + let cfg = auto_bootstrap_config(cert_dir.path()); + let res = handover(3); + // A registered epoch pending activation imports before activation. + let keys = onboard(&cfg, res.clone(), false, registered(&res, 1)) + .await + .unwrap(); + assert_eq!(keys.epoch(), 2); + // A tail nobody registered is refused. + let error = onboard(&cfg, res.clone(), false, registered_up_to(&res, 1, 1)) + .await + .err() + .unwrap(); + assert!( + format!("{error:#}").contains("source KMS holds unregistered root epochs"), + "{error:#}" + ); + // A tail other than the registered one: same current epoch, different epoch 2. + let mut forked = handover(3); + forked.keys[..2].clone_from_slice(&res.keys[..2]); + let error = onboard(&cfg, forked, false, registered(&res, 1)) + .await + .err() + .unwrap(); + assert!( + format!("{error:#}").contains("are not the registered ones"), + "{error:#}" + ); + // A source behind the latest registered epoch still serves the current one. + let mut behind = res.clone(); + behind.keys.pop(); + assert!( + onboard(&cfg, behind.clone(), false, registered_up_to(&res, 1, 2)) + .await + .is_ok() + ); + // But not behind the current epoch. + assert!(onboard(&cfg, behind, false, registered_up_to(&res, 2, 2)) + .await + .is_err()); + // A tail past the current epoch that stops short of the latest one cannot be + // checked, so a forked epoch 2 is refused while epoch 3 is registered. + let longer = handover(4); + let mut partial = handover(3); + partial.keys[..2].clone_from_slice(&longer.keys[..2]); + let error = onboard(&cfg, partial, false, registered_up_to(&longer, 1, 3)) + .await + .err() + .unwrap(); + assert!( + format!("{error:#}").contains("only epoch 3 can be checked"), + "{error:#}" + ); + } + + #[rocket::async_test] + async fn rotation_refuses_a_registered_epoch_pending_activation() { + let cert_dir = tempfile::tempdir().unwrap(); + let cfg = auto_bootstrap_config(cert_dir.path()); + let res = handover(3); + let mut current = res.clone(); + current.keys.pop(); + // The locally generated epoch would collide with the registered epoch 2. + let error = onboard(&cfg, current.clone(), true, registered_up_to(&res, 1, 2)) + .await + .err() + .unwrap(); + assert!( + format!("{error:#}").contains("activate it before rotating"), + "{error:#}" + ); + assert_eq!( + onboard(&cfg, current.clone(), true, registered(¤t, 1)) + .await + .unwrap() + .epoch(), + 2 + ); + } + + #[rocket::async_test] + async fn an_unregistered_deployment_can_only_join_at_epoch_0() { + let cert_dir = tempfile::tempdir().unwrap(); + let cfg = auto_bootstrap_config(cert_dir.path()); + assert!(onboard( + &cfg, + handover(1), + false, + unregistered(RootEpochRegistry::Empty) + ) + .await + .is_ok()); + assert!(onboard( + &cfg, + handover(2), + false, + unregistered(RootEpochRegistry::Empty) + ) + .await + .is_err()); + assert!(onboard( + &cfg, + handover(1), + true, + unregistered(RootEpochRegistry::Empty) + ) + .await + .is_err()); + } + + /// A stored keyring at `latest`, loaded back. + async fn stored_keyring(epochs: u32) -> (tempfile::TempDir, KmsConfig, KmsKeyResponse) { + let cert_dir = tempfile::tempdir().unwrap(); + let cfg = auto_bootstrap_config(cert_dir.path()); + let res = handover(epochs); + onboard( + &cfg, + res.clone(), + false, + unregistered(RootEpochRegistry::Unchecked), + ) + .await + .unwrap() + .store(&cfg) + .unwrap(); + (cert_dir, cfg, res) + } + + #[rocket::async_test] + async fn a_keyring_serves_the_current_epoch_it_holds() { + use crate::main_service::Keyring; + + let (_dir, cfg, res) = stored_keyring(3).await; + let keyring = Keyring::load(&cfg).unwrap(); + assert_eq!(keyring.latest(), 2); + assert_eq!(keyring.servable_epoch(current_of(&res, 1)).unwrap(), 1); + assert_eq!(keyring.servable_epoch(current_of(&res, 2)).unwrap(), 2); + assert_eq!( + keyring + .servable_epoch(RootEpochRegistry::Unchecked) + .unwrap(), + 2 + ); + assert!(keyring.servable_epoch(RootEpochRegistry::Empty).is_err()); + assert!(keyring.servable_epoch(current_of(&handover(3), 1)).is_err()); + let mut ahead = handover(4); + ahead.keys[..3].clone_from_slice(&res.keys); + assert!(keyring.servable_epoch(current_of(&ahead, 3)).is_err()); + + let (_dir, cfg, _) = stored_keyring(1).await; + let keyring = Keyring::load(&cfg).unwrap(); + assert_eq!(keyring.servable_epoch(RootEpochRegistry::Empty).unwrap(), 0); + } + + #[rocket::async_test] + async fn setup_status_reports_the_latest_epoch() { + let cert_dir = tempfile::tempdir().unwrap(); + let cfg = auto_bootstrap_config(cert_dir.path()); + let mut keys = Keys::generate("kms.example.com", false).await.unwrap(); + keys.latest.attestation = vec![7, 8, 9]; + keys.store(&cfg).unwrap(); + let status = setup_status(&cfg).unwrap(); + assert!(status.provisioned); + assert!(status.ready); + assert_eq!(status.k256_pubkey, keys.latest.k256_pubkey()); + assert_eq!(status.ca_pubkey, keys.latest.ca_key.public_key_der()); + assert_eq!(status.attestation, [7, 8, 9]); + + fs::remove_file(cfg.rpc_cert()).unwrap(); + assert!(!setup_status(&cfg).unwrap().ready); + + fs::write(cfg.root_key_paths(0).k256_key, b"invalid key").unwrap(); + let err = setup_status(&cfg).unwrap_err(); + assert!(format!("{err:#}").contains("failed to parse k256 key")); } #[test] @@ -505,12 +923,70 @@ mod tests { } } -struct Keys { - k256_key: SigningKey, - tmp_ca_key: KeyPair, - tmp_ca_cert: Certificate, +/// The root keys of one epoch. +struct EpochRoot { ca_key: KeyPair, ca_cert: Certificate, + k256_key: SigningKey, + /// Evidence produced when the keys were generated; empty if there is none. + attestation: Vec, +} + +impl EpochRoot { + fn new(ca_key: KeyPair, k256_key: SigningKey, attestation: Vec) -> Result { + let ca_cert = self_signed_root_ca(&ca_key)?; + Ok(Self { + ca_key, + ca_cert, + k256_key, + attestation, + }) + } + + fn generate() -> Result { + Self::new( + KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256)?, + SigningKey::random(&mut rand::rngs::OsRng), + Vec::new(), + ) + } + + fn k256_pubkey(&self) -> Vec { + self.k256_key.verifying_key().to_sec1_bytes().to_vec() + } + + /// Attest the freshly generated keys and keep the attestation with them. + async fn attest(&mut self) -> Result { + let ca_pubkey = self.ca_key.public_key_der(); + let k256_pubkey = self.k256_pubkey(); + self.attestation = attest_keys(&ca_pubkey, &k256_pubkey).await?; + Ok(BootstrapResponse { + ca_pubkey, + k256_pubkey, + attestation: self.attestation.clone(), + }) + } + + fn store(&self, paths: &RootKeyPaths) -> Result<()> { + safe_write(&paths.ca_cert, self.ca_cert.pem())?; + if !self.attestation.is_empty() { + safe_write(&paths.attestation, &self.attestation)?; + } else if let Err(err) = fs::remove_file(&paths.attestation) { + // An interrupted attempt may have left one for other keys. + if err.kind() != std::io::ErrorKind::NotFound { + return Err(err.into()); + } + } + safe_write_with_mode(&paths.ca_key, self.ca_key.serialize_pem(), 0o600)?; + safe_write_with_mode(&paths.k256_key, self.k256_key.to_bytes(), 0o600)?; + Ok(()) + } +} + +struct Keys { + /// Root keys of the epochs before the latest, indexed by epoch. + history: Vec, + latest: EpochRoot, rpc_key: KeyPair, rpc_cert: Certificate, rpc_domain: String, @@ -518,91 +994,45 @@ struct Keys { impl Keys { async fn generate(domain: &str, attest_rpc_cert: bool) -> Result { - let tmp_ca_key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256)?; - let ca_key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256)?; - let rpc_key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256)?; - let k256_key = SigningKey::random(&mut rand::rngs::OsRng); - Self::from_keys( - tmp_ca_key, - ca_key, - rpc_key, - k256_key, - domain, - attest_rpc_cert, - ) - .await + Self::new(Vec::new(), EpochRoot::generate()?, domain, attest_rpc_cert).await } - async fn from_keys( - tmp_ca_key: KeyPair, - ca_key: KeyPair, - rpc_key: KeyPair, - k256_key: SigningKey, + /// Issue a fresh RPC certificate under the `latest` root. + async fn new( + history: Vec, + latest: EpochRoot, domain: &str, attest_rpc_cert: bool, ) -> Result { - let tmp_ca_cert = CertRequest::builder() - .org_name("Dstack") - .subject("Dstack Client Temp CA") - .ca_level(0) - .key(&tmp_ca_key) - .build() - .self_signed()?; - - // Create self-signed KMS cert - let ca_cert = CertRequest::builder() - .org_name("Dstack") - .subject("Dstack KMS CA") - .ca_level(1) - .key(&ca_key) - .build() - .self_signed()?; - // The only place the KMS embeds its own attestation. Skipping it lets - // the KMS run outside a TEE for development; it does not affect the - // verification of quotes presented *to* the KMS, which is a separate - // path (main_service::ensure_app_attestation_allowed) and stays on. - let attestation = if attest_rpc_cert { - let pubkey = rpc_key.public_key_der(); - let report_data = QuoteContentType::RaTlsCert.to_report_data(&pubkey); - let response = app_attest(report_data.to_vec()).await.context( - "failed to get a quote for the KMS RPC certificate. The KMS attests \ - itself through the dstack guest agent, so it must run inside a dstack \ - CVM. For local development set attest_rpc_cert = false", - )?; - Some( - VersionedAttestation::from_bytes(&response.attestation) - .context("Invalid attestation")?, - ) - } else { - None - }; - - // Sign WWW server cert with KMS cert - let rpc_cert = CertRequest::builder() - .subject(domain) - .alt_names(&[domain.to_string()]) - .special_usage("kms:rpc") - .maybe_attestation(attestation.as_ref()) - .key(&rpc_key) - .build() - .signed_by(&ca_cert, &ca_key)?; - Ok(Keys { - k256_key, - tmp_ca_key, - tmp_ca_cert, - ca_key, - ca_cert, + let rpc_key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256)?; + let rpc_cert = issue_rpc_cert( + &latest.ca_cert, + &latest.ca_key, + &rpc_key, + domain, + attest_rpc_cert, + ) + .await?; + Ok(Self { + history, + latest, rpc_key, rpc_cert, rpc_domain: domain.to_string(), }) } + fn epoch(&self) -> u32 { + self.history.len() as u32 + } + async fn onboard( cfg: &KmsConfig, other_kms_url: &str, source_token: &str, + launch_ticket: &str, domain: &str, + rotate: bool, attestation_verifier: Arc, ) -> Result { let attestation_slot = Arc::new(Mutex::new(None::)); @@ -628,132 +1058,190 @@ impl Keys { .context("Missing source KMS attestation") }; - if !source_token.is_empty() { - // `other_kms_url` is the source's admin listener. It accepts a self-issued - // RA-TLS client certificate, so no temp CA is fetched first. - let (ra_cert, ra_key) = gen_ra_cert(None).await?; - let client = RaClientConfig::builder() - .tls_no_check(true) - .tls_built_in_root_certs(false) + // Send the launch ticket and the admin token only to a KMS serving the + // registered roots: at the handshake, its RPC certificate must be + // signed by the current root CA registered with our own auth API. + let pin = cfg + .auth_api + .root_ca_pubkey() + .await + .context("failed to get the registered root CA key")? + .map(|pubkey| PinnedIssuer { + pubkey, + usage: "kms:rpc".into(), + }); + let pinned_client = || { + RaClientConfig::builder() + .tls_skip_ca_verification(true) + .maybe_tls_pinned_issuer(pin.clone()) .remote_uri(other_kms_url.to_string()) - .tls_client_cert(ra_cert) - .tls_client_key(ra_key) - .cert_validator(capture_source_attestation) - .attestation_verifier(attestation_verifier.clone()) - .bearer_token(source_token.to_string()) - .build() - .into_client()?; - let info = dstack_client().info().await.context("Failed to get info")?; - let keys_res = AdminClient::new(client) - .get_kms_key(GetKmsKeyRequest { - vm_config: info.vm_config, - }) - .await?; - // The attestation is only captured by that first request; nothing - // received is used before the source passes this check. - ensure_kms_allowed(cfg, &source_attestation()?, &attestation_verifier) + }; + let temp_ca = if source_token.is_empty() { + let client = pinned_client().build().into_client()?; + let ca = KmsClient::new(client) + .get_temp_ca_cert() .await - .context("Source KMS is not allowed for onboarding")?; - return Self::from_key_response(cfg, keys_res, domain).await; - } - - let client = RaClientConfig::builder() - .tls_no_check(true) - .remote_uri(other_kms_url.to_string()) + .context("failed to get the temporary CA from the source KMS")?; + Some((ca.temp_ca_cert, ca.temp_ca_key)) + } else { + None + }; + let (ra_cert, ra_key) = gen_ra_cert(temp_ca).await?; + let client = pinned_client() + .tls_built_in_root_certs(false) + .tls_client_cert(ra_cert) + .tls_client_key(ra_key) .cert_validator(capture_source_attestation) .attestation_verifier(attestation_verifier.clone()) + .maybe_bearer_token((!source_token.is_empty()).then(|| source_token.to_string())) .build() .into_client()?; - let mut kms_client = KmsClient::new(client); - - let tmp_ca = kms_client.get_temp_ca_cert().await?; - let (ra_cert, ra_key) = - gen_ra_cert(Some((tmp_ca.temp_ca_cert, tmp_ca.temp_ca_key))).await?; - let ra_client = RaClient::new_mtls( - other_kms_url.into(), - ra_cert, - ra_key, - attestation_verifier.clone(), - ) - .context("Failed to create client")?; - kms_client = KmsClient::new(ra_client); - ensure_kms_allowed(cfg, &source_attestation()?, &attestation_verifier) - .await - .context("Source KMS is not allowed for onboarding")?; - let info = dstack_client().info().await.context("Failed to get info")?; - let keys_res = kms_client - .get_kms_key(GetKmsKeyRequest { - vm_config: info.vm_config, - }) - .await?; - Self::from_key_response(cfg, keys_res, domain).await + let request = GetKmsKeyRequest { + vm_config: info.vm_config, + launch_ticket: launch_ticket.to_string(), + }; + let keys_res = if source_token.is_empty() { + KmsClient::new(client).get_kms_key(request).await + } else { + AdminClient::new(client).get_kms_key(request).await + } + .context("failed to get the keys from the source KMS")?; + // The attestation is captured only on the connection that returned the keys; + // nothing received is used before the source passes this check. + let highest = keys_res + .keys + .len() + .checked_sub(1) + .context("source KMS handed over no keys")?; + let highest = u32::try_from(highest).context("too many root epochs")?; + let registration = ensure_kms_allowed(cfg, &source_attestation()?, highest) + .await + .context("source KMS is not allowed for onboarding")?; + Self::from_key_response(cfg, keys_res, domain, rotate, registration).await } + /// Import the source's whole keyring, epochs 0..=latest; a rotation then + /// generates epoch latest+1. async fn from_key_response( cfg: &KmsConfig, keys_res: KmsKeyResponse, domain: &str, + rotate: bool, + registration: RootEpochRegistration, ) -> Result { - if keys_res.keys.len() != 1 { - return Err(anyhow::anyhow!("Invalid keys")); + let mut history = keys_res + .keys + .into_iter() + .map(|keys| { + let ca_key = KeyPair::from_pem(&keys.ca_key).context("Failed to parse CA key")?; + let k256_key = + SigningKey::from_slice(&keys.k256_key).context("Failed to parse ECDSA key")?; + EpochRoot::new(ca_key, k256_key, keys.attestation) + }) + .collect::>>()?; + if history.is_empty() { + bail!("source KMS handed over no keys"); } - let keys = keys_res.keys[0].clone(); - let tmp_ca_key_pem = keys_res.temp_ca_key; - let root_ca_key_pem = keys.ca_key; - let root_k256_key = keys.k256_key; - - let rpc_key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256)?; - let ca_key = KeyPair::from_pem(&root_ca_key_pem).context("Failed to parse CA key")?; - let tmp_ca_key = - KeyPair::from_pem(&tmp_ca_key_pem).context("Failed to parse tmp CA key")?; - let ecdsa_key = - SigningKey::from_slice(&root_k256_key).context("Failed to parse ECDSA key")?; - Self::from_keys( - tmp_ca_key, - ca_key, - rpc_key, - ecdsa_key, - domain, - cfg.attest_rpc_cert, - ) - .await + ensure_handover_registered(&history, registration, rotate)?; + let latest = if rotate { + EpochRoot::generate()? + } else { + history.pop().context("source KMS handed over no keys")? + }; + Self::new(history, latest, domain, cfg.attest_rpc_cert).await } - /// The root keys go last: see [`KmsConfig::root_keys_exist`]. + /// The root epoch marker goes last: see [`KmsConfig::root_keys_exist`]. fn store(&self, cfg: &KmsConfig) -> Result<()> { - self.store_certs(cfg)?; + ensure_temp_ca(cfg)?; + safe_write(cfg.rpc_cert(), self.rpc_cert.pem())?; safe_write(cfg.rpc_domain(), self.rpc_domain.as_bytes())?; - self.store_keys(cfg)?; - Ok(()) - } - - fn store_keys(&self, cfg: &KmsConfig) -> Result<()> { - safe_write_with_mode(cfg.tmp_ca_key(), self.tmp_ca_key.serialize_pem(), 0o600)?; safe_write_with_mode(cfg.rpc_key(), self.rpc_key.serialize_pem(), 0o600)?; - safe_write_with_mode(cfg.root_ca_key(), self.ca_key.serialize_pem(), 0o600)?; - safe_write_with_mode(cfg.k256_key(), self.k256_key.to_bytes(), 0o600)?; + for (epoch, root) in (0..).zip(self.history.iter().chain([&self.latest])) { + root.store(&cfg.root_key_paths(epoch))?; + } + safe_write(cfg.root_epoch(), self.epoch().to_string())?; Ok(()) } +} - fn store_certs(&self, cfg: &KmsConfig) -> Result<()> { - safe_write(cfg.tmp_ca_cert(), self.tmp_ca_cert.pem())?; - safe_write(cfg.root_ca_cert(), self.ca_cert.pem())?; - safe_write(cfg.rpc_cert(), self.rpc_cert.pem())?; - Ok(()) +/// Issue the KMS RPC certificate under the root CA `ca_cert`. +async fn issue_rpc_cert( + ca_cert: &Certificate, + ca_key: &KeyPair, + rpc_key: &KeyPair, + domain: &str, + attest_rpc_cert: bool, +) -> Result { + // The only place the KMS embeds its own attestation. Skipping it lets + // the KMS run outside a TEE for development; it does not affect the + // verification of quotes presented *to* the KMS, which is a separate + // path (main_service::ensure_app_attestation_allowed) and stays on. + let attestation = if attest_rpc_cert { + let pubkey = rpc_key.public_key_der(); + let report_data = QuoteContentType::RaTlsCert.to_report_data(&pubkey); + let response = app_attest(report_data.to_vec()).await.context( + "failed to get a quote for the KMS RPC certificate. The KMS attests \ + itself through the dstack guest agent, so it must run inside a dstack \ + CVM. For local development set attest_rpc_cert = false", + )?; + Some( + VersionedAttestation::from_bytes(&response.attestation) + .context("Invalid attestation")?, + ) + } else { + None + }; + + // Sign WWW server cert with KMS cert + CertRequest::builder() + .subject(domain) + .alt_names(&[domain.to_string()]) + .special_usage("kms:rpc") + .maybe_attestation(attestation.as_ref()) + .key(rpc_key) + .build() + .signed_by(ca_cert, ca_key) +} + +/// Keep the public compatibility CA independent of all epoch root keys. +pub(crate) fn ensure_temp_ca(cfg: &KmsConfig) -> Result { + let had_key = cfg.tmp_ca_key().exists(); + let key = if had_key { + KeyPair::from_pem(&fs::read_to_string(cfg.tmp_ca_key())?)? + } else { + let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256)?; + safe_write_with_mode(cfg.tmp_ca_key(), key.serialize_pem(), 0o600)?; + key + }; + let cert = CertRequest::builder() + .org_name("Dstack") + .subject("Dstack Client Temp CA") + .ca_level(0) + .key(&key) + .build() + .self_signed()?; + if had_key && cfg.tmp_ca_cert().exists() { + renew_ca_cert_if_expiring( + cfg.tmp_ca_cert(), + cert.pem(), + "temporary client CA certificate", + )?; + } else { + safe_write(cfg.tmp_ca_cert(), cert.pem())?; } + CaCert::load(cfg.tmp_ca_cert(), cfg.tmp_ca_key()) } -pub(crate) async fn update_certs(cfg: &KmsConfig) -> Result<()> { - // Read existing keys - let tmp_ca_key = KeyPair::from_pem(&fs::read_to_string(cfg.tmp_ca_key())?)?; - let ca_key = KeyPair::from_pem(&fs::read_to_string(cfg.root_ca_key())?)?; +/// Reissue the RPC certificate under the root CA of the served `epoch`, so +/// guests reach this KMS through the CA of the keys it serves. +pub(crate) async fn update_certs(cfg: &KmsConfig, epoch: u32) -> Result<()> { + ensure_temp_ca(cfg)?; + let root = cfg.root_key_paths(epoch); + let ca_key = KeyPair::from_pem(&fs::read_to_string(&root.ca_key)?)?; let rpc_key = KeyPair::from_pem(&fs::read_to_string(cfg.rpc_key())?)?; - // Read k256 key - let k256_key_bytes = fs::read(cfg.k256_key())?; - let k256_key = SigningKey::from_slice(&k256_key_bytes)?; - let domain = if cfg.onboard.auto_bootstrap_domain.is_empty() { fs::read_to_string(cfg.rpc_domain())? } else { @@ -761,32 +1249,15 @@ pub(crate) async fn update_certs(cfg: &KmsConfig) -> Result<()> { }; let domain = domain.trim(); - // Regenerate certificates using existing keys - let keys = Keys::from_keys( - tmp_ca_key, - ca_key, - rpc_key, - k256_key, - domain, - cfg.attest_rpc_cert, - ) - .await - .context("Failed to regenerate certificates")?; - - renew_ca_cert_if_expiring( - cfg.root_ca_cert(), - keys.ca_cert.pem(), - "KMS root CA certificate", - )?; - renew_ca_cert_if_expiring( - cfg.tmp_ca_cert(), - keys.tmp_ca_cert.pem(), - "temporary client CA certificate", - )?; + let ca_cert = self_signed_root_ca(&ca_key)?; + let rpc_cert = issue_rpc_cert(&ca_cert, &ca_key, &rpc_key, domain, cfg.attest_rpc_cert) + .await + .context("Failed to regenerate certificates")?; + renew_ca_cert_if_expiring(&root.ca_cert, ca_cert.pem(), "KMS root CA certificate")?; // The RPC leaf depends on the refreshed domain and platform attestation, so // it is reissued on every startup. - safe_write(cfg.rpc_cert(), keys.rpc_cert.pem())?; + safe_write(cfg.rpc_cert(), rpc_cert.pem())?; info!("Reissued the KMS RPC certificate for {domain}"); Ok(()) @@ -836,21 +1307,98 @@ pub(crate) async fn bootstrap_keys(cfg: &KmsConfig, verifier: &AttestationVerifi ensure_self_kms_allowed(cfg, verifier) .await .context("KMS is not allowed to auto-bootstrap")?; - let keys = Keys::generate(&cfg.onboard.auto_bootstrap_domain, cfg.attest_rpc_cert) + let mut keys = Keys::generate(&cfg.onboard.auto_bootstrap_domain, cfg.attest_rpc_cert) .await .context("Failed to generate keys")?; + if cfg.attest_rpc_cert { + keys.latest.attest().await?; + } keys.store(cfg)?; Ok(()) } +/// Check the handed-over roots against governance: they must include the +/// current epoch with a matching chain hash, and nothing beyond the latest +/// registered epoch. When the source holds the latest registered epoch, its +/// cumulative chain hash binds the pending tail as well. A rotation must start +/// from the current epoch with nothing pending activation, or it would collide +/// with the next registered epoch. +fn ensure_handover_registered( + roots: &[EpochRoot], + registration: RootEpochRegistration, + rotate: bool, +) -> Result<()> { + let RootEpochRegistration { registry, latest } = registration; + if rotate && registry == RootEpochRegistry::Empty { + bail!("register root epoch 0 before rotating"); + } + let hashes = root_chain_hashes(roots.iter().map(|root| (&root.ca_key, &root.k256_key))); + let current = servable_epoch(&hashes, registry)?; + let held = roots.len() as u32 - 1; + if let Some(latest) = latest { + if held > latest.epoch { + bail!( + "source KMS holds unregistered root epochs (up to {held}, registered up to {}); \ + register them first or onboard from another source", + latest.epoch + ); + } + // Only the latest registered epoch's hash binds epochs past the current one. + if held > current && held < latest.epoch { + bail!( + "source KMS holds root epochs up to {held}, past the current {current}, but only \ + epoch {} can be checked; onboard from a source holding every registered epoch", + latest.epoch + ); + } + if held == latest.epoch && hashes[held as usize] != latest.chain_hash { + bail!( + "the source root keys up to epoch {held} are not the registered ones; \ + onboard from another source" + ); + } + if rotate && latest.epoch != current { + bail!( + "root epoch {} is registered but {current} is current; activate it before rotating", + latest.epoch + ); + } + } + if rotate && current != held { + bail!( + "the source holds root epochs up to {held}, but {current} is current; rotate from \ + a source at the current epoch with no epoch pending activation" + ); + } + Ok(()) +} + +fn self_signed_root_ca(ca_key: &KeyPair) -> Result { + CertRequest::builder() + .org_name("Dstack") + .subject("Dstack KMS CA") + .ca_level(1) + .key(ca_key) + .build() + .self_signed() +} + +/// Report data binding freshly generated root public keys, for every epoch. The +/// evidence only proves the keys were generated in an approved TEE; the epoch +/// number and preceding chain come from the on-chain registration. The +/// "genereted" spelling is part of the released format. +fn generated_keys_report_data(p256_pubkey: &[u8], k256_pubkey: &[u8]) -> Vec { + let content = format!( + "dstack-kms-genereted-keys-v1:{};{};", + hex::encode(p256_pubkey), + hex::encode(k256_pubkey) + ); + pad64(keccak256(content.as_bytes())) +} + async fn attest_keys(p256_pubkey: &[u8], k256_pubkey: &[u8]) -> Result> { - let p256_hex = hex::encode(p256_pubkey); - let k256_hex = hex::encode(k256_pubkey); - let content_to_quote = format!("dstack-kms-genereted-keys-v1:{p256_hex};{k256_hex};"); - let hash = keccak256(content_to_quote.as_bytes()); - let report_data = pad64(hash); - let res = app_attest(report_data).await?; - Ok(res.attestation) + let report_data = generated_keys_report_data(p256_pubkey, k256_pubkey); + Ok(app_attest(report_data).await?.attestation) } fn keccak256(msg: &[u8]) -> [u8; 32] { @@ -860,7 +1408,7 @@ fn keccak256(msg: &[u8]) -> [u8; 32] { hasher.finalize().into() } -/// Mint an RA-TLS client certificate, signed by `ca` (cert and key PEM) or self-issued. +/// Legacy sources require a temp-CA-issued client certificate. async fn gen_ra_cert(ca: Option<(String, String)>) -> Result<(String, String)> { use ra_tls::cert::CertRequest; use ra_tls::rcgen::{KeyPair, PKCS_ECDSA_P256_SHA256}; @@ -874,14 +1422,15 @@ async fn gen_ra_cert(ca: Option<(String, String)>) -> Result<(String, String)> { let attestation = VersionedAttestation::from_bytes(&response.attestation).context("Invalid attestation")?; let req = CertRequest::builder() - .subject("RA-TLS TEMP Cert") + .subject("RA-TLS Client Cert") .attestation(&attestation) .key(&key) + .usage_client_auth(true) .build(); let cert = match ca { - Some((cert_pem, key_pem)) => CaCert::new(cert_pem, key_pem)?.sign(req), + Some((cert, key)) => CaCert::new(cert, key)?.sign(req), None => req.self_signed(), } - .context("Failed to sign certificate")?; + .context("failed to sign client certificate")?; Ok((cert.pem(), key.serialize_pem())) } diff --git a/dstack/kms/src/readonly_service.rs b/dstack/kms/src/readonly_service.rs new file mode 100644 index 0000000000..8c6a8ad71f --- /dev/null +++ b/dstack/kms/src/readonly_service.rs @@ -0,0 +1,39 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// +// SPDX-License-Identifier: Apache-2.0 + +//! The read-only KMS RPCs, served on the `[listeners.public]` listener. + +use anyhow::Result; +use dstack_kms_rpc::{ + kms_server::KmsRpc, + read_only_server::{ReadOnlyRpc, ReadOnlyServer}, + AppId, GetMetaResponse, PublicKeyResponse, SealedEnvPubKeyResponse, +}; +use ra_rpc::{CallContext, RpcCall}; + +use crate::main_service::{KmsState, RpcHandler}; + +pub struct ReadOnlyRpcHandler(RpcHandler); + +impl ReadOnlyRpc for ReadOnlyRpcHandler { + async fn get_meta(self) -> Result { + self.0.get_meta().await + } + + async fn get_app_env_encrypt_pub_key(self, request: AppId) -> Result { + self.0.get_app_env_encrypt_pub_key(request).await + } + + async fn get_sealed_env_pub_key(self, request: AppId) -> Result { + self.0.get_sealed_env_pub_key(request).await + } +} + +impl RpcCall for ReadOnlyRpcHandler { + type PrpcService = ReadOnlyServer; + + fn construct(context: CallContext<'_, KmsState>) -> Result { + Ok(Self(RpcHandler::from_context(context))) + } +} diff --git a/dstack/kms/src/www/onboard.html b/dstack/kms/src/www/onboard.html index a61d411fee..ea233938f0 100644 --- a/dstack/kms/src/www/onboard.html +++ b/dstack/kms/src/www/onboard.html @@ -81,10 +81,23 @@ cursor: pointer; } - button:hover { + button:not(:disabled):hover { background-color: #0056b3; } + button:disabled { + background-color: #6c757d; + cursor: wait; + opacity: 0.7; + } + + fieldset { + border: none; + margin: 0; + padding: 0; + min-width: 0; + } + .error { color: #dc3545; margin-top: 10px; @@ -210,10 +223,10 @@

Chain Info

-
+
- - + +
@@ -221,39 +234,56 @@

Chain Info

Bootstrap A New KMS Instance

-
- - -
- +
+
+ + +
+ + +
-

Onboard from an Existing KMS Instance

-
- - -
-
- - -
-
- - -
- +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
+ + +
+ + +
-
@@ -267,7 +297,7 @@

Onboard from an Existing KMS Instance

- +
@@ -292,11 +322,14 @@

Onboard from an Existing KMS Instance

bootstrapDomain: '', sourceUrl: '', sourceToken: '', + launchTicket: '', onboardDomain: '', + rotate: false, error: '', success: '', result: '', setupFinished: false, + busy: true, attestationInfo: null, attestationLoading: true, attestationError: '', @@ -304,65 +337,91 @@

Onboard from an Existing KMS Instance

} }, async mounted() { - try { - const data = await rpcCall('GetAttestationInfo', {}); - if (data.error) { - this.attestationError = data.error; - } else { - this.attestationInfo = data; - if (data.site_name) { - this.siteName = data.site_name; - document.title = data.site_name; - } + rpcCall('GetAttestationInfo', {}).then(attestation => { + if (attestation.error) throw new Error(attestation.error); + this.attestationInfo = attestation; + if (attestation.site_name) { + this.siteName = attestation.site_name; + document.title = attestation.site_name; } - } catch (err) { + }).catch(err => { this.attestationError = err.message; - } finally { + }).finally(() => { this.attestationLoading = false; + }); + const setup = await rpcCall('GetSetupStatus', {}).catch(err => ({ error: err.message })); + if (setup.error) { + this.error = setup.error; + } else if (setup.provisioned) { + this.applySetupStatus(setup); } + this.busy = false; }, methods: { + applySetupStatus(data) { + if (data.provisioned && !data.ready) { + this.selectedOption = null; + this.error = 'KMS setup is incomplete; root keys exist but required certificates are missing'; + return; + } + if (data.attestation) { + this.success = 'Root keys ready!'; + this.result = JSON.stringify({ + caPubkey: '0x' + data.ca_pubkey, + k256Pubkey: '0x' + data.k256_pubkey, + attestation: '0x' + data.attestation + }, null, 2); + } else { + this.success = 'Onboarding successful!'; + this.result = JSON.stringify({ + k256Pubkey: '0x' + data.k256_pubkey, + }, null, 2); + } + this.error = ''; + }, + async recoverSetupStatus(err) { + this.error = err.message; + const setup = await rpcCall('GetSetupStatus', {}).catch(() => ({})); + if (setup.provisioned) this.applySetupStatus(setup); + }, async handleBootstrap() { + this.busy = true; try { - const { ca_pubkey, k256_pubkey, attestation, error } = await rpcCall('Bootstrap', { + const data = await rpcCall('Bootstrap', { domain: this.bootstrapDomain }); - if (error) throw new Error(error); + if (data.error) throw new Error(data.error); - this.success = 'Bootstrap successful!'; - this.result = JSON.stringify({ - caPubkey: '0x' + ca_pubkey, - k256Pubkey: '0x' + k256_pubkey, - attestation: '0x' + attestation - }, null, 2); - this.error = ''; + this.applySetupStatus(data); } catch (err) { - this.error = err.message; - this.success = ''; + await this.recoverSetupStatus(err); + } finally { + this.busy = false; } }, async handleOnboard() { + this.busy = true; try { const data = await rpcCall('Onboard', { source_url: this.sourceUrl + "/prpc", source_token: this.sourceToken, - domain: this.onboardDomain + launch_ticket: this.launchTicket.trim(), + domain: this.onboardDomain, + rotate: this.rotate }); if (data.error) throw new Error(data.error); - this.success = 'Onboarding successful!'; - this.result = JSON.stringify({ - k256Pubkey: '0x' + data.k256_pubkey, - }, null, 2); - this.error = ''; + this.applySetupStatus(data); } catch (err) { - this.error = err.message; - this.success = ''; + await this.recoverSetupStatus(err); + } finally { + this.busy = false; } }, async handleFinish() { + this.busy = true; try { const response = await fetch("/finish"); if (!response.ok) throw new Error(response.statusText); @@ -372,7 +431,8 @@

Onboard from an Existing KMS Instance

this.setupFinished = true; } catch (err) { this.error = err.message; - this.success = ''; + } finally { + this.busy = false; } } } diff --git a/dstack/load_config/Cargo.toml b/dstack/load_config/Cargo.toml index 4ff4b140ba..4739c89b0b 100644 --- a/dstack/load_config/Cargo.toml +++ b/dstack/load_config/Cargo.toml @@ -10,6 +10,7 @@ edition.workspace = true license.workspace = true [dependencies] +anyhow.workspace = true figment = { workspace = true, features = ["json", "toml"] } rocket.workspace = true tracing.workspace = true diff --git a/dstack/load_config/src/lib.rs b/dstack/load_config/src/lib.rs index cd99b6cf78..68ef7c6505 100644 --- a/dstack/load_config/src/lib.rs +++ b/dstack/load_config/src/lib.rs @@ -8,6 +8,9 @@ use figment::{ }; use tracing::info; +mod listeners; +pub use listeners::{listener_figment, reject_moved_settings}; + trait MaybeNested { fn maybe_nested(self, nested: bool) -> Self; } diff --git a/dstack/load_config/src/listeners.rs b/dstack/load_config/src/listeners.rs new file mode 100644 index 0000000000..a8f3aa4a67 --- /dev/null +++ b/dstack/load_config/src/listeners.rs @@ -0,0 +1,72 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// +// SPDX-License-Identifier: Apache-2.0 + +//! Services that serve several Rocket listeners, each configured in +//! `[listeners.]` on top of the shared `[listeners.default]`. + +use std::collections::BTreeSet; + +use anyhow::{bail, Result}; +use figment::{providers::Serialized, value::Dict, Figment, Provider, Source}; + +/// The Rocket config of listener `name`: `[listeners.default]` without the +/// `uninherited` keys, overridden by `[listeners.]`. +pub fn listener_figment(figment: &Figment, name: &str, uninherited: &[&str]) -> Result { + let mut defaults = figment + .find_value("listeners.default") + .ok() + .and_then(|value| value.into_dict()) + .unwrap_or_default(); + defaults.retain(|key, _| !uninherited.contains(&key.as_str())); + let listener = figment.find_value(&format!("listeners.{name}"))?; + Ok(Figment::from(rocket::Config::default()) + .merge(Serialized::defaults(defaults)) + .merge(Serialized::defaults(listener))) +} + +/// Refuse a config that sets a setting at its old location: each `(old, new)` +/// in `moved`, and any other top-level key besides `core` and `listeners`, +/// which the old listeners read as Rocket settings. The defaults use only the +/// new locations, so a key present was set by the operator. Rocket's own +/// defaults are always present at the top level, so those keys count only when +/// a config file sets them. +pub fn reject_moved_settings(figment: &Figment, moved: &[(&str, &str)]) -> Result<()> { + let rocket_keys = keys(&Figment::from(rocket::Config::default()))?; + let is_set = |key: &str| { + figment.find_value(key).is_ok() + && (!rocket_keys.contains(key) + || figment + .find_metadata(key) + .is_some_and(|meta| matches!(meta.source, Some(Source::File(_))))) + }; + let mut found: Vec = moved + .iter() + .filter(|(old, _)| is_set(old)) + .map(|(old, new)| format!("{old} -> {new}")) + .collect(); + found.extend( + keys(figment)? + .into_iter() + .filter(|key| !["core", "listeners"].contains(&key.as_str())) + .filter(|key| !moved.iter().any(|(old, _)| old == key)) + .filter(|key| is_set(key)) + .map(|key| format!("{key} -> listeners.default.{key}")), + ); + if !found.is_empty() { + bail!( + "the config sets listener settings at their old locations; move them: {}", + found.join(", ") + ); + } + Ok(()) +} + +/// The top-level keys of every profile. +fn keys(provider: &impl Provider) -> Result> { + Ok(provider + .data()? + .into_values() + .flat_map(Dict::into_keys) + .collect()) +} diff --git a/dstack/local-key-provider/src/provider.rs b/dstack/local-key-provider/src/provider.rs index 9445648e6e..5a13746fd4 100644 --- a/dstack/local-key-provider/src/provider.rs +++ b/dstack/local-key-provider/src/provider.rs @@ -4,7 +4,7 @@ use dcap_qvl::{ collateral::CollateralClient, - quote::{Quote, TDAttributes, TDReport10}, + quote::{Quote, TDReport10}, }; use sha2::{Digest, Sha256}; use tracing::{debug, info}; @@ -76,30 +76,30 @@ impl KeyProvider { } } +/// `TD_ATTRIBUTES` bit 28; every TD must set it. +const SEPT_VE_DISABLE: u64 = 1 << 28; +/// The `TD_ATTRIBUTES` bits a TD may set: SEPT_VE_DISABLE, PKS, KL and PERFMON. +const ALLOWED_TD_ATTRIBUTES: u64 = SEPT_VE_DISABLE | 1 << 30 | 1 << 31 | 1 << 63; + /// Refuse a TD that the host launched in a state that does not protect it. /// /// `fetch_and_verify` already rejects these TDs under dcap-qvl's default -/// policy. The check is repeated here, following dcap-qvl's `validate_td10`, -/// so that the sealing key does not depend on that default: the key -/// derivation does not cover `td_attributes`, so a debug TD running the same -/// image would derive the production TD's key. The `mr_signer_seam` check -/// matches the guest's `validate_tcb`. +/// policy. The check is repeated here, at least as strict as dcap-qvl's +/// `validate_td10`, so that the sealing key does not depend on that default: +/// the key derivation does not cover `td_attributes`, so a debug TD running +/// the same image would derive the production TD's key. The `mr_signer_seam` +/// check matches the guest's `validate_tcb`. fn require_production_td(report: &TDReport10) -> Result<(), ProviderError> { - let attributes = TDAttributes::parse(report.td_attributes) - .map_err(|error| ProviderError::QuoteVerification(error.to_string()))?; - if attributes.tud & 0x01 != 0 { + let attributes = u64::from_le_bytes(report.td_attributes); + if attributes & 0x01 != 0 { return Err(ProviderError::UntrustedTd("debug mode is enabled")); } - if attributes.tud != 0 - || attributes.sec.reserved_lower != 0 - || attributes.sec.reserved_bit29 - || attributes.other.reserved != 0 - { + if attributes & !ALLOWED_TD_ATTRIBUTES != 0 { return Err(ProviderError::UntrustedTd( "reserved bits in TD attributes are set", )); } - if !attributes.sec.sept_ve_disable { + if attributes & SEPT_VE_DISABLE == 0 { return Err(ProviderError::UntrustedTd("SEPT_VE_DISABLE is not enabled")); } if report.mr_signer_seam != [0_u8; 48] { diff --git a/dstack/ra-rpc/Cargo.toml b/dstack/ra-rpc/Cargo.toml index 8da9df01f8..5d00c2f620 100644 --- a/dstack/ra-rpc/Cargo.toml +++ b/dstack/ra-rpc/Cargo.toml @@ -23,12 +23,14 @@ ra-tls.workspace = true bon.workspace = true rocket-vsock-listener = { workspace = true, optional = true } serde.workspace = true -x509-parser.workspace = true +x509-parser = { workspace = true, features = ["verify"] } prost-types = { workspace = true, optional = true } or-panic.workspace = true [dev-dependencies] -tokio = { workspace = true, features = ["macros", "rt-multi-thread"] } +ra-tls = { workspace = true, features = ["test-pki"] } +tokio-rustls.workspace = true +tokio = { workspace = true, features = ["macros", "rt-multi-thread", "net", "io-util"] } reqwest = { workspace = true, default-features = false, features = [ "rustls", "charset", @@ -37,5 +39,5 @@ reqwest = { workspace = true, default-features = false, features = [ [features] default = ["rocket", "client"] rocket = ["dep:rocket", "dep:rocket-vsock-listener", "dep:rustls"] -client = ["reqwest"] +client = ["reqwest", "dep:rustls"] openapi = ["dep:prost-types"] diff --git a/dstack/ra-rpc/src/client.rs b/dstack/ra-rpc/src/client.rs index 0b6e1d027f..991a29171b 100644 --- a/dstack/ra-rpc/src/client.rs +++ b/dstack/ra-rpc/src/client.rs @@ -18,6 +18,8 @@ use serde::{de::DeserializeOwned, Serialize}; use bon::Builder; +mod tls; + pub struct CertInfo { pub cert_der: Vec, pub attestation: Option, @@ -30,8 +32,13 @@ type CertValidator = Box) -> Result<()> + Send + Sync + #[derive(Builder)] pub struct RaClientConfig { remote_uri: String, + /// Skip CA-based certificate checks (trust chain, hostname, and validity). + /// TLS handshake signatures remain verified; attestation is checked separately. #[builder(default = false)] - tls_no_check: bool, + tls_skip_ca_verification: bool, + /// Instead of a CA chain, require at the handshake a server certificate + /// issued as `PinnedIssuer` says. + tls_pinned_issuer: Option, #[builder(default = true)] verify_server_attestation: bool, #[builder(default = false)] @@ -46,18 +53,39 @@ pub struct RaClientConfig { cert_validator: Option, } +/// A server certificate a client accepts: a valid leaf with special usage +/// `usage`, signed by `pubkey` (SPKI DER). +#[derive(Debug, Clone)] +pub struct PinnedIssuer { + pub pubkey: Vec, + pub usage: String, +} + impl RaClientConfig { pub fn into_client(self) -> Result { let mut builder = Client::builder() .tls_sni(true) - .danger_accept_invalid_certs(self.tls_no_check) .danger_accept_invalid_hostnames(self.tls_no_check_hostname) .connect_timeout(Duration::from_secs(5)) .timeout(Duration::from_secs(60)); if self.cert_validator.is_some() { builder = builder.tls_info(true); } - if let (Some(cert_pem), Some(key_pem)) = (self.tls_client_cert, self.tls_client_key) { + if self.tls_pinned_issuer.is_some() { + // Without TLS, or past a redirect, the request skips the pin. + if !self.remote_uri.starts_with("https://") { + bail!("a pinned issuer requires an https URL"); + } + builder = builder.redirect(reqwest::redirect::Policy::none()); + } + if self.tls_skip_ca_verification || self.tls_pinned_issuer.is_some() { + builder = builder.use_preconfigured_tls(tls::config_without_ca_verification( + self.tls_client_cert.as_deref(), + self.tls_client_key.as_deref(), + self.tls_pinned_issuer, + )?); + } else if let (Some(cert_pem), Some(key_pem)) = (self.tls_client_cert, self.tls_client_key) + { let identity_pem = format!("{cert_pem}\n{key_pem}"); let identity = Identity::from_pem(identity_pem.as_bytes()).context("Failed to parse identity")?; @@ -104,28 +132,10 @@ pub struct RaClient { } impl RaClient { - pub fn new(remote_uri: String, tls_no_check: bool) -> Result { - RaClientConfig::builder() - .tls_no_check(tls_no_check) - .remote_uri(remote_uri) - .build() - .into_client() - .context("failed to create client") - } - - pub fn new_mtls( - remote_uri: String, - cert_pem: String, - key_pem: String, - attestation_verifier: Arc, - ) -> Result { + pub fn new(remote_uri: String, tls_skip_ca_verification: bool) -> Result { RaClientConfig::builder() - .tls_no_check(true) - .tls_built_in_root_certs(false) + .tls_skip_ca_verification(tls_skip_ca_verification) .remote_uri(remote_uri) - .tls_client_cert(cert_pem) - .tls_client_key(key_pem) - .attestation_verifier(attestation_verifier) .build() .into_client() .context("failed to create client") diff --git a/dstack/ra-rpc/src/client/tls.rs b/dstack/ra-rpc/src/client/tls.rs new file mode 100644 index 0000000000..6d4ed35fe5 --- /dev/null +++ b/dstack/ra-rpc/src/client/tls.rs @@ -0,0 +1,111 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// +// SPDX-License-Identifier: Apache-2.0 + +use std::sync::Arc; + +use super::PinnedIssuer; +use anyhow::{bail, Context, Result}; +use rustls::{ + client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}, + crypto::WebPkiSupportedAlgorithms, + pki_types::{CertificateDer, ServerName, UnixTime}, + DigitallySignedStruct, SignatureScheme, +}; + +/// Attestation is checked on the response, but TLS must still prove possession +/// of the attested certificate key. Reqwest's no-verifier also skips that proof. +/// +/// With `pinned`, the server certificate must also match it, so that nothing +/// is sent to a server that fails the pin. +#[derive(Debug)] +struct AttestedCertVerifier { + algorithms: WebPkiSupportedAlgorithms, + pinned: Option, +} + +fn matches_pin(pin: &PinnedIssuer, end_entity: &[u8]) -> bool { + use ra_tls::traits::CertExt; + use x509_parser::prelude::{FromDer, SubjectPublicKeyInfo, X509Certificate}; + let Ok((_, cert)) = X509Certificate::from_der(end_entity) else { + return false; + }; + let Ok((_, pubkey)) = SubjectPublicKeyInfo::from_der(&pin.pubkey) else { + return false; + }; + !cert.is_ca() + && cert.validity().is_valid() + && cert.get_special_usage().ok().flatten().as_deref() == Some(pin.usage.as_str()) + && cert.verify_signature(Some(&pubkey)).is_ok() +} + +impl ServerCertVerifier for AttestedCertVerifier { + fn verify_server_cert( + &self, + end_entity: &CertificateDer<'_>, + _intermediates: &[CertificateDer<'_>], + _server_name: &ServerName<'_>, + _ocsp_response: &[u8], + _now: UnixTime, + ) -> Result { + if let Some(pin) = &self.pinned { + if !matches_pin(pin, end_entity) { + return Err(rustls::Error::General( + "server certificate does not match the pinned issuer".into(), + )); + } + } + Ok(ServerCertVerified::assertion()) + } + + fn verify_tls12_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + signature: &DigitallySignedStruct, + ) -> Result { + rustls::crypto::verify_tls12_signature(message, cert, signature, &self.algorithms) + } + + fn verify_tls13_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + signature: &DigitallySignedStruct, + ) -> Result { + rustls::crypto::verify_tls13_signature(message, cert, signature, &self.algorithms) + } + + fn supported_verify_schemes(&self) -> Vec { + self.algorithms.supported_schemes() + } +} + +pub(super) fn config_without_ca_verification( + cert: Option<&str>, + key: Option<&str>, + pinned: Option, +) -> Result { + use rustls::pki_types::{pem::PemObject, PrivateKeyDer}; + let provider = rustls::crypto::CryptoProvider::get_default() + .cloned() + .unwrap_or_else(|| Arc::new(rustls::crypto::aws_lc_rs::default_provider())); + let verifier = AttestedCertVerifier { + algorithms: provider.signature_verification_algorithms, + pinned, + }; + let builder = rustls::ClientConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions()? + .dangerous() + .with_custom_certificate_verifier(Arc::new(verifier)); + match (cert, key) { + (Some(cert), Some(key)) => builder + .with_client_auth_cert( + CertificateDer::pem_slice_iter(cert.as_bytes()).collect::, _>>()?, + PrivateKeyDer::from_pem_slice(key.as_bytes())?, + ) + .context("invalid RA-TLS client identity"), + (None, None) => Ok(builder.with_no_client_auth()), + _ => bail!("RA-TLS client identity requires both certificate and key"), + } +} diff --git a/dstack/ra-rpc/src/openapi.rs b/dstack/ra-rpc/src/openapi.rs index 8fe2f1561c..a19f9c8872 100644 --- a/dstack/ra-rpc/src/openapi.rs +++ b/dstack/ra-rpc/src/openapi.rs @@ -211,15 +211,24 @@ pub(crate) struct RenderedDoc { pub struct SwaggerUiConfig { pub title: String, pub dark_mode: bool, - pub swagger_ui_dist: String, } +// Pinned with SRI so a CDN or upstream compromise cannot run script on the +// page, which shares an origin with the API it documents. Hashes are of the +// files in the npm tarball for this version. +const SWAGGER_UI_DIST: &str = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.32.15"; +const SWAGGER_UI_CSS_SRI: &str = + "sha384-fgyWYkUAamzuI8mJFu/xpRP0JWCJRwkwUwsYDoOYVHUJ8NQE5cENn8ib3ppwFFSX"; +const SWAGGER_UI_BUNDLE_SRI: &str = + "sha384-m7zaGj7MPzU+G4lz2eyy73GxK9bbRDr9bB2CSdj8wodg2wu/Wnt6wsoLP3JD+RS9"; +const SWAGGER_UI_PRESET_SRI: &str = + "sha384-9rDX8vR4ir9/JIiV/XvxMpb5T9tVyFbssk49PV935hrdwmkVNJ7VZMM0RXAm184h"; + impl Default for SwaggerUiConfig { fn default() -> Self { Self { title: "pRPC Explorer".to_string(), dark_mode: true, - swagger_ui_dist: "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5".to_string(), } } } @@ -1004,18 +1013,6 @@ fn field_type(field: &FieldDescriptorProto) -> FieldType { fn build_swagger_ui_html(spec_url: &str, cfg: &SwaggerUiConfig) -> String { let spec = spec_url.replace('\'', "\\'"); - let css = format!( - "{}/swagger-ui.css", - cfg.swagger_ui_dist.trim_end_matches('/') - ); - let bundle = format!( - "{}/swagger-ui-bundle.js", - cfg.swagger_ui_dist.trim_end_matches('/') - ); - let preset = format!( - "{}/swagger-ui-standalone-preset.js", - cfg.swagger_ui_dist.trim_end_matches('/') - ); let background = if cfg.dark_mode { "#0b0d10" } else { "#fafafa" }; format!( r#" @@ -1023,7 +1020,7 @@ fn build_swagger_ui_html(spec_url: &str, cfg: &SwaggerUiConfig) -> String { {title} - +