# Baseline report pr162 Source: https://docs.phala.com/.doc-review/baseline-report-pr162 # Documentation Baseline Report — PR #162 (confidential-ai-doc) Generated: 2026-06-19 Branch: confidential-ai-doc Scope: 56 changed files (new Confidential AI docs + dstack-cloud section) ## Health Summary | Health | Count | Percentage | | - | - | - | | good | 51 | 91% | | fair | 4 | 7% | | needs work | 1 | 2% | ## Broken Links None found. ## Orphaned Files None — all pages present in docs.json navigation. ## Terminology Issues | Term | Variants Found | Files | Status | | - | - | - | - | | E2EE | Unexpanded in 4 files | 7 | Needs first-use expansion | | TCB | Unexpanded in 4 files | 5 | Needs first-use expansion | | RA-TLS | Unexpanded in 7 files | 8 | Needs first-use expansion | | Remote Attestation / TEE Attestation | Mixed usage in 2 files | 5 | Needs decision | | on-chain KMS | 1 lowercase vs 6 title-case | 6 | Needs standardization | | docker-compose (prose) | 2 prose instances use hyphenated form | 15 | Should be "Docker Compose" | | Dstack-TEE | GitHub org name, not a casing error | 7 | No action | | Confidential AI | Consistently title case | 15+ | Clean | | channel binding | Title case in headings only | 5 | Clean | | GCP / Google Cloud | GCP dominates, 2 natural prose uses of Google Cloud | 14 | Clean | ## Structural Issues ### Heading skip (1) * `confidential-model/confidential-ai-api.mdx:135` — h2 `## Available Models` then h4 `#### Phala Models`, skips h3 ### Code blocks without language tag (9) | File | Content | | - | - | | `dstack-cloud/attestation-integration.mdx:59` | Pseudocode — needs `text` or `python` | | `dstack-cloud/register-enclave-measurement.mdx:72` | PCR hash output — needs `text` | | `confidential-model/images-and-vision.mdx:47` | LLM output — needs `text` | | `confidential-model/streaming.mdx:66` | Output — needs `text` | | `getting-started/deploy-first-cvm.mdx:200` | URL template — needs `text` | | `networking/expose-http-service.mdx:42` | URL template — needs `text` | | `networking/quickstart.mdx:30` | URL template — needs `text` | | `troubleshooting/troubleshooting.mdx:73` | Error output — needs `text` | | `troubleshooting/troubleshooting.mdx:96` | Error output — needs `text` | ### Long paragraphs (>5 sentences) — 24 instances across 17 files Worst offenders (8+ sentences): * `confidential-model/api-reference/receipts.mdx:84` — 13 sentences * `confidential-model/api-reference/attestation.mdx:120` — 12 sentences * `confidential-model/tcb-and-claims.mdx:60` — 10 sentences * `dstack-cloud/upgrade.mdx:184` — 9 sentences * `dstack-cloud/nitro-enclave.mdx:21` — 8 sentences * `dstack-cloud/governance.mdx:98` — 8 sentences * `dstack-cloud/runbook.mdx:216` — 8 sentences * `dstack-cloud/register-enclave-measurement.mdx:100` — 8 sentences * `confidential-model/playground.mdx:24` — 8 sentences * `confidential-model/receipts-and-sessions.mdx:31` — 8 sentences * `confidential-model/channel-binding.mdx:32` — 8 sentences * `verify/verify-attestation.mdx:74` — 8 sentences ### "There is/are" openers (2) * `dstack-cloud/register-enclave-measurement.mdx:14` * `dstack-cloud/run-on-nitro.mdx:6` ## Per-File Detail | File | Type | Lines | Words | Issues | Health | | - | - | - | - | - | - | | dstack-cloud/code-walkthrough.mdx | how-to | 133 | 399 | 6 | needs work | | dstack-cloud/governance.mdx | how-to | 142 | 916 | 3 | fair | | dstack-cloud/manage-governance.mdx | explanation | 165 | 932 | 3 | fair | | dstack-cloud/register-enclave-measurement.mdx | tutorial | 207 | 922 | 3 | fair | | dstack-cloud/runbook.mdx | how-to | 267 | 1062 | 3 | fair | | (remaining 51 files) | — | — | — | 0-2 | good | # README mintlify Source: https://docs.phala.com/README_mintlify # Mintlify Usage ## Redirects Validation Run these two script to check and validate redirect links: .scripts/check\_links.py .scripts/validate-redirects.py # Batch check on-chain deployment allowance for all CVMs under an app Source: https://docs.phala.com/api-reference/apps/batch-check-on-chain-deployment-allowance-for-all-cvms-under-an-app /openapi.json post /api/v1/apps/{app_id}/cvms/is-allowed # Check if app deployment is allowed on-chain Source: https://docs.phala.com/api-reference/apps/check-if-app-deployment-is-allowed-on-chain /openapi.json post /api/v1/apps/{app_id}/is-allowed # Clear the app launch token Source: https://docs.phala.com/api-reference/apps/clear-the-app-launch-token /openapi.json delete /api/v1/apps/{app_id}/launch-token Removes the app's launch token. Remove requirements.launch_token_hash from every CVM of the app first: a CVM whose compose still carries it fails closed at its next boot. Repeating the call changes nothing. # Create a new instance under an existing app Source: https://docs.phala.com/api-reference/apps/create-a-new-instance-under-an-existing-app /openapi.json post /api/v1/apps/{app_id}/instances Deploy a new CVM instance under an existing app, optionally with a new Docker Compose file. For on-chain KMS apps, this uses a two-phase flow: the first request returns HTTP 465 with a commit token; after registering the compose hash on-chain, the second request commits with the token and transaction hash. # Create CVM replica Source: https://docs.phala.com/api-reference/apps/create-cvm-replica /openapi.json post /api/v1/apps/{app_id}/cvms/{vm_uuid}/replicas Clones a CVM to a target node. Uses source node if target not specified. # Get app attestation data Source: https://docs.phala.com/api-reference/apps/get-app-attestation-data /openapi.json get /api/v1/apps/{app_id}/attestations Returns TEE attestation quotes, event logs, and KMS configuration only for running CVMs that opted into public TCB info. # Get app details Source: https://docs.phala.com/api-reference/apps/get-app-details /openapi.json get /api/v1/apps/{app_id} Returns app metadata and current CVM configuration. Response schema varies by API version. # Get app filter options Source: https://docs.phala.com/api-reference/apps/get-app-filter-options /openapi.json get /api/v1/apps/filter-options Returns distinct values for each filterable field based on user's apps. # Get app metered usage Source: https://docs.phala.com/api-reference/apps/get-app-metered-usage /openapi.json get /api/v1/apps/{app_id}/usage Returns billing usage records from ClickHouse. Defaults to 7-day window if dates not specified. # Get app on-chain KMS info Source: https://docs.phala.com/api-reference/apps/get-app-on-chain-kms-info /openapi.json get /api/v1/apps/{app_id}/kms-info Returns on-chain KMS metadata for an app: chain, KMS contract, app contract, deployer address, and deployer type detection (EOA, Safe multisig, legacy multisig, ERC-4337, or generic contract). # Get device allowlist status Source: https://docs.phala.com/api-reference/apps/get-device-allowlist-status /openapi.json get /api/v1/apps/{app_id}/device-allowlist Returns the device_id allowlist status for an app's CVMs. For on-chain KMS apps, queries the blockchain in real-time to check which devices are registered in the app contract. # Get pending compose updates Source: https://docs.phala.com/api-reference/apps/get-pending-compose-updates /openapi.json get /api/v1/apps/{app_id}/pending-updates Returns provisioned compose file updates that have been signed on-chain but not yet applied to CVMs. # Get revision detail Source: https://docs.phala.com/api-reference/apps/get-revision-detail /openapi.json get /api/v1/apps/{app_id}/revisions/{revision_id} Returns full revision data including compose file, encrypted env, and user config. # List app CVMs Source: https://docs.phala.com/api-reference/apps/list-app-cvms /openapi.json get /api/v1/apps/{app_id}/cvms Returns CVM instances for an app. Admins see all instances; users see only their own. # List app revisions Source: https://docs.phala.com/api-reference/apps/list-app-revisions /openapi.json get /api/v1/apps/{app_id}/revisions Returns deployment history with compose hashes, operation types, and user refs. # List apps Source: https://docs.phala.com/api-reference/apps/list-apps /openapi.json get /api/v1/apps Returns paginated app list with filtering. Response schema varies by API version. # Preview a pending compose update Source: https://docs.phala.com/api-reference/apps/preview-a-pending-compose-update /openapi.json get /api/v1/apps/{app_id}/pending-updates/{vm_uuid}/{compose_hash}/preview Returns current and pending docker compose file and pre-launch script for diffing before applying an update. # Redeploy app from a specific revision Source: https://docs.phala.com/api-reference/apps/redeploy-app-from-a-specific-revision /openapi.json post /api/v1/apps/{app_id}/revisions/{revision_id}/redeploy Redeploy a CVM to a specific revision. If the app has exactly one CVM, it will be redeployed by default. If the app has multiple CVMs, you must specify target vm_uuids in request body. Does not change encrypted env unless encrypted_env is supplied. A mismatch between allowed_envs and the last env write is rejected unless encrypted_env is supplied or allow_env_mismatch is true. This schedules async CVM update task(s). # Run app TCB evaluation Source: https://docs.phala.com/api-reference/apps/run-app-tcb-evaluation /openapi.json get /api/v1/apps/{app_id}/attestations/tcb-evaluation Runs a live Intel PCS TCB evaluation only for running CVMs that opted into public TCB info. # Set or rotate the app launch token Source: https://docs.phala.com/api-reference/apps/set-or-rotate-the-app-launch-token /openapi.json post /api/v1/apps/{app_id}/launch-token Sets the app's launch token, generating one when the body omits it, and returns the plaintext and its hash once. CVMs keep booting with their current compose: update each CVM's requirements.launch_token_hash to the returned hash before its next boot, or it fails closed. Phala Cloud and the node operator can read the token, so it protects only against parties who know the public compose. # Apply staged CVM changes Source: https://docs.phala.com/api-reference/cvms/apply-staged-cvm-changes /openapi.json post /api/v1/cvms/{cvm_id}/draft/apply Applies every staged change as one PATCH /cvms/{cvm_id}: one VMM update and at most one restart; a stopped CVM stays stopped. Rejected with ERR-03-053 when the CVM's compose changed since the first change was staged. Accepts the same X-Compose-Hash, X-Transaction-Hash and X-Prepare-Only headers and returns the same responses as PATCH /cvms/{cvm_id}; the staged changes are kept until an apply dispatches them. A phase 2 apply is rejected with ERR-03-054 when changes were staged after its phase 1; apply again without the headers to prepare them. An update committed through a commit token (POST /cvms/{cvm_id}/commit-update) does not clear them: the next apply is then rejected with ERR-03-053, and the staged changes must be discarded. # Batch refresh CVM instance IDs Source: https://docs.phala.com/api-reference/cvms/batch-refresh-cvm-instance-ids /openapi.json patch /api/v1/cvms/instance-ids Resolves and persists missing instance_id values. Admin can pass cross-workspace CVM IDs. # Batch stop CVMs Source: https://docs.phala.com/api-reference/cvms/batch-stop-cvms /openapi.json post /api/v1/cvms/batch-stop Force stop multiple CVMs at once. Non-admin users can only stop CVMs in their current workspace. Admin users can stop any CVM. Max 50 per request. # Cancel in-progress CVM operation Source: https://docs.phala.com/api-reference/cvms/cancel-in-progress-cvm-operation /openapi.json post /api/v1/cvms/{cvm_id}/operations/cancel Cancel the current in-progress operation for a CVM. Revokes the Celery task and clears the operation lock. # Commit CVM replica (token-based, no auth required) Source: https://docs.phala.com/api-reference/cvms/commit-cvm-replica-token-based-no-auth-required /openapi.json post /api/v1/cvms/{cvm_id}/commit-replica Completes a two-phase CVM replication using a one-time commit token. The token was generated during a prepare-only or hash-required replica request. # Commit CVM update (token-based, no auth required) Source: https://docs.phala.com/api-reference/cvms/commit-cvm-update-token-based-no-auth-required /openapi.json post /api/v1/cvms/{cvm_id}/commit-update Completes a two-phase CVM update using a one-time commit token. The token was generated during a prepare-only PATCH request. No workspace authentication is required — the commit token is the credential. # Create CVM (two-phase on one path) Source: https://docs.phala.com/api-reference/cvms/create-cvm-two-phase-on-one-path /openapi.json post /api/v1/cvms Single entry point for CVM creation. Send a provision payload (compose_file + name) to prepare: validates the configuration, caches it for 14 days, and returns app_id, compose_hash, the env-encryption pubkey, and a commit token. Then send the token back with the encrypted environment to create the CVM. The legacy pair (POST /cvms/provision then POST /cvms with app_id + compose_hash) keeps working during the deprecation window. # Delete CVM Source: https://docs.phala.com/api-reference/cvms/delete-cvm /openapi.json delete /api/v1/cvms/{cvm_id} Stops and permanently deletes CVM. Data is not recoverable. # Diagnose custom domain DNS Source: https://docs.phala.com/api-reference/cvms/diagnose-custom-domain-dns /openapi.json post /api/v1/cvms/{cvm_id}/customize-domain-diagnose Verify DNS records for custom domain configuration. Checks CNAME pointing to CVM, TXT records for app verification, and CAA records. # Discard staged CVM changes Source: https://docs.phala.com/api-reference/cvms/discard-staged-cvm-changes /openapi.json delete /api/v1/cvms/{cvm_id}/draft # Force stop CVM Source: https://docs.phala.com/api-reference/cvms/force-stop-cvm /openapi.json post /api/v1/cvms/{cvm_id}/stop Immediately stops CVM (like pulling power). Cancels any in-progress operation. Triggers billing. # Get commit token info (no auth required) Source: https://docs.phala.com/api-reference/cvms/get-commit-token-info-no-auth-required /openapi.json get /api/v1/cvms/{cvm_id}/commit-update Read-only lookup of commit token metadata for the confirm-update page. # Get CVM annotations Source: https://docs.phala.com/api-reference/cvms/get-cvm-annotations /openapi.json get /api/v1/cvms/{cvm_id}/annotations Returns the annotations the node's VMM stores for this CVM. Annotations are opaque key/value metadata for host-side tooling, such as a QEMU wrapper that reads the VM manifest. The dstack VMM stores them with the VM. They are not passed to the guest, not measured, and not part of the compose hash, so attestation does not cover them: tenants must not rely on them for security. Phala Cloud keeps no copy of annotations as CVM state: only the node's VMM holds them, and Cloud never copies or restores them. A replica starts without annotations; a relocated CVM keeps whatever its VMM manifest carries. A create request that carries annotations is recorded in the audit log. Requires the `cvm_annotations` feature flag (ERR-03-049) and dstack VMM 0.6.1 or newer on the node (ERR-03-050). # Get CVM attestation Source: https://docs.phala.com/api-reference/cvms/get-cvm-attestation /openapi.json get /api/v1/cvms/{cvm_id}/attestation Returns TEE attestation data including TCB info and app certificates. # Get CVM details Source: https://docs.phala.com/api-reference/cvms/get-cvm-details /openapi.json get /api/v1/cvms/{cvm_id} Returns full CVM details including status, network info, and KMS configuration. # Get CVM init scripts Source: https://docs.phala.com/api-reference/cvms/get-cvm-init-scripts /openapi.json get /api/v1/cvms/{cvm_id}/init-scripts Lists the platform init scripts (docker_cleanup, env_merge) in their fixed run order: whether the CVM's current compose runs each one, and whether the caller could select it for this CVM, with the reason when not. docker_cleanup needs OS 0.6.x, ext4 storage and the docker-compose runner; env_merge needs OS 0.6.0 or newer and the managed_env_create feature flag. # Get CVM network info Source: https://docs.phala.com/api-reference/cvms/get-cvm-network-info /openapi.json get /api/v1/cvms/{cvm_id}/network Returns gateway status (internal IP, handshake time, public URLs) and the three network layers: gateway ingress from the compose (ingress), direct port mappings (port_mappings, as GET /ports) and the KMS/gateway URLs updates send (endpoints). # Get CVM system stats Source: https://docs.phala.com/api-reference/cvms/get-cvm-system-stats /openapi.json get /api/v1/cvms/{cvm_id}/stats Returns live system metrics (CPU, memory, disk) from the running CVM. # Get CVM user config Source: https://docs.phala.com/api-reference/cvms/get-cvm-user-config /openapi.json get /api/v1/cvms/{cvm_id}/user_config Returns the user_config stored in Teepod for this CVM, including injected SSH keys. launch_token is the app's launch token when the CVM's compose requires one. # Get Docker Compose file Source: https://docs.phala.com/api-reference/cvms/get-docker-compose-file /openapi.json get /api/v1/cvms/{cvm_id}/docker-compose.yml Returns the raw Docker Compose YAML content. Served from teepod when the CVM is live; falls back to the latest stored revision (marked via X-Compose-Source) for deleted CVMs or when teepod is unreachable — enables admin audit of past deployments. # Get firewall availability for this CVM's node Source: https://docs.phala.com/api-reference/cvms/get-firewall-availability-for-this-cvms-node /openapi.json get /api/v1/cvms/{cvm_id}/firewall-status Checks teescope capabilities.firewall on the node hosting this CVM. # Get network configuration Source: https://docs.phala.com/api-reference/cvms/get-network-configuration /openapi.json get /api/v1/cvms/{cvm_id}/network-config Returns real-time KMS URLs, Gateway URLs, and port mappings from VMM. # Get operation status Source: https://docs.phala.com/api-reference/cvms/get-operation-status /openapi.json get /api/v1/cvms/{cvm_id}/operation-status Returns current in-progress operation details including Celery task status. # Get port mappings Source: https://docs.phala.com/api-reference/cvms/get-port-mappings /openapi.json get /api/v1/cvms/{cvm_id}/ports Returns persisted port mappings for this CVM. # Get pre-launch script Source: https://docs.phala.com/api-reference/cvms/get-pre-launch-script /openapi.json get /api/v1/cvms/{cvm_id}/pre-launch-script Returns the shell script that runs before containers start. Served from teepod when the CVM is live; falls back to the latest stored revision (marked via X-Compose-Source) for deleted CVMs or when teepod is unreachable. # Get raw compose file Source: https://docs.phala.com/api-reference/cvms/get-raw-compose-file /openapi.json get /api/v1/cvms/{cvm_id}/compose_file Returns the complete compose file as JSON or raw text based on query param. # Get staged CVM changes Source: https://docs.phala.com/api-reference/cvms/get-staged-cvm-changes /openapi.json get /api/v1/cvms/{cvm_id}/draft Returns the CVM's staged changes, who staged each one, and the compose hash applying them produces. # Handle Get Cvm State Source: https://docs.phala.com/api-reference/cvms/handle-get-cvm-state /openapi.json get /api/v1/cvms/{cvm_id}/state Get CVM state. Supports two modes: 1. Immediate mode (no target): Returns current state immediately 2. SSE mode (with target): Streams state updates until status matches target or timeout Example: GET /cvms/{cvm_id}/state - Returns current state GET /cvms/{cvm_id}/state?target=running - Streams until status becomes 'running' SSE connection limit: 5 concurrent connections per user # Handle Update Cvm Name Source: https://docs.phala.com/api-reference/cvms/handle-update-cvm-name /openapi.json patch /api/v1/cvms/{cvm_id}/name Update CVM name with RFC 1123 validation and availability check # Handle Update Cvm Scheduled Delete Source: https://docs.phala.com/api-reference/cvms/handle-update-cvm-scheduled-delete /openapi.json patch /api/v1/cvms/{cvm_id}/scheduled-delete Update CVM scheduled delete time # List available OS images Source: https://docs.phala.com/api-reference/cvms/list-available-os-images /openapi.json get /api/v1/cvms/{cvm_id}/available-os-images Returns OS images this CVM can upgrade to, filtered by node availability, KMS allowlist, dev/prod upgrade rules, and GPU compatibility. # List CVM operations Source: https://docs.phala.com/api-reference/cvms/list-cvm-operations /openapi.json get /api/v1/cvms/{cvm_id}/operations Returns operation records grouped by correlation_id. Only includes events with correlation_id (new format since 2024-01). Error messages are sanitized for non-admin users. # List CVMs Source: https://docs.phala.com/api-reference/cvms/list-cvms /openapi.json get /api/v1/cvms Returns CVMs in current workspace. # List CVMs (paginated) Source: https://docs.phala.com/api-reference/cvms/list-cvms-paginated /openapi.json get /api/v1/cvms/paginated Returns paginated CVMs in current workspace with total count. # Provision compose file update Source: https://docs.phala.com/api-reference/cvms/provision-compose-file-update /openapi.json post /api/v1/cvms/{cvm_id}/compose_file/provision Validates new compose file and returns compose_hash for on-chain registration. Cache expires after 14 days. # Redeploy CVM from a specific revision Source: https://docs.phala.com/api-reference/cvms/redeploy-cvm-from-a-specific-revision /openapi.json post /api/v1/cvms/{cvm_id}/revisions/{revision_id}/redeploy Switch/rollback a CVM to a specified app revision (compose_hash). Does not change encrypted env unless encrypted_env is supplied. A mismatch between allowed_envs and the last env write is rejected unless encrypted_env is supplied or allow_env_mismatch is true. # Refresh CVM instance ID Source: https://docs.phala.com/api-reference/cvms/refresh-cvm-instance-id /openapi.json patch /api/v1/cvms/{cvm_id}/instance-id Resolve and persist instance_id for a CVM. Default behavior only backfills missing values. # Replace CVM annotations Source: https://docs.phala.com/api-reference/cvms/replace-cvm-annotations /openapi.json put /api/v1/cvms/{cvm_id}/annotations Replaces every annotation of this CVM; an empty object clears them. The VMM applies the change at once, without a restart and without a compose change. Host tools that read annotations only when QEMU launches (for example memory tiers or vCPU pinning) see the new values after the CVM restarts. Other CVM updates never change annotations. Annotations are opaque key/value metadata for host-side tooling, such as a QEMU wrapper that reads the VM manifest. The dstack VMM stores them with the VM. They are not passed to the guest, not measured, and not part of the compose hash, so attestation does not cover them: tenants must not rely on them for security. Phala Cloud keeps no copy of annotations as CVM state: only the node's VMM holds them, and Cloud never copies or restores them. A replica starts without annotations; a relocated CVM keeps whatever its VMM manifest carries. A create request that carries annotations is recorded in the audit log. Requires the `cvm_annotations` feature flag (ERR-03-049) and dstack VMM 0.6.1 or newer on the node (ERR-03-050). # Replicate CVM Source: https://docs.phala.com/api-reference/cvms/replicate-cvm /openapi.json post /api/v1/cvms/{cvm_id}/replicas Create a replica of the CVM on a target node. If request body is omitted, it replicates to the source node and reuses existing env. # Restart CVM Source: https://docs.phala.com/api-reference/cvms/restart-cvm /openapi.json post /api/v1/cvms/{cvm_id}/restart Stops and starts CVM. Use force=true to skip graceful shutdown. # Set port mappings Source: https://docs.phala.com/api-reference/cvms/set-port-mappings /openapi.json put /api/v1/cvms/{cvm_id}/ports Bulk-replace all port mappings for this CVM. Admins with two-factor authentication enabled may specify host_port within the node's managed range; other callers cannot pin ports. Omitted or null host_port keeps an existing allocation or randomly allocates a new one. User-NIC port changes require restart confirmation; bridge-NIC rules apply live. # Set Trust Center listing for the app Source: https://docs.phala.com/api-reference/cvms/set-trust-center-listing-for-the-app /openapi.json patch /api/v1/cvms/{cvm_id}/listed Trust Center listing is per app. The flag is written to every non-deleted CVM of the app's project, so toggling it here applies to the whole app, and Trust Center re-indexes the app. # Shutdown CVM Source: https://docs.phala.com/api-reference/cvms/shutdown-cvm /openapi.json post /api/v1/cvms/{cvm_id}/shutdown Gracefully shuts down CVM (SIGTERM then SIGKILL after timeout). Triggers billing. # Stage CVM changes Source: https://docs.phala.com/api-reference/cvms/stage-cvm-changes /openapi.json patch /api/v1/cvms/{cvm_id}/draft Adds an update to the CVM's staged changes without restarting it. The body is the PATCH /cvms/{cvm_id} body. Applying runs the staged compose changes in order on the CVM's compose; other fields take the last staged value. Scripts this change sends are reviewed as the draft would leave them. The first staged change records the CVM's compose hash. # Start CVM Source: https://docs.phala.com/api-reference/cvms/start-cvm /openapi.json post /api/v1/cvms/{cvm_id}/start Powers on a stopped CVM. GPU allocation happens during start. # Submit compose file update Source: https://docs.phala.com/api-reference/cvms/submit-compose-file-update /openapi.json post /api/v1/cvms/{cvm_id}/compose_file Submit complete compose file with hash verification. Use when you have pre-computed compose_hash and want to skip provision step. # Trigger compose file update Source: https://docs.phala.com/api-reference/cvms/trigger-compose-file-update /openapi.json patch /api/v1/cvms/{cvm_id}/compose_file Applies a provisioned compose file update. Requires compose_hash from provision endpoint. Restarts the CVM with new configuration. # Update CVM Source: https://docs.phala.com/api-reference/cvms/update-cvm /openapi.json patch /api/v1/cvms/{cvm_id} Unified PATCH endpoint for CVM updates. Only fields present in the request body are applied. Handles resource resize, compose configuration, visibility, environment, and OS image updates. For contract-owned KMS, compose-hash-affecting changes require two-phase flow with on-chain hash registration. # Update Docker Compose file Source: https://docs.phala.com/api-reference/cvms/update-docker-compose-file /openapi.json patch /api/v1/cvms/{cvm_id}/docker-compose Replaces the docker-compose.yml and restarts the CVM. For contract-owned KMS, requires two-phase flow with on-chain hash registration. # Update environment variables Source: https://docs.phala.com/api-reference/cvms/update-environment-variables /openapi.json patch /api/v1/cvms/{cvm_id}/envs Updates encrypted environment variables. If env_keys changes for contract-owned KMS, requires two-phase flow with on-chain hash registration. # Update KMS/Gateway URLs Source: https://docs.phala.com/api-reference/cvms/update-kmsgateway-urls /openapi.json patch /api/v1/cvms/{cvm_id}/network-config Update KMS and/or Gateway URLs for this CVM. Requires VMM >= 0.5.7. The URLs are kept: later compose and configuration updates send them instead of the KMS cluster's. An empty list removes that override; moving the CVM to another node removes both. # Update OS image Source: https://docs.phala.com/api-reference/cvms/update-os-image /openapi.json patch /api/v1/cvms/{cvm_id}/os-image Upgrades the CVM to a different OS image. Shuts down, updates, and restarts. Takes several minutes. Track progress via correlation_id. # Update pre-launch script Source: https://docs.phala.com/api-reference/cvms/update-pre-launch-script /openapi.json patch /api/v1/cvms/{cvm_id}/pre-launch-script Replaces the pre-launch script and restarts the CVM. For contract-owned KMS, requires two-phase flow with on-chain hash registration. # Predict next app IDs Source: https://docs.phala.com/api-reference/kms/predict-next-app-ids /openapi.json get /api/v1/kms/phala/next_app_id Predict the next N app IDs that will be assigned to the team's wallet. Maximum 20 predictions allowed. # Check raw quote exists Source: https://docs.phala.com/api-reference/public/check-raw-quote-exists /openapi.json head /api/v1/attestations/raw/{checksum} Returns headers without body. Use to check existence and get Content-Length. # Download raw quote Source: https://docs.phala.com/api-reference/public/download-raw-quote /openapi.json get /api/v1/attestations/raw/{checksum} Returns raw quote bytes as binary file attachment. # Get app encryption pubkey Source: https://docs.phala.com/api-reference/public/get-app-encryption-pubkey /openapi.json get /api/v1/kms/{kms_id}/pubkey/{app_id} Retrieve the public key for encrypting environment variables before deployment. # Get KMS contract details Source: https://docs.phala.com/api-reference/public/get-kms-contract-details /openapi.json get /api/v1/kms/{kms_id} Get a KMS contract by slug (API >= 2026-06-23). Older versions return a single KMS node by hashed id or slug. # Get on-chain KMS details by chain Source: https://docs.phala.com/api-reference/public/get-on-chain-kms-details-by-chain /openapi.json get /api/v1/kms/on-chain/{chain} Returns KMS contracts on the specified chain with device and OS image whitelist status. # Get quote collateral Source: https://docs.phala.com/api-reference/public/get-quote-collateral /openapi.json get /api/v1/attestations/collateral/{checksum} Returns TCB collateral data for quote verification. Cached for 24 hours. # Inspect KMS instance Source: https://docs.phala.com/api-reference/public/inspect-kms-instance /openapi.json get /api/v1/kms/{kms_id}/info Real-time inspection of a KMS instance. Queries KMS RPC, guest agent, associated Teepod VMMs, and on-chain contract data with cross-validation. # List family instance types Source: https://docs.phala.com/api-reference/public/list-family-instance-types /openapi.json get /api/v1/instance-types/{family} Public endpoint. Returns all public instance types for a specific family. # List instance type families Source: https://docs.phala.com/api-reference/public/list-instance-type-families /openapi.json get /api/v1/instance-types Public endpoint. Returns all families with their public instance types grouped. # List KMS contracts Source: https://docs.phala.com/api-reference/public/list-kms-contracts /openapi.json get /api/v1/kms List available KMS contracts (API >= 2026-06-23). Older versions return the legacy paginated KMS node list. # List node device IDs Source: https://docs.phala.com/api-reference/public/list-node-device-ids /openapi.json get /api/v1/attestations/device_ids Public endpoint. Returns device_id list from nodes table (excluding deleted). # List node PPIDs Source: https://docs.phala.com/api-reference/public/list-node-ppids /openapi.json get /api/v1/attestations/ppids Public endpoint. Returns PPID list from nodes table (excluding deleted). # List nodes Source: https://docs.phala.com/api-reference/public/list-nodes /openapi.json get /api/v1/attestations/nodes Public endpoint. Returns NodeRef list derived from nodes table (excluding deleted). # List recent quotes Source: https://docs.phala.com/api-reference/public/list-recent-quotes /openapi.json get /api/v1/attestations/recent Public endpoint. Returns recently uploaded quotes ordered by timestamp. # Verify TEE quote Source: https://docs.phala.com/api-reference/public/verify-tee-quote /openapi.json post /api/v1/attestations/verify Accepts quote as file upload, form hex, or JSON hex. 0x prefix handled automatically. # View quote details Source: https://docs.phala.com/api-reference/public/view-quote-details /openapi.json get /api/v1/attestations/view/{checksum} Public endpoint. Returns parsed quote data with verification status. # Add SSH key Source: https://docs.phala.com/api-reference/user/add-ssh-key /openapi.json post /api/v1/user/ssh-keys Validates and stores an SSH public key. Minimum RSA 2048-bit, Ed25519 recommended. # Delete SSH key Source: https://docs.phala.com/api-reference/user/delete-ssh-key /openapi.json delete /api/v1/user/ssh-keys/{key_id} Soft-deletes an SSH key. Key must belong to the authenticated user. # Handle Batch Cvm Status Source: https://docs.phala.com/api-reference/user/handle-batch-cvm-status /openapi.json post /api/v1/status/batch Batch query CVM real-time status. Groups by teepod and queries VMM status in parallel. Resource usage comes from VictoriaMetrics, not a per-node teescope fan-out. # Import keys from GitHub profile Source: https://docs.phala.com/api-reference/user/import-keys-from-github-profile /openapi.json post /api/v1/user/ssh-keys/github-profile Fetches public SSH keys from any GitHub user's profile via the unauthenticated GitHub API. Deduplicates against the user's existing keys by fingerprint. # List user SSH keys Source: https://docs.phala.com/api-reference/user/list-user-ssh-keys /openapi.json get /api/v1/user/ssh-keys Returns all SSH keys belonging to the authenticated user. # Sync keys from GitHub Source: https://docs.phala.com/api-reference/user/sync-keys-from-github /openapi.json post /api/v1/user/ssh-keys/github-sync Imports SSH keys from linked GitHub account. Adds new keys, updates existing, removes deleted. # Create workspace webhook Source: https://docs.phala.com/api-reference/webhooks/create-workspace-webhook /openapi.json post /api/v1/workspace/webhooks # Delete webhook Source: https://docs.phala.com/api-reference/webhooks/delete-webhook /openapi.json delete /api/v1/workspace/webhooks/{webhook_id} # Get webhook delivery stats Source: https://docs.phala.com/api-reference/webhooks/get-webhook-delivery-stats /openapi.json get /api/v1/workspace/webhooks/{webhook_id}/stats # Get webhook details Source: https://docs.phala.com/api-reference/webhooks/get-webhook-details /openapi.json get /api/v1/workspace/webhooks/{webhook_id} # List webhook deliveries Source: https://docs.phala.com/api-reference/webhooks/list-webhook-deliveries /openapi.json get /api/v1/workspace/webhooks/{webhook_id}/deliveries # List workspace webhooks Source: https://docs.phala.com/api-reference/webhooks/list-workspace-webhooks /openapi.json get /api/v1/workspace/webhooks # Resend a webhook delivery Source: https://docs.phala.com/api-reference/webhooks/resend-a-webhook-delivery /openapi.json post /api/v1/workspace/webhooks/{webhook_id}/deliveries/{event_id}/resend # Reveal webhook secret (requires 2FA) Source: https://docs.phala.com/api-reference/webhooks/reveal-webhook-secret-requires-2fa /openapi.json post /api/v1/workspace/webhooks/{webhook_id}/reveal-secret # Rotate webhook secret (requires 2FA) Source: https://docs.phala.com/api-reference/webhooks/rotate-webhook-secret-requires-2fa /openapi.json post /api/v1/workspace/webhooks/{webhook_id}/rotate-secret # Send test webhook event Source: https://docs.phala.com/api-reference/webhooks/send-test-webhook-event /openapi.json post /api/v1/workspace/webhooks/{webhook_id}/test # Update webhook Source: https://docs.phala.com/api-reference/webhooks/update-webhook /openapi.json put /api/v1/workspace/webhooks/{webhook_id} # Doc requirements Source: https://docs.phala.com/doc-requirements Act as a 10 year technical writer. Now you are performing an audit of the given doc page in this docs repo. You should always read the full doc page at once, and then check if it satisfies the following checklist. # Check list 1. Content is self contained 2. Content is helpful to the audience 3. Ensure no redundant info is repeated in the doc 4. Always use conversational language 5. No text-wall. Each paragraph should be less than 4 sentences. 6. Flow of the doc is simple and clear 7. Human-style natural writing rather than AI-style 8. Lead with the key takeaway 9. Tutorials should guide step by step with context and purpose (if applicable) 10. Respect documentation types and their promises 11. Avoid bullet point overload # Explaination of each criteria ## Ensure no redundant info is repeated in the doc Watch for sections that present the same information from different perspectives without adding new value. Common redundancy patterns: **Opposite perspectives that say the same thing:** * "What We Protect Against" (threat model) vs "What You Don't Need to Trust" (trust model) * If section A says "we protect against X" and section B says "you don't trust X", they're often redundant * Consider combining them into a single section **Same concept explained multiple times:** * Hardware encryption mentioned in overview, threat model, architecture, and trust model * Gateway TEE protection explained in 3+ different sections * Ask: Does each mention add new information, or just rephrase? **How to fix:** * Combine related sections when they cover the same ground * Keep one detailed explanation, use brief references elsewhere * If repetition serves a purpose (overview vs deep-dive), make sure the detail level differs significantly Good example: A single "Security Model" section with subsections for threats, trust requirements, and limitations. Bad example: Separate "Threat Model" and "Trust Model" sections that list the same protections from opposite angles. ## Content is self contained Ask a few questions to yourself and make sure the answer is yes: * Can you understand all the contents in this doc? * Do you feel confused why you are reading a piece of the content? ## Content is helpful to the audience Our audience are developers with CS foundamentals, knowledge of AI and Confidential Computing. Ensure anything we write in the doc is helpful to the audience. Ask a few questions: * Does the doc help the audience to learn more? (Should be Yes) * Does the language sounds like a sales pitch? (Should be No) ## Human-style natural writing rather than AI-style The doc should have a very natural flow. Ensure: * Conversational but precise. Write like you're explaining to a peer, not a professor. * Short sentences. One idea per sentence. Avoid comma chains and overlong clauses. * Use active voice. "TEE mode scales well" > "The scalability of TEE mode is underscored." * Include links/tables/figures only if they add real value (not filler). * Minimize em-dashes for better flow. Em-dashes create dramatic pauses but feel heavy when overused. Limit to 1-2 per page, reserved for high-impact emphasis. Replace most em-dashes with "because", "so", commas, or separate sentences. Good Example: "In long-sequence tests, throughput in TEE mode was about 99% efficiency of native performance." Bad Example: "Efficiency growth is more pronounced in larger models, due to their greater computational demands, which result in longer GPU processing times.” (dense, academic)" ## Lead with the key takeaway The doc should open with the most important result or insight, not the setup or background. Ask yourself: * Does the first sentence clearly tell the reader why this page matters? * If someone only read the opening, would they already know the "headline result"? Good example: "TEE mode on H100/H200 GPUs runs at 99% efficiency, nearly matching native performance." Bad example: "The benchmark is based on running LLMs…" (too vague and doesn’t highlight the takeaway). ## Tutorials should guide step by step with context and purpose Identify if the doc is a tutorial or a reference page. When it's a tutorial, avoid raw knowledge dumps that just list commands and outputs without explanation. Ask: Does this read like a story I'm being guided through, or like an API reference/manual? ## Respect documentation types and their promises Different documentation types serve different purposes. Never mix them up: * Tutorials: Learning-oriented content for new users * How-to guides: Task-oriented guidance for specific problems * Explanations: Understanding-oriented conceptual discussions * Reference: Information-oriented technical descriptions Bad example: A "quickstart" that includes full API specifications, conceptual explanations, and multiple advanced scenarios. Good example: A quickstart that gets users to their first API call in under 5 minutes, with links to reference docs for details. ## Avoid bullet point overload Too many bullet points make documentation feel like an outline, not documentation for humans. Rules: * Maximum 3-5 bullets before breaking with prose * Use bullets for true lists, not as an organizational crutch * Conversational flow > perfect organization Bad example: * Step 1: Do this * Step 2: Do that * Note: Remember this * Important: Don't forget * Also: Consider this * Furthermore: Think about that * Additionally: Keep in mind Good example: Here's how to verify your quote. First, you'll need either a binary file or hex string. Choose your method: * Binary file upload for quote.bin files * Hex string for data from APIs * Direct checksum lookup if already verified After verification, you'll get a unique checksum that serves as your quote's permanent identifier. Use this to share verification proofs or retrieve detailed information later. # API Reference Source: https://docs.phala.com/dstack-cloud/api-reference API reference for Guest Agent (Unix Socket), KMS Onboard API, and management endpoints. # API Reference dstack-cloud exposes three API surfaces: the Guest Agent's Unix socket (for apps inside the CVM), the KMS RPC (for key delivery over RA-TLS (Remote Attestation TLS)), and the Onboard HTTP endpoints (for first-time KMS bootstrap). ## Guest Agent API (Unix Socket) The Guest Agent runs inside each dstack CVM and provides local APIs via a Unix socket at `/var/run/dstack.sock`. ### Get TDX Quote Obtain a TDX attestation quote from the hardware. **GCP (TDX) only.** ```bash theme={"system"} curl --unix-socket /var/run/dstack.sock \ "http://localhost/GetQuote?report_data=0x1234deadbeef" ``` **Parameters:** | Parameter | Type | Description | | - | - | - | | `report_data` | string (hex) | Optional challenge value (32 bytes). Used to prevent replay attacks. | **Response:** ```json theme={"system"} { "quote": "", "rtmr0": "...", "rtmr1": "...", "rtmr2": "...", "rtmr3": "..." } ``` ### Get NSM Attestation Obtain a Nitro Attestation Document from the NSM. **AWS Nitro only.** ```bash theme={"system"} curl --unix-socket /var/run/dstack.sock \ "http://localhost/GetAttestation?user_data=0x1234deadbeef" ``` **Parameters:** | Parameter | Type | Description | | - | - | - | | `user_data` | string (hex) | Optional challenge value. | **Response:** ```json theme={"system"} { "document": "" } ``` ### Get Attestation (HTTP) External attestation endpoint, accessible via HTTPS. ```bash theme={"system"} curl https://your-app.example.com/attestation ``` **Response:** Full attestation data (Quote or Document) for external verification. *** ## KMS API The KMS exposes an RPC interface for key management. All communication uses RA-TLS — the KMS verifies the workload's attestation before processing any request. ### getKey(name) Request a key from the KMS. ```bash theme={"system"} # Called from within the application via dstack SDK # Not directly callable via curl (requires RA-TLS handshake) ``` **Parameters:** | Parameter | Type | Description | | - | - | - | | `name` | string | The name of the requested key. Keys are scoped per application. | **Returns:** The requested key as raw bytes. **Error Codes:** | Error | Description | | - | - | | `UNAUTHORIZED` | Workload attestation verification failed. The workload is not running in a verified TEE. | | `MEASUREMENT_NOT_FOUND` | The workload's measurement is not registered on-chain. | | `KEY_NOT_FOUND` | No key exists for the requested name. | | `INTERNAL_ERROR` | KMS encountered an internal error. | ### How Applications Use getKey Applications retrieve keys through the dstack SDK, which handles attestation and the RA-TLS connection automatically: **Python:** ```python theme={"system"} from dstack import DstackClient client = DstackClient() key = client.get_key("my-api-key") ``` **TypeScript:** ```typescript theme={"system"} import { DstackClient } from '@dstack/sdk'; const client = new DstackClient(); const key = await client.getKey("my-api-key"); ``` **Rust:** ```rust theme={"system"} use dstack_sdk::DstackClient; let client = DstackClient::new()?; let key = client.get_key("my-api-key")?; ``` *** ## KMS Onboard API (HTTP, Bootstrap Only) These endpoints are only available during the first-time bootstrap (Onboard mode). After bootstrap is completed, KMS switches to RA-TLS-only mode. ### Onboard.Bootstrap Generate the KMS key pair and obtain attestation information. ```bash theme={"system"} curl -s "http://:12001/prpc/Onboard.Bootstrap?json" \ -d '{"domain": ""}' ``` **Parameters:** | Parameter | Type | Description | | - | - | - | | `domain` | string | The domain name or IP address where KMS is accessible. Used in the attestation data. | **Response:** ```json theme={"system"} { "publicKey": "...", "attestation": "...", "measurement": "..." } ``` ### /finish Complete the bootstrap process. KMS restarts and switches to Normal mode (HTTPS + RA-TLS). ```bash theme={"system"} curl "http://:12001/finish" ``` **Response:** HTTP 200 on success. *** ## Docker Compose Volume for Guest Agent To access the Guest Agent from within a Docker container, mount the socket: ```yaml theme={"system"} services: my-app: image: my-app:latest volumes: - /var/run/dstack.sock:/var/run/dstack.sock ``` ## Next Steps * **[Configuration Reference](/dstack-cloud/configuration)** — Configuration file formats * **[Glossary](/dstack-cloud/glossary)** — Term definitions # Attestation Integration Source: https://docs.phala.com/dstack-cloud/attestation-integration How dstack-cloud integrates remote attestation mechanisms on GCP (TDX Quote) and AWS Nitro (NSM Attestation Document). # Attestation Integration Remote attestation is how a TEE proves it's running genuine, unmodified code on real hardware. dstack-cloud integrates two different attestation mechanisms — Intel TDX on GCP and AWS NSM on Nitro — to give KMS confidence before dispatching keys. > For the fundamentals of dstack remote attestation, the RA-TLS (Remote Attestation TLS) protocol design, and ZT-TLS / ACME certificate management, refer to the official Phala documentation: > > * [TEE Attestation Guide](https://docs.phala.com/dstack/trust-center-technical) > * [TEE-Controlled Domain Certificates](https://docs.phala.com/dstack/design-documents/tee-controlled-domain-certificates) ## What Is Remote Attestation Remote attestation is the process by which a TEE proves its identity and integrity to an external party. The proof contains: 1. **Hardware signature** — Confirms the workload is running in genuine TEE hardware (not emulated) 2. **Workload measurements** — Cryptographic hash of the code and configuration running inside the TEE 3. **User data** — An optional challenge value to prevent replay attacks The verifier (e.g., KMS) checks the hardware signature and measurements to confirm the workload has not been tampered with. ## Attestation on GCP (Intel TDX + vTPM) On GCP, dstack uses a **dual-attestation approach** combining Intel TDX and Google-managed vTPM to build a comprehensive trust chain. ### Architecture Overview GCP Confidential VMs provide two independent attestation mechanisms: | Source | Type | Coverage | Trust Root | | - | - | - | - | | **Intel TDX Module** | Hardware-based | Firmware + RTMR registers | Intel TDX hardware | | **Google vTPM** | Software-based | Boot loader + kernel integrity | Google's certificate authority | dstack binds these two mechanisms together to provide defense-in-depth attestation. ### Attestation Creation Flow When a dstack CVM starts on GCP, the Guest Agent performs the following steps: 1. **Collect report\_data** (64 bytes), optionally bound to an RA-TLS public key 2. **Generate TDX Quote** via `tdx-attest::get_quote(report_data)`: * Includes all measurement values (MRTD, RTMR0-3) * Signed by the Intel TDX module 3. **Read TDX event log** via `cc-eventlog::tdx::read_event_log()` 4. **Compute TPM qualifying data** as `sha256(tdx_quote)` — this binds the two attestations together 5. **Generate vTPM Quote** via `tpm-attest::TpmContext::create_quote(qualifying_data, policy)`: * Signed by Google's vTPM attestation key * Includes PCR values representing boot chain integrity 6. **Package attestation** as `DstackGcpTdxQuote { tdx_quote, tpm_quote }` ### Trust Chain Binding The key innovation is the **qualifying data binding**: ```text theme={"system"} tpm_quote.qualifying_data = sha256(tdx_quote) ``` This creates a cryptographic link between the two independent attestation mechanisms: * **TDX Quote** proves the workload runs in genuine Intel TDX hardware with specific RTMR values * **vTPM Quote** proves the boot chain integrity via PCR values * The SHA-256 binding ensures both attestations come from the same CVM instance ### Verification Flow The verifier (e.g., KMS) performs dual verification: **TDX Verification:** 1. Retrieve TDX collateral and verify quote signature using Intel's TCB (Trusted Computing Base) info 2. Verify TCB status (debug mode disabled, mr\_signer\_seam valid) 3. Replay runtime events and compare RTMR3 with quote's RTMR3 4. Verify `report_data` matches expected value **vTPM Verification:** 1. Retrieve vTPM collateral and verify quote signature using Google's certificate chain 2. Replay runtime events and compare PCR values 3. Verify `qualifying_data == sha256(tdx_quote)` — confirms binding Only when **both** verifications succeed is the attestation considered valid ### Measurement Registers (GCP) **TDX RTMR Registers:** | Register | Contents | | - | - | | **MRTD** | Measured firmware (virtual firmware measurement) | | **RTMR0** | OS kernel and initramfs | | **RTMR1** | OS kernel command-line parameters | | **RTMR2** | OS runtime and init scripts | | **RTMR3** | Application `compose-hash` + KMS binding + instance ID | **vTPM PCR Registers:** The vTPM provides an independent measurement of the boot chain. While dstack primarily relies on TDX RTMRs for application attestation, the vTPM PCRs offer an additional layer of verification for the boot process. > **Note:** For detailed PCR assignments and event log structure, refer to the [GCP Confidential VM Attestation Documentation](https://cloud.google.com/confidential-computing/confidential-vm/docs/attestation). ## Attestation on AWS Nitro (NSM) When a Nitro Enclave launches from its EIF (Enclave Image File): 1. **NSM auto-generation** — The Nitro Secure Module automatically generates an Attestation Document when the Enclave launches 2. **Document contents** — The Attestation Document includes: * PCR0-2 values (Platform Configuration Registers) — 3 measurements generated during EIF build * NSM signature * Enclave ID and launch timestamp 3. **OS\_IMAGE\_HASH** — The 3 PCR values (PCR0, PCR1, PCR2) are combined into a single `OS_IMAGE_HASH`, which serves as the unique workload identifier 4. **Verification** — KMS verifies the Attestation Document: * Validates the NSM signature using AWS root certificates * Checks that the `OS_IMAGE_HASH` matches an authorized value registered on-chain * Confirms the Enclave is running on genuine Nitro hardware ### Measurement Registers (Nitro) | Register | Contents | | - | - | | **PCR0** | OS image (kernel + initramfs) | | **PCR1** | Application code and runtime | | **PCR2** | Additional configuration and dstack-util | These 3 PCR values are combined into a single `OS_IMAGE_HASH`, which is the unique identifier used for on-chain authorization. Any change to the Dockerfile, application code, or `dstack-util` version produces a different `OS_IMAGE_HASH`. ## GCP vs. Nitro: Attestation Comparison Both platforms generate hardware-signed attestations that KMS verifies before dispatching keys. The main differences are in the attestation format (TDX Quote vs. NSM Document), verification method (Intel DCAP QVL vs. AWS certificate chain), and how measurements are stored (RTMR registers vs. PCR values). For platform-specific details, see the sections above. For a broader architectural comparison, see [AWS Nitro Enclave Integration](/dstack-cloud/nitro-enclave). ## Measurements and On-chain Authorization Measurements are the foundation of on-chain key access control: * Before KMS dispatches keys to a workload, the workload's measurements must be **registered on-chain** * This ensures only audited, approved code versions can obtain keys * If you update your application code, the measurements change, and you must re-register them through governance ![Measurement Registration Flow](https://mintcdn.com/phalanetwork-1606097b/kLcECSdhM8pjBAIk/images/dstack-cloud/measurement-registration-flow.png?fit=max\&auto=format\&n=kLcECSdhM8pjBAIk\&q=85\&s=a2f0a15efc35d656fcf06b56d9b3628f) For the registration process, see [Register Workload Measurements](/dstack-cloud/register-enclave-measurement). ## Verifying Attestation You can verify that a dstack CVM is running in genuine TEE by requesting its attestation: ```bash theme={"system"} # Request attestation from a running CVM curl https://your-app.example.com/attestation ``` The response includes the full attestation data that can be independently verified using: * **dstack-verifier** — HTTP service or CLI tool provided by dstack-cloud * **dcap-qvl** — Open-source Intel DCAP Quote Verification Library * **dstack SDK** — `replayRtmrs()` function for local verification For more details, see the [dstack-cloud Verification Guide](https://github.com/Phala-Network/dstack-cloud/blob/master/docs/verification.md). ## Next Steps * **[Security Model](/dstack-cloud/security-model)** — Trust boundaries and security guarantees * **[Register Workload Measurements](/dstack-cloud/register-enclave-measurement)** — How to register measurements on-chain * **[Runbook](/dstack-cloud/runbook)** — Troubleshooting attestation failures # Code Walkthrough and KT Materials Source: https://docs.phala.com/dstack-cloud/code-walkthrough Code walkthrough and knowledge transfer materials for the dstack-cloud project. # Code Walkthrough and KT Materials This page is an internal knowledge-transfer resource. It maps the codebase structure, traces the key request path from application to KMS, and highlights the files you'll need to understand when contributing to dstack-cloud. > **Note:** This document is an internal deliverable for new contributors and team members. ## Guide for New Contributors If you're new to dstack-cloud, here's the recommended reading order: 1. **Understand the architecture** — Read [overview](/dstack-cloud/overview) first to get the big picture 2. **Set up the development environment** — Follow the README in the repository root 3. **Start with a simple workload** — Deploy a basic nginx container on GCP using the Quick Start 4. **Explore the KMS** — Deploy KMS and observe the bootstrap flow 5. **Read the attestation code** — Understand how measurements are generated and verified 6. **Review the contracts** — Understand the governance model and on-chain authorization ## Repository Structure The codebase is organized into these key areas: ``` dstack-cloud/ ├── cli/ # dstack-cloud CLI tool ├── kms/ # dstack-kms service ├── packages/ │ ├── attestation/ # Attestation modules (TDX, NSM, TPM) │ ├── guest-agent/ # Guest Agent (runs inside CVM) │ ├── gateway/ # TLS termination and RA-TLS gateway │ └── vmm/ # Virtual Machine Monitor ├── contracts/ # Smart contracts (DstackKms, DstackApp) ├── scripts/ # Build and deployment scripts └── docs/ # Documentation ``` ## Core Request Paths Understanding how a key request flows through the system is the best way to learn the codebase. Here's what happens when an application asks KMS for a key: ### Key Request Flow **GCP (via Guest Agent):** ``` Application (in CVM) → dstack SDK (via /var/run/dstack.sock) → Guest Agent → RA-TLS connection → dstack-kms (in separate TEE) → Attestation verification → On-chain measurement check → Key derivation and dispatch → RA-TLS response → Guest Agent → Application receives key ``` **AWS Nitro (via dstack-util):** ``` dstack-util (in Enclave) → NSM attestation document obtained → VSOCK → VSOCK Proxy → dstack-kms (in separate TEE) → Attestation verification (NSM + OS_IMAGE_HASH) → On-chain measurement check → Key derivation and dispatch → Key returned to dstack-util → Application receives key (user decides usage) ``` ![Key Request Flow](https://mintcdn.com/phalanetwork-1606097b/kLcECSdhM8pjBAIk/images/dstack-cloud/key-request-flow.png?fit=max\&auto=format\&n=kLcECSdhM8pjBAIk\&q=85\&s=f9a5cc316e35f21acbb48df6dc94473e) ### CVM Deployment Flow When you run `dstack-cloud deploy`, the CLI parses your configuration and orchestrates the creation of a TEE environment. The flow differs by platform: **GCP (dstack CVM):** ``` dstack-cloud deploy → Parse docker-compose.yaml → Build CVM image (dstack-os + containers) → Generate measurements (RTMR values) → Create Confidential VM with TDX → Guest Agent starts inside CVM → Attestation obtained from hardware ``` **AWS Nitro (Enclave):** ``` dstack-cloud deploy → Build Docker image from Dockerfile → Run nitro-cli build-enclave → generates EIF → 3 PCRs (PCR0-2) produced at build time → Combine 3 PCRs into 1 OS_IMAGE_HASH → Register OS_IMAGE_HASH on-chain (via governance) → Launch Enclave on EC2 instance → dstack-util handles attestation and key retrieval ``` ![CVM Deployment Flow](https://mintcdn.com/phalanetwork-1606097b/kLcECSdhM8pjBAIk/images/dstack-cloud/cvm-deployment-flow.png?fit=max\&auto=format\&n=kLcECSdhM8pjBAIk\&q=85\&s=54cf2ebd060bac503834f365965b2910) ## Attestation Module The attestation module abstracts platform-specific hardware attestation behind a common interface. Each platform has its own module: | Platform | Module | Input | Output | | - | - | - | - | | GCP (TDX) | `tdx-attest` | TDX hardware | TDX Quote | | AWS Nitro | `nsm-attest` | NSM device | Attestation Document | | GCP (TPM) | `tpm-attest` | TPM device | TPM Quote | ## Key Files These are the files you'll spend the most time in when contributing: | File | Purpose | | - | - | | `kms/src/main.rs` | KMS service entry point, RPC handlers, bootstrap logic | | `packages/guest-agent/src/main.rs` | Guest Agent entry point, local API server | | `packages/attestation/src/lib.rs` | Platform-agnostic attestation interface | | `cli/src/main.rs` | CLI entry point, deploy/status/logs commands | | `contracts/contracts/DstackKms.sol` | KMS policy contract | | `contracts/contracts/DstackApp.sol` | Application contract | ## Resources * [dstack-cloud GitHub](https://github.com/Phala-Network/dstack-cloud) * [dstack framework GitHub](https://github.com/Dstack-TEE/dstack) * [dstack Official Documentation](https://docs.phala.com/dstack/overview) * [dstack Whitepaper](https://docs.phala.com/dstack/design-documents/whitepaper) # Configuration Reference Source: https://docs.phala.com/dstack-cloud/configuration Configuration reference for dstack-cloud global config, app.json, docker-compose.yaml, and CLI commands. # Configuration Reference dstack-cloud uses three layers of configuration: a global CLI config, a per-project `app.json`, and a standard `docker-compose.yaml` for your application. This page documents every field and available option. ## dstack-cloud Global Configuration **Location:** `~/.config/dstack-cloud/config.json` ```json theme={"system"} { "image_search_paths": ["/path/to/your/images"], "gcp": { "project": "your-gcp-project-id", "zone": "us-central1-a", "bucket": "gs://your-bucket-name" }, "nitro": { "region": "us-east-1" } } ``` ### Fields | Field | Type | Description | | - | - | - | | `image_search_paths` | array of string | Local paths where dstack-cloud looks for OS images | | `gcp.project` | string | GCP project ID | | `gcp.zone` | string | GCP zone for VM deployment | | `gcp.bucket` | string | GCS bucket for storing CVM images | | `nitro.region` | string | AWS region for Nitro Enclave deployment | ## app.json (Project Configuration) **Location:** `/app.json` Generated by `dstack-cloud new` and edited manually for advanced configuration. ```json theme={"system"} { "os_image": "dstack-cloud-0.6.0", "key_provider": "local", "instance_name": "my-app", "platform": "nitro" } ``` ### Fields | Field | Type | Description | | - | - | - | | `os_image` | string | The dstack OS image version to use | | `key_provider` | string | Key provider mode: `local` (default), `tpm`, or `kms` | | `instance_name` | string | Human-readable name for the instance | | `platform` | string | Target platform: `gcp` or `nitro` | ### key\_provider Values | Value | Description | Use Case | | - | - | - | | `local` | Keys generated locally within the CVM | Development, testing, single-node | | `tpm` | Use the platform TPM as root of trust | KMS instances on GCP | | `kms` | Use an external dstack-kms for key delivery | Production workloads that need attested key delivery | ## docker-compose.yaml The standard Docker Compose file defines your application. dstack-cloud reads this file and packages all containers into the CVM. ### dstack-specific Extensions dstack-cloud reads the standard `docker-compose.yaml` format. No special extensions are required. **Important notes:** * All images must be pullable by the build system (use public registries or pre-pull images) * Use SHA256 digests for pinned images (recommended for reproducible measurements): ```yaml theme={"system"} services: web: image: nginx:latest@sha256:abc123... ``` * The `runtime: nvidia` field is supported for GPU workloads on compatible instances * `volumes` that reference `/var/run/dstack.sock` are automatically mounted for Guest Agent access ### Example: Web Application ```yaml theme={"system"} services: web: image: nginx:latest ports: - "80:80" ``` ### Example: AI Inference with GPU ```yaml theme={"system"} services: vllm: image: vllm/vllm-openai:latest runtime: nvidia command: --model Qwen/Qwen2.5-7B-Instruct ports: - "8000:8000" volumes: - /var/run/dstack.sock:/var/run/dstack.sock ``` ### Example: KMS Instance ```yaml theme={"system"} services: dstack-kms: image: phalanetwork/dstack-kms:latest environment: - KMS_HTTPS_PORT=12001 - ETH_RPC_URL=https://sepolia.base.org - KMS_CONTRACT_ADDR=0x... - APP_CONTRACT_ADDR=0x... ports: - "12001:12001" ``` ## .env (Environment Variables) **Location:** `/.env` Standard dotenv format. Used for environment variables that are injected into the CVM. ```bash theme={"system"} API_KEY=your-api-key-here DATABASE_URL=postgres://user:pass@host:5432/db ``` ### KMS Environment Variables | Variable | Description | Example | | - | - | - | | `KMS_HTTPS_PORT` | Port for KMS HTTPS/RA-TLS (Remote Attestation TLS) service | `12001` | | `ETH_RPC_URL` | Ethereum RPC endpoint URL | `https://sepolia.base.org` | | `KMS_CONTRACT_ADDR` | DstackKms contract address | `0x1234...abcd` | | `APP_CONTRACT_ADDR` | DstackApp contract address | `0x5678...efgh` | | `USE_LIGHT_CLIENT` | Use helios light client instead of direct RPC | `true` or `false` | ### Security of Environment Variables * Environment variables are encrypted before leaving your machine * They are decrypted only inside the CVM/TEE * The cloud provider and host OS cannot read them in plaintext ## prelaunch.sh (Pre-launch Script) **Location:** `/prelaunch.sh` An optional shell script that runs before the CVM/Enclave launches. Common uses: * Start the VSOCK proxy (Nitro) * Inject environment variables * Generate dynamic configuration ```bash theme={"system"} #!/bin/bash # prelaunch.sh — runs before CVM launch # Start VSOCK proxy (Nitro only) socat VSOCK-LISTEN:8000,reuseaddr,fork TCP:localhost:8000 & # Inject environment variables export KMS_HTTPS_PORT=12001 export ETH_RPC_URL=https://sepolia.base.org echo "Prelaunch complete" ``` ## dstack-cloud CLI Commands | Command | Description | | - | - | | `dstack-cloud new ` | Create a new project directory | | `dstack-cloud deploy` | Build and deploy the CVM/Enclave | | `dstack-cloud status` | Show deployment status and measurements | | `dstack-cloud logs [--follow]` | View container logs | | `dstack-cloud stop` | Stop the running CVM/Enclave | | `dstack-cloud start` | Start a stopped CVM/Enclave | | `dstack-cloud remove` | Remove the deployment and clean up resources | | `dstack-cloud fw allow ` | Allow inbound traffic on a port | | `dstack-cloud fw deny ` | Deny inbound traffic on a port | | `dstack-cloud pull --os-image ` | Download an OS image | | `dstack-cloud config-edit` | Edit the global configuration | ## Next Steps * **[API Reference](/dstack-cloud/api-reference)** — Guest Agent and KMS APIs * **[Glossary](/dstack-cloud/glossary)** — Term definitions # Deploy On-chain KMS Smart Contracts Source: https://docs.phala.com/dstack-cloud/deploy-onchain-kms Deploy DstackKms smart contracts and configure governance with Multisig and Timelock. # Deploy On-chain KMS Smart Contracts Deploy the `DstackKms` smart contract to enforce that only authorized workloads can receive keys. This page covers the full contract deployment workflow, including the recommended Safe + Timelock governance setup for production. ## Overview | Component | Required | Description | | - | - | - | | **DstackKms** | Yes | Stores authorized workload measurements, admin roles, and KMS configuration | | **ERC1967Proxy** | Yes | Proxy contract for upgradeable DstackKms (UUPS pattern) | | **TimelockController** | Optional | Enforces a delay on governance actions | | **Safe (Multisig)** | Optional | Multi-signature wallet for governance | > **Note:** Safe and Timelock are **optional security enhancements**, not part of dstack. They are recommended for production but not required for development. ## Governance Models ### Model A: Direct Admin (Simplest) * Admin is a single EOA (externally owned account) * No multisig, no timelock * Governance actions execute immediately * Suitable for development and testing ### Model B: Timelock Only * Admin is a TimelockController contract * Governance actions require a delay before execution * Anyone can execute after delay (or restricted to specific executors) * Suitable for simple production setups ### Model C: Safe + Timelock (Recommended for Production) * Admin is a Safe multisig wallet * Timelock enforces a delay * Requires multi-party approval + delay period * Maximum security and transparency *** ## Prerequisites * [Foundry](https://book.getfoundry.sh/getting-started/installation) installed (`forge`, `cast`) * A wallet with funds for deployment gas * Testnet: Use a faucet (e.g., [Base Sepolia faucet](https://www.alchemy.com/faucets/base-sepolia)) * Mainnet: Sufficient ETH for contract deployment * RPC endpoint for the target network *** ## Step 1: Set Up the Project ```bash theme={"system"} # Clone the dstack repository (contains KMS contracts) git clone https://github.com/Dstack-TEE/dstack.git cd dstack/kms/auth-eth/contracts # Install dependencies (OpenZeppelin) forge install OpenZeppelin/openzeppelin-contracts@v5.6.1 --no-git forge install OpenZeppelin/openzeppelin-contracts-upgradeable@v5.6.1 --no-git # Build contracts forge build ``` *** ## Step 2: Configure Environment Create a `.env` file: ```bash theme={"system"} # .env RPC_URL=https://sepolia.base.org PRIVATE_KEY=0x... ``` > **Security:** Never commit your private key. Add `.env` to `.gitignore`. *** ## Step 3: Deploy DstackKms (Basic, No Timelock) For development/testing, you can deploy DstackKms with direct EOA admin: ```bash theme={"system"} # Deploy DstackKms implementation KMS_IMPL=$(forge create src/DstackKms.sol:DstackKms \ --broadcast \ --rpc-url $RPC_URL \ --private-key $PRIVATE_KEY | grep "Deployed to:" | tail -1 | cut -d' ' -f3) echo "DstackKms implementation: $KMS_IMPL" # Encode initializer calldata DEPLOYER=$(cast wallet address --private-key $PRIVATE_KEY) INIT_DATA=$(cast calldata "initialize(address,address)" $DEPLOYER $ZERO_ADDRESS) # Deploy ERC1967Proxy KMS_PROXY=$(forge create lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Proxy.sol:ERC1967Proxy \ --broadcast \ --rpc-url $RPC_URL \ --private-key $PRIVATE_KEY \ --constructor-args $KMS_IMPL $INIT_DATA | grep "Deployed to:" | tail -1 | cut -d' ' -f3) echo "DstackKms proxy: $KMS_PROXY" ``` > **Why ERC1967Proxy?** DstackKms uses UUPS upgradeable pattern. You must deploy a proxy to have a working upgradeable instance. The proxy is the actual application address. *** ## Step 4: Deploy with Timelock (Recommended for Production) ### Timelock Configuration The timelock delay depends on your deployment environment: | Parameter | Testnet | Mainnet | | - | - | - | | **Timelock delay** | 1-4 hours | 24-72 hours | | **Safe signers** | 2-3 addresses | 5-7 addresses (from multiple organizations) | | **Safe threshold** | 2/3 | ≥ 2/3 | | **Executor role** | Open or EOA | Safe only (strict control) | | **Admin role** | EOA or 0x0 | 0x0 (self-managed by timelock) | ### 4.1 Prepare Timelock Configuration ```bash theme={"system"} # Set environment variables export MIN_DELAY=86400 # 1 day in seconds (production: 2-3 days) export PROPOSER=0x... # Address that can schedule operations (your Safe or EOA) export EXECUTOR=0x... # Address that can execute operations (Safe, or 0x0 for open execution) export ADMIN=0x... # Admin address (can grant/revoke roles) ``` ### 4.2 Deploy All Contracts ```bash theme={"system"} # Get deployer address DEPLOYER=$(cast wallet address --private-key $PRIVATE_KEY) # 1. Deploy DstackKms implementation KMS_IMPL=$(forge create src/DstackKms.sol:DstackKms \ --broadcast \ --rpc-url $RPC_URL \ --private-key $PRIVATE_KEY | grep "Deployed to:" | tail -1 | cut -d' ' -f3) # 2. Encode initializer (owner = deployer initially) INIT_DATA=$(cast calldata "initialize(address,address)" $DEPLOYER $ZERO_ADDRESS) # 3. Deploy ERC1967Proxy KMS_PROXY=$(forge create lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Proxy.sol:ERC1967Proxy \ --broadcast \ --rpc-url $RPC_URL \ --private-key $PRIVATE_KEY \ --constructor-args $KMS_IMPL $INIT_DATA | grep "Deployed to:" | tail -1 | cut -d' ' -f3) # 4. Deploy TimelockController TIMELOCK=$(forge create lib/openzeppelin-contracts/contracts/governance/TimelockController.sol:TimelockController \ --broadcast \ --rpc-url $RPC_URL \ --private-key $PRIVATE_KEY \ --constructor-args $MIN_DELAY "[$PROPOSER]" "[$EXECUTOR]" $ADMIN | grep "Deployed to:" | tail -1 | cut -d' ' -f3) # 5. Transfer ownership to Timelock cast send $KMS_PROXY "transferOwnership(address)" $TIMELOCK \ --rpc-url $RPC_URL \ --private-key $PRIVATE_KEY # 6. Verify ownership OWNER=$(cast call $KMS_PROXY "owner()(address)" --rpc-url $RPC_URL) echo "=== Deployment Result ===" echo "DstackKms implementation: $KMS_IMPL" echo "DstackKms proxy: $KMS_PROXY" echo "TimelockController: $TIMELOCK" echo "DstackKms owner: $OWNER" ``` ### 4.3 Understanding TimelockController Roles | Role | Description | Who Should Have It | | - | - | - | | **Proposer** | Can schedule operations | Safe multisig or trusted EOA | | **Executor** | Can execute operations after delay | Safe, or `address(0)` for open execution | | **Admin** | Can grant/revoke roles | Should be `address(0)` after setup (self-managed by timelock) | *** ## Step 5: Configure Safe (Optional but Recommended) For production, use a Safe multisig as the proposer/executor: ### 5.1 Create a Safe 1. Go to [Safe web app](https://app.safe.global) 2. Connect your wallet 3. Create a new Safe on your target network 4. Add signers (3-7 addresses recommended) 5. Set threshold (≥ 2/3 of signers) ### 5.2 Use Safe Address in Deployment When deploying the TimelockController, use your Safe address: ```bash theme={"system"} export PROPOSER= export EXECUTOR= export ADMIN=0x0000000000000000000000000000000000000000 # Let timelock manage itself ``` ### 5.3 Governance Flow with Safe + Timelock 1. **Draft transaction** — Use Safe web interface to create a transaction 2. **Collect signatures** — Required signers approve 3. **Schedule in timelock** — Safe calls `timelock.schedule()` 4. **Wait for delay** — Wait the configured delay period 5. **Execute** — Anyone (or only executor) calls `timelock.execute()` *** ## Step 6: Verify Deployment Verify on block explorer: ```bash theme={"system"} # Verify implementation forge verify-contract $KMS_IMPL src/DstackKms.sol:DstackKms \ --chain base-sepolia \ --verifier etherscan # Verify proxy forge verify-contract $KMS_PROXY lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Proxy.sol:ERC1967Proxy \ --chain base-sepolia \ --verifier etherscan \ --constructor-args $(cast abi-encode "constructor(address,bytes)" $KMS_IMPL $INIT_DATA) ``` Check on block explorer: * `DstackKms` owner is set to the TimelockController address * TimelockController has correct proposer/executor roles *** ## How to Execute Governance Actions (With Timelock) Once deployed, all `onlyOwner` operations must go through the timelock: ### Schedule an Operation ```bash theme={"system"} # Example: Add an authorized measurement cast send $TIMELOCK "schedule(address,uint256,bytes,bytes32,bytes32,uint256)" \ $KMS_PROXY \ 0 \ $(cast calldata "addKmsAggregatedMr(bytes32)" $YOUR_MEASUREMENT) \ 0x0000000000000000000000000000000000000000000000000000000000000000 \ $(cast keccak "unique-operation-id") \ $MIN_DELAY \ --rpc-url $RPC_URL \ --private-key $PROPOSER_KEY ``` ### Execute After Delay ```bash theme={"system"} # Wait for MIN_DELAY to pass, then: cast send $TIMELOCK "execute(address,uint256,bytes,bytes32,bytes32)" \ $KMS_PROXY \ 0 \ $(cast calldata "addKmsAggregatedMr(bytes32)" $YOUR_MEASUREMENT) \ 0x0000000000000000000000000000000000000000000000000000000000000000 \ $(cast keccak "unique-operation-id") \ --rpc-url $RPC_URL \ --private-key $EXECUTOR_KEY ``` *** ## All Governance-Protected Methods Once ownership is transferred to timelock, these methods require timelock governance: | Method | Purpose | | - | - | | `setKmsInfo` | Update KMS public key and attestation info | | `setKmsQuote` | Update KMS quote | | `setKmsEventlog` | Update KMS event log | | `setGatewayAppId` | Set gateway application ID | | `setAppImplementation` | Update app implementation address | | `addKmsAggregatedMr` | Authorize a KMS measurement | | `removeKmsAggregatedMr` | Revoke a KMS measurement | | `addKmsDevice` | Authorize a KMS device | | `removeKmsDevice` | Revoke a KMS device | | `addOsImageHash` | Authorize an OS image hash | | `removeOsImageHash` | Revoke an OS image hash | *** ## Common Issues | Issue | Solution | | - | - | | "Insufficient funds" | Get testnet ETH from faucet, or ensure mainnet wallet has enough ETH | | "Ownable: caller is not the owner" | Ownership already transferred to timelock. Use timelock.schedule/execute | | "Timelock: operation is not ready" | Wait for the delay period to pass before executing | | "Timelock: operation already scheduled" | Use a different salt (unique operation ID) | | Proxy verification fails | Use `cast abi-encode` to construct the constructor arguments | *** ## Next Steps * **[Register KMS Measurements](/dstack-cloud/run-kms-on-gcp)** — Register KMS measurements before bootstrap * **[Register Workload Measurements](/dstack-cloud/register-enclave-measurement)** — Authorize workloads to receive keys * **[Manage Governance](/dstack-cloud/manage-governance)** — How to create proposals and execute governance actions * **[Concept: Governance](/dstack-cloud/governance)** — Understand the governance model # E2E Test Report Source: https://docs.phala.com/dstack-cloud/e2e-test-report End-to-end test report covering test coverage and pre-production validation results. # E2E Test Report **This document is a work in progress.** Test results will be populated as they become available. ## Test Coverage Tests are being conducted across the following scenarios. Results will be added as each test completes. | Category | Status | Notes | | - | - | - | | GCP CVM deployment | In progress | | | GCP KMS deployment + bootstrap | In progress | | | Nitro Enclave deployment | In progress | | | RA-TLS connection (GCP KMS → GCP workload) | In progress | | | RA-TLS connection (GCP KMS → Nitro workload) | In progress | | | getKey() key retrieval | In progress | | | On-chain measurement registration | In progress | | | On-chain measurement revocation | In progress | | | Governance flow (propose → approve → timelock → execute) | In progress | | | KMS bootstrap (Onboard → Finish) | In progress | | | Multi-node key replication | Planned | | ## Test Environment | Component | Version | | - | - | | dstack-cloud | 0.6.0-test | | dstack OS | dstack-cloud-0.6.0 | | GCP zone | us-central1-a | | AWS region | us-east-1 | | Blockchain | Base Sepolia (testnet) | ## Known Limitations | Limitation | Impact | Mitigation | | - | - | - | | KMS root key is single-point | If the KMS TEE is compromised, all keys are at risk | MPC distribution planned for future version | | Nitro Enclaves are stateless | Workloads lose state on restart | Use GCP for persistent workloads; KMS runs on GCP only | | Public RPC reliability | Testnet RPCs may return stale state | Use multiple RPC providers | ## Accepted Risks | Risk | Acceptance Criteria | | - | - | | TEE hardware side-channels | Accept residual risk. Monitor Intel/AWS advisories. | | Smart contract vulnerabilities | Mitigate with audits. Re-audit after each contract change. | # Quick Start: Deploy Your First dstack App on GCP Source: https://docs.phala.com/dstack-cloud/get-started Quick start tutorial to deploy your first dstack CVM on GCP in 15-25 minutes. # Quick Start: Deploy Your First dstack App on GCP You'll have a Docker application running inside a hardware-encrypted Confidential VM on GCP within 25 minutes. This tutorial covers the full path: install the CLI, configure your project, deploy, and verify that attestation proves your workload runs in genuine TEE hardware. **Estimated time:** 15–25 minutes (first run). **What you will do:** 1. Install `dstack-cloud` CLI 2. Configure global GCP/KMS settings 3. Create a project and define workload 4. Deploy to GCP TDX CVM 5. Verify workload access and runtime status *** ## Prerequisites Before you begin: * GCP project with Intel TDX quota in target zone (for example `us-central1-a`) * `gcloud` authenticated ```bash theme={"system"} gcloud auth login gcloud config set project YOUR_PROJECT_ID ``` * **Linux host** (required — `dstack-cloud deploy` uses FAT32 disk images, which don't work on macOS) * Docker installed * `gsutil`, `jq`, `mtools` (for `mcopy`), `dosfstools` (for `mkfs.fat`) — these are needed by the deploy process to build a shared disk image *** ## Step 1: Install dstack-cloud CLI ```bash theme={"system"} curl -fsSL -o ~/.local/bin/dstack-cloud \ https://raw.githubusercontent.com/Phala-Network/meta-dstack-cloud/main/scripts/bin/dstack-cloud chmod +x ~/.local/bin/dstack-cloud dstack-cloud --help ``` *** ## Step 2: Configure global settings ```bash theme={"system"} dstack-cloud config-edit ``` Use JSON config (`~/.config/dstack-cloud/config.json`): ```json theme={"system"} { "services": { "kms_urls": ["https://kms.tdxlab.dstack.org:12001"], "gateway_urls": ["https://gateway.tdxlab.dstack.org:12002"], "pccs_url": "" }, "image_search_paths": ["/path/to/images"], "gcp": { "project": "YOUR_PROJECT_ID", "zone": "us-central1-a", "bucket": "gs://YOUR_BUCKET" } } ``` If bucket does not exist: ```bash theme={"system"} gcloud storage buckets create gs://YOUR_BUCKET --project YOUR_PROJECT_ID --location us-central1 ``` ### Optional: configure external KMS If you already deployed your own KMS, replace `services.kms_urls`: ```json theme={"system"} "services": { "kms_urls": ["https://YOUR_KMS_IP_OR_DOMAIN:12001"] } ``` *** ## Step 3: Pull OS image ```bash theme={"system"} dstack-cloud pull https://github.com/Phala-Network/meta-dstack-cloud/releases/download/v0.6.0-test/dstack-cloud-0.6.0.tar.gz dstack-cloud pull https://github.com/Phala-Network/meta-dstack-cloud/releases/download/v0.6.0-test/dstack-cloud-0.6.0-uki.tar.gz ``` Verify: ```bash theme={"system"} ls -lh /path/to/images/dstack-cloud-0.6.0/disk.raw ``` *** ## Step 4: Create project ```bash theme={"system"} dstack-cloud new my-first-app --os-image dstack-cloud-0.6.0 --instance-name dstack-first-app cd my-first-app ``` Project files include: ``` my-first-app/ ├── app.json # Application metadata ├── docker-compose.yaml # Your container definition ├── .env # Environment variables (encrypted) └── prelaunch.sh # Optional pre-launch script (e.g., setup, data download) ``` *** ## Step 5: Configure app Edit `app.json` and set: * `gcp_config.project = "YOUR_PROJECT_ID"` * `gcp_config.zone = "us-central1-a"` * `gcp_config.bucket = "gs://YOUR_BUCKET"` Default key mode is `kms`. If you want no external KMS for a basic quick test, switch to: * `"key_provider": "tpm"` * `"gateway_enabled": false` * remove `.env` file and remove `env_file` field from `app.json` *** ## Step 6: Define workload Edit `docker-compose.yaml`: ```yaml theme={"system"} services: web: image: nginx:latest ports: - "8080:80" ``` *** ## Step 7: Deploy ```bash theme={"system"} dstack-cloud deploy --delete ``` This will create a TDX CVM and start your workload. *** ## Step 8: Open firewall ```bash theme={"system"} dstack-cloud fw allow 8080 ``` *** ## Step 9: Verify Check that the CVM is running and your workload is accessible: ```bash theme={"system"} dstack-cloud status # Expected: shows "RUNNING" with measurements (RTMR values) dstack-cloud logs --follow # Get attestation from your app curl https://app-abc123.your-gateway-domain.com/attestation # Verify using dstack-verifier dstack-verifier verify ``` The attestation proves: * The workload runs in genuine Intel TDX hardware * The exact code and measurements match expectations * The boot chain integrity is verified via TDX + vTPM For detailed verification, see [Attestation Integration](/dstack-cloud/attestation-integration). **Test workload:** ```bash theme={"system"} curl http://:8080 ``` If gateway is enabled, use the URL shown by `dstack-cloud status`. ## Understanding What Happened When you deployed your application: 1. **Confidential VM Created** — A GCP VM with Intel TDX was provisioned 2. **dstack OS Booted** — A minimal, attested guest OS started inside the TEE 3. **Automatic Disk Encryption** — All disk I/O is encrypted with keys managed by the Guest Agent 4. **TEE Attestation** — The Guest Agent provides attestation proof via the TDX + vTPM mechanism 5. **TLS Certificate** — Gateway automatically provisions ACME certificates for your domain ### Key Delivery via KMS dstack uses an external **Key Management Service (dstack-kms)** to deliver keys to your confidential workloads. The KMS runs in its own TEE and only dispatches keys to workloads that pass attestation verification. *** ## Managing Your Deployment Your application now runs in a hardware-protected environment where even the cloud provider cannot access the memory or data. *** ## Troubleshooting | Issue | Fix | | - | - | | `Boot image ... not found` | verify image path and `disk.raw` existence | | VM UEFI boot loop | use valid UKI boot image (`-uki.tar.gz`) | | `.env found but KMS is not enabled` | remove `.env` and remove `env_file` in `app.json` | | Port not reachable | ensure firewall rule exists and container has started | | missing `gsutil` / `mcopy` / `mkfs.fat` | install required dependencies | *** ## Next steps * Detailed guide: [Run a Workload on GCP with Self-hosted KMS](/dstack-cloud/run-on-gcp) * External KMS flow: [Run a dstack-kms CVM on GCP](/dstack-cloud/run-kms-on-gcp) * Concepts: [Attestation Integration](/dstack-cloud/attestation-integration) # Glossary Source: https://docs.phala.com/dstack-cloud/glossary Glossary of core terminology used in dstack-cloud documentation. # Glossary Core terminology used in this documentation. *** ## Infrastructure | Term | Definition | | - | - | | **TEE (Trusted Execution Environment)** | A hardware-isolated compute environment that protects code and data from the rest of the system. Memory is encrypted, and the hardware proves the environment's integrity via attestation. | | **CVM (Confidential Virtual Machine)** | A virtual machine running in a TEE. In dstack-cloud, a CVM runs dstack-os with your Docker containers inside. | | **Intel TDX (Trust Domain Extensions)** | Intel's TEE technology that provides memory encryption and isolation at the VM level. Supported on GCP Confidential VMs and certain bare-metal servers. | | **SGX (Software Guard Extensions)** | Intel's earlier TEE technology. Provides memory encryption at the enclave (process) level. | | **AWS Nitro Enclaves** | AWS's TEE technology. Provides process-level isolation within an EC2 instance. Memory is encrypted and inaccessible to the host. | | **NSM (Nitro Secure Module)** | The hardware component in AWS Nitro that generates attestation documents and manages Enclave lifecycle. | | **VSOCK** | A socket interface for communication between a Nitro Enclave and its host EC2 instance. The Enclave cannot directly access the network — all traffic goes through VSOCK. | | **EIF (Enclave Image File)** | The image format used by AWS Nitro Enclaves. Built from a Docker image, it contains the OS and application code that runs inside the Enclave. | | **TPM (Trusted Platform Module)** | A hardware security module that provides secure key storage and measurement. Used on GCP Confidential VMs as the root of trust. | | **PCCS (Provisioning Certificate Caching Service)** | Intel's service for caching attestation certificate chains, used in DCAP (Data Center Attestation Primitives) workflows. | *** ## Security Mechanisms | Term | Definition | | - | - | | **Remote Attestation** | The process by which a TEE proves its identity and integrity to an external party. The TEE generates a cryptographic proof (signed by hardware) containing measurements of the running code. | | **RA-TLS (Remote Attestation TLS)** | An extension of TLS where both parties verify each other's TEE attestation during the handshake. Used for secure communication between workloads and KMS. | | **ZT-TLS (Zero Trust TLS)** | A TLS variant that requires TEE attestation for every connection, regardless of network location. | | **Measurement** | A cryptographic hash of the code and configuration running inside a TEE. Any change to the code produces a different measurement. | | **PCR (Platform Configuration Register)** | Measurement registers used by AWS Nitro Enclaves (PCR0-3). | | **RTMR (Runtime Measurement Register)** | Measurement registers used by Intel TDX (RTMR0-3). | | **OS\_IMAGE\_HASH** | A composite hash derived from all PCR values, used as the unique identifier for a Nitro Enclave image on-chain. | | **compose-hash** | The SHA256 hash of the `docker-compose.yaml` file, stored in RTMR3 on GCP TDX deployments. | | **Quote (TDX Quote)** | A hardware-signed attestation proof generated by Intel TDX. Contains measurement values (RTMR0-3) and an Intel hardware signature. | | **Attestation Document** | The attestation proof generated by AWS NSM. Contains PCR values and an NSM signature. | *** ## dstack Components | Term | Definition | | - | - | | **dstack** | The open-source confidential computing framework. Provides a CLI, KMS, attestation, and SDK libraries (Python, TypeScript, Rust, Go) for building confidential applications. [GitHub](https://github.com/Dstack-TEE/dstack) | | **dstack-sdk** | Client libraries (Python, TypeScript, Rust, Go) that applications use to interact with dstack features such as attestation, key retrieval, and storage encryption. Part of the dstack framework. | | **dstack-cloud** | An extension of dstack that enables deployment on GCP Confidential VMs and AWS Nitro Enclaves. Provides the `dstack-cloud` CLI. [GitHub](https://github.com/Phala-Network/dstack-cloud) | | **dstack-os** | The minimal operating system that runs inside each dstack CVM. Built from a reproducible Docker image. | | **Guest Agent** | A process that runs inside each dstack CVM alongside your application containers. Handles attestation, key retrieval from KMS, and storage encryption. Exposes a local API at `/var/run/dstack.sock`. | | **KMS (Key Management Service)** | A standalone service that runs in its own TEE. Verifies workload attestation and dispatches keys to authorized workloads. Also known as DeRoT (Decentralized Root-of-Trust). | | **Gateway** | An edge component that handles TLS termination, automatic ACME certificate provisioning, and RA-TLS support for incoming connections. | | **VMM (Virtual Machine Monitor)** | The component that parses Docker Compose files and boots CVMs from reproducible OS images. | *** ## On-chain Governance | Term | Definition | | - | - | | **DstackKms** | The On-chain KMS policy contract. Stores authorized workload measurements and admin roles. | | **DstackApp** | The on-chain application entry contract. Holds a reference to DstackKms. | | **Multisig (Safe)** | A multi-signature wallet that controls governance actions. Requires multiple parties to approve any transaction. | | **Timelock** | A delay mechanism that enforces a mandatory waiting period between approval and execution of governance transactions. | | **GovernanceSafe** | The specific Safe wallet instance used for dstack governance. | *** ## Cryptography | Term | Definition | | - | - | | **MPC (Multi-Party Computation)** | A cryptographic technique where multiple parties jointly compute a result without any single party learning the inputs. Planned for future KMS root key generation. | | **KDF (Key Derivation Function)** | A function that derives application-specific keys from a root key. Each workload gets a unique key derived this way. | | **SealingKey** | A key used to encrypt data at rest (disk storage) inside the CVM. Derived from the KMS-delivered key. | | **RootKey** | The top-level key in the KMS hierarchy. All application keys are derived from the RootKey. | # On-chain Governance Model Source: https://docs.phala.com/dstack-cloud/governance The on-chain governance model using Multisig + Timelock to control KMS authorization and prevent covert upgrades. # On-chain Governance Model On-chain governance ensures that key policy changes — like adding or revoking workload measurements — cannot happen silently. Every authorization change goes through a Multisig + Timelock process and is recorded on-chain for anyone to audit. ## Core Smart Contracts ### DstackKms The KMS policy contract. It stores: * **Authorized measurements** — The list of workload measurements (RTMR / OS\_IMAGE\_HASH) that are allowed to receive keys * **Configuration parameters** — KMS-related settings controlled by governance * **Admin roles** — Addresses authorized to perform governance operations The off-chain dstack-kms service queries DstackKms to determine whether a workload is authorized before dispatching keys. ### DstackApp The application-level entry contract. It: * Holds a reference to DstackKms * Enforces application-specific checks before delegating to the KMS * Acts as the on-chain identity for a specific deployment ### GovernanceSafe **Optional.** A multisig wallet (typically [Safe](https://safe.global)) that you can introduce to enhance governance security: * Owns DstackKms and DstackApp * Is the only entity allowed to execute governance operations (registering measurements, changing admin, upgrading contracts) * Requires multiple signers to approve any transaction > **Note:** GovernanceSafe is not part of dstack or dstack-cloud. It is an optional governance mechanism you can add to prevent unilateral control over key policies. ### Timelock **Optional.** A delay module attached to the multisig that: * Enforces a mandatory waiting period between approval and execution * Maintains a queue of pending governance actions * Gives the community time to review and respond to proposed changes > **Note:** Like GovernanceSafe, Timelock is an optional enhancement. You can use it with a multisig to add a delay before governance actions take effect. ## Governance Workflow ### Basic Workflow (without Multisig/Timelock) At minimum, governance operations (registering measurements, updating configuration) are performed by the admin address directly: 1. Admin submits a transaction to DstackKms or DstackApp 2. Transaction executes immediately 3. Changes take effect right away This is suitable for development and testing, but lacks the security guarantees needed for production. ### Enhanced Workflow (with Multisig + Timelock) For production deployments, we recommend introducing a multisig wallet (e.g., Safe) and a timelock. The workflow becomes: ![Governance Workflow](https://mintcdn.com/phalanetwork-1606097b/kLcECSdhM8pjBAIk/images/dstack-cloud/governance-workflow.png?fit=max\&auto=format\&n=kLcECSdhM8pjBAIk\&q=85\&s=016e4bdf468444b83dc5ae530d728f61) 1. **Draft** — A governance action is proposed (e.g., register new measurement) 2. **Submit to Multisig** — The action is submitted to the multisig wallet 3. **Approve** — Required number of signers approve the transaction 4. **Queue in Timelock** — The approved action is queued and must wait for the delay period 5. **Wait** — The delay period passes (e.g., 48 hours), allowing time for review 6. **Execute** — After the delay, anyone can execute the action This ensures: * No single party can unilaterally modify key policies * All changes are visible and reviewable before taking effect * Stakeholders have time to respond to suspicious proposals ## Role of Multisig + Timelock | Mechanism | Purpose | | - | - | | **Multisig** | Prevents unilateral actions. No single person can modify key policies — requires multi-party approval. | | **Timelock** | Enforces a delay, giving all stakeholders time to detect and respond to suspicious changes. | ### Recommended Configuration | Parameter | Production | Non-production | | - | - | - | | **Number of signers** | 5-7 (from at least 2 organizations) | 2-3 | | **Signature threshold** | ≥ 2/3 (e.g., 4-of-6) | ≥ 2/3 | | **Timelock delay** | 24-72 hours | 1-4 hours | | **Transaction expiration** | 7-14 days | 3-7 days | ## Typical Governance Scenarios ### Register New Measurements (New Version Deploy) When you update your application code or dstack OS version, the measurements change. You must register the new measurements before KMS will dispatch keys: 1. Build the updated CVM image 2. Extract new measurements (RTMR3 / OS\_IMAGE\_HASH) 3. Draft a governance transaction to add the new measurements to DstackKms 4. Submit to multisig for approval 5. Wait for timelock 6. Execute — KMS now authorizes workloads with the new measurements 7. Deploy the updated CVM ### Revoke a Compromised Measurement (Emergency) If a measurement is found to be vulnerable or unauthorized: 1. Draft a governance transaction to remove the measurement from DstackKms 2. Submit to multisig for expedited approval 3. Wait for timelock (cannot be bypassed — this is by design) 4. Execute — KMS immediately stops dispatching keys to workloads with that measurement > **Note:** Even in emergencies, the timelock cannot be skipped. This is intentional — it ensures all changes are visible and reviewable. Plan your security incident response accordingly. ### Upgrade Smart Contracts If the contracts need to be upgraded (e.g., bug fix, new feature): 1. Deploy the new contract implementation 2. Draft a governance transaction to update the proxy's implementation address 3. Submit to multisig for approval 4. Wait for timelock 5. Execute — the proxy now points to the new implementation ## Security Considerations * **Use hardware wallets:** All multisig signers should use hardware wallets (e.g., Ledger, Trezor) to protect their signing keys. * **Set appropriate thresholds:** A threshold of ≥ 2/3 ensures that compromising a minority of signers is insufficient to push through malicious changes. * **Regular health checks:** Periodically verify that all signers are still accessible and the governance configuration is as expected. * **Monitor governance activity:** Set up alerts for governance transactions (proposals, approvals, executions) to detect suspicious activity early. ## Next Steps * **[Deploy On-chain KMS Smart Contracts](/dstack-cloud/deploy-onchain-kms)** — Set up contracts on testnet or mainnet * **[Manage Governance](/dstack-cloud/manage-governance)** — How to create proposals and execute governance actions * **[Security Model](/dstack-cloud/security-model)** — Trust boundaries and security guarantees # KMS and Key Delivery Source: https://docs.phala.com/dstack-cloud/kms-and-key-delivery Understand KMS operating modes, key delivery flow, and GCP vs Nitro differences in dstack-cloud deployments. # KMS and Key Delivery KMS is the component that decides whether a workload is trustworthy enough to receive keys. This page explains the two operating modes (local vs. external KMS), the key delivery flow on each platform, and how on-chain smart contracts add an auditable authorization layer. > For the core design of dstack's Key Management System — including the Decentralized Root-of-Trust (DeRoT) protocol, MPC key generation, key derivation, and rotation — refer to the official Phala documentation: > > * [Key Management Protocol](https://docs.phala.com/dstack/design-documents/key-management-protocol) > * [Decentralized Root-of-Trust](https://docs.phala.com/dstack/design-documents/decentralized-root-of-trust) ## Operating Modes dstack supports two KMS operating modes: ### Local Key Provider Keys are generated and managed locally within each dstack CVM. No separate KMS service is needed. * **How it works:** The Guest Agent generates keys using hardware-rooted entropy (TPM on GCP, NSM on Nitro). Keys are sealed to the TEE and never leave the CVM. * **Use when:** Development, testing, or single-node deployments where key sharing between instances is not required. * **Limitation:** Keys cannot be shared across multiple CVMs. If you need the same key in different workloads, use KMS mode. ### KMS Mode A standalone **dstack-kms** service runs in its own TEE (a dedicated dstack CVM). It verifies workload identity before dispatching keys. * **How it works:** When a dstack application CVM starts, it obtains a hardware attestation and sends it to KMS. KMS verifies the attestation and checks whether the workload is authorized. If verification passes, KMS dispatches the requested key. * **Use when:** Production deployments, multi-node setups, or when multiple CVM instances need access to the same keys. * **Requirement:** A dstack-kms instance must be deployed and running before application's CVM can request keys. ### On-chain Smart Contracts (Security Enhancement) KMS mode can optionally integrate with on-chain smart contracts (`DstackKms`, `DstackApp`) to provide an additional layer of security: * On-chain contracts control which application CVM are authorized to receive keys (via registered measurements) * All authorization changes are visible on-chain — anyone can audit which measurements are approved * Changes follow a Multisig + Timelock process, preventing covert key policy modifications * This is a **security enhancement** to KMS mode, not a separate operating mode For details on governance, see [On-chain Governance Model](/dstack-cloud/governance). ## Key Delivery Flow (KMS Mode) The following describes the high-level key delivery flow: ### GCP (dstack CVM with Guest Agent) 1. **CVM Startup** — A dstack CVM boots and its Guest Agent obtains a TDX Quote from hardware. 2. **Secure Channel** — The CVM establishes a secure connection with KMS using RA-TLS (Remote Attestation TLS). Both sides verify each other's attestation during the TLS handshake. 3. **Attestation Verification** — KMS verifies the TDX Quote: * Confirms the CVM is running in genuine TEE hardware * Extracts the workload measurement (RTMR values) * Checks whether the measurement matches an authorized value 4. **On-chain Check** *(if on-chain contracts are configured)* — KMS queries the blockchain to verify that the workload's measurement is registered and authorized. 5. **Key Dispatch** — If all checks pass, KMS derives the requested key and sends it to the CVM over the encrypted channel. 6. **Key Usage** — The Guest Agent manages the key lifecycle. Your application retrieves the key via the dstack SDK (Python, TypeScript, Rust, or Go) by connecting to the Guest Agent at `/var/run/dstack.sock`. The Guest Agent can also automatically handle disk encryption. ### AWS Nitro (Enclave with dstack-util) 1. **Enclave Startup** — A Nitro Enclave launches from the EIF. `dstack-util` inside the Enclave obtains an NSM Attestation Document. 2. **Secure Channel** — `dstack-util` establishes a connection with KMS through the VSOCK proxy on the host. The connection uses TLS (RA-TLS if available). 3. **Attestation Verification** — KMS verifies the NSM Attestation Document: * Confirms the Enclave is running on genuine Nitro hardware * Extracts the PCR values (measurements) * Checks whether the `OS_IMAGE_HASH` matches an authorized value 4. **On-chain Check** *(if on-chain contracts are configured)* — KMS queries the blockchain to verify that the measurement is registered and authorized. 5. **Key Dispatch** — If all checks pass, KMS derives the requested key and sends it back through the encrypted channel. 6. **Key Usage** — `dstack-util` makes the key available to your application. **You decide how to use the key** — common patterns include encrypting model weights in memory, decrypting configuration secrets, or encrypting a RAM-disk. Unlike GCP, there is no automatic disk encryption on Nitro. > **Key difference:** On GCP, the Guest Agent manages the entire key lifecycle including automatic disk encryption. On Nitro, `dstack-util` only retrieves the key — your application is responsible for using it. ## GCP vs. Nitro: Key Delivery Differences The key delivery flow is similar on both platforms, but the implementation details differ: * **Attestation format:** TDX Quote (GCP) vs. NSM Attestation Document (Nitro) * **Communication with KMS:** Direct network on GCP vs. VSOCK proxy on Nitro * **Key usage:** Guest Agent manages the full key lifecycle on GCP (including automatic disk encryption), while on Nitro `dstack-util` only retrieves the key — your application decides how to use it * **Persistent storage:** Available on GCP, not on Nitro (stateless Enclave) For a complete comparison, see [AWS Nitro Enclave Integration](/dstack-cloud/nitro-enclave). ### VSOCK Proxy (Nitro-specific) On AWS Nitro, the Enclave cannot directly access the external network. A **VSOCK proxy** runs on the host EC2 instance to forward network requests: * `dstack-util` inside the Enclave sends requests to the VSOCK proxy * The proxy forwards them to the destination (KMS, RPC endpoints, etc.) * Responses are routed back through the proxy to the Enclave This means that on Nitro, you must deploy and configure a VSOCK proxy on the host machine before `dstack-util` can communicate with KMS or any external service. ## KMS Bootstrap (First-time Setup) When a dstack-kms CVM starts for the first time, it enters **Onboard mode** (HTTP, unauthenticated). This is a one-time initialization process: 1. Call `Onboard.Bootstrap` to generate the KMS key pair and obtain attestation info. 2. Register the KMS attestation on-chain (if using on-chain contracts). 3. Call `/finish` to complete initialization. KMS restarts and switches to HTTPS mode. After bootstrap, KMS operates in **Normal mode** and only accepts RA-TLS connections from verified workloads. > **Implementation:** The KMS bootstrap logic is implemented in the [dstack repository](https://github.com/Phala-Network/dstack). ## Key Lifecycle The full key lifecycle is documented in the [Key Management Protocol](https://docs.phala.com/dstack/design-documents/key-management-protocol). At a high level: | Stage | Description | | - | - | | **Generation** | Root keys are generated within the KMS TEE using hardware-rooted entropy | | **Derivation** | Application-specific keys are derived from root keys using KDF (Key Derivation Function) | | **Delivery** | Keys are delivered to verified CVMs over RA-TLS encrypted channels | | **Rotation** | Keys can be rotated by updating the derivation inputs; old keys are naturally phased out | | **Revocation** | Workloads can be de-authorized by revoking their on-chain measurement registration | ## Next Steps * **[Run a dstack-kms CVM on GCP](/dstack-cloud/run-kms-on-gcp)** — Deploy KMS on GCP * **[Deploy On-chain KMS Smart Contracts](/dstack-cloud/deploy-onchain-kms)** — Set up on-chain authorization # Governance Operations Source: https://docs.phala.com/dstack-cloud/manage-governance Create governance proposals, manage Multisig signing, and execute Timelock transactions. # Governance Operations Every governance action — registering measurements, revoking access, upgrading contracts — follows the same pattern: propose, collect signatures, wait for timelock, execute. This page walks through that pattern step by step. ## Prerequisites * Access to a signer wallet in the GovernanceSafe * The Safe web interface ([https://app.safe.global](https://app.safe.global)) or Safe CLI * Understanding of the governance model — see [On-chain Governance Model](/dstack-cloud/governance) ## Creating a Governance Proposal All governance changes start as a transaction submitted to the GovernanceSafe. ### Via Safe Web Interface 1. Go to [https://app.safe.global](https://app.safe.global) and connect your signer wallet 2. Select your governance Safe 3. Click **"New Transaction"** 4. Choose the transaction type: * **Contract interaction** — Call a function on DstackKms, DstackApp, or other contracts * **Transfer** — Send funds (if needed for gas or contract operations) * **Raw transaction** — For complex multi-call transactions ### Common Governance Actions | Action | Contract | Function | | - | - | - | | Register new measurement | DstackKms | `addOsImageHash(bytes32)` | | Revoke measurement | DstackKms | `removeOsImageHash(bytes32)` | | Update admin role | DstackKms | `setAdmin(address)` | | Update KMS reference | DstackApp | `setKms(address)` | | Upgrade contract implementation | Proxy | `upgradeTo(address)` | ### Example: Register a New Measurement 1. **New Transaction** → **Contract interaction** 2. Select `DstackKms` contract 3. Select `addMeasurement(bytes32)` function 4. Enter the measurement hash: `0x1234abcd...` 5. Click **"Create"** 6. The transaction enters the Safe queue ## Multisig Signing and Approval After a transaction is created, it must be approved by enough signers to meet the threshold. ### Approving a Transaction 1. Each signer connects to the Safe web interface 2. Opens the pending transaction 3. Reviews: * Target contract address * Function name and parameters * Simulation result (if available) 4. Clicks **"Confirm"** (signs with their wallet) ### Tracking Approval Progress The Safe interface shows: * Number of confirmations collected * Required threshold (e.g., "3 of 5 confirmations") * Status: Pending / Awaiting execution / Executed ### Rejecting a Transaction If a signer disagrees with a proposal, they should: 1. Not sign the transaction 2. Communicate concerns to other signers 3. If the transaction has already been approved, wait for the timelock — there is no "cancel" after execution ## Timelock After the required number of signatures is collected, the transaction enters the Timelock queue. ### How It Works 1. The transaction is queued with a mandatory delay 2. No one can execute the transaction until the delay expires 3. During the delay, anyone can review the transaction on-chain 4. After the delay, any authorized address (typically a signer) can execute it ### Timelock Duration | Environment | Typical Duration | | - | - | | Testnet | 1-4 hours | | Staging | 4-24 hours | | Production | 24-72 hours | ### Monitoring the Timelock * **Safe web interface:** Shows the queue position and remaining time * **Block explorer:** Look for the Timelock contract's `QueuedTransactions` event ## Execution After the timelock expires: 1. Open the Safe web interface 2. Find the transaction (status: "Ready to execute") 3. Click **"Execute"** 4. Confirm the transaction in your wallet 5. The transaction is submitted on-chain After execution, the change takes effect immediately. KMS syncs the latest on-chain state on its next query. ## Emergency Operations ### Revoke a Compromised Measurement If you discover that a measurement is compromised: 1. Draft a transaction to call `DstackKms.removeOsImageHash(bytes32)` with the compromised hash 2. Submit to the Safe for priority approval 3. Collect signatures as quickly as possible 4. **Wait for the timelock** — this cannot be bypassed 5. Execute after the delay > **Important:** The timelock cannot be skipped, even in emergencies. This is by design — it prevents covert changes. Plan your incident response to account for the delay. ### Replace a Signer If a signer key is compromised or a signer needs to be replaced: 1. Draft a transaction to call `Safe.addOwner(address)` and `Safe.removeOwner(address, address)` 2. Submit for multisig approval 3. Wait for timelock 4. Execute The replacement signer should use a hardware wallet. ### Governance Health Check Periodically verify the health of your governance setup: | Check | How | | - | - | | All signers are reachable | Contact each signer; confirm they have access to their wallet | | Signer keys are secure | Verify signers are using hardware wallets | | Threshold is appropriate | Review the threshold against the number of active signers | | Timelock duration is appropriate | Adjust if the threat landscape has changed | | No stale transactions in queue | Review and cancel any outdated proposals | | Contract ownership is correct | Verify DstackKms and DstackApp owners point to the Safe | ## Common Issues | Issue | Solution | | - | - | | Transaction not appearing in queue | Ensure the transaction was submitted correctly. Check the nonce. Verify gas is sufficient. | | Signer cannot confirm | Ensure the signer is connected to the correct network. Check that the wallet has ETH for gas. | | Timelock delay seems too long | Adjust the Timelock parameters through a governance action (which itself goes through the current timelock). | | Transaction execution reverts | Check the contract state. The transaction may depend on state that changed during the timelock period. Simulate the transaction before executing. | | Lost signer key | Immediately add a new signer and remove the lost one through governance. Use the remaining signers to approve. | ## Next Steps * **[Register Workload Measurements](/dstack-cloud/register-enclave-measurement)** — Most common governance action * **[Deploy On-chain KMS Smart Contracts](/dstack-cloud/deploy-onchain-kms)** — Initial contract setup * **[Concept: Governance](/dstack-cloud/governance)** — Understand the governance model # Monitoring and Alerting Source: https://docs.phala.com/dstack-cloud/monitoring-alerting Set up monitoring, alerting, and dashboards for dstack-cloud deployments. # Monitoring and Alerting You can't secure what you can't see. This page covers the key metrics to watch, log collection patterns, and alert rules that help you catch attestation failures, governance anomalies, or KMS downtime before they become incidents. ## Key Metrics ### KMS Metrics These metrics tell you whether KMS is healthy and delivering keys promptly: | Metric | Description | Alert Threshold | | - | - | - | | **Key request success rate** | Percentage of key requests that succeed | \< 99% | | **Key dispatch latency (p50/p99)** | Time from request to key delivery | p99 > 5s | | **Attestation verification success rate** | Percentage of attestation verifications that pass | \< 99% | | **On-chain sync lag** | Time between on-chain state change and KMS picking it up | > 60s | | **KMS uptime** | Percentage of time KMS is reachable | \< 99.9% | ### CVM / Enclave Metrics Track workload health and resource usage: | Metric | Description | Alert Threshold | | - | - | - | | **CVM uptime** | Percentage of time the CVM is running | \< 99% | | **CVM boot time** | Time from deploy command to CVM ready | > 5 minutes | | **RA-TLS (Remote Attestation TLS) handshake success rate** | Percentage of successful RA-TLS connections | \< 99% | | **Container restart count** | Number of container restarts within the CVM | > 0 | | **Memory usage** | CVM memory utilization | > 90% | ### Governance Metrics Governance metrics help you catch stalled proposals or signer inactivity: | Metric | Description | Alert Threshold | | - | - | - | | **Pending proposals** | Number of governance proposals awaiting execution | > 0 for > 24h | | **Signer participation rate** | Percentage of signers active in last 7 days | \< 80% | | **Timelock queue depth** | Number of transactions in the timelock queue | > 3 | ## Log Collection ### dstack-cloud Logs Use the built-in log viewer: ```bash theme={"system"} # View recent logs dstack-cloud logs # Follow logs in real-time dstack-cloud logs --follow # View logs for a specific container dstack-cloud logs --container ``` ### KMS Logs KMS logs are available through `dstack-cloud logs` when the KMS is deployed as a dstack CVM. Key log patterns to monitor: | Log Pattern | Meaning | | - | - | | `attestation verification failed` | A workload's attestation was rejected | | `measurement not authorized` | The workload's measurement is not registered on-chain | | `key dispatched` | A key was successfully delivered to a workload | | `on-chain sync completed` | KMS synced its on-chain state | | `RA-TLS handshake failed` | TLS connection with attestation failed | ### Infrastructure Logs **GCP:** * Cloud Logging: `gcloud logging read "resource.type=gce_instance AND labels.instance_id="` * Serial port output for boot diagnostics **AWS Nitro:** * EC2 instance system logs * VSOCK proxy logs (if running as a systemd service) ## Dashboard Configuration ### Recommended Dashboard Panels 1. **KMS Health** * Request rate (requests/min) * Success rate (%) * Latency histogram (p50, p95, p99) * Active connections 2. **CVM Health** * Number of running CVMs * Per-CVM status (running/stopped/error) * Boot time trend 3. **Governance** * Pending proposals count * Recent governance transactions * Signer activity heatmap ### Integration with Datadog To integrate with Datadog, you'll need a Datadog agent on each host machine that collects custom metrics from dstack-cloud. The key metric namespaces are `dstack.cloud.cvm.*`, `dstack.cloud.kms.*`, and `dstack.cloud.governance.*`. 1. Set up a Datadog agent on each host machine 2. Configure custom metrics collection for KMS, CVM, and governance events 3. Create dashboards and monitors based on the metrics above ## Alert Rules ### Critical Alerts (Page immediately) | Alert | Condition | Response | | - | - | - | | **KMS down** | KMS unreachable for > 2 minutes | Check CVM/Enclave status. Restart if needed. | | **Attestation failure spike** | > 10 attestation failures in 5 minutes | May indicate a compromised or misconfigured workload. Investigate immediately. | | **Governance: suspicious transaction** | New proposal to revoke critical measurements | Review the proposal. Alert all signers. | ### Warning Alerts (Page during business hours) | Alert | Condition | Response | | - | - | - | | **High key dispatch latency** | p99 > 5s for > 10 minutes | Check KMS load. Scale if needed. | | **CVM restart loop** | CVM restarted > 3 times in 1 hour | Investigate container health. Check resource limits. | | **On-chain sync lag** | KMS on-chain state > 60s behind | Check RPC provider health. Switch to backup RPC. | | **VSOCK proxy failure** (Nitro) | VSOCK proxy process not running | Restart the proxy. Check host health. | ### Info Alerts (Log only) | Alert | Condition | | - | - | | **New governance proposal** | Any new proposal submitted to the Safe | | **CVM deployed** | New CVM deployment completed | | **Measurement registered** | New measurement added on-chain | ## Escalation Policies | Severity | Escalation | Response Time | | - | - | - | | **Critical** | Page on-call SRE + notify security team | 15 minutes | | **Warning** | Notify platform team via Slack/Teams | 2 hours | | **Info** | Log to incident channel | Next business day | Use [Incident.io](https://incident.io) or similar tools to manage incident lifecycle. ## On-chain Monitoring Monitor the blockchain for governance activity: * **Safe Transaction Service:** Subscribe to the Safe's transaction feed for real-time notifications * **The Graph / Dune Analytics:** Query governance transaction history for reporting * **Block explorer alerts:** Set up watch-only notifications for DstackKms and DstackApp contract events ## Next Steps * **[Runbook](/dstack-cloud/runbook)** — Step-by-step troubleshooting for common incidents * **[Upgrade Procedures](/dstack-cloud/upgrade)** — How to upgrade CVMs, KMS, and contracts # AWS Nitro Enclave Integration Source: https://docs.phala.com/dstack-cloud/nitro-enclave How AWS Nitro Enclaves work with dstack-cloud, including EIF, VSOCK proxy, and key architectural differences from GCP. ## What Are Nitro Enclaves AWS Nitro Enclaves provide process-level isolation on EC2: the host OS cannot read or write enclave memory, even with root access. dstack-cloud packages your application into an Enclave Image File (EIF) and uses `dstack-util` for attestation and key retrieval — replacing the Guest Agent used on GCP. Key properties: * **Memory-isolated:** The host OS cannot read or write Enclave memory * **No persistent storage:** Every Enclave launch starts from a clean state * **No external network access:** Enclaves communicate through VSOCK (a socket interface to the host machine) * **Cryptographic attestation:** AWS Nitro Secure Module (NSM) generates an Attestation Document proving the Enclave's identity ## How dstack Uses Nitro Enclaves The Nitro integration differs significantly from GCP. On GCP, dstack-cloud deploys a full virtual machine (dstack CVM) with a Guest Agent. On AWS Nitro, the workload runs inside an AWS Enclave OS image — there is no Guest Agent and no dstack OS. ![Nitro Enclave Architecture](https://mintcdn.com/phalanetwork-1606097b/kLcECSdhM8pjBAIk/images/dstack-cloud/nitro-enclave-architecture-v2.png?fit=max\&auto=format\&n=kLcECSdhM8pjBAIk\&q=85\&s=41df8f273c63ac0fca726b51e5b75c1f) On AWS Nitro, the flow is: 1. You define your application in a `Dockerfile` 2. AWS Nitro CLI (`nitro-cli build-enclave`) converts the Dockerfile into an **Enclave Image File (EIF)** — the Enclave OS image 3. dstack packages **`dstack-util`** into the EIF. This tool handles attestation and key retrieval from KMS 4. The Enclave runs your application code inside the AWS-provided Enclave OS — not dstack OS 5. Inside the Enclave, `dstack-util` communicates with KMS through the VSOCK proxy on the host to obtain keys 6. Your application decides how to use the key (e.g., encrypting disk in-memory, decrypting model weights, etc.) ### Key Differences from GCP | Aspect | GCP (dstack CVM) | AWS Nitro (Enclave) | | - | - | - | | **OS inside TEE** | dstack OS (custom Linux with Guest Agent) | Enclave OS (provided by AWS) | | **Guest Agent** | Yes — handles attestation, key management, storage encryption | **No** — replaced by `dstack-util` | | **Disk encryption** | Automatic (Guest Agent handles it) | **User-managed** — `dstack-util` provides the key, your application decides what to encrypt | | **Image build** | dstack-cloud builds a CVM disk image | AWS Nitro CLI builds EIF from a Dockerfile | | **Application format** | `docker-compose.yaml` | `Dockerfile` (single container) | ## Enclave Image (EIF) Build Process A Nitro Enclave is launched from an **Enclave Image File (EIF)**. The build process has two stages: ### Stage 1: Build Docker Image First, build a Docker image from your Dockerfile: ```bash theme={"system"} docker build -t my-app -f Dockerfile . ``` Your Dockerfile should include your application and `dstack-util`. ### Stage 2: Build EIF from Docker Image Then, convert the Docker image into an EIF using the Nitro CLI: ```bash theme={"system"} nitro-cli build-enclave --docker-uri my-app:latest \ --output-file my-app.eif ``` This command: * Uses the AWS-provided Enclave OS as the base * Packages your Docker image content into an EIF * Generates 3 PCR values (PCR0, PCR1, PCR2) that uniquely identify the image ### Stage 3: Register OS\_IMAGE\_HASH The 3 PCR values are combined into a single `OS_IMAGE_HASH` for on-chain authorization: ```bash theme={"system"} # Example: combine PCRs into OS_IMAGE_HASH OS_IMAGE_HASH=$(sha256sum <<< "${PCR0}${PCR1}${PCR2}" | cut -d' ' -f1) ``` The `OS_IMAGE_HASH` must be registered via [governance](/dstack-cloud/governance) before KMS will deliver keys to this Enclave. > **Note:** Any change to the Dockerfile, application code, or `dstack-util` version produces different PCR values and a different `OS_IMAGE_HASH`. ### Automated Deployment In practice, these steps are automated by deployment scripts. See [Run a Workload on AWS Nitro](/dstack-cloud/run-on-nitro) for the full workflow using the `deploy_host.sh` and `get_keys.sh` scripts. ## Key Retrieval with dstack-util On Nitro, `dstack-util` replaces the Guest Agent for key management. It is a lightweight tool that: * Obtains the Enclave's attestation document from NSM (Nitro Secure Module) * Sends the attestation to dstack-kms through the VSOCK proxy * Receives the requested key if the attestation is valid (and the measurement is authorized on-chain, when using On-chain KMS mode) * Makes the key available to your application (e.g., via stdout, file, or shared memory) > **Note:** Unlike GCP where the Guest Agent automatically handles disk encryption, on Nitro you are responsible for deciding how to use the key. Common patterns include encrypting model weights in memory, decrypting configuration secrets, or encrypting a RAM-disk. ## Networking and Communication Nitro Enclaves have no direct network access. All communication goes through VSOCK: ![VSOCK Communication](https://mintcdn.com/phalanetwork-1606097b/kLcECSdhM8pjBAIk/images/dstack-cloud/vsock-communication-v2.png?fit=max\&auto=format\&n=kLcECSdhM8pjBAIk\&q=85\&s=2163f12c0d41da829011cfaf8cd89bcc) * The Enclave communicates with the host via VSOCK (AF\_VSOCK socket family) * A VSOCK proxy on the host forwards TCP connections to the outside world (including KMS) * The proxy must be started before the Enclave launches * If the proxy crashes, the Enclave loses external connectivity ### VSOCK Proxy Setup The VSOCK proxy translates between VSOCK (Enclave↔Host) and TCP (Host↔Network): ```bash theme={"system"} # Example: forward Enclave VSOCK port 8000 to host TCP port 8000 socat VSOCK-LISTEN:8000,reuseaddr,fork TCP:localhost:8000 ``` dstack-cloud provides helper scripts and configuration for setting up the VSOCK proxy as part of the deployment process. ## Resource Constraints Nitro Enclaves have static resource allocation: | Resource | Behavior | | - | - | | **CPU** | Allocated at launch (in vCPUs), cannot be changed during runtime | | **Memory** | Allocated at launch (in MB), cannot be changed during runtime | | **Maximum** | Depends on the host EC2 instance type | ### Supported EC2 Instance Types Nitro Enclaves are supported on instances built on the AWS Nitro System. Common choices: | Instance Type | vCPUs | Memory | Notes | | - | - | - | - | | `m5.xlarge` | 4 | 16 GB | General purpose | | `m5.2xlarge` | 8 | 32 GB | General purpose | | `c5.2xlarge` | 8 | 16 GB | Compute optimized | | `r5.2xlarge` | 8 | 64 GB | Memory optimized | Note: The EC2 instance must have Nitro Enclave support enabled in its Nitro configuration, and you must allocate enough CPU/memory to accommodate both the host OS and the Enclave. ## When to Use Nitro vs. GCP Choose **AWS Nitro Enclaves** when: * Your existing infrastructure is on AWS * You need the strongest possible isolation (process-level, no host access) * Your workload fits within static resource limits * You don't need persistent disk storage or you want to do it with the key by yourself * You want full control over how keys are used (encryption strategy, key usage pattern) Choose **GCP Confidential VMs** when: * Your existing infrastructure is on GCP * You need automatic disk encryption managed by dstack-cloud * You need direct network access without a VSOCK proxy * You need persistent disk storage * You need elastic resource allocation * You prefer a more managed experience with the Guest Agent handling attestation and key lifecycle ## Next Steps * **[Quick Start: Deploy on AWS Nitro](/dstack-cloud/get-started)** — Hands-on tutorial * **[Run a Workload on AWS Nitro](/dstack-cloud/run-on-nitro)** — Detailed deployment guide * **[Attestation Integration](/dstack-cloud/attestation-integration)** — How attestation works on Nitro # dstack-cloud Overview Source: https://docs.phala.com/dstack-cloud/overview dstack-cloud is an extension of the dstack framework that enables deploying confidential Docker applications on GCP Confidential VMs and AWS Nitro Enclaves. # dstack-cloud Overview dstack-cloud lets you run Docker applications inside hardware-encrypted Trusted Execution Environments (TEEs) on **GCP Confidential VMs** and **AWS Nitro Enclaves** — without owning specialized bare-metal servers. Built on the open-source [dstack framework](https://github.com/Dstack-TEE/dstack), it brings TEE security to mainstream cloud platforms. Your code and data stay encrypted in memory, even from the cloud provider. ## What is dstack dstack is an open-source confidential computing framework originally designed to run on TDX BareMetal servers. It provides: * Hardware-level memory encryption and isolation via TEE (Trusted Execution Environment) * A key management system (KMS) that delivers secrets exclusively to verified workloads * Remote attestation to prove that code is running in genuine TEE hardware * SDK libraries in Python, TypeScript, Rust, and Go for application integration (the **dstack-sdk**) ## What is dstack-cloud dstack-cloud extends dstack to run on major cloud platforms. Instead of requiring bare-metal TDX hardware, it enables deployment on: * **GCP Confidential VMs** (Intel TDX) * **AWS Nitro Enclaves** (NSM) This means you can use the full dstack security model — hardware isolation, attested key delivery, encrypted storage — without owning specialized hardware. ## How It Works ![How It Works](https://mintcdn.com/phalanetwork-1606097b/kLcECSdhM8pjBAIk/images/dstack-cloud/architecture-overview-v2.png?fit=max\&auto=format\&n=kLcECSdhM8pjBAIk\&q=85\&s=20b7697eee6e63e3d1e4882b718fea9c) You define your application, and `dstack-cloud deploy` handles the rest: building a TEE environment, managing attestation, and delivering keys. ### On GCP: 1. `dstack-cloud deploy` creates a **Confidential Virtual Machine** running dstack OS with Intel TDX enabled. 2. A **Guest Agent** inside the CVM handles attestation, key retrieval from KMS, and automatic disk encryption. 3. Your application communicates with the Guest Agent via a Unix socket (`/var/run/dstack.sock`). ### On AWS Nitro: 1. AWS Nitro CLI converts your Dockerfile into an **Enclave Image File (EIF)** using Enclave OS (AWS-provided). 2. The EIF runs as a Nitro Enclave — there is no dstack OS and no Guest Agent. 3. **`dstack-util`** inside the Enclave handles attestation and key retrieval from KMS. Your application decides how to use the key. > The two platforms have different architectures. See [Nitro Enclave Integration](/dstack-cloud/nitro-enclave) for a detailed comparison. ## Key Components | Component | Role | | - | - | | **dstack-cloud CLI** | Build and deployment tool for both GCP and Nitro | | **dstack-kms** | Key Management Service running in its own TEE; verifies workloads and dispatches keys | | **Gateway** | Edge TLS termination, automatic ACME certificate provisioning, RA-TLS (Remote Attestation TLS) support | | **Guest Agent** (GCP only) | Process inside each CVM that handles attestation, key management, and automatic disk encryption | | **dstack-util** (Nitro only) | Lightweight tool packaged into the EIF; handles attestation and key retrieval from KMS | | **VSOCK Proxy** (Nitro only) | Runs on the EC2 host; forwards network traffic between the Enclave and external services | ## Typical Use Cases ### AI Inference with Model Protection Deploy AI models with model weights fully encrypted in memory. The cloud provider cannot access or copy your proprietary models. ### Sensitive Data Processing Process healthcare, financial, or personal data in a hardware-isolated environment. Memory encryption ensures that even system administrators cannot read your data. ### DeFi and Web3 Applications Run smart contract backend services or trading bots with private keys that never leave the TEE. The on-chain governance model provides verifiable, auditable key management. ## Supported Environments | Platform | TEE Technology | Attestation | Status | | - | - | - | - | | GCP Confidential VMs | Intel TDX + TPM | TDX Quote | Available | | AWS Nitro Enclaves | Nitro Secure Module | NSM Attestation Document | Available | ## What You Need * An AWS or GCP account with appropriate permissions * `dstack-cloud` CLI installed * A `docker-compose.yaml` defining your application * (Optional) [dstack-sdk](https://github.com/Dstack-TEE/dstack/tree/master/sdk) integration for key retrieval from within your containers ## Next Steps * **[Quick Start Tutorial](/dstack-cloud/get-started)** — Deploy your first dstack CVM in 30 minutes * **[Nitro Enclave](/dstack-cloud/nitro-enclave)** — How AWS Nitro Enclaves work in dstack-cloud * **[KMS and Key Delivery](/dstack-cloud/kms-and-key-delivery)** — Understand how keys are managed and delivered * **[Security Model](/dstack-cloud/security-model)** — Trust boundaries and security guarantees * **[Attestation Integration](/dstack-cloud/attestation-integration)** — How remote attestation works across platforms # Register Workload Measurements On-chain Source: https://docs.phala.com/dstack-cloud/register-enclave-measurement Register workload measurements (OS_IMAGE_HASH / RTMR) on-chain for KMS authorization. # Register Workload Measurements On-chain This guide explains how to register workload measurements (RTMR / OS\_IMAGE\_HASH) on-chain so that KMS will authorize your workloads to receive keys. ## Background When a TEE workload starts — whether a dstack CVM (GCP) or a Nitro Enclave (AWS) — it generates a hardware attestation that includes measurements (cryptographic hashes of the code and configuration). KMS checks these measurements against an on-chain allowlist before dispatching keys. If you update your application code, Docker images, or the base image version, the measurements change. You must register the new measurements before KMS will authorize the updated workload. ### Two Layers of On-chain Registration The dstack ecosystem has two distinct registration flows: | Registration Type | What Gets Registered | Purpose | Where to Find | | - | - | - | - | | **KMS Registration** | KMS's `mrAggregated` (GCP) or public key | Proves KMS runs in a genuine TEE | [Run dstack-kms on GCP](/dstack-cloud/run-kms-on-gcp) Step 8 | | **Workload Registration** (this guide) | Workload's `compose-hash` or `OS_IMAGE_HASH` | Authorizes workload to receive keys from KMS | This document | **This guide covers workload registration** — the process of registering your application's measurement so that KMS will dispatch keys to it. This applies to: * **GCP workloads** — dstack CVMs running applications that need keys from KMS * **Nitro workloads** — Enclaves that need keys from KMS (KMS itself runs on GCP only) Both types of workloads must register their measurements on-chain before KMS will authorize key delivery. | Platform | Measurement Field | Where It Comes From | | - | - | - | | GCP (TDX) | `compose-hash` (in RTMR3) | `dstack-cloud deploy` output | | AWS Nitro | `OS_IMAGE_HASH` | `nitro-cli describe-enclave` output | ## Prerequisites * A deployed dstack-kms instance with on-chain governance configured * Governance contracts (DstackKms, DstackApp) deployed * Multisig Safe with signer access * The new measurement value (from your build/deploy output) ## Step 1: Build and Deploy Your Workload First, build and deploy your application to get the measurements: ```bash theme={"system"} # On GCP dstack-cloud deploy dstack-cloud status # Note the compose-hash value in RTMR3 # On Nitro ./scripts/build-eif.sh # Note the OS_IMAGE_HASH value from output ``` ## Step 2: Extract the Measurement **GCP (TDX):** The measurement is the `compose-hash` value in RTMR3, displayed in the `dstack-cloud status` output. This value represents the hash of your docker-compose.yaml configuration. **AWS Nitro:** The measurement is the `OS_IMAGE_HASH`, calculated as `sha256(PCR0 || PCR1 || PCR2)`. Run: ```bash theme={"system"} ./scripts/build-eif.sh ``` The script outputs: ```text theme={"system"} PCR0: PCR1: PCR2: OS_IMAGE_HASH: ``` **PCR values are derived from:** * **PCR0** — Complete EIF content hash (enclave image) * **PCR1** — Linux kernel and boot ramdisk * **PCR2** — Application layer (Docker image filesystem) > **Note:** The `OS_IMAGE_HASH` is the value you register on-chain. Any change to the Dockerfile, application code, or configuration produces a different hash. **Alternative: Preview measurements without full build:** ```bash theme={"system"} dstack-util get-keys --show-mrs \ --kms-url "https://your-kms:12001" \ --app-id "0xYOUR_APP_ID" ``` > **Important:** When using `--show-mrs` to preview, you must use the exact same `KMS_URL`, `APP_ID`, and `root_ca.pem` as the production build. Any difference will produce different PCR values. ## Step 3: Prepare the Governance Transaction You need to call `DstackKms.addOsImageHash()` with the new measurement value. ### 3.1 Draft the Transaction Using the Safe web interface ([https://app.safe.global](https://app.safe.global)): 1. Connect your signer wallet 2. Go to your Safe 3. Click "New Transaction" → "Contract interaction" 4. Select the `DstackKms` contract 5. Select the `addOsImageHash` function 6. Enter the measurement value (hex string) 7. Review and submit ### 3.2 Alternative: Using CLI ```bash theme={"system"} # Using cast (from Foundry) cast send \ "addOsImageHash(bytes32)" \ 0xYOUR_MEASUREMENT_HASH \ --rpc-url $RPC_URL \ --private-key $SIGNER_KEY ``` > **Note:** In production, do not use a single private key. Submit the transaction through the multisig Safe instead. ## Step 4: Collect Signatures The transaction enters the multisig queue. Other signers must approve it. 1. Each signer connects to the Safe web interface 2. Opens the pending transaction 3. Reviews the measurement value 4. Confirms (signs) the transaction The transaction is executed once the required threshold of signatures is collected. ## Step 5: Wait for Timelock After multisig approval, the transaction enters the Timelock queue. * **Production:** Wait 24-72 hours (depending on your configuration) * **Testnet:** Wait 1-4 hours During this period, any signer or observer can review and, if necessary, raise concerns. ## Step 6: Execute After the Timelock expires, the transaction can be executed: 1. Open the Safe web interface 2. Find the transaction in the queue 3. Click "Execute" The measurement is now registered on-chain. KMS will authorize workloads with this measurement. ## Step 7: Verify Verify that the measurement is registered: ```bash theme={"system"} # Using cast cast call \ "isAuthorized(bytes32)(bool)" \ 0xYOUR_MEASUREMENT_HASH \ --rpc-url $RPC_URL ``` Expected output: `true` ## Workflow Summary ![Measurement Registration Flow](https://mintcdn.com/phalanetwork-1606097b/kLcECSdhM8pjBAIk/images/dstack-cloud/measurement-registration-flow.png?fit=max\&auto=format\&n=kLcECSdhM8pjBAIk\&q=85\&s=a2f0a15efc35d656fcf06b56d9b3628f) ## Registering Multiple Measurements If you are deploying multiple workloads (e.g., different application versions for canary testing), you can register multiple measurements in a single governance transaction: 1. Call `addOsImageHash` for each measurement value 2. Bundle them into a batch transaction in the Safe 3. Submit for approval as usual ## Revoking a Measurement If a measurement is found to be compromised or no longer needed: ```bash theme={"system"} cast send \ "removeOsImageHash(bytes32)" \ 0xCOMPROMISED_MEASUREMENT_HASH \ --rpc-url $RPC_URL ``` Follow the same governance flow (multisig → timelock → execute). ## Common Issues | Issue | Solution | | - | - | | KMS refuses to dispatch keys | Verify the measurement is registered: `cast call ... isAuthorized(...)`. Check that the measurement matches exactly (case-sensitive hex). | | Governance transaction stuck | Verify the timelock has expired. Check that the Safe has sufficient gas. | | Wrong measurement registered | You must revoke the wrong measurement and register the correct one through separate governance transactions. | | Measurement changes on every deploy | The `compose-hash` / `OS_IMAGE_HASH` is derived from your Docker images and configuration. Use pinned image tags (SHA256 digests) for reproducible builds. | ## Next Steps * **[Manage Governance](/dstack-cloud/manage-governance)** — Other governance operations * **[Concept: Attestation Integration](/dstack-cloud/attestation-integration)** — How measurements are generated * **[Concept: KMS and Key Delivery](/dstack-cloud/kms-and-key-delivery)** — How KMS uses measurements # Release Notes Source: https://docs.phala.com/dstack-cloud/release-notes Release notes, version history, compatibility notes, and known issues. # Release Notes ## v0.6.0 (Current) ### Features * Initial release with support for GCP Confidential VMs and AWS Nitro Enclaves * dstack-cloud CLI for launching CVMs from Docker Compose configurations * KMS with two modes: Local Key Provider and standalone KMS * On-chain governance (DstackKms, DstackApp, Multisig + Timelock) * RA-TLS for secure KMS ↔ workload communication * VSOCK proxy support for Nitro Enclave networking * KMS bootstrap (Onboard → Finish) flow * Attestation verification (TDX Quote on GCP, NSM Document on Nitro) ### Compatibility Notes * Requires Intel TDX-capable GCP zones or Nitro Enclave-capable EC2 instances *** ## Changelog All notable changes will be documented here. Format follows [Keep a Changelog](https://keepachangelog.com/). # Run a dstack-kms CVM on GCP Source: https://docs.phala.com/dstack-cloud/run-kms-on-gcp Deploy a dstack-kms (Key Management Service) instance on GCP as a Confidential VM with on-chain governance. # Run a dstack-kms CVM on GCP Run your own dstack-kms instance on GCP so you have full control over key policy. This page covers the production deployment workflow: bootstrap the KMS, register its attestation on-chain, and verify it's serving keys correctly. > **Reference:** This guide is based on the [official deployment guide](https://github.com/Phala-Network/dstack-cloud-deployment-guide/blob/main/guide_EN.md). > **Platform Requirement:** `dstack-cloud deploy` must be run on **Linux**. macOS is not supported because the FAT32 shared disk image created by macOS `dosfstools` fails GCP image validation. *** ## Prerequisites * A GCP project with Confidential VM (TDX) quota * `gcloud` CLI installed and authenticated (`gcloud auth login`) * `gsutil` available in PATH (required by `dstack-cloud deploy` for GCS upload) * `docker` / `docker compose` * `node` + `npm` (for smart contract deployment) * `jq` * `mtools` (provides `mcopy`) * `dosfstools` (provides `mkfs.fat`) * **`dstack-cloud` CLI** installed: ```bash theme={"system"} curl -fsSL -o ~/.local/bin/dstack-cloud \ https://raw.githubusercontent.com/Phala-Network/meta-dstack-cloud/main/scripts/bin/dstack-cloud chmod +x ~/.local/bin/dstack-cloud ``` * **For on-chain governance mode:** * A blockchain RPC endpoint (e.g., `https://sepolia.base.org`) * A wallet with sufficient balance * Deployed smart contracts (DstackKms, DstackApp) — see [Deploy On-chain KMS Smart Contracts](/dstack-cloud/deploy-onchain-kms) * You’ll need `KMS_CONTRACT_ADDR` and `APP_CONTRACT_ADDR` before KMS bootstrap/finish > **Note:** This guide uses pre-built KMS Docker images. If you need to build KMS from source or customize configuration, see the [official KMS build guide](https://github.com/Phala-Network/dstack-cloud/blob/master/docs/tutorials/kms-build-configuration.md). *** ## Step 1: Configure dstack-cloud Follow the same steps as [Run a Workload on GCP](/dstack-cloud/run-on-gcp#step-1-configure-dstack-cloud) to set up your global config and GCS bucket. *** ## Step 2: Pull the OS Images Follow the same steps as [Run a Workload on GCP](/dstack-cloud/run-on-gcp#step-2-pull-the-os-image) to download the `dstack-cloud-0.6.0` images. > If `disk.raw` is missing, deployment may create a VM that cannot boot (UEFI loop: `Failed to load image`). *** ## Step 3: Create a KMS Project ```bash theme={"system"} mkdir -p workshop-run dstack-cloud new workshop-run/kms-prod \ --os-image dstack-cloud-0.6.0 \ --key-provider tpm \ --instance-name dstack-kms cd workshop-run/kms-prod ``` Generated files include: * `app.json` * `docker-compose.yaml` * `prelaunch.sh` *** ## Step 4: Build or Select KMS Docker Image Use pre-built image or build your own: ```bash theme={"system"} # Option 1: Pre-built # KMS_IMAGE=cr.kvin.wang/dstack-kms:latest # Option 2: Build from source (from deployment-guide workshop repo) cd workshop/kms/builder ./build-image.sh dstack-kms:latest docker push dstack-kms:latest ``` *** ## Step 5: Configure KMS Runtime Replace generated compose/prelaunch with KMS config. > The compose templates below come from:\ > `Phala-Network/dstack-cloud-deployment-guide`\ > Clone that repo first if you only cloned this docs repo. ### Option A: Direct RPC ```bash theme={"system"} cp /path/to/dstack-cloud-deployment-guide/workshop/kms/docker-compose.direct.yaml docker-compose.yaml ``` Create `prelaunch.sh`: ```bash theme={"system"} cat > prelaunch.sh <<'EOF' #!/bin/sh cat > .env <<'ENVEOF' KMS_HTTPS_PORT=12001 AUTH_HTTP_PORT=18000 KMS_IMAGE=cr.kvin.wang/dstack-kms:latest ETH_RPC_URL=https://sepolia.base.org KMS_CONTRACT_ADDR= APP_CONTRACT_ADDR= DSTACK_REPO=https://github.com/Phala-Network/dstack-cloud.git DSTACK_REF=14963a2ccb0ec7bef8a496c1ac5ac40f5593145d ENVEOF EOF chmod +x prelaunch.sh ``` ### Option B: Light Client (Helios) ```bash theme={"system"} cp /path/to/dstack-cloud-deployment-guide/workshop/kms/docker-compose.light.yaml docker-compose.yaml ``` `prelaunch.sh` can stay the same unless your template requires different vars. *** ## Step 6: Deploy KMS CVM ```bash theme={"system"} dstack-cloud deploy --delete ``` If bucket does not exist, create explicitly first: ```bash theme={"system"} gcloud storage buckets create gs:// \ --project \ --location us-central1 ``` *** ## Step 7: Open Firewall ```bash theme={"system"} dstack-cloud fw allow 12001 dstack-cloud fw allow 18000 ``` For light-client mode: ```bash theme={"system"} dstack-cloud fw allow 18545 ``` Port notes: * `12001/tcp`: KMS API (**required**) * `18000/tcp`: auth-api debug endpoint (**optional**) * `18545/tcp`: helios RPC (light mode only) *** ## Step 8: Bootstrap (First-time) ### 8.1 Check KMS endpoint ```bash theme={"system"} dstack-cloud status ``` ### 8.2 Get attestation info ```bash theme={"system"} KMS_URL="http://:12001" curl -s "$KMS_URL/prpc/Onboard.GetAttestationInfo?json" | jq . ``` Capture: * `device_id` * `mr_aggregated` * `os_image_hash` ### 8.3 Register measurements on-chain (required for on-chain mode) ```bash theme={"system"} npx hardhat kms:add-image 0x --network custom npx hardhat kms:add 0x --network custom npx hardhat kms:add-device 0x --network custom ``` > `device_id` must come from `Onboard.GetAttestationInfo` (not dummy serial-console value). ### 8.4 Run bootstrap ```bash theme={"system"} curl -s "$KMS_URL/prpc/Onboard.Bootstrap?json" \ -d '{"domain":""}' | tee bootstrap-info.json | jq . ``` ### 8.5 Finish ```bash theme={"system"} curl "$KMS_URL/finish" sleep 5 ``` *** ## Step 9: Verify ```bash theme={"system"} # Onboard mode check (before finish) curl -s "http://:12001/prpc/Onboard.GetAttestationInfo?json" | jq . # Normal mode check (after finish) curl -sk "https://:12001/prpc/GetMeta?json" -d '{}' | jq . ``` *** ## Common Issues | Issue | Solution | | - | - | | macOS image/shared-disk errors | Use Linux host for deploy | | `Boot image ... not found` | Ensure image search path is correct and `disk.raw` exists under `/dstack-cloud-0.6.0/` | | VM `RUNNING` but 12001/18000 unreachable + serial shows `UEFI: Failed to load image` | Wrong boot image format/content. Ensure `disk.raw` comes from `dstack-cloud-0.6.0-uki.tar.gz` (do **not** rename `rootfs.img.parted.verity` as `disk.raw`) | | `gsutil` missing | Install Google Cloud SDK/gsutil and ensure in PATH | | `mcopy` missing | Install `mtools` | | `mkfs.fat` missing | Install `dosfstools` | | `missing field 'status'` from KMS flow | Usually indicates auth-eth / on-chain config mismatch (RPC/contract addresses/registrations). Verify `ETH_RPC_URL`, `KMS_CONTRACT_ADDR`, `APP_CONTRACT_ADDR`, and on-chain image/MR/device registration | | KMS port responds but APIs return 404 | Shared disk config stale/wrong; `dstack-cloud deploy --delete` | *** ## Cleanup ```bash theme={"system"} dstack-cloud stop dstack-cloud remove ``` Or manually: ```bash theme={"system"} gcloud compute instances delete dstack-kms --zone=us-central1-a gcloud compute images delete dstack-kms-boot gcloud compute images delete dstack-kms-shared ``` *** ## Next Steps * [Register Workload Measurements](/dstack-cloud/register-enclave-measurement) * [KMS and Key Delivery](/dstack-cloud/kms-and-key-delivery) * [Attestation Integration](/dstack-cloud/attestation-integration) * [Deploy On-chain KMS Smart Contracts](/dstack-cloud/deploy-onchain-kms) # Run a Workload on GCP Source: https://docs.phala.com/dstack-cloud/run-on-gcp Step-by-step guide to deploy a Docker application as a dstack CVM on GCP with Intel TDX. # Run a Workload on GCP Deploy a Docker application as a dstack CVM on GCP with Intel TDX. This page covers the full workflow — from configuration to verification — including how to choose between managed and self-hosted KMS endpoints. *** ## Prerequisites * A GCP project with Confidential VM quota enabled * Intel TDX Confidential VMs are available in select zones (for example `us-central1-a`) * `gcloud` CLI installed and authenticated ```bash theme={"system"} gcloud auth login gcloud config set project YOUR_PROJECT_ID ``` * Linux host for deployment (recommended) * Docker installed * `gsutil` available in PATH * `mtools` (`mcopy`) and `dosfstools` (`mkfs.fat`) installed * `dstack-cloud` CLI installed ```bash theme={"system"} curl -fsSL -o ~/.local/bin/dstack-cloud \ https://raw.githubusercontent.com/Phala-Network/meta-dstack-cloud/main/scripts/bin/dstack-cloud chmod +x ~/.local/bin/dstack-cloud ``` > Why Linux + mtools + dosfstools? `dstack-cloud deploy` builds a shared FAT image and needs these tools in local environment. *** ## Step 1: Configure `dstack-cloud` Edit global config: ```bash theme={"system"} dstack-cloud config-edit ``` `dstack-cloud` uses **JSON** config (`~/.config/dstack-cloud/config.json`). Example: ```json theme={"system"} { "services": { "kms_urls": ["https://kms.tdxlab.dstack.org:12001"], "gateway_urls": ["https://gateway.tdxlab.dstack.org:12002"], "pccs_url": "" }, "image_search_paths": ["/path/to/images"], "gcp": { "project": "YOUR_PROJECT_ID", "zone": "us-central1-a", "bucket": "gs://YOUR_BUCKET_NAME" } } ``` Create bucket if needed: ```bash theme={"system"} gcloud storage buckets create gs://YOUR_BUCKET_NAME --project YOUR_PROJECT_ID --location us-central1 ``` ### KMS Options | Option | Description | When to Use | | - | - | - | | **Phala Official KMS** | Use managed KMS endpoints in `services.kms_urls` | Quick start, testing | | **Self-hosted KMS** | Use your own KMS endpoint in `services.kms_urls` | Production, compliance, full control | For Self-hosted KMS, point `services.kms_urls` to your deployed KMS URL (see [Run a dstack-kms CVM on GCP](/dstack-cloud/run-kms-on-gcp) for how to set one up). If you run with key provider `tpm`/`none` (no external KMS), remove `.env` in project and remove `env_file` from `app.json`. *** ## Step 2: Pull the OS Image For `dstack-cloud-0.6.0`, download both archives: ```bash theme={"system"} dstack-cloud pull https://github.com/Phala-Network/meta-dstack-cloud/releases/download/v0.6.0-test/dstack-cloud-0.6.0.tar.gz dstack-cloud pull https://github.com/Phala-Network/meta-dstack-cloud/releases/download/v0.6.0-test/dstack-cloud-0.6.0-uki.tar.gz ``` Verify boot image file exists: ```bash theme={"system"} ls -lh /path/to/images/dstack-cloud-0.6.0/disk.raw ``` > If `disk.raw` is missing, VM may boot-loop with UEFI `Failed to load image`. *** ## Step 3: Create a Project ```bash theme={"system"} dstack-cloud new my-gcp-app --os-image dstack-cloud-0.6.0 --instance-name dstack-my-app cd my-gcp-app ``` *** ## Step 4: Configure Project (`app.json`) Update key fields in `app.json`: * `gcp_config.project` * `gcp_config.zone` * `gcp_config.bucket` * `gcp_config.instance_name` Choose key provider mode: * **External KMS mode (recommended):** `"key_provider": "kms"` * **No external KMS mode:** `"key_provider": "tpm"` (or `none`) Gateway options: * If you use dstack gateway URL routing, keep `gateway_enabled: true` * If you access service directly via VM public IP + opened port, set `gateway_enabled: false` *** ## Step 5: Define Your Application Edit `docker-compose.yaml`: ```yaml theme={"system"} services: web: image: nginx:latest ports: - "8080:80" ``` *** ## Step 6: (Optional) Add Environment Variables If your app needs secrets/config, create `.env`: ```env theme={"system"} API_KEY=your-api-key DATABASE_URL=postgres://user:pass@host:5432/db ``` In KMS mode, env values are encrypted client-side and only decrypted inside CVM after attestation. *** ## Step 7: Deploy ```bash theme={"system"} dstack-cloud deploy --delete ``` `dstack-cloud` will: 1. Prepare shared config files 2. Upload image artifacts to GCS 3. Create a GCP TDX Confidential VM 4. Start VM and run compose workload First deployment usually takes several minutes. *** ## Step 8: Open Firewall Open app port(s): ```bash theme={"system"} dstack-cloud fw allow 8080 ``` List firewall rules: ```bash theme={"system"} dstack-cloud fw list ``` *** ## Step 9: Verify Check status: ```bash theme={"system"} dstack-cloud status ``` View logs: ```bash theme={"system"} dstack-cloud logs --follow ``` Access app: * Direct VM mode (`gateway_enabled=false`): ```bash theme={"system"} curl http://:8080 ``` * Gateway mode (`gateway_enabled=true`): use URL printed in `dstack-cloud status`. *** ## Managing Your Deployment ```bash theme={"system"} dstack-cloud logs dstack-cloud stop dstack-cloud start dstack-cloud remove ``` *** ## Common Issues | Issue | Solution | | - | - | | `Boot image 'dstack-cloud-0.6.0' not found locally` | Ensure `disk.raw` exists under `/dstack-cloud-0.6.0/` | | VM RUNNING but serial log shows UEFI load failures | Wrong boot image source; use official `-uki.tar.gz` image containing `disk.raw` | | `gsutil` not found | Install Google Cloud SDK / ensure PATH | | `mcopy` not found | Install `mtools` | | `mkfs.fat` not found | Install `dosfstools` | | `.env found but KMS is not enabled` | Remove `.env` and remove `env_file` from `app.json`, or set key provider back to `kms` | | App not reachable immediately | Wait for compose startup to complete; check `dstack-cloud logs` | *** ## Next Steps * [Run a dstack-kms CVM on GCP](/dstack-cloud/run-kms-on-gcp) * [Attestation Integration](/dstack-cloud/attestation-integration) * [Run a Workload on AWS Nitro](/dstack-cloud/run-on-nitro) # Run a Workload on AWS Nitro Source: https://docs.phala.com/dstack-cloud/run-on-nitro Step-by-step guide to deploy a Docker application as a Nitro Enclave on AWS. # Run a Workload on AWS Nitro Run a Docker application inside an AWS Nitro Enclave — one of the strongest isolation guarantees available in the public cloud. The host OS cannot read your enclave's memory, even with root access. > **Important:** On AWS Nitro, your workload runs inside an **AWS Enclave OS image** — not a dstack CVM. The Guest Agent is not available. `dstack-util` is packaged into the Enclave for attestation and key retrieval. You control how keys are used (for example disk/data decryption in your app). ## Prerequisites * AWS account permissions for EC2 + Nitro Enclaves * AWS CLI configured (`aws configure`) * Docker installed * Git + `gh` CLI (if using GitHub template/release flow) * The [dstack-nitro-enclave-app-template](https://github.com/Phala-Network/dstack-nitro-enclave-app-template) repository ## Overview Deployment flow: 1. Create app from template 2. Replace KMS root CA certificate (**required before build**) 3. Build EIF and get measurements 4. Register OS\_IMAGE\_HASH on-chain 5. Deploy/run on Nitro host and retrieve keys ### Key Delivery via KMS On Nitro, `dstack-util` inside Enclave reaches KMS through host-side VSOCK proxy. KMS verifies Nitro attestation and policy before returning keys. **KMS Options** | Option | Description | When to Use | | - | - | - | | **Phala Official KMS** | Managed KMS by Phala | Quick start/testing | | **Self-hosted KMS** | Your own dstack-kms | Production/compliance/full control | Self-hosted KMS can run on: * GCP TDX CVM — see [Run a dstack-kms CVM on GCP](/dstack-cloud/run-kms-on-gcp) * Intel TDX bare metal *** ## Step 1: Create Your App from Template ```bash theme={"system"} gh repo create my-enclave-app \ --template Phala-Network/dstack-nitro-enclave-app-template \ --private git clone https://github.com/YOUR_USER/my-enclave-app.git cd my-enclave-app ``` *** ## Step 2: Replace KMS Root CA Certificate > ⚠️ Required. Template `app/root_ca.pem` is placeholder only. `root_ca.pem` is baked into image and affects measured hash. ```bash theme={"system"} # From your running KMS endpoint curl -sk https://:12001/prpc/GetTempCaCert?json \ | jq -r .temp_ca_cert > app/root_ca.pem ``` > Use a **domain name** in KMS URL when possible. Avoid raw IP in production. If KMS CA rotates, rebuild EIF and re-register new image hash. *** ## Step 3: Configure and Build EIF ### 3.1 Template Variables `app/entrypoint.sh` uses placeholders: ```bash theme={"system"} KMS_URL="__KMS_URL__" APP_ID="__APP_ID__" ``` Do not hardcode manually; pass via build inputs. ### 3.2 Local Build ```bash theme={"system"} DSTACK_UTIL=/path/to/dstack-util \ KMS_URL=https://your-kms-domain:12001 \ APP_ID=0xYOUR_APP_ID \ ./scripts/build-eif.sh ``` or source build variant: ```bash theme={"system"} KMS_URL=https://your-kms-domain:12001 \ APP_ID=0xYOUR_APP_ID \ DSTACK_COMMIT=14963a2ccb0ec7bef8a496c1ac5ac40f5593145d \ ./scripts/build-eif.sh ``` ### 3.3 GitHub Actions Build ```bash theme={"system"} git add . git commit -m "configure enclave app" git push origin main git tag v0.1.0 git push origin v0.1.0 ``` ### 3.4 Output `./output/`: * `enclave.eif` * `measurements.json` * `measurements.sigstore.json` (CI) Output includes: * `PCR0`, `PCR1`, `PCR2` * `OS_IMAGE_HASH = sha256(PCR0 || PCR1 || PCR2)` *** ## Step 4: Register OS\_IMAGE\_HASH On-chain Before key retrieval, register measured image hash. ### Development ```bash theme={"system"} cd dstack/kms/auth-eth npx hardhat kms:add-image --network ``` ### Production Use governance/multisig/timelock flow. See [Register Workload Measurements](/dstack-cloud/register-enclave-measurement). ### App policy check (important) For successful `GetAppKey`, app policy must also allow your runtime attestation: * compose hash/image hash allowed (`app:add-hash`) * device policy satisfied (either `allowAnyDevice=true` or device explicitly added) Useful commands: ```bash theme={"system"} npx hardhat app:add-hash --app-id --network # Choose one: npx hardhat app:set-allow-any-device --app-id true --network # or npx hardhat app:add-device --app-id --network ``` *** ## Step 5: Deploy on EC2 ### 5.1 Launch Nitro-capable instance | Setting | Value | | - | - | | Instance type | `c5.xlarge` or larger (c5/m5/r5 families) | | AMI | Amazon Linux 2023 | | Nitro Enclaves | enabled | ### 5.2 Install Nitro tooling ```bash theme={"system"} sudo yum install -y aws-nitro-enclaves-cli sudo systemctl enable nitro-enclaves-allocator.service sudo systemctl start nitro-enclaves-allocator.service ``` ### 5.3 Allocator resources `/etc/nitro_enclaves/allocator.yaml`: ```yaml theme={"system"} memory_mib: 2048 cpu_count: 2 ``` ```bash theme={"system"} sudo systemctl restart nitro-enclaves-allocator.service ``` ### 5.4 Run EIF ```bash theme={"system"} gh release download v0.1.0 -p 'enclave.eif' nitro-cli run-enclave --eif-path enclave.eif --cpu-count 2 --memory 2048 ``` ### 5.5 Verify ```bash theme={"system"} nitro-cli describe-enclaves nitro-cli console ``` *** ## Entrypoint Notes The template uses `dstack-util get-keys` and a VSOCK proxy for key retrieval. Keys are returned to `/var/run/dstack/keys.json` inside the enclave, or captured on the host via VSOCK in helper scripts. > **Important:** The KMS URL, APP\_ID, and `root_ca.pem` are all baked into the enclave image and affect the measured hash. You must use the exact same inputs between `--show-mrs` preview and the real run — any difference produces a different `OS_IMAGE_HASH`. *** ## Troubleshooting | Issue | Solution | | - | - | | `Boot denied: OS image is not allowed` | register the exact runtime OS\_IMAGE\_HASH; ensure runtime build inputs match show-mrs inputs | | Raw IP in KMS URL causes TLS/SAN issues | use DNS name (`kms.example.com`), not bare IP | | `get_keys.sh` completes but key file is empty | treat as failure; inspect enclave console and KMS policy response | | `DEBUG_ENCLAVE=1` run cannot pass policy | expected for production validation; debug mode alters attestation behavior and should be used only for diagnostics | | `Insufficient CPUs available in the pool` | terminate leftover enclaves and adjust allocator CPU count | *** ## Differences from GCP Nitro and GCP take fundamentally different approaches. On GCP, the Guest Agent handles attestation, key management, and automatic disk encryption. On Nitro, `dstack-util` only retrieves the key — your application decides what to encrypt. For a full comparison, see the [overview](/dstack-cloud/overview) and [KMS and Key Delivery](/dstack-cloud/kms-and-key-delivery). *** ## Next Steps * [Register Workload Measurements](/dstack-cloud/register-enclave-measurement) * [Run a dstack-kms on GCP](/dstack-cloud/run-kms-on-gcp) * [Nitro Enclave concept](/dstack-cloud/nitro-enclave) # Troubleshooting Runbook Source: https://docs.phala.com/dstack-cloud/runbook Troubleshooting runbook for common dstack-cloud deployment issues. # Troubleshooting Runbook When something breaks in a dstack-cloud deployment, the root cause usually falls into one of these categories: attestation mismatch, KMS unavailability, governance hold-up, or infrastructure issues. This runbook covers the most common failure modes and how to diagnose them. ## RA-TLS (Remote Attestation TLS) Connection Failures ### Symptoms * Workload logs show "RA-TLS handshake failed" * KMS logs show "connection from unverified peer" * Workload cannot obtain keys ### Diagnosis ```bash theme={"system"} # Check workload logs dstack-cloud logs # Check KMS logs cd kms-prod dstack-cloud logs ``` ### Common Causes and Fixes | Cause | Fix | | - | - | | Workload attestation invalid | Verify the workload's measurements match what is registered on-chain. Run `dstack-cloud status` to get current measurements. | | KMS attestation invalid | Verify KMS is running in a genuine TEE. Check `dstack-cloud status` for the KMS instance. | | Clock skew between workload and KMS | RA-TLS requires relatively synchronized clocks. Check NTP configuration on both sides. | | Certificate expired | Check that the RA-TLS certificates have not expired. Restart the CVM to regenerate. | ## Attestation Verification Failures ### Symptoms * KMS refuses to dispatch keys * Logs show "measurement not authorized" or "attestation verification failed" ### Diagnosis ```bash theme={"system"} # Get current measurements dstack-cloud status # Note the RTMR3 / OS_IMAGE_HASH # Check on-chain authorization cast call \ "isAuthorized(bytes32)(bool)" \ 0xYOUR_MEASUREMENT_HASH \ --rpc-url $RPC_URL ``` ### Common Causes and Fixes | Cause | Fix | | - | - | | Measurement not registered on-chain | Register the measurement via governance. See [Register Workload Measurements](/dstack-cloud/register-enclave-measurement). | | Measurement changed after update | Application code or Docker image changed. Register the new measurement. | | KMS pointing to wrong contract | Verify `KMS_CONTRACT_ADDR` environment variable. | | RPC returns stale state | Check RPC provider health. Switch to a backup RPC endpoint. | ## CVM / Enclave Startup Failures ### Symptoms * `dstack-cloud deploy` succeeds but CVM exits immediately * `dstack-cloud status` shows "ERROR" or "STOPPED" ### Diagnosis ```bash theme={"system"} # Check logs for the reason dstack-cloud logs # Check resource allocation (GCP) gcloud compute instances describe # Check resource allocation (Nitro) sudo amazon-nitro-enclaves-cli describe-enclaves ``` ### Common Causes and Fixes | Cause | Fix | | - | - | | Insufficient memory | Allocate more memory. On GCP, use a larger machine type. On Nitro, increase `--memory` in `allocate-enclaves`. | | Invalid Docker image | Verify the image exists and is accessible. Use SHA256 digests for pinned images. | | Container crash loop | Check application logs. The container may have a runtime error. | | OS image incompatible | Ensure the OS image version matches the dstack-cloud CLI version. | ### GCP-specific | Cause | Fix | | - | - | | Confidential VM quota exceeded | Request quota increase in GCP Console. | | VM not booting as TDX | Verify the VM has `confidential-compute: enabled` in GCP Console. | ### Nitro-specific | Cause | Fix | | - | - | | Enclave image (EIF) too large | Reduce Docker image size. Use multi-stage builds. | | Nitro driver not installed | Install: `sudo apt-get install -y aws-nitro-enclaves-cli` | | Enclave resource limit exceeded | Run `allocate-enclaves` with higher values and retry. | ## On-chain Authorization Failures ### Symptoms * KMS logs show "workload not authorized" * Keys are not dispatched despite correct attestation ### Diagnosis ```bash theme={"system"} # Check if measurement is authorized on-chain cast call "isAuthorized(bytes32)(bool)" 0xHASH --rpc-url $RPC_URL # Check DstackKms contract state cast call "owner()(address)" --rpc-url $RPC_URL ``` ### Common Causes and Fixes | Cause | Fix | | - | - | | Measurement registered on wrong contract | Verify the KMS is configured to use the correct `DstackKms` address. | | Governance transaction not yet executed | Check the Safe for pending transactions. Wait for timelock. | | Measurement was revoked | Check the Safe transaction history. If revoked by mistake, re-register via governance. | ## KMS Unavailable ### Symptoms * Workloads cannot connect to KMS * `dstack-cloud status` shows KMS as stopped or unreachable ### Diagnosis ```bash theme={"system"} # Check KMS status cd kms-prod dstack-cloud status # Check KMS logs dstack-cloud logs # Test connectivity curl -k https://:12001/health ``` ### Common Causes and Fixes | Cause | Fix | | - | - | | KMS CVM stopped | Restart: `dstack-cloud start` | | KMS bootstrap not completed | Complete the bootstrap procedure. See [Run a dstack-kms CVM on GCP](/dstack-cloud/run-kms-on-gcp). | | Network issue | Verify firewall rules. Check VSOCK proxy on Nitro. | | KMS out of memory | Allocate more resources. Check `dstack-cloud logs` for OOM errors. | ## Governance Transactions Stuck ### Symptoms * Governance proposal not advancing * Transaction in Safe queue not executing ### Diagnosis 1. Check the Safe web interface for transaction status 2. Check if the timelock has expired 3. Verify the Safe has sufficient gas ### Common Causes and Fixes | Cause | Fix | | - | - | | Not enough signatures | Contact missing signers. If a signer is unavailable, consider adding a new signer (requires governance). | | Timelock not yet expired | Check the exact expiry time. Wait. | | Safe out of gas | Send ETH to the Safe address. | | Transaction will revert | Simulate the transaction before executing. The contract state may have changed since the proposal was created. Cancel and re-submit. | | Stale transaction in queue | Cancel the stale transaction through the Safe interface. Submit a new one. | ## VSOCK Proxy Failures (Nitro-specific) ### Symptoms * Enclave cannot reach KMS or external services * `dstack-cloud logs` shows network timeout errors ### Diagnosis ```bash theme={"system"} # Check if socat is running ps aux | grep socat # Check VSOCK proxy logs journalctl -u vsock-proxy -f # if running as systemd service # Test VSOCK connectivity from the host echo "test" | socat - VSOCK-CONNECT:1:8000 ``` ### Common Causes and Fixes | Cause | Fix | | - | - | | socat not running | Start the VSOCK proxy. Check `prelaunch.sh` for the proxy startup command. | | Wrong VSOCK port | Verify the VSOCK port matches between the Enclave and the proxy. | | socat crashed | Restart socat. Check system logs for crash reason. Consider running as a systemd service with auto-restart. | | Port conflict | Another process is using the same port. Change the proxy port configuration. | ## Emergency Operations ### Revoke a Compromised Measurement 1. Draft a governance transaction to remove the measurement from `DstackKms` 2. Request expedited approval from all signers 3. Wait for the timelock (cannot be bypassed) 4. Execute after the delay 5. Verify the measurement is no longer authorized ### KMS Key Compromise If the KMS root key may have been compromised: 1. Stop the KMS immediately: `dstack-cloud stop` 2. Audit all workloads that received keys from the compromised KMS 3. Rotate affected application keys 4. Deploy a new KMS instance with fresh measurements 5. Register the new KMS measurements on-chain 6. Revoke the old KMS measurements 7. Restart workloads against the new KMS ### Full System Recovery 1. Stop all CVMs and KMS instances 2. Verify blockchain state is consistent 3. Redeploy from known-good configuration 4. Re-register measurements if needed 5. Verify end-to-end key delivery 6. Review governance activity for suspicious transactions ## Diagnostic Commands Cheat Sheet ```bash theme={"system"} # Check deployment status dstack-cloud status # View logs dstack-cloud logs dstack-cloud logs --follow dstack-cloud logs --container # Check measurements dstack-cloud status | grep -E "measurement|hash|rtmr" # On-chain queries (using cast) cast call "isAuthorized(bytes32)(bool)" 0xHASH --rpc-url $RPC_URL cast call "owner()(address)" --rpc-url $RPC_URL # GCP diagnostics gcloud compute instances describe gcloud logging read "resource.type=gce_instance" # Nitro diagnostics sudo amazon-nitro-enclaves-cli describe-enclaves sudo amazon-nitro-enclaves-cli allocate-enclaves --cpu-count 2 --memory 4096 ``` ## Next Steps * **[Monitoring and Alerting](/dstack-cloud/monitoring-alerting)** — Set up proactive monitoring * **[Upgrade Procedures](/dstack-cloud/upgrade)** — Upgrade versions to fix known issues # Threat Model and Security Guarantees Source: https://docs.phala.com/dstack-cloud/security-model Trust boundaries, threat categories, security guarantees, and residual risks for dstack-cloud deployments. # Threat Model and Security Guarantees ## Trust Boundaries Understanding what you must trust — and what's protected by hardware or blockchain — is the foundation of evaluating dstack-cloud's security. This page maps out trust boundaries, threat categories, and the guarantees the system provides. ![Trust Boundaries](https://mintcdn.com/phalanetwork-1606097b/kLcECSdhM8pjBAIk/images/dstack-cloud/trust-boundaries.png?fit=max\&auto=format\&n=kLcECSdhM8pjBAIk\&q=85\&s=11d317e5d8106813a9506d04f0797293) ### Untrusted | Entity | Assumption | | - | - | | **Cloud platform** (GCP / AWS) | May attempt to read workload memory, inspect traffic, or modify configurations. TEE hardware prevents memory access. | | **Host machine** (EC2 instance on Nitro) | Has root access to the host OS. Cannot access Enclave memory or modify Enclave code. | | **Network attackers** | May intercept, modify, or replay network traffic. Defended by TLS / RA-TLS. | | **RPC providers** | May return stale or malicious blockchain state. KMS should use multiple RPC sources. | ### Protected by Hardware (TEE) | Entity | Protection | | - | - | | **dstack CVM** (GCP workload) | Memory encrypted by TDX. Host and cloud platform cannot read or modify it. Guest Agent handles attestation and key management. | | **Nitro Enclave** (AWS workload) | Memory encrypted by Nitro. Host and cloud platform cannot read or modify it. `dstack-util` handles attestation and key retrieval. | | **dstack-kms** (KMS) | Runs in its own TEE. Keys are generated and stored inside; never exposed outside. | ### Protected by Blockchain Consensus | Entity | Protection | | - | - | | **On-chain contracts** (DstackKms, DstackApp) | Immutable unless governance process is followed. Changes require multisig + timelock. | ### Partially Trusted | Entity | Risk | | - | - | | **Multisig signers** | Can collude to push through unauthorized changes. Impact is limited by the signature threshold and timelock delay. | ## Threat Categories ### T1: Malicious Cloud Platform Operator or Compromised Host OS * **Attack:** Cloud provider or host OS administrator attempts to read workload memory or extract keys. * **Impact:** Data breach, key compromise. * **Mitigation:** TEE hardware encryption prevents memory access on both GCP (TDX) and AWS (Nitro Enclave). Attestation proves hardware authenticity. * **Residual risk:** Microarchitectural side-channel attacks (speculative execution, etc.). See Residual Risks. ### T3: Malicious or Compromised Workload * **Attack:** An attacker gains control of a workload container inside the CVM or Enclave. * **Impact:** Data within that container is compromised. The attacker may try to escalate to the Guest Agent (GCP) or dstack-util (Nitro). * **Mitigation:** Container isolation within the CVM/Enclave. The Guest Agent (GCP) or dstack-util (Nitro) validates attestation before delivering keys. * **Residual risk:** If the attacker can modify the CVM/Enclave image itself, the measurements change and KMS will refuse to deliver keys. On Nitro, since encryption strategy is user-controlled, a compromised workload may misuse any keys it has already obtained. ### T4: Man-in-the-Middle / Network Attack * **Attack:** Attacker intercepts communication between CVM and KMS, or between CVM and external services. * **Impact:** Key interception, data theft, configuration tampering. * **Mitigation:** All communication uses TLS or RA-TLS. RA-TLS additionally verifies both parties' attestation. * **Residual risk:** TLS implementation vulnerabilities, certificate authority compromise. ### T5: Compromised RPC Provider * **Attack:** Attacker operates a malicious RPC node that returns false blockchain state. * **Impact:** KMS may accept unauthorized measurements or reject authorized ones. * **Mitigation:** Use multiple independent RPC providers. KMS should verify blockchain state across sources. * **Residual risk:** If all RPC providers are colluding or compromised. ### T6: Compromised or Colluding Multisig Signers * **Attack:** Multiple signers collude to push through unauthorized governance changes (e.g., register malicious measurements). * **Impact:** Unauthorized workloads receive keys from KMS. * **Mitigation:** Signature threshold (≥ 2/3) limits the number of signers that must be compromised. Timelock provides a window for detection. * **Residual risk:** If enough signers collude to meet the threshold, the system is compromised. ### T7: Covert Deployer Attack * **Attack:** A workload deployer secretly modifies the application code after deployment. * **Impact:** The workload behaves differently from what was approved. * **Mitigation:** On-chain measurement registration. Any code change produces new measurements. KMS refuses to deliver keys to unregistered measurements. * **Residual risk:** If the attacker can register the new measurements through governance without being detected. ## Security Guarantees | Guarantee | Mechanism | | - | - | | **Keys never leave verified TEE** | KMS runs in its own TEE. Keys are generated, stored, and dispatched entirely within TEE. The cloud provider cannot access them. | | **Only approved code receives keys** | Workload measurements must be registered on-chain. KMS verifies measurements before dispatching keys. | | **Governance changes are auditable** | All governance actions go through Multisig + Timelock and are recorded on-chain. Anyone can verify the history. | | **Memory is encrypted** | TEE hardware encrypts all memory. The host OS and cloud platform cannot read CVM (GCP) or Enclave (Nitro) memory. | | **Code integrity is verifiable** | Attestation proves the exact code and configuration running in the TEE. External parties can independently verify. | ## Residual Risks These are risks that the current architecture does not fully mitigate: | Risk | Description | Mitigation | | - | - | - | | **Hardware side-channels** | TEE hardware may be vulnerable to microarchitectural side-channel attacks (e.g., Spectre, Meltdown variants). | Keep TCB (Trusted Computing Base) firmware updated. Monitor Intel / AWS security advisories. | | **Smart contract vulnerabilities** | Bugs in DstackKms, DstackApp, or governance contracts could lead to unauthorized access. | Conduct formal smart contract audits. Use well-tested contract libraries (Safe, Timelock). | | **KMS root key** | The KMS root key is currently a single point of trust within the KMS TEE. | Future plans include MPC (Multi-Party Computation) to distribute root key generation. | | **Denial of service** | The cloud provider or host operator can shut down CVMs or Enclaves, denying service. | Use cross-region, cross-provider redundancy for high-availability deployments. | ## Security Checklist for Deployments Before going to production, verify: **TEE and Attestation:** * [ ] dstack OS image is built from audited source code * [ ] All measurements (RTMR / OS\_IMAGE\_HASH) are registered on-chain * [ ] TLS certificates are valid and properly configured **Governance:** * [ ] Multisig signers are using hardware wallets * [ ] Signature threshold is ≥ 2/3 * [ ] Timelock delay is appropriate for your risk profile **Operations:** * [ ] Multiple independent RPC providers are configured * [ ] Monitoring and alerting are set up for attestation failures and governance events * [ ] Runbook exists for common failure scenarios ## Next Steps * **[Glossary](/dstack-cloud/glossary)** — Definitions of security-related terms * **[Runbook](/dstack-cloud/runbook)** — Troubleshooting security-related issues * **[dstack Security Model](https://github.com/Phala-Network/dstack-cloud/blob/master/docs/security/security-model.md)** — Official security model document # Upgrade Procedures Source: https://docs.phala.com/dstack-cloud/upgrade Upgrade procedures for KMS images, CVM applications, and smart contracts. # Upgrade Procedures Upgrading in a TEE environment is different from normal cloud upgrades: changing your Docker image or OS version changes the measurements, which means you need to go through governance before KMS will deliver keys to the new version. This page covers the upgrade procedures for KMS, CVMs/Enclaves, and smart contracts. ## Pre-upgrade Checklist Before any upgrade: * [ ] Review the changelog for the new version * [ ] Test the upgrade in a non-production environment first * [ ] Ensure you have access to all required signers (for governance changes) * [ ] Back up current configuration (`app.json`, `docker-compose.yaml`, `.env`) * [ ] Verify monitoring and alerting is operational * [ ] Notify stakeholders of planned downtime (if applicable) * [ ] Prepare a rollback plan ## KMS Image Upgrade ### When to Upgrade * New dstack-cloud version available with security fixes * New KMS features needed * KMS vulnerability disclosed ### Procedure (GCP) 1. **Pull the new OS image:** ```bash theme={"system"} dstack-cloud pull --os-image dstack-cloud-0.7.0 ``` 2. **Stop the current KMS CVM:** ```bash theme={"system"} cd kms-prod dstack-cloud stop ``` 3. **Update the OS image reference in `app.json`:** ```json theme={"system"} { "os_image": "dstack-cloud-0.7.0" } ``` 4. **Redeploy:** ```bash theme={"system"} dstack-cloud deploy ``` 5. **Re-bootstrap if the KMS image changed:** * If the new KMS image produces different measurements, you must register them on-chain before KMS will work * Follow the bootstrap procedure in [Run a dstack-kms CVM on GCP](/dstack-cloud/run-kms-on-gcp) 6. **Verify:** ```bash theme={"system"} dstack-cloud status dstack-cloud logs --follow ``` ### Procedure (Nitro) The process is similar, but note: * The Enclave is stateless — after stopping and restarting, key material must be re-derived * Ensure the VSOCK proxy is running before deploying the new Enclave * New measurements may require on-chain registration ### Rollback 1. Stop the new KMS CVM: `dstack-cloud stop` 2. Revert `app.json` to the previous OS image version 3. Redeploy: `dstack-cloud deploy` 4. If measurements changed during upgrade, the old measurements should still be registered on-chain ## CVM / Enclave Application Upgrade ### When Upgrading Requires Governance If your application upgrade changes the measurements (different Docker images, different `docker-compose.yaml`, different dstack OS version), you must go through governance: 1. **Build and deploy the updated CVM/Enclave** (in a test environment first) 2. **Extract the new measurements:** ```bash theme={"system"} dstack-cloud status # Note the RTMR3 / OS_IMAGE_HASH ``` 3. **Register new measurements on-chain:** * See [Register Workload Measurements](/dstack-cloud/register-enclave-measurement) 4. **Wait for governance approval and timelock** 5. **Deploy to production:** ```bash theme={"system"} dstack-cloud deploy ``` ### When Upgrading Does NOT Require Governance If the upgrade only changes application logic without changing the Docker images or configuration (e.g., updating application code via a mounted volume, which is not possible in TEE), no governance is needed. In practice, most upgrades in a TEE environment require governance because the code is measured at build time. ### Procedure (GCP) 1. Update `docker-compose.yaml` with new image versions: ```yaml theme={"system"} services: web: image: my-app:v2.0.0@sha256:abcd1234... ``` 2. Redeploy: ```bash theme={"system"} dstack-cloud deploy ``` 3. Verify: ```bash theme={"system"} dstack-cloud logs --follow ``` ### Procedure (Nitro) 1. Update `docker-compose.yaml` 2. Redeploy: ```bash theme={"system"} dstack-cloud deploy ``` 3. The Enclave is rebuilt from the new image 4. Verify via VSOCK proxy ## Smart Contract Upgrade ### When to Upgrade * Security vulnerability in contract code * New governance feature needed * Bug fix in contract logic ### Procedure (Using Proxy Pattern) If contracts use an upgradeable proxy pattern: 1. **Deploy the new implementation contract:** ```bash theme={"system"} npx hardhat run scripts/deploy-kms-v2.ts --network ``` 2. **Draft a governance transaction** to call `proxy.upgradeTo(newImplementation)`: * Use the Safe web interface * The transaction must go through multisig + timelock 3. **Test the upgrade on testnet first:** * Deploy new implementation on testnet * Run through governance on testnet * Verify the upgraded contract works as expected 4. **Execute governance on mainnet:** * Collect signatures * Wait for timelock * Execute 5. **Verify:** ```bash theme={"system"} # Check the implementation address cast call "implementation()(address)" --rpc-url $RPC_URL ``` ### Rollback To rollback, follow the same procedure with the previous implementation address. ### Important Notes * The proxy admin must be the governance Safe — never an EOA * Upgrades cannot be rushed — the timelock delay applies * Plan upgrades during low-traffic windows * Have a tested rollback procedure ready before upgrading ## Coordinated Upgrade: Application + Measurements + Contracts A full-stack upgrade requires careful coordination because each step may depend on the previous one completing. The general order is: 1. Test new application + new KMS + new contracts in staging 2. Deploy new contracts to mainnet (through governance) 3. Register new measurements on-chain (through governance) 4. Wait for all governance actions to complete 5. Deploy new KMS image to production 6. Deploy new application CVMs to production 7. Verify end-to-end key delivery 8. Optionally revoke old measurements after verification ## Downtime Considerations | Component | Downtime During Upgrade | | - | - | | KMS (GCP) | 1-2 minutes (stop + redeploy) | | CVM (GCP) | 2-3 minutes | | CVM (Nitro) | 30 seconds to 1 minute | | Smart contracts | No downtime (upgrade is a transaction) | To minimize downtime: * Deploy new CVMs first, then switch traffic * Keep old CVMs running until new ones are verified * For KMS, consider running multiple instances for high availability ## Next Steps * **[Monitoring and Alerting](/dstack-cloud/monitoring-alerting)** — Monitor upgrade impact * **[Runbook](/dstack-cloud/runbook)** — Troubleshoot upgrade issues # Acknowledgement Source: https://docs.phala.com/dstack/acknowledgement Deploy confidential applications with dstack — a TEE-based infrastructure platform. ## Contributors The inspiration for this work stems from [Andrew Miller](https://github.com/amiller)’s pioneering concept of a [Docker-based P2P TEE SDK](https://collective.flashbots.net/t/dstack-speedrunning-a-p2p-confidential-vm/3876). Special acknowledgment to [Flashbots](https://github.com/flashbots) for building a community around TEE. The TEE Hacker House initiative, organized by [Flashbots](https://github.com/flashbots) and led by [Tina](https://github.com/CarboClanC), has brought together TEE builders to develop tools for TEE-Web3 integration. This collaborative journey has generated invaluable insights for advancing secure, confidential environments within Web3. Special recognition goes to the Pi-rateship builders who contributed their expertise: * Teleport: [Sxy Sun](https://github.com/sxysun) * Flashbots: [Tina](https://github.com/CarboClanC), [Mateusz](https://github.com/Ruteri), [Dmarz](https://github.com/dmarzzz), [Moe](https://github.com/MoeMahhouk) * Ithaca: [Georgios](https://github.com/gakonst) * Fabric: [@gaoist](https://x.com/gaoist) * Phala Network: [Kevin Wang](https://github.com/kvinwang), [Shelven Zhou](https://github.com/shelvenzhou) * And many more... This project cannot be built without standing on the shoulders of giants: * [konvera/meta-confidential-compute](https://github.com/konvera/meta-confidential-compute) Together, we’re shaping the future of TEE in Web3, paving the way for more secure and developer-accessible confidential computing! For a full list of the direct contributors to this repo, see [Contributors](https://github.com/Dstack-TEE/dstack/contributors) on GitHub. # Decentralized Root-of-Trust Source: https://docs.phala.com/dstack/design-documents/decentralized-root-of-trust Technical design documents and architecture details for the dstack TEE platform. Root-of-Trust (RoT) is the cornerstone of the TEE chain-of-trust. The end user verifies Remote Attestations signed by the CPU, which ultimately rely on keys derived from a set of hardware-held secrets. The hardware component that manages these root secrets, verifies firmware and applications, and issues Remote Attestations is called the Root-of-Trust. ## Hardware Root-of-Trust [#p-8175-hardware-root-of-trust-1](#p-8175-hardware-root-of-trust-1) ![](https://mintcdn.com/phalanetwork-1606097b/HhZAgNWhhdRirRzb/images/hardware-root-of-trust.png?fit=max\&auto=format\&n=HhZAgNWhhdRirRzb\&q=85\&s=22c2e683f316cd86a0bc1d6224c0ecb2) However, hardware RoT has several drawbacks due to the limitations of physical hardware: * **Unrecoverable TCB**: Usually, bugs in TEE can be fixed by microcode upgrades with a TCB Recovery process. However, when the secret keys in the RoT are extracted, an attacker can simulate a RoT outside of the hardware and issue arbitrary Remote Attestations using the secrets. This invalidates the TCB Recovery process. * **Vendor/Physical Chip Locked**: The app running in the TEE relies on keys derived from the RoT to seal data and maintain identities (e.g., for signing signatures and establishing TLS connections). When the RoT is lost, the corresponding data and identities are lost as well. This prevents workloads from migrating between TEEs and blocks users from building services with high availability. ## Software Root-of-Trust [#p-8175-software-root-of-trust-2](#p-8175-software-root-of-trust-2) Given these significant drawbacks of hardware RoT, it’s imperative to explore alternative approaches that offer greater flexibility and resilience. One such approach is abstracting the RoT into software. To understand how a software RoT can address these challenges, let’s reconsider its role in the context of a TEE and explore how it can enhance security: 1. **Measurement**: Verify the authenticity of the child layer in the chain-of-trust. * In Intel SGX, RoT verifies the version of the CPU microcode, BIOS configuration, and the code loaded into the SGX enclave. 2. **Key Derivation Service**: Provide a service to derive keys for the child layer. The derived keys can be used to implement data sealing, message signing, and Remote Attestation when combined with the measurements. These two properties can also be implemented in software, offering better flexibility and resilience. A simple software RoT can be implemented as follows: * A KMS that maintains a set of secrets. * Implement **Measurement**: Verify the authenticity of a physical TEE by requesting and verifying the native Remote Attestation from the TEE (e.g., Intel SGX DCAP Remote Attestation). Once this measurement is taken, the RoT can trust that the desired software is running on the desired hardware environment with all the proper properties, usually integrity and confidentiality. * Implement **Key Derivation Service**: Once verification passes, the KMS can provide services allowing TEE applications to obtain derived keys from the RoT. The communication channel between the RoT and the TEE application can be secured using end-to-end encryption protocols like RA-TLS. Similar to a hardware RoT, the service provides capabilities to seal data, sign certificates, and implement Remote Attestation for TEE applications. Implementing a software RoT offers several advantages but also introduces new challenges that must be carefully considered: * **Pros** * **Always Recoverable TCB**: TEEs with a compromised hardware RoT can be rejected by the RoT system when measuring their Remote Attestations. In case of a hardware RoT breach, the software RoT remains secure. The software RoT can blacklist the entire product line of the affected hardware to recover the TCB of the system. * **Dynamic Measurement**: Instead of relying on static secrets stored in the hardware RoT, a software RoT can measure the physical TEE periodically and detect vulnerabilities as they occur. When a vulnerability is detected, the RoT can trigger a TEE *application migration*, remove the affected TEE from the network, and perform a key rotation to reduce the risk (with forward and backward secrecy). * **Application Migration**: The keys the application relies on (for sealing, signing, etc.) are no longer associated with the hardware RoT. Regardless of which hardware TEE the application runs on, it can always obtain the same set of derived keys from the software RoT, decoupling TEE applications from the hardware implementation. * **Cons** * **Centralization Risk**: It’s challenging to run a software RoT securely. The RoT must (1) keep the secrets confidential, (2) ensure the integrity of its code, and (3) maintain the liveness of the service. These three properties are especially challenging without relying on trust in a centralized party. ## Decentralized Root-of-Trust [#p-8175-decentralized-root-of-trust-3](#p-8175-decentralized-root-of-trust-3) ![](https://mintcdn.com/phalanetwork-1606097b/HhZAgNWhhdRirRzb/images/decentralized-root-of-trust-architecture.png?fit=max\&auto=format\&n=HhZAgNWhhdRirRzb\&q=85\&s=83c10ace220a175069a30a13de7d6203) While a software-based RoT offers significant benefits, it introduces the risk of centralization, which compromises security. To address this, a decentralized RoT can eliminate such risks and offer a more secure, distributed alternative. We propose a decentralized RoT model. This approach distributes trust across multiple independent nodes, eliminating reliance on a single entity. A decentralized RoT serves as the foundational trust anchor for the entire TEE network, removing dependencies on specific TEE manufacturers or cloud providers. A decentralized RoT can be implemented as follows: * A software RoT using Secure Multi-party Computation (MPC) to manage and use the root secrets. MPC distributes trust across multiple independent nodes, ensuring that no single entity can compromise the RoT. Attackers must control a majority (typically two-thirds) of nodes to access the secrets. * The RoT nodes run in TEEs to (1) measure the integrity of the code and (2) provide defense-in-depth to reduce the risk of MPC collusion attacks. With reproducible builds, anyone can verify that the RoT nodes have implemented the protocol properly. * Smart contracts on the blockchain act as the governance layer for the decentralized RoT, enforcing rules around RoT node behavior, including blacklisting certain hardware from joining the TEE network. By verifying Remote Attestations on-chain, smart contracts ensure that only nodes running approved code are part of the system. * Additionally, staking mechanisms can be introduced to add cryptoeconomic security, where node operators must stake tokens as collateral. Any malicious behavior risks losing this stake, incentivizing honest participation. The decentralized architecture solves the centralization risk in software RoT because: 1. **Confidentiality**: The secrets are protected by threshold MPC, eliminating the single point of failure, with TEE providing defense-in-depth. 2. **Integrity**: The code is protected by both TEE Remote Attestation and threshold MPC for redundancy. 3. **Liveness**: The MPC setup can tolerate the failure of up to one-third of the nodes. Cryptoeconomics can be introduced to further incentivize operators to behave well. This decentralized model effectively overcomes the vulnerabilities of centralized RoT by distributing control across a secure, blockchain-governed network of MPC nodes. Additionally, the architecture reduces the complexity for users in verifying the security properties of TEE applications by providing a chain-of-trust. Users can easily verify the chain-of-trust by checking the signatures originating from the smart contract. # Key Management Service Source: https://docs.phala.com/dstack/design-documents/key-management-protocol Technical design documents and architecture details for the dstack TEE platform. In [Decentralized Root-of-Trust](/dstack/design-documents/decentralized-root-of-trust), we described our motivation to update the TEE Root-of-Trust from hardware-kept unrecoverable secret keys to a smart-contract-governed software (i.e., DeRoT). In this article, we’ll delve deeper into the details of its key management protocol. ## Threat Model [#p-8432-threat-model-1](#p-8432-threat-model-1) A fundamental assumption in our threat model is that *TEE can be compromised*. Therefore, our primary goal is to ensure that even if the TEE hardware is compromised, the application should still function correctly with minimal data leakage. This is why we introduce Decentralized Root-of-Trust (DeRoT), a verifiable Key Management Service (KMS) for TEE governed by smart contracts, to replace the hardware-kept unrecoverable secret keys in TEE. Based on this assumption, we discuss potential threats and corresponding countermeasures. Specifically, both the confidentiality and integrity guarantees provided by TEE hardware can be compromised. * If confidentiality is compromised, encrypted memory values may be leaked, and this will further affect the sealed data on persistent storage. The countermeasures aim to: * Limit the damage scope when a single worker is compromised to only the minimal amount of data it knows. * Ensure forward and backward secrecy so that historical and future data remains safe. * If the integrity promise is broken, an adversary can instruct the TEE to produce false results. In this case, all outputs from the compromised TEE should not be trusted or used by other TEE hardware and clients. While detecting TEE vulnerabilities and compromises is beyond the scope of DeRoT, it should be able to revoke authentication and prevent dirty data from being persisted. ## Introducing DeRoT [#p-8432-introducing-derot-2](#p-8432-introducing-derot-2) Compared to traditional key management services, DeRoT differs in two aspects: * **Access Control on Clients:** DeRoT verifies its clients to ensure they are genuine TEE hardware running valid applications. * **Verifiable Chain-of-Trust:** The DeRoT program, along with all its generated keys, must be verifiable through blockchain technology. We will explain how to verify the integrity of the DeRoT program and check whether a key is genuinely generated by DeRoT in the following sections. DeRoT is designed to enhance the functionalities of the current hardware-kept secret key in TEE in two major scenarios: 1) identifying the TEE hardware, and 2) [data sealing](https://www.intel.com/content/www/us/en/developer/articles/technical/introduction-to-intel-sgx-sealing.html) (i.e., the encryption of persistent storage). Its advantages include: * **Vendor- and Hardware-Agnostic TEE Verification:** DeRoT is responsible for distributing secret keys only to valid TEE hardware and controlling the key lifecycle. Clients can delegate the Remote Attestation (RA) report verification to DeRoT, needing only to verify whether the key held by the TEE is valid. This simplifies client implementation and abstracts away the details of RA reports. Additionally, this approach can be easily extended to support different TEE hardware and get integrated into existing certificate chains. * **Key Rotation in Data Sealing with Enhanced Security Features:** With key rotation, the time window for attackers is significantly limited. Furthermore, this approach ensures forward and backward secrecy for sealed data, enhancing overall security. * **Support for Upgradable and Migratable Applications:** Since the sealed data is now encrypted with keys generated by the standalone DeRoT, storage can be entirely separated from TEE hardware. This allows upgraded applications to decrypt saved states in a controllable way, and enables dynamic addition or removal of TEE hardware without concerns about data loss. Additionally, this architecture aligns with the existing cloud paradigm, facilitating easier migration. ## Unique Challenge: Stealthy Deployer Attack [#p-8432-unique-challenge-stealthy-deployer-attack-3](#p-8432-unique-challenge-stealthy-deployer-attack-3) Unlike in smart contracts that every operation is observable on-chain, the introduce of DeRoT enables a blockchain-TEE hybrid system where the interactions can happen both on-chain and invisibly off-chain. Also, the support for upgradable application code will introduce more risks since the benign code may be changed to dump the encrypted data in an unconscious way. Considering the following attack from a malicious application deployer: 1. An open-source benign application is deployed to TEE and trusted by its users to process the privacy data; 2. The deployer asks the DeRoT to upgrade the application code. It seems no reason to reject it since he is the owner; 3. The deployer injects malicious logic to dump all the privacy data in the new code, but doesn’t announce this to the public. Since this upgrade is between the TEE and DeRoT, it is not observable from the on-chain perspective; 4. The deployer can make another upgrade to remove the malicious logic to erase the evidence. Actually, similar attacks on the upgradable smart contracts happened before, but the difference is that such attack will not be naturally perceived when the application and the DeRoT are running off-chain. It’s worth noting that adding more access control on the application upgrade operation (e.g. enforce a multi-sig smart contract) cannot mitigate this risk. This attack motivates an important principle in our design: *every operation involving key authorization changes must be initiated on-chain to ensure observability*. This will ensure the security equivalence to existing smart contracts. ## Design [#p-8432-design-4](#p-8432-design-4) ### Verifiable DeRoT and Key Chain [#p-8432-verifiable-derot-and-key-chain-5](#p-8432-verifiable-derot-and-key-chain-5) ![](https://mintcdn.com/phalanetwork-1606097b/HhZAgNWhhdRirRzb/images/derot-key-chain.png?fit=max\&auto=format\&n=HhZAgNWhhdRirRzb\&q=85\&s=8513a31b2d85250aceb4e054904fd521) To enable the verification on the DeRoT program integrity and correctness, its measurement will be specified in the governance smart contract. Several steps need to be followed to ensure the smart contract’s governance over the DeRoT program. 1. The DeRoT code is open-source for anyone to do code and security review to ensure the correctness of key management logic and no backdoors; 2. The executable must be produced with reproducible build so the verifier can know it matches the source code; 3. The digest of valid executable is published through on-chain governance; 4. Multiple DeRoT instances run inside TEE. Here we only rely on TEE to provide the measurement over the executable, and ensure it matches the digest on chain. Apart from RA report verification, the core logic of key management in DeRoT is quite compact. It just involves two operations: * the creation of the RootKey; * the derivation of each application key using RootKey and nonce including deployer identity and application measurement. Because of the simple logic, it can use MPC/FHE-based threshold key generation and derivation with no concern about the performance overhead. The public key of RootKey must be published on-chain to enable any party to verify the validity of application keys with it. We will show that such root-key-derivation pattern is important to enable an efficient key rotation in the following section. ### Key Derivation [#p-8432-key-derivation-6](#p-8432-key-derivation-6) The key management of DeRoT follows the *Principle of Least Privilege* that the secrecy known by each entity in the system is strictly limited to what it requires to finish the jobs. We first explain the keys used during program execution, and then discuss the privileges of different entities. ![](https://mintcdn.com/phalanetwork-1606097b/HhZAgNWhhdRirRzb/images/key-derivation-hierarchy.png?fit=max\&auto=format\&n=HhZAgNWhhdRirRzb\&q=85\&s=7eda9f1c80b6e8147d0ec73b21f39794) DeRoT turns the previous hardware-centric key management to application-centric key management. That is, each application has its own keys to seal the states and encrypt the databases, and they can be distributed to different TEE workers to enable the applications to be migrated between them. There are three entities involved in the key management protocol, and they have different knowledge of the keys: * DeRoT, which knows the RootKey and is able to generate any key; * Storage service, which can be the external storage server or service containing the data and states of the application. The storage service holds the StorageKey and can rotate it independently to keep re-encrypting the data. It’s worth noting that the DeRoT can rotate it synchronously if they share the same timestamp; * The TEE worker running the applications. Every key it holds must be distributed from DeRoT. An important feature here is that *every key received by TEE worker is kept in rotation*, so the DeRoT can passively “revoke” the worker’s access to certain program states by not to deliver the newly rotated keys. Once DeRoT rejects to deliver the latest keys, the TEE worker will not able to decrypt the local sealed data or read/write to the external storage. During program execution, the DeRoT keeps delivering the latest AppKeys to functional workers so they can correctly decrypt the program states. Although this makes DeRoT the single point of failure, we want to argue that since the DeRoT only focuses on key management, it is easier to do thorough code review to ensure its security. Further, as discussed above, the DeRoT only listens to the application deployment request from blockchain and is not accessible to others, which greatly reduces the attack interface. The RootKey is only known by DeRoT and a Key Derivation Function (KDF) is used to generate all the other keys. The AppRootKey above is merely a logical entity and can be skipped in the actual key generate. For example, $SealingKey_{epoch}=KDF(RootKey,(deployer\_id,app\_hash,nonce,"seal",epoch))$ ### Key Rotation [#p-8432-key-rotation-7](#p-8432-key-rotation-7) There are two rotation variables above: the RootKey itself and by changing `epoch` during key derivation. The rotation of the RootKey will immediately changes all the keys in the system, while the interval of updating `epoch` can be configured independently for different storage services so they can be rotated in different frequencies based on the requirements. The update of the applications, which will change the `app_hash` above, can be regarded as a special key rotation for the application. #### Forward and Backward Secrecy Ensurance in TEE Workers [#p-8432-forward-and-backward-secrecy-ensurance-in-tee-workers-8](#p-8432-forward-and-backward-secrecy-ensurance-in-tee-workers-8) On one hand, the TEE worker runtime will only keep the latest AppKeys and remove all the used keys from its memory to preserve the forward secrecy; on the other hand, once a worker is considered compromised, the DeRoT will stop delivered the rotated new keys, so the worker will not be able to get further access to the following code and state updates of the program, preserving the backward secrecy. # TEE-Controlled Domain Certificates Source: https://docs.phala.com/dstack/design-documents/tee-controlled-domain-certificates Technical design documents and architecture details for the dstack TEE platform. ## The Problem In this article, we answer a practical question: *How to ensure that the certificate for a specific domain is controlled and can only be controlled by a TEE program (in our case, the DeRoT).* Once we can achieve this, DeRoT, as the root of trust, can then sign more certificates for every application it has verified. This will be an important building block to enable users to seamlessly verify whether an application is actually running within valid TEEs using the existing TLS-based protocols (like HTTPS). The DeRoT-controlled certificate can not only prove its identity under this paradigm, but extend the chain of trust from the blockchain ecosystem to any website. Given the key management protocol mentioned above, the DeRoT becomes the root-of-trust of the whole system as it is responsible for verifying all the TEE hardware and managing the data encryption. Its identity can be verified with the *RootPubKey* published on-chain. If the DeRoT can use this *RootKey* as the certificate’s private key, then it owns a TLS certificate which is verifiable on chain and can issue certificates to valid TEE applications running in verified hardware. Since the DeRoT is running inside TEE, it is not hard to generate a certificate that never leaves TEE. The real challenge here is how to ensure this certificate is tightly bound with a domain and cannot be replaced, given that the DNS servers are centralized services that cannot be controlled by smart contract or TEE application. ## Building Blocks [#p-8526-building-blocks-2](#p-8526-building-blocks-2) Here we introduce two extra building blocks: * Certification Authority Authorization (CAA) in DNS record. This is used to specify which certificate authorities (CAs) are permitted to issue certificates for their domain. It prevents unauthorized issuance of SSL/TLS certificates. With CAA, we can ensure that the DeRoT-owned certificate is the only valid one for its domain. * Certificate Transparency (CT) is an Internet security standard for monitoring and auditing the issuance of digital certificates. Although the CAA ensures the DeRoT ownership over the certificate, the CAA itself, which can be configured in centralized service providers, may be changed. The CT logs can be used for two purposes: 1) to verify whether the CAA is really set to the expected certificate, and 2) to enable users to detect and reject unauthorized CAA modifications. ## System Design [#p-8526-system-design-3](#p-8526-system-design-3) Here we introduce the certificate managing module in the DeRoT serving as a reverse proxy for applications running in the network. It’s worth noting that as a part of DeRoT, it runs in TEE and is also governed by the smart contract. ![](https://mintcdn.com/phalanetwork-1606097b/qg5qPVMhhp3UKpah/images/tee-controlled-domain-certificates.png?fit=max\&auto=format\&n=qg5qPVMhhp3UKpah\&q=85\&s=1f69f90482cdc3c2cc91a8ba72ac46dc) ### DeRoT Certificate Registration [#p-8526-derot-certificate-registration-4](#p-8526-derot-certificate-registration-4) The DeRoT will generate a x.509 certificate using the *RootKey* as the private key. Compared with other TLS certificates, the only difference is that the *RootPubKey* is available on-chain, so any users can verify that this certificate is really owned by DeRoT. This certificate is sent to CA (e.g. Let’s Encrypt) for signing, then a DNS CAA record is registered. In the example above, the CAA record means “only [letsencrypt.org](http://letsencrypt.org/) is allowed to issue certificates for [derot.com](http://derot.com/)”. We further utilize CAA records to restrict the authentication methods, as some of them are not secure. For example, when verifying with HTTPS, Let’s Encrypt only requires you to place a specific text file at **`http:///verify.txt`** to confirm domain ownership. However, Let’s Encrypt cannot verify whether the endpoint is within a TEE. To address this, we limit the authentication method to API access only, which can be fully controlled by a TEE. This ensures that there is no possibility of issuing the certificate to an incorrect target. ### TEE App Registration [#p-8526-tee-app-registration-5](#p-8526-tee-app-registration-5) Although a senior user can request to verify the Remote Attestation report from a TEE app directly, most of the users could delegate the verification to DeRoT by verifying its certificate. To get reverse proxy from DeRoT, a TEE app needs to register itself to DeRoT, during which DeRoT will do the RA verification on it to ensure the DeRoT policy is followed. ### Protection against Unauthorized Certificate Changes [#p-8526-protection-against-unauthorized-certificate-changes-6](#p-8526-protection-against-unauthorized-certificate-changes-6) Since the DNS servers are centralized services which cannot be controlled by smart contracts, there is risk that the attackers will change the DNS record to break the limitation on the certificate owner. Although we cannot technically prevent this, we can monitor the unexpected DNS record updates and notify the clients to avoid trusting invalid certificates. # Whitepaper Source: https://docs.phala.com/dstack/design-documents/whitepaper Technical design documents and architecture details for the dstack TEE platform. ## dstack Whitepaper ## Call for Next Generation Zero Trust Platform The Web3 ecosystem represents a paradigm shift in digital trust models, fundamentally transforming the relationship between users and application developers. Unlike traditional systems, Web3 empowers users with unprecedented control over their data through the principle of “Code is Law” — once deployed, code operates autonomously beyond external control. This transformation demands robust execution platforms that maintain confidentiality and integrity without relying on centralized trust authorities. ![](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/dstack-wp1.png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=19c19acba986b2a0c49d4eac6571eb73) The evolution of trust models from Web2 to Web3, highlighting the shift from centralized control to decentralized governance and execution. The contrast between Web2 and Web3 architectures in Figure 1 illustrates this fundamental shift.\ In Web2 systems, developers maintain complete control through proprietary applications and centralized servers, retaining administrative privileges to access and modify user data at will. Web3’s smart contracts, however, represent the first significant advancement toward true trustlessness by executing programs on decentralized platforms (blockchains). Once deployed, administrators cannot affect program execution, and lifecycle management (e.g., code updates) follows coded agreements through democratic governance mechanisms like multi-signature wallets and Decentralized Autonomous Organizations (DAOs). This evolving trust model extends beyond basic applications to mission-critical scenarios such as AI model training, where data providers and model developers often have competing interests, and autonomous AI agents designed to operate independently of human intervention. In these contexts, Zero Trust platforms become essential to host applications and enforce verification mechanisms that appropriately constrain developer authority. A Zero Trust platform must enforce the following key principles: * **Code is Law**: This manifests in two dimensions: (1) the application logic, once deployed, cannot be changed unexpectedly; and (2) the lifecycle management of code — including deployment, upgrades, and deletion — follows predefined governance rules. * **Censorship Resistance**: User data remains beyond the control of any single entity, with data\ availability protected against Denial-of-Service attacks. * **Full Chain-of-Trust**: When users interact with applications on a Zero Trust platform, they\ must be able to verify all aspects of that application, including network setup, application identity and code logic, underlying hardware, and execution environment. * **Assume Breach**: The platform operates under the assumption that compromises will occur,\ implementing mechanisms for damage containment, rapid recovery, and minimization of data\ exposure during security incidents. ## From TEE to Zero Trust Platform Confidential Computing, particularly through Trusted Execution Environments (TEEs), has emerged as a promising foundation for extending blockchain capabilities to support complex computational tasks with confidentiality guarantees. Recent advances in VM-level TEE solutions, including Intel TDX and AMD SEV, have demonstrated substantial performance improvements and developer-friendly interfaces, making them compelling candidates for Web3 deployment. The integration of GPUs within TEEs now enables verifiable execution of both Large Language Models and AI agents, providing cryptographic guarantees of computational integrity. However, there exists a significant gap between raw TEE technology and the requirements of a true Zero Trust platform. Current TEE implementations face several critical limitations when applied to Web3 contexts: * Security Reliability: Recent vulnerability discoveries in TEE systems have raised significant concerns about their effectiveness as trust anchors. The persistence of side-channel attacks and micro-architectural vulnerabilities undermines confidence in TEE security guarantees, particularly for high-value Web3 applications where a single compromise could lead to catastrophic data exposure. * Censorship Vulnerability: Conventional TEE encryption schemas bind encryption keys to specific hardware instances, creating single points of failure that contradict Web3’s requirement\ for censorship resistance. This architectural limitation means that data availability cannot be\ guaranteed if specific hardware instances are compromised or become unavailable. * Vendor Dependencies: Current trust models heavily rely on centralized hardware manufacturers and verification processes, introducing risks of vendor lock-in and potential censorship vectors. This centralization contradicts Web3’s core principles of decentralization and trustlessness, creating systemic risks for the ecosystem. * Incomplete Verifiability: While TEEs provide Remote Attestation capabilities to verify application and hardware identity, they fail to deliver the comprehensive chain of trust required in Zero Trust environments. Users need guarantees that programs process their data as expected and cannot be modified without proper authorization — capabilities beyond current attestation mechanisms. To bridge this gap between raw TEE technology and Zero Trust requirements, we present [dstack](https://github.com/Dstack-TEE/dstack),\ a comprehensive framework for confidential containers that introduces three key innovations: * **Portable Confidential Container**: Our architecture enables seamless migration of confidential workloads across different TEE instances and hardware vendors, significantly reducing vendor lock-in risks while maintaining robust security guarantees. This innovation directly addresses the censorship vulnerability and vendor dependency limitations by providing hardware abstraction and state continuity across heterogeneous TEE environments. * **Decentralized Code Management**: We implement a comprehensive governance framework\ that leverages smart contracts for transparent and decentralized management of TEE applications. This system ensures verifiable deployment and upgrade processes, enforcing the “Code is Law” principle by binding application lifecycles to on-chain governance decisions. This innovation addresses the incomplete verifiability limitation by creating an immutable audit trail of application changes. * **Verifiable Domain Management**: Our novel approach to certificate management ensures that\ confidential containers can exclusively control domains and provide native HTTPS support to\ TEE applications without relying on centralized authorities. This system serves as a middleware between TEE applications and existing TLS-based networks, enabling users to establish end-to-end encrypted channels to TEE applications without modifications to client software. ## dstack Components ![](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/dstack-wp2.png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=d587e8bb27b68aa52c3239889c6848cb) The architecture of dstack, including dstack-os, dstack-kms and dstack-gateway. These innovations are implemented through a cohesive system architecture comprising three core components: * *dstack-os*: A hardware abstraction layer with a minimized operating system image that eliminates differences in underlying TEE hardware while reducing the attack surface. This component provides a consistent, secure runtime environment across diverse TEE implementations. * *dstack-kms*: A blockchain-controlled key management service that replaces hardware-based encryption schemas with an independent service for generating and managing secret keys. This component enables secure data migration across TEE instances and supports key rotation to provide forward and backward data secrecy, mitigating the impact of potential TEE compromises. * *dstack-ingress* and *dstack-gateway*: Complementary systems providing TEE-controlled domain management through different approaches — dstack-ingress enables applications to specify custom domains with minimal integration requirements, while dstack-gateway offers pre-registered wildcard domains requiring no application code changes. By addressing the critical limitations of current TEE implementations, dstack establishes a comprehensive framework that transforms raw TEE technology into a true Zero Trust platform aligned with Web3’s fundamental principles. Our approach not only enhances the security and reliability of confidential computing but also provides a practical path toward truly decentralized, censorship-resistant infrastructure for next-generation applications. The remainder of this article details the technical design of dstack, evaluates its security characteristics, and demonstrates how our innovations collectively create a Zero Trust platform\ that maintains the performance advantages of VM-level TEE solutions while addressing their inherent limitations in Web3 contexts. ## System Design ### Portable Confidential Container Containerization has revolutionized cloud-native application deployment by providing unparalleled portability and scalability through effective data separation. These capabilities are particularly critical for Trusted Execution Environment (TEE) applications, as they directly address the inherent limitations above: * **Security Reliability**: Containerized applications can be seamlessly migrated from compromised TEE hardware to secure instances, preserving code integrity. Combined with our secure data migration mechanism that ensures both forward and backward secrecy, this approach significantly mitigates privacy leakage risks even when individual TEE instances are compromised. * **Censorship Resistance**: The architecture’s inherent scalability provides robust defense against Denial-of-Service attacks. Additionally, by decoupling data storage from execution environments, established data availability solutions can be readily integrated to ensure persistent access to application data. * **Vendor Independence**: Our hardware abstraction layer enables confidential containers to\ operate across diverse TEE hardware platforms without modification, eliminating vendor lock-in while facilitating rapid adoption of emerging TEE technologies as they become available. However, implementing truly portable confidential containers presents substantial technical challenges that differentiate them from conventional containerization. Two fundamental obstacles must be overcome: * First, existing TEE implementations generate data sealing keys derived from hardware-bound root keys unique to each TEE instance. This architectural design creates an inherent barrier to portability — data encrypted by one TEE instance cannot be decrypted by any other, even when running identical application code. Prior research has largely circumvented this limitation by restricting TEEs to stateless applications, but this approach severely constrains their utility in complex real-world scenarios. * Second, TEE implementations from different vendors impose disparate specifications for deployable programs. This fragmentation forces developers to create and maintain multiple artifacts across platforms, each requiring separate (and expensive) code reviews to verify functional equivalence — a process that undermines the trust guarantees central to Web3 applications. To address these challenges comprehensively, we introduce two complementary components: dstack-kms and dstack-os. #### dstack-kms: Blockchain-Controlled Secret Derivation dstack-kms is a secret derivation service that fundamentally transforms how encryption keys are managed in confidential computing environments. Its primary function is to generate a unique and stable secret (the *Root Key*) for each application based on its code and configurations. This Root Key serves as the foundation for deriving additional application-specific secrets used for data encryption and verifiable random number generation. Unlike hardware-based encryption approaches, dstack-kms deliberately decouples key generation from specific TEE hardware instances. This architectural decision enables the critical capability of encrypted data migration between different TEE instances, with decryption possible after proper authorization. This feature is essential for achieving true censorship resistance. Given its position as the root-of-trust for the entire system, the verifiability and availability of\ dstack-kms are paramount. Unlike previous approaches that assume TEE infallibility, our threat\ model explicitly acknowledges that ***TEEs can be compromised***. To address this reality, dstack-kms implements comprehensive key rotation capabilities that provide both backward and forward secrecy for application data. This ensures that even if a specific TEE hardware instance is compromised, applications can be migrated with minimal data exposure. ![](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/dstack-wp3.png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=2230b6cdc031c40525f04186989d8233) The key derivation hierarchy of Intel SGX illustrates how conventional TEE implementations bind encryption keys to hardware. To understand the limitations of conventional approaches, this figure illustrates the key derivation hierarchy in Intel SGX. This design uses a hardware-bound key to both identify the TEE instance (for Remote Attestation) and generate encryption keys for data sealing. While this approach effectively establishes hardware identity, it fundamentally undermines censorship resistance: * The root key cannot be updated, meaning a compromised TEE with a leaked root key remains\ permanently vulnerable even after patching the underlying vulnerability. * Encrypted data becomes intrinsically bound to specific TEE hardware instances, creating single points of failure that contradict Web3’s censorship resistance requirements. Our dstack-kms addresses these limitations by delegating secret generation to an independent\ service that ensures encrypted data remains portable across TEE instances. ![](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/dstack-wp4.png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=14905784784b8c2760c0a87f4f2b2007) The architecture of dstack-kms combines on-chain governance through smart contracts with an off-chain P2P network of secret derivation service nodes. This design ensures both verifiability and resilience against compromise. As illustrated in figure above, dstack-kms consists of an on-chain governance smart contract coupled with an off-chain peer-to-peer network where the actual secret derivation service operates. Every off-chain node here runs a light client to continuously synchronize with the governance contract. To ensure comprehensive verifiability of the dstack-kms program’s integrity and correctness, we implement a multi-stage verification process: 1. The dstack-kms codebase is fully open-sourced, enabling thorough code and security reviews to verify key management logic and ensure the absence of backdoors. 2. Executable binaries are produced with Github Actions, allowing verifiers to confirm that the\ runtime code matches the reviewed source code. 3. The cryptographic digest of valid executables is published through the governance smart contract, creating an immutable reference for verification. 4. Each service node operates within its own TEE instance. Critically, we rely on the TEE solely for measuring the executable and ensuring it matches the on-chain digest — not for the fundamental security of the key management process. This verification framework ensures that dstack-kms remains trustworthy to any third-party verifier while avoiding dependency on the absolute security of any single TEE instance. The core logic of each dstack-kms service node is intentionally minimalist, focusing exclusively on the generation and secure distribution of the root key, along with deriving encryption keys for TEE applications. This simplicity enables the implementation of Multi-Party Computation (MPC) based threshold key generation and derivation without concerning performance overhead. We have developed two complementary implementations: * **Simple Duplication**: The first node in the P2P network generates a cryptographically secure\ random number as the root key, then shares it with other nodes after verifying their attestation reports. All nodes maintain identical copies of the root key and derive consistent encryption keys for applications. This approach maximizes availability — as long as at least one node remains operational, the root key can be recovered. * **MPC-Based Key Generation**: While simple duplication provides robust availability, it creates vulnerability to single-node compromises. Our MPC implementation uses Shamir’s Secret\ Sharing scheme to distribute the root key across multiple nodes, ensuring that compromising\ any individual node (or even up to *t-1* nodes, where *t* is the configured threshold) does not\ expose the root key. This approach also enables advanced features like key rotation without\ requiring application reconfiguration. **Key Derivation** dstack-kms implements a comprehensive key derivation framework to generate application-specific keys from the root key: * **Application CA Key**: Derived from the root CA key using the application’s unique identifier\ registered on-chain. * **Disk Encryption Key**: Derived using a combination of the application identifier and instance\ identifier, enabling secure storage with portability. * **Environment Encryption Key**: Derived using the application identifier alone, allowing secure\ environment variable management across instances. * **ECDSA Key**: Derived from the root ECDSA key, providing applications with consistent cryptographic identity for signing operations. Each derived key maintains cryptographic isolation while ensuring consistency across different TEE instances running the same application. **Key Rotation** A critical security feature of dstack-kms is its support for key rotation, which significantly limits the exposure window during potential attacks while ensuring both forward and backward secrecy for sealed data. Key rotation procedures are initiated exclusively through the governance smart\ contract, ensuring transparency and auditability. We discuss two distinct rotation mechanisms: * **Root Key Share Rotation**: Our MPC-based implementation enables rotation of individual\ key shares without modifying the root key itself. This process enhances root key security by\ regularly updating the distribution mechanism while remaining transparent to applications, as\ all derived application keys remain unchanged. * **Root Key Rotation**: In scenarios where the root key may have been compromised, we support\ complete root key rotation. This process generates an entirely new root key and implements a\ controlled handover period during which both old and new keys remain valid. This transition\ window allows applications to re-encrypt their data with keys derived from the new root key\ before the old root key is permanently destroyed, minimizing service disruption while enhancing security. Through these mechanisms, dstack-kms provides the foundation for truly portable confidential containers by decoupling encryption from hardware dependencies while maintaining robust security guarantees. #### dstack-os: Hardware Abstraction Layer dstack-os provides a comprehensive hardware abstraction layer with a minimized operating system image that bridges the gap between application containers and VM-level TEE implementations. This layer enables applications to deploy across diverse TEE environments without code modifications while maintaining security integrity. As a shared component across all TEE applications, dstack-os must be intrinsically secure and verifiable, with no administrative backdoors that could compromise program code or user data. VM-level TEE solutions typically require developers to provide complete system images encompassing bootloader, kernel, operating system, and application components. This requirement not only increases development complexity but also introduces potential security vulnerabilities through misconfigured system components. A secure and properly configured operating system environment fundamentally determines the security baseline for all TEE applications built upon it. ![](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/dstack-wp5.png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=1eda4cbbc488ded83c366768dbd0a7bc) The architecture of dstack-os establishes a secure and verifiable startup chain from TEE hardware through to user applications. This figure illustrates how dstack-os establishes a secure and verifiable startup chain from the TEE hardware foundation through to user-provided container images. Our modular design ensures that the majority of the system can be reused across different TEE hardware implementations, substantially reducing the effort required for code review and security auditing. Combined with reproducible build processes, this approach enables comprehensive verification of dstack-os with minimal overhead while supporting multiple TEE hardware platforms. Using Intel TDX as an exemplar (with similar procedures applicable to other TEE implementations like AMD SEV), dstack-os consists of the following components, presented in boot sequence\ order. During this process, each component measures the next one and records these measurements in hardware registers, which are ultimately incorporated into the TEE attestation report: * **Hypervisor**: When application deployment initiates, the underlying hypervisor (the TDX module) loads the Open Virtual Machine Firmware (OVMF), enabling UEFI support for confidential virtual machines. The TDX module measures the OVMF code and records its cryptographic digest in the MRTD register, with the hypervisor’s integrity guaranteed by the TEE hardware\ itself. * **Open Virtual Machine Firmware (OVMF)**: The OVMF configures virtual machine hardware specifications (CPU, memory, and device configurations) and records the configuration measurement to the RTMR0 register. It then loads the Linux kernel and records the kernel\ image measurement to the RTMR1 register. * **Kernel**: The kernel first loads an initial ramdisk (initrd) — a temporary in-memory filesystem\ containing minimal command-line tools and disk encryption libraries. The initrd mounts the\ root filesystem and then the kernel will call the OVMF to record a full measurement (including\ kernel, initrd and RootFs to load) in the RTMR2 register. * **Root Filesystem**: The root filesystem (RootFs) is a read-only environment containing essential system libraries and tools. It manages the entire lifecycle of deployed applications, measuring application images along with their associated key management system and storing these measurements in the RTMR3 register. The RootFs serves two primary functions: (1) providing the runtime environment for user-level container images, and (2) managing application data encryption. It interfaces with dstack-kms to acquire encryption secrets and implements Linux Unified Key Setup (LUKS) to encrypt application data in isolated volumes. Its data integrity is ensured through dm-verity, a Merkle-tree-based block-level verification tool. Finally, the RootFs configures network ingress for the application and initiates execution. Rather than adapting existing system images, we built dstack-os from scratch to ensure only essential components are included in both the initrd and RootFs. Generally, dstack-os includes only basic utilities (busybox), filesystem support, and container runtime components. By implementing Docker support while delegating orchestration to the application level, we maintain a minimal base image footprint. To ensure comprehensive verifiability, dstack-os is fully open-sourced and supports reproducible\ builds, allowing anyone to review the code and generate identical artifacts for verification. This\ approach provides significant benefits for applications requiring security reviews, as evaluators need only review the application code rather than the entire system image. **Data Backup and Defense against Rollback Attacks** A critical challenge in confidential computing is ensuring data durability and integrity, particularly against rollback attacks where adversaries attempt to revert applications to previous states to bypass security checks or reuse expired secrets. Our architecture provides comprehensive secure data backup support and implements robust anti-rollback mechanisms that application developers can integrate: * **Secure Backup**: Application data is encrypted using keys derived from dstack-kms and can be backed up to external storage providers. Since encryption keys are not bound to specific TEE instances, data can be restored on any authorized TEE, supporting true portability and disaster recovery. * **Monotonic Counters**: To prevent rollback attacks, developers can implement monotonic counters that increment with each critical data update, incorporating the counter value into the encrypted data. During restoration, applications verify that the counter value equals or exceeds the last known value, preventing replay of outdated snapshots. By combining these techniques, dstack ensures both the recoverability and integrity of confidential data across portable container migrations and backup scenarios. Together, dstack-kms and dstack-os provide the foundational infrastructure for truly portable confidential containers that maintain security and integrity across heterogeneous TEE environments while eliminating vendor lock-in and supporting comprehensive verifiability. ### Decentralized Code Management A core principle of Zero Trust platforms is the enforcement of “Code is Law”, ensuring that application code operates as intended without unexpected modifications. While TEE hardware provides code integrity guarantees during execution, it cannot independently prevent administrators from deploying malicious code or making unauthorized modifications. Conversely, smart contracts have established robust methodologies for implementing programmable governance over code lifecycle management — such as multi-signature requirements that prevent single-actor manipulation. Our decentralized code management framework bridges these two worlds by placing TEE application governance under smart contract control, creating a transparent and auditable system for application deployment and updates that aligns with Web3 principles. ![](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/dstack-wp6.png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=138074947172484bc590adef882fe2ea) The architecture of decentralized code management integrates on-chain governance contracts with off-chain TEE through dstack-kms. Our architecture consists of two complementary components: on-chain governance smart contracts and off-chain TEE execution environments connected through dstack-kms. This design establishes the on-chain contracts as the definitive root-of-trust for the entire system. Every\ operation — from initial deployment to code updates — must first be initiated and authorized through the governance contracts before off-chain TEE instances can execute these operations. The governance framework implements a two-tier structure: * **KmsAuth Contract**: Serves as the global authority controlling dstack-kms operations. This\ contract maintains the registry of authorized dstack-os images, applications and their governance parameters, enforcing system-wide policies for TEE deployment. By controlling whether dstack-kms shares application secrets with specific TEE instances, the KmsAuth contract effectively determines whether applications can decrypt their data, thus controlling their complete lifecycle. * **AppAuth Contracts**: Individual governance contracts deployed for each application that define application-specific management rules. These contracts specify permissible code versions (through cryptographic hashes), authorized TEE instance identities, and upgrade approval requirements. This modular approach enables customized governance models ranging from traditional multi-signature schemes to complex DAO voting mechanisms, allowing each application to implement governance appropriate to its requirements. The enforcement mechanism operates through dstack-kms, which will only provide application\ secrets to TEE instances running code versions explicitly authorized by the governance contracts. This creates a cryptographically enforced governance system where unauthorized code versions cannot access application data, regardless of administrative privileges. To illustrate this mechanism, consider a code update process for an application using a multi-\ signature AppAuth contract: 1. Developers publish the new code version and submit its cryptographic hash to the AppAuth\ contract. 2. The contract initiates the approval process, requiring signatures from designated key holders\ (e.g., core developers, security auditors, and community representatives). 3. Each signature is recorded on-chain, creating an immutable audit trail of the approval process. 4. Once the required signature threshold is reached, the AppAuth contract updates its registry of authorized code versions. 5. The KmsAuth contract calls the corresponding AppAuth contract, and updates its authorization records accordingly. 6. dstack-kms, which continuously synchronizes with the KmsAuth contract, begins providing application secrets to TEE instances running the newly approved code version. 7. TEE instances can now deploy the new code with full access to encrypted application data. This process ensures that every code change follows predefined governance rules with complete transparency. The on-chain approval records create an immutable audit trail that allows users to verify the entire history of application changes, while the cryptographic enforcement through dstack-kms guarantees that only properly authorized code can access application data. By combining the code integrity guarantees of TEEs with the transparent governance capabilities\ of smart contracts, our decentralized code management framework ensures that applications truly embody the ”Code is Law” principle. Every aspect of the application lifecycle — from initial deployment to version updates and potential retirement — follows predefined, transparent rules that cannot be circumvented by any single entity, including the platform operators themselves. ### Verifiable Domain Management A complete Zero Trust platform must enable seamless verification for users across both Web3 and traditional Web2 environments. Our Verifiable Domain Management system completes the chain-of-trust by allowing standard Web browsers to cryptographically verify TEE applications without requiring any client-side modifications or specialized knowledge. This capability is critical for mainstream adoption, as it allows users to interact with confidential\ applications using familiar tools while maintaining the same security guarantees provided by the underlying TEE infrastructure. We implement this through two complementary components — dstack-ingress and dstack-gateway — both leveraging our novel **Zero Trust TLS** (ZT-TLS) protocol. The fundamental innovation in ZT-TLS is establishing cryptographic proof that a specific TLS\ certificate (and therefore a domain) is exclusively controlled by a verified TEE application. This\ creates a verification chain extending from the blockchain to standard HTTPS connections, enabling users to confirm application authenticity through familiar security indicators in their browsers. ![](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/dstack-wp7.png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=24d06259b9bc1ea648ad8da2214c9787) The Zero Trust TLS architecture establishes a cryptographically verifiable connection between standard web browsers and TEE applications through blockchain-anchored certificate management. #### Zero Trust TLS Protocol The ZT-TLS protocol addresses a critical challenge: how to cryptographically bind a domain to a\ specific TEE application in a way that prevents unauthorized certificate issuance or domain hijacking. Our solution integrates three key components: * **TEE-Generated Certificates**: The TEE application (specifically dstack-gateway) setups all\ the information for the certificate, including Automated Certificate Management Environment\ (ACME), the secret key and Certificate Signing Request (CSR), and request the CA (e.g. letsencrypt) to issue its TLS certificate using application secrets derived from dstack-kms. This ensures the private key never exists outside the TEE environment and creates a cryptographic link between the on-chain governance and the TLS certificate. * **Certificate Authority Authorization (CAA)**: We leverage DNS CAA records to restrict\ that only TEE-controlled ACME is valid, and which certificate authorities can issue certificates\ for managed domains. By configuring CAA records to only authorize certificates from specific\ issuers (which verify TEE attestation), we prevent unauthorized certificate issuance through\ alternative validation methods. * **Certificate Transparency (CT) Monitoring**: To protect against unauthorized DNS record\ modifications, we implement continuous monitoring of Certificate Transparency logs. This allows detection of any unauthorized certificates and provides an immutable audit trail of certificate issuance history. It is worth noting that such monitoring service can be implemented by anyone to be truly decentralized. #### Implementation Components We provide two complementary implementations to accommodate different application requirements: * **dstack-gateway**: A fully managed reverse proxy running within a TEE that provides immediate domain verification with zero application code changes. Applications register with dstack-gateway through a simple API call, during which dstack-gateway verifies the application’s remote attestation report. Once verified, applications receive a subdomain under a pre-registered wildcard domain (e.g., [app-id.dstack.com](http://app-id.dstack.com/)), with all TLS termination and certificate management handled automatically. * **dstack-ingress**: A more flexible solution for applications requiring custom domain names.\ dstack-ingress provides libraries and services that enable applications to manage their own TLS certificates while maintaining the same verification guarantees. This approach requires minimal integration work while supporting application-specific domain requirements. When the customized domains are enabled, our gateway will fallback to TLS passthrough mode, where the TLS connection is directly established between the client and the application. Both implementations ensure that certificates are cryptographically bound to verified TEE environments, with the verification chain extending from the blockchain governance contracts through to the TLS certificates presented to users’ browsers. #### Security Guarantees and Protections Our Verifiable Domain Management system provides several critical security guarantees: * **Certificate Provenance Verification**: Users can verify that the TLS certificate presented by\ an application was issued to a legitimate TEE environment with the ZT-TLS protocol above. * **Domain Binding Integrity**: The combination of CAA records and Certificate Transparency\ monitoring ensures that domains remain bound to their designated TEE applications, preventing unauthorized certificate issuance. * **Tamper-Evident Certificate Changes**: Any unauthorized attempts to modify domain configurations or issue alternative certificates are detected through Certificate Transparency monitoring, with alerts propagated to clients. While we cannot technically prevent all attacks against centralized DNS infrastructure, our multi-layered approach creates a tamper-evident system where unauthorized changes are quickly detected and rejected by client verification processes. This approach aligns with the ”Assume Breach” principle by implementing defense-in-depth strategies that maintain security even when individual components are compromised. By extending the verification chain from blockchain governance through TEE attestation to standard TLS certificates, our Verifiable Domain Management system enables seamless integration of Zero Trust applications into existing web infrastructure. This creates a practical path for mainstream adoption without requiring specialized knowledge or tools from end users, while maintaining the comprehensive security guarantees that define true Zero Trust platforms. # FAQs Source: https://docs.phala.com/dstack/faqs Deploy confidential applications with dstack — a TEE-based infrastructure platform. ## Does dstack support GCP / Azure dstack is open for PRs to add that support. Currently it focuses on bare metal because it offers the most fine-grained control and access to vanilla TDX. ## How does KMS key generation work and how can it be modified? The key generation logic is implemented in the onboard service:\ Reference: [https://github.com/Dstack-TEE/dstack/blob/next/dstack/kms/src/onboard\_service.rs](https://github.com/Dstack-TEE/dstack/blob/next/dstack/kms/src/onboard_service.rs) ## How does on-chain KMS work and how can I customize its governance? The KMS contract allows for customizable ownership and governance: * During deployment, you can specify an owner * After deployment, ownership can be transferred using transferOwnership function\ Reference: [https://github.com/Dstack-TEE/dstack/blob/next/dstack/kms/auth-eth/contracts/DstackKms.sol#L72](https://github.com/Dstack-TEE/dstack/blob/next/dstack/kms/auth-eth/contracts/DstackKms.sol#L72) ## Where can I find KMS deployment instructions? Complete deployment documentation is available here: Reference: [https://github.com/Dstack-TEE/dstack/blob/master/docs/deployment.md](https://github.com/Dstack-TEE/dstack/blob/master/docs/deployment.md) ## How does the current data encryption system work? The CVM data disk is a LUKS2 volume encrypted with `aes-xts-plain64`. The guest creates it on first boot and unlocks it on every boot after that. The key comes from KMS, which releases it only after the CVM's attestation passes the app's on-chain authorization. KMS derives it from its root key over the app ID and instance ID, so each instance gets a distinct key that exists only inside the CVM. The host holds ciphertext and never sees the key. LUKS encrypts the disk but does not authenticate it, so detecting a modified block is the filesystem's job. The default `zfs` checksums every block and fails the read. `ext4` checksums metadata but not file data. Reference: [`dstack-util/src/system_setup.rs`](https://github.com/Dstack-TEE/dstack/blob/next/dstack/dstack-util/src/system_setup.rs) ## Where is the deployment function located in the Dstack-TEE codebase, and can it be integrated with custom tools? The deployment logic for Dstack-TEE is part of its Rust-based implementation, there are multiple services involved in the deployment pipeline. The [Dstack-TEE GitHub repository](https://github.com/Dstack-TEE/dstack) contains the core services (e.g., vmm, gateway, kms, meta-dstack). ## Can I run a Docker image directly in a TEE without setting up all dstack components? Yes, you can run a Docker image in a TEE using the dstack SDK without setting up all components, but with limitations. The SDK provides a base VM image that runs a minimal VM containing your Docker container. The essential components are kms (key management service) and vmm (TEE runtime), which must be included. Optional components like dstack-gateway (for TLS support) can be skipped if you don’t need features like encrypted communication. Configure the SDK with your Docker image and the required components as per the documentation. # Getting Started Source: https://docs.phala.com/dstack/getting-started Set up and deploy your first confidential application using dstack TEE infrastructure. > [!NOTE] > > **WARNING** > > **This tutorial assumes your have access to a compatible Intel TDX Server ready to be configured with dstack. Check the** [**Hardware Requirements**](/dstack/hardware-requirements) **for more information or skip setting everything up from scratch and** [**Sign-up for Phala Cloud Account**](/phala-cloud/getting-started/sign-up-for-cloud-account)**.** > [!NOTE] > > For the latest information, please refer to the [dstack README](https://github.com/Dstack-TEE/dstack/blob/next/README.md). ## dstack dstack is a **developer friendly** and **security first** SDK to simplify the deployment of arbitrary Docker-based apps into TEE. Main features: * 🔒 Deploy containerized apps securely in TEE in minutes * 🛠️ Use familiar tools - just write a docker-compose.yaml * 🔑 Safely manage secrets and sensitive data * 📡 Expose services via built-in TLS termination dstack is community driven. Open sourced and built by [Kevin Wang](https://github.com/kvinwang) and many others from [Phala Network](https://github.com/Phala-Network), inspired by [Andrew Miller](https://github.com/amiller) (Flashbots & Teleport), and contributed by [Nethermind](https://github.com/NethermindEth/nethermind) and [many others](#contributors). ## Overview Components in dstack: * `dstack-vmm`: A service running in bare TDX host to manage CVMs * `dstack-gateway`: A reverse proxy to forward TLS connections to CVMs * `dstack-kms`: A KMS server to generate keys for CVMs * `dstack-guest-agent`: A service running in CVM to serve containers' key derivation and attestation requests * `meta-dstack`: A Yocto meta layer to build CVM guest images The overall architecture is shown below: ## Directory structure ``` dstack/ kms/ A prototype KMS server guest-agent/ A service running in CVM to serve containers' key derivation and attestation requests. dstack-util/ A CLI tool in the guest setting up the system, getting TDX quote, extending RTMR, generating cert for RA-TLS, etc. vmm/ A service running in bare TDX host to manage CVMs gateway/ A reverse proxy to forward TLS connections to CVMs certbot/ A tool to automatically obtain and renew TLS certificates for dstack-gateway ra-rpc/ RA-TLS support for pRPC ra-tls/ RA-TLS support library tdx-attest/ Guest library for getting TDX quote and extending RTMR ``` ## Build and play locally ### Prerequisites * A bare metal TDX server setup following [canonical/tdx](https://github.com/canonical/tdx) * Public IPv4 address assigned to the machine * At least 16GB RAM, 100GB free disk space. * A domain with DNS access if you want to set up `dstack-gateway` for Zero Trust HTTPS ### Install dependencies ```bash theme={"system"} # for Ubuntu 24.04 sudo apt install -y build-essential chrpath diffstat lz4 wireguard-tools xorriso # install rust curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` ### Build and run ```bash theme={"system"} git clone https://github.com/Dstack-TEE/meta-dstack.git --recursive cd meta-dstack/ mkdir build cd build ../build.sh hostcfg # This outputs the following message: # Config file ../build-config.sh created, please edit it to configure the build vim ./build-config.sh ``` Review and customize the `build-config.sh` configuration file according to your environment requirements. The file contains network ports, domain settings, and other important parameters. Once configured, run the build script again to generate the necessary artifacts: ```bash theme={"system"} ../build.sh hostcfg # If everything is okay, you should see the built artifacts in the `build` directory. $ ls certs images dstack-kms kms.toml run dstack-vmm vmm.toml dstack-gateway gateway.toml ``` ### Download guest image or build guest image from source ```bash theme={"system"} # This will download the guest image from the release page. ../build.sh dl 0.5.2 ``` Or build guest image from source: ```bash theme={"system"} # This will build the guest image from source using the yocto meta layer. This will take a while. ../build.sh guest ``` Now you can open 3 terminals to start the components: 1. Run `./dstack-kms -c kms.toml` 2. Run `sudo ./dstack-gateway -c gateway.toml` 3. Run `./dstack-vmm -c vmm.toml` ### Deploy an App Open the dstack-vmm webpage [http://localhost:9080](http://localhost:9080)(change the port according to your configuration) on your local machine to deploy a `docker-compose.yaml` file: ![dstack-vmm web interface](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/dstack-vmm.png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=2a83849f3900de30058c4d62c2ad7b9f) dstack-vmm web interface After the container deployed, it should need some time to start the CVM and the containers. Time would be vary depending on your workload. * Click the \[Logs] button to see the logs of the CVM, you can see if the container is finished starting there. * Once the container is running, you can click the \[Dashboard] button to see some information of the container. And the logs of the containers can be seen in the \[Dashboard] page. ![dstack guest agent status](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/dstack-guest-agent.png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=ddec07000b35cd847189e0e035a7aef3) dstack guest agent status * You can open dstack-gateway's dashboard at [https://localhost:9070](https://localhost:9070) to see the CVM's wireguard ip address, as shown below: ![dstack gateway dashboard](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/dstack-gateway.png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=817a522da712165b1d345423d47647df) dstack gateway dashboard ### Pass Secrets to Apps When deploying a new App, you can pass private data via Encrypted Environment Variables. These variables can be referenced in the docker-compose.yaml file as shown below: ![dstack secret management](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/dstack-secret.png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=c4253a999583c3a5148a2e7d01f64ca0) dstack secret management The environment variables will be encrypted in the client-side and decrypted in the CVM before being passed to the containers. ### Access the App Once the app is deployed and listening on an HTTP port, you can access the HTTP service via tproxy's public domain. The ingress mapping rules are: * `[s].` maps to port `80` or `443` if with `s` in the CVM. * `-[s].` maps to port `` in the CVM. For example, `3327603e03f5bd1f830812ca4a789277fc31f577-8080.app.kvin.wang` maps to port `8080` in the CVM. Where the `` can be either the app id or the instance id. If the app id is used, one of the instances will be selected by the load balancer.\ If the `id-port` part ends with `s`, it means the TLS connection will be passthrough to the app rather than terminating at dstack-gateway. You can also ssh into the CVM to inspect more information, if your deployment uses the image `dstack-x.x.x-dev`: ```bash theme={"system"} # The IP address of the CVM can be found in the gateway dashboard. ssh root@10.0.3.2 ``` ### Getting TDX quote in docker container To get a TDX quote within app containers: 1. Mount `/var/run/dstack.sock` to the target container in `docker-compose.yaml` ```yaml theme={"system"} version: "3" services: nginx: image: nginx:latest volumes: - /var/run/dstack.sock:/var/run/dstack.sock ports: - "8080:80" restart: always ``` 2. Execute the quote request command in the container. ```bash theme={"system"} # The report_data must be max 64 bytes. For larger data, hash it first. # Example using a hash of the data: curl -X POST --unix-socket /var/run/dstack.sock \ -H 'Content-Type: application/json' \ -d '{"reportData": "0x1234deadbeef00000000000000000000000000000000000000000000000000"}' \ http://dstack/GetQuote | jq . ``` For automated verification of your application's attestation, see the [Trust Center Technical Documentation](/dstack/trust-center-technical) which explains how to use these quotes with the Trust Center verification platform. ### Container logs Container logs can be obtained from the CVM's `dashboard` page or by curl: ```bash theme={"system"} curl 'http://.app.kvin.wang:9090/logs/?since=0&until=0&follow=true&text=true×tamps=true&bare=true' ``` Replace `` and `` with actual values. Available parameters: * since=0: Starting Unix timestamp for log retrieval * until=0: Ending Unix timestamp for log retrieval * follow: Enables continuous log streaming * text: Returns human-readable text instead of base64 encoding * timestamps: Adds timestamps to each log line * bare: Returns the raw log lines without json format The response of the RPC looks like: ``` $ curl 'http://0.0.0.0:9190/logs/zk-provider-server?text×tamps' {"channel":"stdout","message":"2024-09-29T03:05:45.209507046Z Initializing Rust backend...\n"} {"channel":"stdout","message":"2024-09-29T03:05:45.209543047Z Calling Rust function: init\n"} {"channel":"stdout","message":"2024-09-29T03:05:45.209544957Z [2024-09-29T03:05:44Z INFO rust_prover] Initializing...\n"} {"channel":"stdout","message":"2024-09-29T03:05:45.209546381Z [2024-09-29T03:05:44Z INFO rust_prover::groth16] Starting setup process\n"} ``` ## TLS Passthrough with Custom Domain dstack-gateway supports TLS passthrough for custom domains. See the example [here](https://github.com/Dstack-TEE/dstack-examples/tree/main/custom-domain/dstack-ingress) for more details. ### Upgrade an App Got to the dstack-vmm webpage, click the \[Upgrade] button, select or paste the compose file you want to upgrade to, and click the \[Upgrade] button again.\ The app id does not change after the upgrade. Stop and start the app to apply the upgrade. ### HTTPS Certificate Transparency In the tutorial above, we used a TLS certificate with a private key external to the TEE. To establish trust, we need to generate and maintain the certificate's private key within the TEE and provide evidence that all TLS certificates for the domain were originate solely from dstack-gateway CVM. By combining Certificate Transparency Logs and CAA DNS records, we can make best effort to minimize security risks. Here's our approach: * Set CAA records to allow only the account created in dstack-gateway CVM to request Certificates. * Launch a program to monitor Certificate Transparency Log and give alarm once any certificate issued to a pubkey that isn’t generated by dstack-gateway CVM. #### Configurations To launch Certbot, you need to own a domain hosted on Cloudflare. Obtain an API token with DNS operation permissions from the Cloudflare dashboard. Configure it in the `build-config.sh`: ```bash theme={"system"} # The directory to store the auto obtained TLS certificate and key GATEWAY_CERT=${CERBOT_WORKDIR}/live/cert.pem GATEWAY_KEY=${CERBOT_WORKDIR}/live/key.pem # for certbot CF_ZONE_ID=cc0a40... CF_API_TOKEN=g-DwMH... # ACME_URL=https://acme-v02.api.letsencrypt.org/directory ACME_URL=https://acme-staging-v02.api.letsencrypt.org/directory ``` Then re-run the ../build.sh: ```bash theme={"system"} ../build.sh ``` #### Launch certbot Then run the certbot in the `build/` and you will see the following log: ``` $ RUST_LOG=info,certbot=debug ./certbot renew -c certbot.toml 2024-10-25T07:41:00.682990Z INFO certbot::bot: creating new ACME account 2024-10-25T07:41:00.869246Z INFO certbot::bot: created new ACME account: https://acme-staging-v02.api.letsencrypt.org/acme/acct/168601853 2024-10-25T07:41:00.869270Z INFO certbot::bot: setting CAA records 2024-10-25T07:41:00.869276Z DEBUG certbot::acme_client: setting guard CAA records for app.kvin.wang 2024-10-25T07:41:01.740767Z DEBUG certbot::acme_client: removing existing CAA record app.kvin.wang 0 issuewild "letsencrypt.org;validationmethods=dns-01;accounturi=https://acme-staging-v02.api.letsencrypt.org/acme/acct/168578683" 2024-10-25T07:41:01.991298Z DEBUG certbot::acme_client: removing existing CAA record app.kvin.wang 0 issue "letsencrypt.org;validationmethods=dns-01;accounturi=https://acme-staging-v02.api.letsencrypt.org/acme/acct/168578683" 2024-10-25T07:41:02.216751Z DEBUG certbot::acme_client: setting CAA records for app.kvin.wang, 0 issue "letsencrypt.org;validationmethods=dns-01;accounturi=https://acme-staging-v02.api.letsencrypt.org/acme/acct/168601853" 2024-10-25T07:41:02.424217Z DEBUG certbot::acme_client: setting CAA records for app.kvin.wang, 0 issuewild "letsencrypt.org;validationmethods=dns-01;accounturi=https://acme-staging-v02.api.letsencrypt.org/acme/acct/168601853" 2024-10-25T07:41:02.663824Z DEBUG certbot::acme_client: removing guard CAA records for app.kvin.wang 2024-10-25T07:41:03.095564Z DEBUG certbot::acme_client: generating new cert key pair 2024-10-25T07:41:03.095678Z DEBUG certbot::acme_client: requesting new certificates for *.app.kvin.wang 2024-10-25T07:41:03.095699Z DEBUG certbot::acme_client: creating new order 2024-10-25T07:41:03.250382Z DEBUG certbot::acme_client: order is pending, waiting for authorization 2024-10-25T07:41:03.283600Z DEBUG certbot::acme_client: creating dns record for app.kvin.wang 2024-10-25T07:41:04.027882Z DEBUG certbot::acme_client: challenge not found, waiting 500ms tries=2 domain="_acme-challenge.app.kvin.wang" 2024-10-25T07:41:04.600711Z DEBUG certbot::acme_client: challenge not found, waiting 1s tries=3 domain="_acme-challenge.app.kvin.wang" 2024-10-25T07:41:05.642300Z DEBUG certbot::acme_client: challenge not found, waiting 2s tries=4 domain="_acme-challenge.app.kvin.wang" 2024-10-25T07:41:07.715947Z DEBUG certbot::acme_client: challenge not found, waiting 4s tries=5 domain="_acme-challenge.app.kvin.wang" 2024-10-25T07:41:11.724831Z DEBUG certbot::acme_client: challenge not found, waiting 8s tries=6 domain="_acme-challenge.app.kvin.wang" 2024-10-25T07:41:19.815990Z DEBUG certbot::acme_client: challenge not found, waiting 16s tries=7 domain="_acme-challenge.app.kvin.wang" 2024-10-25T07:41:35.852790Z DEBUG certbot::acme_client: setting challenge ready for https://acme-staging-v02.api.letsencrypt.org/acme/chall-v3/14584884443/mQ-I2A 2024-10-25T07:41:35.934425Z DEBUG certbot::acme_client: challenges are ready, waiting for order to be ready 2024-10-25T07:41:37.972434Z DEBUG certbot::acme_client: order is ready, uploading csr 2024-10-25T07:41:38.052901Z DEBUG certbot::acme_client: order is processing, waiting for challenge to be accepted 2024-10-25T07:41:40.088190Z DEBUG certbot::acme_client: order is valid, getting certificate 2024-10-25T07:41:40.125988Z DEBUG certbot::acme_client: removing dns record 6ab5724e8fa7e3e8f14e93333a98866a 2024-10-25T07:41:40.377379Z DEBUG certbot::acme_client: stored new cert in /home/kvin/codes/meta-dstack/dstack/build/run/certbot/backup/2024-10-25T07:41:40.377174477Z 2024-10-25T07:41:40.377472Z INFO certbot::bot: checking if certificate needs to be renewed 2024-10-25T07:41:40.377719Z DEBUG certbot::acme_client: will expire in Duration { seconds: 7772486, nanoseconds: 622281542 } 2024-10-25T07:41:40.377752Z INFO certbot::bot: certificate /home/kvin/codes/meta-dstack/dstack/build/run/certbot/live/cert.pem is up to date ``` Where the command did are: * Registered to letsencrypt and got a new account `https://acme-staging-v02.api.letsencrypt.org/acme/acct/168601853` * Auto set CAA records for the domain on cloudflare, you can open the CF dashboard to see the record: ![certbot CAA record configuration](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/dstack-certbot-caa.png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=224b0fe57ed0c5e49822ed137de5b98b) certbot CAA record configuration * Auto requested a new certificate from Let's Encrypt. Automatically renews the certificate to maintain its validity #### Launch dstack-gateway Execute dstack-gateway with `sudo ./dstack-gateway -c gateway.toml`, then access the web portal to check the dstack-gateway CVM managed Let's Encrypt account. The account's private key remains securely sealed within the TEE. ![dstack gateway account ID](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/dstack-gateway-accountid.png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=8c9f36072aef3be8ddc62540ec848b36) dstack gateway account ID ### Certificate transparency log monitor To enhance security, we've limited TLS certificate issuance to dstack-gateway via CAA records. However, since these records can be modified through Cloudflare's domain management, we need to implement global CA certificate monitoring to maintain security oversight. `ct_monitor` tracks Certificate Transparency logs via [https://crt.sh](https://crt.sh/?q=app.kvin.wang), comparing their public key with the ones got from dstack-gateway RPC. It immediately alerts when detecting unauthorized certificates not issued through dstack-gateway: ``` $ ./ct_monitor -t https://localhost:9010/prpc -d app.kvin.wang 2024-10-25T08:12:11.366463Z INFO ct_monitor: monitoring app.kvin.wang... 2024-10-25T08:12:11.366488Z INFO ct_monitor: fetching known public keys from https://localhost:9010/prpc 2024-10-25T08:12:11.566222Z INFO ct_monitor: got 2 known public keys 2024-10-25T08:12:13.142122Z INFO ct_monitor: ✅ checked log id=14705660685 2024-10-25T08:12:13.802573Z INFO ct_monitor: ✅ checked log id=14705656674 2024-10-25T08:12:14.494944Z ERROR ct_monitor: ❌ error in CTLog { id: 14666084839, issuer_ca_id: 295815, issuer_name: "C=US, O=Let's Encrypt, CN=R11", common_name: "kvin.wang", name_value: "*.app.kvin.wang", not_before: "2024-09-24T02:23:15", not_after: "2024-12-23T02:23:14", serial_number: "03ae796f56a933c8ff7e32c7c0d662a253d4", result_count: 1, entry_timestamp: "2024-09-24T03:21:45.825" } 2024-10-25T08:12:14.494998Z ERROR ct_monitor: error: certificate has issued to unknown pubkey: 30820122300d06092a864886f70d01010105000382010f003082010a02820101009de65c767caf117880626d1acc1ee78f3c6a992e3fe458f34066f92812ac550190a67e49ebf4f537003c393c000a8ec3e114da088c0cb02ffd0881fd39a2b32cc60d2e9989f0efab3345bee418262e0179d307d8d361fd0837f85d17eab92ec6f4126247e614aa01f4efcc05bc6303a8be68230f04326c9e85406fc4d234e9ce92089253b11d002cdf325582df45d5da42981cd546cbd2e9e49f0fa6636e747a345aaf8cefa02556aa258e1f7f90906be8fe51567ac9626f35bc46837e4f3203387fee59c71cea400000007c24e7537debc1941b36ff1612990233e4c219632e35858b1771f17a71944adf6c657dd7303583e3aeed199bd36a3152f49980f4f30203010001 ``` ## Troubleshooting #### Error from dstack-vmm: qemu-system-x86\_64: -device vhost-vsock-pci,guest-cid=: vhost-vsock: unable to set guest cid: Address already in use `dstack-vmm` may throw this error when creating a new VM if the [Unix Socket CID](https://man7.org/linux/man-pages/man7/vsock.7.html) is occupied. To solve the problem, first, you should list the occupied CID: ```bash theme={"system"} ps aux | grep 'guest-cid=' ``` Then choose a new range of the CID not conflicting with the CID in use. You can change `build/vmm.toml` file and restart `dstack-vmm`. This error should disappear. For example, you may find 33000-34000 free to use: ```toml theme={"system"} [cvm] cid_start = 33000 cid_pool_size = 1000 ``` When building the dstack from scratch, you should change the CID configs in `build-config.sh` instead, because `vmm.toml` file is generated by `build.sh`. Its content is derived from `build-config.sh`. You may encounter this problem when upgrading from an older version of dstack, because CID was introduced in `build-config.sh` in later versions. In such case, please follow the docs to add the missing entries in `build-config.sh` and rebuild dstack. #### Error: Operation not permitted when building guest image When running `../build.sh guest`, you might encounter this error: ``` Traceback (most recent call last): File "/meta-dstack/poky/bitbake/bin/bitbake-worker", line 278, in child bb.utils.disable_network(uid, gid) File "/meta-dstack/poky/bitbake/lib/bb/utils.py", line 1696, in disable_network with open("/proc/self/uid_map", "w") as f: PermissionError: [Errno 1] Operation not permitted ``` This error occurs because Ubuntu 23.10 and later versions restrict unprivileged user namespaces by default. To fix this, run: ```bash theme={"system"} sudo sysctl kernel.apparmor_restrict_unprivileged_userns=0 ``` Then try building again. For more information about this restriction, see the [Ubuntu discourse post](https://discourse.ubuntu.com/t/spec-unprivileged-user-namespace-restrictions-via-apparmor-in-ubuntu-23-10/37626). ## Contributors dstack is proudly built by open source and Pi-rateship contributors: * Phala Network: [Kevin Wang](https://github.com/kvinwang), [Shelven Zhou](https://github.com/shelvenzhou), [Leechael](https://github.com/leechael) * Teleport: [Andrew Miller](https://github.com/amiller), [Sxy Sun](https://github.com/sxysun) * Flashbots: [Tina](https://github.com/CarboClanC), [Mateusz](https://github.com/Ruteri), [Dmarz](https://github.com/dmarzzz), [Moe](https://github.com/MoeMahhouk) * Ithaca: [Georgios](https://github.com/gakonst) * Fabric: [@gaoist](https://x.com/gaoist) * And many more... The inspiration for this work stems from [Andrew Miller](https://github.com/amiller)’s pioneering concept of a [Docker-based P2P TEE SDK](https://collective.flashbots.net/t/dstack-speedrunning-a-p2p-confidential-vm/3876). This project cannot be built without standing on the shoulders of giants: * [konvera/meta-confidential-compute](https://github.com/konvera/meta-confidential-compute) Special acknowledgment to [Flashbots](https://github.com/flashbots) for building a community around TEE. The TEE Hacker House initiative, organized by [Flashbots](https://github.com/flashbots) and led by [Tina](https://github.com/CarboClanC), has brought together TEE builders to develop tools for TEE-Web3 integration. This collaborative journey has generated invaluable insights for advancing secure, confidential environments within Web3. Together, we’re shaping the future of TEE in Web3, paving the way for more secure and developer-accessible confidential computing! For a full list of the direct contributors to this repo, see [Contributors](https://github.com/Dstack-TEE/dstack/contributors) on GitHub. # Hardware Requirements Source: https://docs.phala.com/dstack/hardware-requirements Hardware requirements and specifications for running dstack TEE infrastructure. When running dstack from a hardware perspective, users have three primary options. * **Physical Server:** The first option is to utilize a physical server, also known as a bare metal server, by purchasing and configuring it themselves, which gives complete control over the hardware environment. * **Rent Server from OVH:** Alternatively, users may choose to rent a server from OVH, a reputable hosting provider, and handle the necessary configurations to run dstack. * **Host on Phala Cloud:** For a more streamlined approach that bypasses configuring the system entirely, getting a Phala Cloud account is a viable option, allowing users to leverage cloud infrastructure, pre-configured for dstack's operations without the need for initial server setup. Let's dive into the the options. ### Physical Server Minimum requirement is to buy an Intel Xeon 5th/6th Generation CPU (TDX Support) and 8 RAM slots filled. The lowest starting cost for a server will be around \$3763 USD. Here is a recommended server if you would like to buy your own and set up dstack. * [https://store.supermicro.com/us\_en/iot-edge-superserver-sys-111e-fwtr.html](https://store.supermicro.com/us_en/iot-edge-superserver-sys-111e-fwtr.html) ### Rent Server from OVH Renting bare metal from OVH has the same requirements as a Physical Server. Typical starting prices for renting a server will run about \$854.50/mo. Here is a link to some OVH servers for rent. * [https://www.ovhcloud.com/en/bare-metal/prices/?display=list\&use\_cases=confidential-computing\&cpu\_brand=Intel](https://www.ovhcloud.com/en/bare-metal/prices/?display=list\&use_cases=confidential-computing\&cpu_brand=Intel) ### Host on Phala Cloud For those that want to get straight to hosting and testing out dstack, [sign-up for your Phala Cloud](/phala-cloud/getting-started/sign-up-for-cloud-account) account and head over to the [getting started](/phala-cloud/getting-started/start-from-cloud-ui) section in Phala Cloud to deploy your first CVM in minutes. # Local Development Guide Source: https://docs.phala.com/dstack/local-development Deploy confidential applications with dstack - a TEE-based infrastructure platform. dstack enables running containerized applications in Trusted Execution Environments (TEE). For development purposes, you can use our TEE simulator to develop and test your applications locally without TEE hardware. This guide covers setting up the simulator and using our SDKs to interact with TEE functionalities. Refer to the [**Hardware Requirements**](/dstack/hardware-requirements) for release. ## Prerequisites * Rust toolchain (for building the simulator) * Git * One of the following development environments: * Node.js 16+ (for JavaScript SDK) * Python 3.7+ (for Python SDK) * Go 1.16+ (for Go SDK) * Rust 1.70+ (for Rust SDK) ## Simulator The latest TEE simulator is available in [dstack](https://github.com/Dstack-TEE/dstack/tree/master/sdk/simulator) code repository. Use the following commands to build it: ### Build Simulator ```bash theme={"system"} # Install rust curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh # Clone the repository git clone https://github.com/Dstack-TEE/dstack.git # Build the simulator cd dstack/sdk/simulator ./build.sh # Run the simulator ./dstack-simulator # The simulator will create the following socket files: # dstack.sock // Current TEE service interface (v0.5+) # tappd.sock // Legacy TEE service interface (v0.3) # external.sock # guest.sock ``` To use the simulator with any SDK, set the following environment variable with the absolute path: ```bash theme={"system"} export DSTACK_SIMULATOR_ENDPOINT=/path/to/dstack.sock ``` ### Verifying Simulator Setup After starting the simulator, verify the setup by checking: 1. The socket files exist in the simulator directory: ```bash theme={"system"} ls *.sock ``` 2. The environment variable is set correctly: ```bash theme={"system"} echo $DSTACK_SIMULATOR_ENDPOINT ``` ## dstack API The dstack API provides the basic abstraction of the TEE functionalities. In general, it provides the following functions: * **Get Key**: Generate a cryptographic key from the specified key path and returns it along with its certificate chain. * **Get TDX Quote**: Generate a TDX quote with report data. This can be further verified in our [TEE Attestation Explorer](https://proof.t16z.com/) to prove your application and data are in TEE. * **Get TDX Information**: Retrieve worker information, one example response is like ```json theme={"system"} { "app_id": "", "instance_id": "", "app_cert": "", "tcb_info": "", "app_name": "my-app", "public_logs": true, "public_sysinfo": true, "device_id": "", "mr_aggregated": "", "os_image_hash": "", "key_provider_info": "", "compose_hash": "" } ``` The `dstack.sock` is the current TEE RPC API (v0.5+). For more detailed documents, check the [SDK documentation](https://github.com/Dstack-TEE/dstack/tree/master/sdk). > **Note**: If you're upgrading from dstack v0.3, see the [Migration Guide](/phala-cloud/references/migration-from-dstack-v03) for breaking changes. ## Programming Language Support ### JavaScript Check the latest version in [dstack](https://github.com/Dstack-TEE/dstack/tree/master/sdk/js) code repository. #### Installation ```bash theme={"system"} npm install @phala/dstack-sdk ``` #### Basic Usage ```js theme={"system"} import { DstackClient } from '@phala/dstack-sdk'; import crypto from 'crypto'; const client = new DstackClient(); // Check if service is reachable (500ms timeout, never throws) const isReachable = await client.isReachable(); if (!isReachable) { console.log('dstack service is not available'); return; } // Get the information of the Base Image. await client.info(); // Get a deterministic key with path const keyResult = await client.getKey('my-app/encryption/v1'); console.log(keyResult.key); // Uint8Array(32) - already a Uint8Array console.log(keyResult.signature_chain); // Signature chain // Generate TDX quote (manually hash data if > 64 bytes) const data = 'some-data'; const hash = crypto.createHash('sha256').update(data).digest(); const quoteResult = await client.getQuote(hash.slice(0, 32)); console.log(quoteResult.quote); // TDX quote in hex format console.log(quoteResult.event_log); // Event log const rtmrs = quoteResult.replayRtmrs(); // Replay RTMRs ``` ### Python Check the latest version in [dstack](https://github.com/Dstack-TEE/dstack/tree/master/sdk/python) code repository. #### Installation ```bash theme={"system"} pip install dstack-sdk ``` #### Basic Usage ```python theme={"system"} from dstack_sdk import DstackClient import hashlib # Synchronous client client = DstackClient() # Caution: You don't need to do this most of the time. http_client = DstackClient('http://localhost:8000') # Get the information of the Base Image. info = client.info() print(info.app_id) # Application ID print(info.tcb_info.mrtd) # Access TCB info directly print(info.tcb_info.event_log[0].event) # Access event log entries # Get a deterministic key with path key_result = client.get_key('my-app/encryption/v1') print(key_result.key) # Hex string print(key_result.signature_chain) # Signature chain key_bytes = key_result.decode_key() # Decode to bytes (32 bytes) # Generate TDX quote (manually hash data if > 64 bytes) data = b'some-data' hash_value = hashlib.sha256(data).digest() quote_result = client.get_quote(hash_value[:32]) print(quote_result.quote) # TDX quote in hex format print(quote_result.event_log) # Event log rtmrs = quote_result.replay_rtmrs() # Replay RTMRs ``` ### Golang Check the latest version in [dstack](https://github.com/Dstack-TEE/dstack/tree/master/sdk/go) code repository. #### Installation ```bash theme={"system"} go get github.com/Dstack-TEE/dstack/sdk/go ``` #### Basic Usage ```go theme={"system"} package main import ( "context" "fmt" "log/slog" "github.com/Dstack-TEE/dstack/sdk/go/dstack" ) func main() { client := dstack.NewDstackClient( // dstack.WithEndpoint("http://localhost"), // dstack.WithLogger(slog.Default()), ) // Get information about the dstack client instance info, err := client.Info(context.Background()) if err != nil { fmt.Println(err) return } fmt.Println(info.AppID) // Application ID fmt.Println(info.TcbInfo.Mrtd) // Access TCB info directly fmt.Println(info.TcbInfo.EventLog[0].Event) // Access event log entries path := "/test" purpose := "test" // or leave empty // Derive a key with optional path and purpose deriveKeyResp, err := client.GetKey(context.Background(), path, purpose) if err != nil { fmt.Println(err) return } fmt.Println(deriveKeyResp.Key) // Generate TDX quote tdxQuoteResp, err := client.GetQuote(context.Background(), []byte("test")) if err != nil { fmt.Println(err) return } fmt.Println(tdxQuoteResp.Quote) // 0x0000000000000000000 ... rtmrs, err := tdxQuoteResp.ReplayRTMRs() if err != nil { fmt.Println(err) return } fmt.Println(rtmrs) // map[0:00000000000000000 ... } ``` #### Rust Check the latest version in [dstack](https://github.com/Dstack-TEE/dstack/tree/master/sdk/rust) code repository. #### Installation ```toml theme={"system"} [dependencies] dstack-rust = { git = "https://github.com/Dstack-TEE/dstack.git", package = "dstack-rust" } ``` #### Basic Usage ```rust theme={"system"} use dstack_sdk::DstackClient; #[tokio::main] async fn main() -> Result<(), Box> { let client = DstackClient::new(None); // Uses env var or default to Unix socket // Get system info let info = client.info().await?; println!("Instance ID: {}", info.instance_id); // Derive a key let key_resp = client.get_key(Some("my-app".to_string()), None).await?; println!("Key: {}", key_resp.key); println!("Signature Chain: {:?}", key_resp.signature_chain); // Generate TDX quote let quote_resp = client.get_quote(b"test-data".to_vec()).await?; println!("Quote: {}", quote_resp.quote); let rtmrs = quote_resp.replay_rtmrs()?; println!("Replayed RTMRs: {:?}", rtmrs); // Emit an event client.emit_event("BootComplete".to_string(), b"payload-data".to_vec()).await?; Ok(()) } ``` # Media Kit Source: https://docs.phala.com/dstack/media-kit Download official dstack logos, brand assets, and media resources # dstack Media Kit Welcome to the official dstack media kit. Here you'll find all the brand assets, logos, and resources you need to represent dstack in your projects, presentations, and communications. ## Logo Variants ### Horizontal Logos > [card] Primary Horizontal > > ![Dstack Horizontal Primary Logo](https://mintcdn.com/phalanetwork-1606097b/8ugPHitzPXM68J0c/images/Dstack%20Logo%20Kit/01%20Horizontal/01%20Dstack%20_Horizontal_primary.svg?fit=max\&auto=format\&n=8ugPHitzPXM68J0c\&q=85\&s=46a1a023c03efde5b5db9133f74569ea) > > * **Use case**: Light backgrounds, presentations, headers > * **Format**: SVG, PNG > * [Download SVG]() > * [Download PNG]() > [card] Dark Horizontal > > ![Dstack Horizontal Dark Logo](https://mintcdn.com/phalanetwork-1606097b/8ugPHitzPXM68J0c/images/Dstack%20Logo%20Kit/01%20Horizontal/02%20Dstack%20_Horizontal_dark.svg?fit=max\&auto=format\&n=8ugPHitzPXM68J0c\&q=85\&s=ccef8801355dacb6bb689dc5a3481876) > > * **Use case**: Dark backgrounds, dark mode interfaces > * **Format**: SVG, PNG > * [Download SVG]() > * [Download PNG]() ### Vertical Logos > [card] Primary Vertical > > ![Dstack Vertical Primary Logo](https://mintcdn.com/phalanetwork-1606097b/8ugPHitzPXM68J0c/images/Dstack%20Logo%20Kit/02%20Vertical/01%20Dstack_Vertical_primary.svg?fit=max\&auto=format\&n=8ugPHitzPXM68J0c\&q=85\&s=3b447d9d02338c0cde75029b8fadc3a6) > > * **Use case**: Square layouts, social media profiles, app icons > * **Format**: SVG, PNG > * [Download SVG]() > * [Download PNG]() > [card] Dark Vertical > > ![Dstack Vertical Dark Logo](https://mintcdn.com/phalanetwork-1606097b/8ugPHitzPXM68J0c/images/Dstack%20Logo%20Kit/02%20Vertical/02%20Dstack_Vertical_dark.svg?fit=max\&auto=format\&n=8ugPHitzPXM68J0c\&q=85\&s=80cba5127a9c15e6c2dc6368d01c3a11) > > * **Use case**: Square layouts on dark backgrounds > * **Format**: SVG, PNG > * [Download SVG]() > * [Download PNG]() ### Icon/Symbol Only > [card] Primary Icon > > ![Dstack Icon Primary](https://mintcdn.com/phalanetwork-1606097b/8ugPHitzPXM68J0c/images/Dstack%20Logo%20Kit/03%20icon/01%20Dstack%20icon_primary.svg?fit=max\&auto=format\&n=8ugPHitzPXM68J0c\&q=85\&s=0c398861f003d01687f990261e67be65) > > * **Use case**: Favicon, small spaces, minimal branding > * **Format**: SVG, PNG > * [Download SVG]() > * [Download PNG]() > [card] Dark Icon > > ![Dstack Icon Dark](https://mintcdn.com/phalanetwork-1606097b/8ugPHitzPXM68J0c/images/Dstack%20Logo%20Kit/03%20icon/02%20Dstack%20icon_dark.svg?fit=max\&auto=format\&n=8ugPHitzPXM68J0c\&q=85\&s=4e43a6e010930be479907e8ab4991569) > > * **Use case**: Favicon on dark themes, minimal dark branding > * **Format**: SVG, PNG > * [Download SVG]() > * [Download PNG]() ## Usage Guidelines ### Do's ✅ * Use the appropriate logo variant for your background (primary on light, dark on dark backgrounds) * Maintain adequate clear space around the logo * Use vector formats (SVG) when possible for crisp scaling * Keep the logo proportions intact when resizing ### Don'ts ❌ * Don't modify the logo colors, fonts, or proportions * Don't place the logo on busy backgrounds that reduce readability * Don't use low-resolution versions when high-quality options are available * Don't combine with other brand elements in confusing ways ## Brand Colors While specific brand color guidelines aren't provided in this media kit, ensure consistency with dstack's visual identity when using these logos in your designs. ## Questions? If you need additional formats, have questions about usage, or require custom variations of these assets, please reach out to the dstack team through our [community channels](/dstack/acknowledgement#contributors). *** *This media kit is provided to help partners, developers, and community members properly represent dstack in their communications and projects.* # Overview Source: https://docs.phala.com/dstack/overview Deploy confidential applications with dstack — a TEE-based infrastructure platform. > [Phala Cloud](/) is the managed version of dstack deployment that enables developers to deploy programs to CVM (Confidential VM), and to follow the security best practices by default. The dstack SDK simplifies deploying programs to CVMs (Confidential VMs) with security best practices built in. Explore [dstack's blockchain-verified computing](https://phala.com/dstack) capabilities and architecture. The main features include: * Deploy any Docker container as a CVM on supported TEEs * Generate remote attestation reports and visualize the chain of trust via Web UI * Wrap HTTP services with automatic RA-HTTPS and content-addressed domains (`0xABCD.dstack.host`) * Keep applications portable across hardware via decentralized Root-of-Trust key management The following example shows how dstack works with a typical multi-container application configured with Docker Compose. ![](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/dstack-cvm%20\(1\).png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=83135271ccb857f0fe97dc3b11789f94) As the architecture shown below, multiple docker containers can run inside one single CVM. The underlying infrastructure we provide is to make sure the application is secure and verifiable. Your containers use the `dstack` component to communicate with the underlying `tappd`. `dstack` sets up the CVM environment, handles remote attestation, and manages the lifecycle of all Docker containers running inside the CVM. `tappd` communicates with a decentralized Key Management Service (KMS) that derives deterministic encryption keys for the application. These keys encrypt application-specific storage and protect data integrity. Because the KMS operates independently from any specific TEE instance, your applications avoid vendor lock-in and can be securely migrated between different hardware environments without data loss. ![dstack CVM architecture diagram showing the relationship between docker containers, dstack, tappd, and decentralized KMS](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/dstack-cvm-arch.png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=8193a9bc12e6245b55facbfbe8aed007) ## Verify If An Application is Running Inside a TEE When the application launches, dstack exports a Remote Attestation (RA) Report that cryptographically binds the application's runtime information — Docker image hash, startup arguments, and environment variables. The TEE hardware signs this report, and the application's own derived key co-signs it. Anyone can verify the report using standard TEE RA verification tools. For applications deployed on Phala Intel TDX workers, RA reports are exported and verified by default — use the [TEE Attestation Explorer](https://proof.t16z.com/) to inspect them. ## Conclusion Ready to build? See [Getting Started](/phala-cloud/getting-started/overview) for deployment options. For managed hosting without running dstack on your own hardware, use [Phala Cloud](/). # dstack Security Audit Source: https://docs.phala.com/dstack/security-audit Third-party security audit of dstack by zkSecurity covering system architecture, TEE integration, and production hardening # dstack Security Audit Phala Network engaged zkSecurity to conduct a comprehensive security audit of the dstack project in May 2025. This audit provides an independent assessment of dstack's security architecture, implementation quality, and production readiness. ## Audit Overview **Auditor:** zkSecurity **Engagement Period:** May 26 - June 13, 2025 **Audit Team:** Two security consultants **Report Date:** May 26, 2025 ### Scope The audit covered two primary areas: #### Low-Level Libraries and Tooling * **ra-tls and ra-rpc**: Remote attestation TLS implementation * **guest-agent**: In-CVM service for key derivation and attestation * **dstack-util**: CLI tools including full-disk encryption functionality #### Image-Related Files * **Yocto BitBake recipes**: Production image build configurations * **Base initialization scripts**: System setup and hardening * **Production vs development images**: Security difference analysis ### Methodology The audit followed a two-phase approach: **Phase 1: Core Security Analysis** * Understanding attacker models and trust boundaries * Reviewing RATLS (Remote Attestation TLS) protocol implementation * Analyzing CVM interfaces and access controls * Evaluating privilege escalation strategies **Phase 2: System Image Analysis** * Reviewing build reproducibility * Validating measurement integrity * Analyzing production image hardening * Assessing dm-verity integration * Evaluating host operator attack vectors ## Key Findings Summary The audit identified **12 findings** across different risk levels: | Risk Level | Count | Examples | | - | - | - | | **High** | 1 | VMM currently trusted in OVMF build | | **Medium** | 6 | Terminal binaries in production, symbolic link vulnerabilities | | **Low** | 3 | Incomplete measurement checks, documentation gaps | | **Informational** | 2 | Production deployment guidance, design documentation | ### Critical Finding: OVMF Configuration The highest-severity finding identified that dstack was using OVMF Configuration A, which trusts the Virtual Machine Manager (VMM). The audit recommended moving to Configuration B, which places the VMM outside the Trusted Computing Base (TCB). **Impact:** This configuration choice affects the fundamental trust model of the TEE environment. **Status:** ✅ **Addressed** - The dstack team implemented the recommended OVMF Configuration B. ## Implementation Status The dstack team has been proactive in addressing audit findings: ✅ **Fixed**: OVMF configuration upgraded to secure mode ✅ **Fixed**: Production image hardening improvements ✅ **Fixed**: Symbolic link vulnerability patched ✅ **Fixed**: Terminal binary removal from production ✅ **Enhanced**: Documentation and security guides added ## Access Full Report > [card] [Download Complete Audit Report](/images/audits/dstack-audit.pdf) > > Access the complete 39-page security audit report with detailed technical findings, recommendations, and implementation guidance. ## Related Documentation > [card] [dstack Overview](/dstack/overview) > > Learn about dstack's architecture and core concepts > [card] [Security Architecture](/phala-cloud/security-and-privacy/security-architecture) > > Understand Phala Cloud's security model > [card] [Attestation Guide](/phala-cloud/attestation/overview) > > Deep dive into TEE attestation mechanisms > [card] [Production Checklist](/phala-cloud/production-checklist) > > Security checklist for production deployments # Trust Center Technical Documentation Source: https://docs.phala.com/dstack/trust-center-technical Technical architecture and API reference for Trust Center verification system ## Overview The Trust Center is an open-source verification platform that automates the validation of TEE attestations for dstack-based applications. It performs multi-dimensional verification across hardware, operating system, source code, and domain ownership to provide cryptographic proof of deployment integrity. **Architecture**: Monorepo with TypeScript verifier library, background worker queue, and web dashboard. **Repository**: [https://github.com/Phala-Network/trust-center](https://github.com/Phala-Network/trust-center) ## System Architecture ### Components 1. **Verifier Package** (`@phala/dstack-verifier`) * Core TypeScript library for attestation verification * Modular verifier classes with configurable flags * Supports Intel TDX quote validation * Platform-specific verifiers (Phala Cloud and Private AI) 2. **Background Worker** * Built on BullMQ for reliable job processing * PostgreSQL for task persistence * Redis for queue management * Asynchronous verification execution 3. **Web Application** * Next.js dashboard for report visualization * Direct database access for read operations * Real-time verification status updates * Public report URLs for transparency 4. **Storage Layer** * PostgreSQL: Verification tasks and results * Redis: Job queue state * S3-compatible: Raw attestation data and quotes ## Verification Phases The Trust Center performs verification in four distinct phases: ### Phase 1: Hardware Attestation Validates the TEE quote to prove execution on genuine Intel hardware. **What's verified:** * **Quote signature**: ECDSA-P256 signature validation using Intel certificates * **Certificate chain**: Validates back to Intel root CA * **TCB status**: Checks Trusted Computing Base security version * **Platform identity**: Confirms genuine Intel TDX processor * **Revocation status**: Verifies no certificates or platforms are revoked **Tools used:** * Quote verification with [DCAP-QVL](https://github.com/Phala-Network/dcap-qvl) **Implementation:** ```typescript theme={"system"} // Note: verifyQuote is an internal utility in @phala/dstack-verifier // For hardware verification, use VerificationService with hardware flag import { VerificationService } from '@phala/dstack-verifier'; const service = new VerificationService(); // For Private AI apps (with GPU models) const result = await service.verify({ contractAddress: '0x...', model: 'phala/gemma-4-26b-a4b-uncensored' }, { hardware: true, os: false, sourceCode: false }); // Or for Phala Cloud apps const result2 = await service.verify({ contractAddress: '0x...', domain: 'myapp.phala.network' }, { hardware: true, os: false, sourceCode: false }); console.log('Hardware verified:', result.success); ``` **Failure modes:** * Invalid signature: Quote not signed by genuine TEE * Revoked certificates: Platform or attestation key compromised * Outdated TCB: Security patches not applied ### Phase 2: Operating System Integrity Confirms the OS image matches a known trusted dstack version. **What's verified:** * **MRTD**: Measurement Root of Trust Domain (TD initial state) * **RTMR0**: Virtual hardware environment * **RTMR1**: Linux kernel measurement * **RTMR2**: Kernel command line and initrd **Tools used:** * dstack image verification with [dstack-mr-cli](https://github.com/Dstack-TEE/dstack/tree/next/dstack/dstack-mr/cli) **Measurement calculation:** ```bash theme={"system"} # Calculate OS measurements using dstack-mr-cli dstack-mr-cli --kernel bzImage --initrd initrd.img --cmdline "console=htyS0" # Output: MRTD, RTMR0, RTMR1, RTMR2 values ``` **Verification logic:** ```typescript theme={"system"} // OS verification is performed by VerificationService // The service automatically downloads trusted dstack images and compares measurements import { VerificationService } from '@phala/dstack-verifier'; const service = new VerificationService(); const result = await service.verify({ contractAddress: '0x...', model: 'phala/gemma-4-26b-a4b-uncensored', // For Private AI // OR domain: 'myapp.phala.network' // For Phala Cloud metadata: { osSource: { github_repo: 'https://github.com/Dstack-TEE/meta-dstack', git_commit: 'abc123', version: 'v0.5.2' } } }, { hardware: false, os: true, // Enable OS verification sourceCode: false }); console.log('OS verified:', result.success); ``` **Why it matters**: Ensures the OS hasn't been modified, backdoored, or replaced with an untrusted image. ### Phase 3: Source Code Verification Validates the application code matches the deployed version. **What's verified:** * **compose-hash**: SHA256 hash of `docker-compose.yaml` * **app-id**: Application identifier (used for key derivation) * **instance-id**: Specific deployment instance * **key-provider**: KMS service address * **RTMR3**: Application measurement register containing above values **RTMR3 structure:** ```typescript theme={"system"} interface RTMR3Events { 'app-id': string; // Application identifier 'compose-hash': string; // SHA256 of docker-compose.yaml 'instance-id': string; // Deployment instance UUID 'key-provider': string; // KMS endpoint URL } ``` **RTMR3 calculation:** ```typescript theme={"system"} // RTMR3 is computed as a hash chain of events function computeRTMR3(events: RTMR3Events): string { let rtmr3 = '0'.repeat(96); // Initial value (all zeros) for (const [key, value] of Object.entries(events)) { const event = JSON.stringify({ [key]: value }); const eventHash = sha384(event); rtmr3 = sha384(rtmr3 + eventHash); } return rtmr3; } ``` **Verification against blockchain:** ```typescript theme={"system"} import { createPublicClient, http } from 'viem'; import { mainnet } from 'viem/chains'; const client = createPublicClient({ chain: mainnet, transport: http() }); // Read compose-hash from blockchain registry const onChainHash = await client.readContract({ address: '0x...', abi: registryABI, functionName: 'getAppComposeHash', args: [appId] }); const match = onChainHash === quote.body.rtmr3.composeHash; console.log('Source code verified:', match); ``` **Tools:** * [dstack attestation docs](https://github.com/Dstack-TEE/dstack/blob/next/docs/attestation-tdx.md) ### Phase 4: Domain Verification (Gateway Only) For applications with custom domains, verifies zero-trust HTTPS. **What's verified:** * **TLS certificate**: Private key generated in TEE * **CAA records**: DNS locked to TEE-controlled Let's Encrypt account * **Certificate Transparency**: All certs logged to public CT logs * **Domain control**: Cryptographic proof of domain ownership **Verification process:** 1. Extract TLS public key from `reportData` field 2. Query Certificate Transparency logs (via crt.sh) 3. Verify all certificates for domain match the TEE public key 4. Check CAA records point to TEE Let's Encrypt account 5. Confirm no unauthorized certificates exist **CAA record format:** ``` example.com CAA 0 issue "letsencrypt.org;validationmethods=dns-01;accounturi=https://acme-v02.api.letsencrypt.org/acme/acct/XXXXXX" ``` **CT Log monitoring:** ```typescript theme={"system"} // Domain verification (including CT logs) is performed by VerificationService // The service checks Certificate Transparency logs when ctLog flag is enabled import { VerificationService } from '@phala/dstack-verifier'; const service = new VerificationService(); const result = await service.verify({ contractAddress: '0x...', domain: 'example.com' }, { hardware: false, os: false, sourceCode: false, teeControlledKey: true, // Verify TEE controls TLS private key certificateKey: true, // Verify certificate matches dnsCAA: true, // Verify DNS CAA records ctLog: true // Check Certificate Transparency logs (can be slow) }); if (!result.success) { console.error('❌ Domain verification failed:', result.errors); } ``` **Why it matters**: Traditional cloud providers can intercept HTTPS traffic because they control certificate private keys. Zero-trust HTTPS proves even the cloud provider cannot decrypt your traffic. ## Using the Verifier Package ### Basic Usage ```typescript theme={"system"} import { VerificationService } from '@phala/dstack-verifier'; const service = new VerificationService(); // For Private AI models const result = await service.verify({ contractAddress: '0x...', model: 'phala/gemma-4-26b-a4b-uncensored', metadata: { osSource: { github_repo: 'https://github.com/Dstack-TEE/meta-dstack', git_commit: 'abc123', version: 'v0.5.2' } } }, { hardware: true, // Verify Intel TDX quote os: true, // Verify OS integrity sourceCode: true, // Verify compose-hash teeControlledKey: false, certificateKey: false, dnsCAA: false, ctLog: false }); // For Phala Cloud apps with custom domains const result2 = await service.verify({ contractAddress: '0x...', domain: 'myapp.phala.network' }, { hardware: true, os: true, sourceCode: true, teeControlledKey: true, // Verify TEE controls TLS key certificateKey: true, // Verify certificate dnsCAA: false, // Skip DNS CAA check (can be slow) ctLog: false // Skip CT log check (can be very slow) }); console.log('Verification success:', result.success); console.log('Verification errors:', result.errors); console.log('Data objects:', result.dataObjects); ``` ### Configurable Verification Flags ```typescript theme={"system"} import type { VerificationFlags } from '@phala/dstack-verifier'; // Available verification flags (all optional, defaults shown) const flags: VerificationFlags = { hardware: true, // Verify Intel TDX quote os: true, // Verify OS integrity (MRTD, RTMR0-2) sourceCode: true, // Verify source code (compose-hash in RTMR3) teeControlledKey: true, // Verify TEE controls private key certificateKey: true, // Verify certificate matches attestation dnsCAA: true, // Verify DNS CAA records (can be slow) ctLog: false // Verify Certificate Transparency logs (can be very slow) }; // Use with VerificationService const service = new VerificationService(); const result = await service.verify(config, flags); ``` ### Platform-Specific Configuration ```typescript theme={"system"} import { VerificationService } from '@phala/dstack-verifier'; import type { PhalaCloudConfig, RedpillConfig } from '@phala/dstack-verifier'; const service = new VerificationService(); // Phala Cloud configuration const phalaConfig: PhalaCloudConfig = { contractAddress: '0x...', domain: 'myapp.phala.network', metadata: { osSource: { github_repo: 'https://github.com/Dstack-TEE/meta-dstack', git_commit: 'abc123', version: 'v0.5.2' } } }; // Private AI configuration const redpillConfig: RedpillConfig = { contractAddress: '0x...', model: 'phala/gemma-4-26b-a4b-uncensored', metadata: { osSource: { github_repo: 'https://github.com/Dstack-TEE/meta-dstack', git_commit: 'def456', version: 'v0.5.3' } } }; // Use the same service for both platforms const phalaResult = await service.verify(phalaConfig); const redpillResult = await service.verify(redpillConfig); ``` ### Error Handling ```typescript theme={"system"} import { VerificationService } from '@phala/dstack-verifier'; import type { VerificationError } from '@phala/dstack-verifier'; const service = new VerificationService(); try { const result = await service.verify(config, flags); if (!result.success) { console.error('Verification failed'); // Errors are objects with { message: string } for (const error of result.errors) { console.error('Error:', error.message); // Check error messages for specific issues if (error.message.includes('signature')) { console.error('→ Hardware signature invalid - not genuine TEE'); } else if (error.message.includes('compose')) { console.error('→ Deployed code does not match source'); } else if (error.message.includes('MRTD') || error.message.includes('RTMR')) { console.error('→ OS measurements do not match trusted version'); } } } else { console.log('✓ All verification checks passed'); console.log('Data objects:', result.dataObjects); } } catch (err) { // Handle unexpected errors during verification console.error('Verification process error:', err); } ``` ## Self-Hosting Trust Center Organizations can run their own Trust Center instance for private verification. ### Prerequisites * Node.js 18+ / Bun * PostgreSQL 14+ * Redis 6+ * S3-compatible storage (MinIO, AWS S3, etc.) ### Setup ```bash theme={"system"} # Clone repository git clone https://github.com/Phala-Network/trust-center.git cd trust-center # Install dependencies bun install # Configure environment cp .env.example .env # Edit .env with your database, redis, and S3 credentials # Run database migrations bun run db:migrate # Start services bun run worker # Background verification worker bun run webapp # Web dashboard (localhost:3000) ``` ### Configuration **`.env` file:** ```bash theme={"system"} # Database DATABASE_URL=postgresql://user:pass@localhost:5432/trust_center # Redis REDIS_URL=redis://localhost:6379 # S3 Storage S3_ENDPOINT=https://s3.amazonaws.com S3_BUCKET=trust-center-quotes S3_ACCESS_KEY=... S3_SECRET_KEY=... # PCCS (for quote verification) PCCS_URL=https://pccs.phala.network/sgx/certification/v4/ # Optional: Blockchain RPC for source code verification ETH_RPC_URL=https://eth-mainnet.g.alchemy.com/v2/... ``` ### Docker Deployment ```yaml theme={"system"} version: '3.8' services: postgres: image: postgres:14 environment: POSTGRES_DB: trust_center POSTGRES_USER: trust_center POSTGRES_PASSWORD: secure_password volumes: - postgres_data:/var/lib/postgresql/data redis: image: redis:6 volumes: - redis_data:/data worker: build: . command: bun run worker depends_on: - postgres - redis env_file: .env webapp: build: . command: bun run webapp ports: - "3000:3000" depends_on: - postgres env_file: .env volumes: postgres_data: redis_data: ``` ## Next Steps * **User Documentation**: [Trust Center Verification Reports](/phala-cloud/attestation/trust-center-verification) * **Attestation Basics**: [Understanding TEE Attestation](/phala-cloud/attestation/verifying-attestation) * **API Reference**: [Attestation API](/phala-cloud/phala-cloud-api/attestations) * **dstack SDK**: [Getting Started with dstack](/dstack/getting-started) ## Additional Resources * **GitHub Repository**: [trust-center](https://github.com/Phala-Network/trust-center) * **DeepWiki Analysis**: [Technical Deep Dive](https://deepwiki.com/Phala-Network/trust-center) * **Live Platform**: [trust.phala.com](https://trust.phala.com) * **dstack Attestation Docs**: [attestation.md](https://github.com/Dstack-TEE/dstack/blob/next/docs/attestation-tdx.md) # Overview Source: https://docs.phala.com/index Official documentation for Phala Cloud - deploy AI applications with hardware-level privacy, TEE security, and verifiable computation. Get started with confidential computing today. ![Phala Documentation - confidential AI and TEE computing platform](https://mintcdn.com/phalanetwork-1606097b/Z_xV6g4Cdei2rfqm/images/phala-docs-og.png?fit=max\&auto=format\&n=Z_xV6g4Cdei2rfqm\&q=85\&s=e0d65106aa4afa7766452b497d5ec9ca) Welcome to the official documentation for **Phala** - the secure cloud platform that enables AI developers to deploy applications with hardware-level privacy and verifiable computation. ## What is Phala Cloud Phala Cloud is a confidential AI native Neocloud solution that provides you with a secure, user-friendly environment for running AI applications. You can deploy any standard Docker application directly into a **Trusted Execution Environment (TEE)**, ensuring your AI models and data remain confidential and tamper-proof. ### Key Features for AI Developers * **Confidential AI computing**: Run LLMs and AI models in GPU TEE with hardware-level security * **Verifiable Results**: Cryptographic proof that your AI computations are genuine and unmodified * **Privacy Protection**: Complete confidentiality for your models, data, and algorithms * **Easy Deployment**: Deploy existing Docker applications with zero code changes * **Cost Effective**: Web2 pricing model, billed by the minute ## Getting Started New to Phala Cloud? You can start here: > [card] [Quick Start](/phala-cloud/getting-started/overview) > > Deploy your first secure application in minutes > [card] [Phala Cloud Platform](/phala-cloud/cvm/overview) > > Explore the complete cloud platform features > [card] [Private AI](/phala-cloud/confidential-ai/overview) > > Run LLMs in GPU TEE environments ## Core Concepts Understanding Phala Cloud's architecture: > [card] [Trusted Execution Environment](/phala-cloud/attestation/overview) > > Learn how TEE provides hardware-level security > [card] [Key Management](/dstack/design-documents/key-management-protocol) > > Secure cryptographic key generation and management > [card] [Dstack SDK](/dstack/getting-started) > > Developer tools for building on Phala Cloud ## Explore More * **Platform**: Learn more about [Phala Cloud](https://phala.com) * **Blog & Tutorials**: Read the latest [blog posts and guides](https://phala.com/blog) * **About Us**: Discover [Phala's mission and team](https://phala.com/about) ## Support Need help? We're here to assist: * **Documentation Issues**: Report problems with our docs on [GitHub](https://github.com/Phala-Network/phala-docs) * **Technical Support**: Join our [Telegram community](https://t.me/+nbhjx1ADG9EyYmI9) for real-time help * **Enterprise**: [Contact us](https://phala.com/contact) for enterprise solutions and partnerships *** Ready to build secure AI? [Get started with Phala Cloud →](https://cloud.phala.com) # Introduction Source: https://docs.phala.com/network/compute-providers/introduction Essential information for becoming a compute provider on Phala Network(ETH L2). After [Sunsetting Phala Parachain and Migrating to Ethereum L2](https://phala.subsquare.io/democracy/referenda/77), and upgrading the network infrastructure to Intel TDX and GPU Confidential Computing, computing power providers will migrate from the parachain-based environment to the new Ethereum L2 ecosystem. But Phala’s core tokenomics and incentive structure remain largely consistent and predictable. ## 1. Total Supply & High-Level Distribution Phala maintains a fixed total token supply of: * **1,000,000,000 PHA (1 billion PHA)** Out of the total supply, **70% is allocated to mining rewards**. This portion is designed to: * Incentivize long-term network participation * Reward resource providers (especially GPU miners) * Support staking-based security and governance * Fund ecosystem growth via the treasury The **70% mining reward pool** is further split into three parts: | Allocation Target | Share of Mining Rewards | Description | | - | - | - | | **Treasury** | 20% | Ecosystem, development, and long-term strategic funding | | **Ethereum Staking Rewards** | 40% | Rewards for PHA staked into the Ethereum staking contract | | **GPU Miners** | 40% | Rewards for contributing TDX-secured GPU compute | ## 2. PHA → vPHA: The L2 Native & Governance Token After the migration to Ethereum and an L2-based architecture, Phala introduced a **staking contract on Ethereum** that allows users to convert: PHA → vPHA ### 2.1 What is vPHA? **vPHA** is the core token for the **Phala L2 Network**, and is designed to be the primary token used within the L2 ecosystem. Key roles of **vPHA** include: * **Governance**\ Used to participate in community governance and protocol decision-making. * **GPU Worker Staking**\ Used as stake/collateral for GPU workers to participate in the mining set. * **L2 Application Token Use Cases**\ Intended to be the core token for future GPU-related L2 applications and usage scenarios. ### 2.2 Why Stake PHA into vPHA? By staking PHA into the Ethereum staking contract and receiving vPHA, users: * Help secure and govern the Phala L2 ecosystem * Gain access to **staking rewards** (from the 40% mining reward share allocated to Ethereum staking) * Obtain the core utility token for future L2 GPU-related use cases Therefore, the community is **encouraged to convert PHA into vPHA**, and the protocol offers **corresponding PHA staking rewards** to incentivize this behavior. ## 3. GPU Miners: Core of the TDX-Backed GPU Compute Network **GPU miners** are the backbone of Phala’s future **TDX-secured GPU computing network**. By contributing GPU resources to the network, miners receive a portion of the mining rewards based primarily on: * **GPU type** (hardware class and performance) * **Online time** (availability and stability) Rewards are essentially a function of **hardware weight × uptime**. ### 3.1 Reward Weights by GPU Type Different GPU models receive different reward weights to reflect their relative performance and compute value. Currently supported GPU models and their reward weights: | GPU Model | Reward Weight | | - | - | | **H100** | 1.0 | | **H200** | 1.5 | | **B200** | 1.8 | A higher weight implies a higher share of GPU mining rewards, assuming comparable uptime and reliability. ### 3.2 GPU Reward Distribution Mechanism GPU mining rewards are distributed in the form of **vPHA**. * Rewards are calculated continuously based on validated GPU uptime and hardware weight. * **Payouts occur every hour**, with rewards sent at the **end of each hour**. ## 4. vPHA Collateral Requirements for GPU Miners To ensure the **security and reliability** of GPU compute in the network, Phala requires GPU miners to provide additional **vPHA collateral** for each GPU they operate. > This collateral is **not** the same as staking into the Ethereum staking contract.\ > It is **non-yield-bearing** and exists purely as a **security guarantee** for GPU compute. ### 4.1 Required vPHA per GPU The collateral requirements per GPU are: | GPU Model | Required vPHA Stake per GPU | | - | - | | **H100** | 1250 vPHA | | **H200** | 1875 vPHA | | **B200** | 2250 vPHA | Characteristics of this collateral: * It does **not** accrue staking rewards or interest. * It is used strictly as a security mechanism. * It links the operator’s economic interest to the quality and honesty of the GPU service they provide. This design improves: * **Sybil resistance** – prevents low-cost spam or malicious GPU registration * **Reliability** – encourages miners to maintain high-quality nodes and configurations * **Accountability** – provides economic basis for punitive or exclusion mechanisms if needed ## 5. Quality Control & Governance Over GPU Capacity To uphold network reliability, the Phala team will **periodically verify the quality of GPU compute** available in the network. These verifications may include: * Performance and benchmark validation * TDX integrity and security checks * Uptime and stability metrics * Other trust and safety standards defined by the protocol and community If a GPU is found to be **non-compliant** (e.g., underperforming, misconfigured, or malicious), the process is: 1. The issue is documented and shared with the community. 2. Upon announced, the corresponding GPU(s) can be **removed from the mining set**, and associated rewards can be stopped. This ensures the GPU mining ecosystem remains: * **Secure** * **Reliable** * **Aligned with community standards** # Phala GPU Mining Deployment Guide (H100 / H200 / B200) Source: https://docs.phala.com/network/compute-providers/run-GPU-on-phala/gpu-deployment-guide Deploy and manage worker nodes to provide computing power on Phala Network. This document is a step-by-step guide for community members to deploy **Phala GPU Mining** on their own servers. Currently supported GPU models: * **NVIDIA H100** * **NVIDIA H200** * **NVIDIA B200** Deployment is divided into **two major stages**: 1. **Enable TDX in BIOS, configure the system environment, and install Dstack (with GPU stack enabled)** 2. **Run the Phala GPU Mining service inside the server via Docker and connect to Phala Cloud** ## 1. Enable TDX & Install Dstack ### 1.1 Enable TDX in BIOS Before installing or booting the OS, enter the server BIOS and enable: * Intel TDX * Intel VT-x / VT-d * SR-IOV (if available) * Any required CPU virtualization / security features (names may vary by vendor) > Different hardware vendors may use different BIOS names. Please refer to your server’s manual. ### 1.2 Configure TDX System Environment Follow Intel’s / Dstack’s official instructions to configure the TDX system environment: * Dstack repo & basic setup:\ **[https://github.com/Dstack-TEE/dstack](https://github.com/Dstack-TEE/dstack)** If you encounter errors related to **Intel modules** (for example, TDX module installation failures), refer to Intel’s enabling guide: * Intel TDX hardware setup guide:\ **[https://cc-enabling.trustedservices.intel.com/intel-tdx-enabling-guide/04/hardware\_setup/](https://cc-enabling.trustedservices.intel.com/intel-tdx-enabling-guide/04/hardware_setup/)** Make sure all required kernel modules and firmware settings for TDX are correctly configured before continuing. ### 1.3 Upgrade NVIDIA Driver to Latest Version Phala GPU Mining relies on NVIDIA Confidential Computing–capable GPUs and drivers.\ Please upgrade your NVIDIA driver to the latest supported version and verify compatibility: * NVIDIA Confidential Computing compatibility matrix:\ **[https://www.nvidia.com/en-us/data-center/solutions/confidential-computing/secure-ai-compatibility-matrix/](https://www.nvidia.com/en-us/data-center/solutions/confidential-computing/secure-ai-compatibility-matrix/)** After installation, verify that the GPU is correctly recognized: ```bash theme={"system"} nvidia-smi ``` ### 1.4 Install and Run Dstack The base deployment of Dstack follows the official documentation: * Dstack repo:\ **[https://github.com/Dstack-TEE/dstack](https://github.com/Dstack-TEE/dstack)** > By default, the Dstack GitHub documentation focuses on **Confidential CPU** only.\ > To run **Phala GPU Mining**, you must additionally enable and configure the **GPU Stack**. #### 1.4.1 Update `vmm.toml` for GPU Stack Locate your `vmm.toml` configuration file and update (or add) the following fields. **Global paths & KMS configuration:** ```toml theme={"system"} image_path = "" run_path = "" kms_url = "" [cvm] kms_urls = [""] gateway_urls = [""] cid_start = 672000 cid_pool_size = 1000 max_disk_size = 2000 qemu_single_pass_add_pages = false qemu_pic = false qemu_pci_hole64_size = 1125899906842624 qemu_hotplug_off = true ``` **GPU configuration:** ```toml theme={"system"} [cvm.gpu] enabled = true # To expose all available GPU devices to the dashboard and VMs: include = [] # Alternatively, you can explicitly list GPU PCI IDs, e.g.: # include = ["0000:17:00.0"] ``` **Supervisor configuration:** ```toml theme={"system"} [supervisor] detached = true auto_start = false ``` **Notes:** * `cvm.gpu.include` * `[]` = use **all** available GPUs * Or specify specific GPU device IDs as needed. * `kms_url` / `kms_urls` * Replace with your actual KMS installation address or domain. * `gateway_urls` * Replace with your actual Dstack gateway URL(s). * `qemu_path` * In some environments, `qemu` is **not** located at `/opt/qemu-xxx`.\ Check the actual QEMU location and ensure your Dstack configuration points to the correct path. * `image_path` / `run_path` * Use paths where your VM images and runtime files will be stored. #### 1.4.2 Start Dstack Services Once configuration is complete, start the core Dstack components in the following order: 1. **Start KMS** ```bash theme={"system"} ./dstack-kms -c kms.toml ``` 2. **Start Gateway** ```bash theme={"system"} sudo ./dstack-gateway -c gateway.toml ``` 3. **Start VMM** ```bash theme={"system"} ./dstack-vmm -c vmm.toml ``` #### 1.4.3 Verify Dstack Setup Dstack is considered correctly deployed if: * All three processes (**KMS**, **Gateway**, **VMM**) run without critical errors. * You can access the Dstack web UI via its URL (dashboard loads successfully). * GPU devices are visible/usable through Dstack after enabling `[cvm.gpu]`. If these are met, your **Confidential CPU + GPU Stack environment is ready**. ## 2. Run the Phala GPU Mining Service After Dstack and the GPU stack are running correctly, you can start deploying the Phala GPU Mining service. The mining backend is a Docker-based service that: * Connects to your local Dstack instance * Registers the node with **Phala Cloud** * Exposes your GPU resources for Phala GPU mining > It is recommended to run the backend as **root** (or with equivalent privileges). ### 2.1 Use the Official Mining Backend Docker Setup Phala provides an official Docker Compose configuration: * Docker Compose file:\ **[https://github.com/Phala-Network/dstack-mining-backend/blob/main/docker-compose.yaml](https://github.com/Phala-Network/dstack-mining-backend/blob/main/docker-compose.yaml)** * Full backend repo:\ **[https://github.com/Phala-Network/dstack-mining-backend](https://github.com/Phala-Network/dstack-mining-backend)** ### 2.2 Clone the Repository and Configure ```bash theme={"system"} git clone https://github.com/Phala-Network/dstack-mining-backend.git cd dstack-mining-backend ``` Edit `docker-compose.yaml` and update necessary fields: * Dstack gateway and KMS endpoints * Phala Cloud API credentials * Optional: volume mounts, logging, etc. ### 2.3 Start the Mining Backend ```bash theme={"system"} docker compose up -d ``` This will: * Launch the backend container * Connect it to your local Dstack instance * Register your GPU node with Phala Cloud ### 2.4 Confirm Mining Is Active Check Docker containers: ```bash theme={"system"} docker ps ``` View logs: ```bash theme={"system"} docker compose logs -f ``` Your setup is successful when: * Backend connects to Dstack gateway & KMS * GPUs (H100 / H200 / B200) are detected * Your node registers on Phala Cloud * Mining jobs begin to run ## 3. Troubleshooting Common issues: * **Intel TDX module errors**\ → Re-check BIOS and Intel’s TDX guide. * **GPU not detected**\ → Ensure `cvm.gpu.enabled = true` and correct NVIDIA drivers. * **QEMU path issue**\ → Verify QEMU location on your OS. * **Backend cannot reach Dstack**\ → Confirm gateway/KMS URLs and firewall settings. * **Docker device permission issues**\ → Use root or ensure access to `/dev/nvidia*`. # Register Your GPU Worker On-Chain and Start Earning Rewards Source: https://docs.phala.com/network/compute-providers/run-GPU-on-phala/register-work-onchain How to Register Your GPU Worker On-Chain and Start Earning Rewards: After successfully deploying Dstack, enabling TDX + GPU stack support, your GPU worker is technically online — but **not yet registered on-chain**.\ To actually start earning GPU mining rewards, each GPU must: 1. Pass environment verification 2. Receive an official **GPU NFT** 3. Create a **stakepool** 4. Lock the GPU NFT into the stakepool 5. Deposit required **vPHA collateral** 6. Activate mining This guide walks you through each step. ## 1. Manual Environment Verification (Required Before On-Chain Registration) Because the automated GPU verification pipeline is still under development, GPU miners must currently undergo **manual verification**. After your machine: * appears online in Phala Cloud * shows healthy TDX + GPU stack operation * completes all configuration steps Please contact the Phala Delegation Team: [delegation@phala.network](mailto:delegation@phala.network) Include the following: * Your GPU hardware model (H100 / H200 / B200) * Your wallet address (for receiving the NFT) * Any logs or additional information if requested The Phala team will manually verify: * TDX environment readiness * GPU compatibility and stability * Proper Dstack configuration * Worker reliability Once approved, you may proceed to on-chain registration. ## 2. Receive Your GPU NFT After the manual verification is completed, the Phala team will help mint a **GPU Worker NFT** for your device. This NFT: * Represents your GPU on-chain * Stores metadata such as GPU model & reward weight * Is mandatory for earning mining rewards * Must be locked into your stakepool Without the NFT, your GPU **cannot** receive vPHA mining rewards, even if it is online. ## 3. Create Your StakePool A **stakepool** is a container that: * Holds your GPU NFTs * Stores your required vPHA collateral * Tracks your mining activity and earnings * Acts as your mining identity on-chain Each miner typically only needs **one stakepool**, unless managing GPUs under different ownership structures. Using your wallet interface (e.g., MetaMask): 1. Click **Create StakePool** 2. Sign the transaction 3. Wait for on-chain confirmation Your stakepool is now ready. ## 4. Lock Your GPU NFT Into the StakePool Once your stakepool is created: 1. Open the stakepool interface 2. Choose **“Lock NFT”** 3. Select the GPU Worker NFT you just received 4. Confirm the transaction Your GPU is now officially registered on-chain. ## 5. Deposit Required vPHA Collateral Each GPU requires a certain amount of **vPHA collateral** to ensure network security. | GPU Model | Required vPHA | | - | - | | **H100** | 1250 vPHA | | **H100x8** | 10000 vPHA | | **H200** | 1875 vPHA | | **H200x8** | 15000 vPHA | | **B200** | 2250 vPHA | | **B200x8** | 18000 vPHA | To deposit collateral: 1. Convert PHA → vPHA through the staking contract if needed 2. Bridge the vPHA to L2 network via "bridge.phala.network" 3. Open your stakepool 4. Choose **Deposit Collateral** 5. Deposit the required amount (based on GPU type) This collateral: * Does **not** earn rewards * Is used purely as a **security guarantee** * Is fully withdrawable when you retire your GPU and exit properly ## 6. Start Mining and Earn vPHA Rewards After completing: * NFT lock * vPHA collateral deposit * Worker online status in Phala Cloud Your GPU will automatically start the mining process. ### Reward Distribution Details * Rewards are paid in **vPHA** * Rewards are calculated hourly and **Payout happens every hour** at the **end of each hour** ### Reward Weights by GPU Type | GPU Model | Weight | | - | - | | H100 | 1.0 | | H200 | 1.5 | | B200 | 1.8 | You can monitor these metrics on app.phala.network * Worker status * On-chain status (stakepool interface) * Earnings flow (vPHA rewards updated hourly) # Phala Network Overview Source: https://docs.phala.com/network/index Build confidential, verifiable, and decentralized applications with Phala Network's TEE technology. # 👾 Phala Network Docs Welcome to the official documentation for Phala Network, the decentralized cloud computing protocol that enables confidential smart contracts and secure off-chain computation. ## Quick Start * **[Overview](/overview/phala-network)** - Learn about Phala Network's architecture and core concepts * **[Phala Cloud](/phala-cloud/getting-started/overview)** - Deploy confidential applications in Trusted Execution Environments ## What is Phala Network? Phala Network is a decentralized cloud computing protocol that: * **Provides Privacy**: Execute smart contracts and computations in secure enclaves * **Ensures Verifiability**: All computations are cryptographically verifiable * **Scales Efficiently**: Off-chain execution with on-chain verification * **Maintains Decentralization**: Distributed network of compute providers ## Key Products * **[Phala Cloud](/phala-cloud/getting-started/overview)**: Deploy TEE applications easily * **[Dstack](/dstack/overview)**: Decentralized cloud infrastructure * **[GPU TEE](/phala-cloud/confidential-ai/overview)**: Run AI models in secure environments ## Community Join our growing community of developers and users: * [Discord](https://phala.com/discord) * [GitHub](https://phala.com/github) * [Twitter](https://phala.com/x) # Block Explorers Source: https://docs.phala.com/network/overview/block-explorers Support resources, endpoints, and compatibility information for Phala Network. | Chain | URL | | - | - | | Ethereum Mainnet | [https://etherscan.io/](https://etherscan.io/) | | Phala network (Ethereum L2) | [https://explorer.phala.network/](https://explorer.phala.network/) | # Acquiring PHA Source: https://docs.phala.com/network/overview/get-pha-and-transfer Reference documentation and resources for Phala Network development. Phala tokens exist in multiple environments, and it is important for community members to correctly recognize and verify the token contracts they interact with. > [!NOTE] > > **Migrating from Phala/Khala Parachain?** The Phala parachain has been sunset. If you have assets on Khala, Phala parachain, Hydration, or stuck in XCM bridges, see the [Migration Guide](#migrating-from-phala-parachain) section below. ## PHA as an ERC-20 Token **PHA** is an ERC-20 token and can be displayed, transferred, and managed in any **EVM-compatible wallet**, including: * MetaMask * Rabby * Safe (Gnosis Safe) * WalletConnect-compatible wallets This means PHA can be used across the broader Ethereum ecosystem without special configuration. ## What Is vPHA? **vPHA** is the token generated from the **Phala staking contract** on Ethereum.\ Users stake PHA → receive vPHA. vPHA serves several important roles: * **Community governance** * **Staking on Phala L2** * **Required collateral for GPU mining** * **Utility token for future Phala L2 applications** Unlike PHA, vPHA is generally not used for transfers or payments — it represents staked value and governance power. ## How to Add Phala L2 Network to Your Wallet You can add **Phala L2** to any EVM wallet (such as MetaMask or Rabby) by manually entering the official network details. Simply open “Add Network,” fill in: RPC `https://rpc.phala.network`, Chain ID `2035`, Symbol `ETH`, and Explorer `https://explorer.phala.network`, then save. After adding the network, you may also import PHA and vPHA tokens using the correct contract addresses if needed. Once done, your wallet is ready to interact with Phala L2. ## Always Verify Token Contract Addresses For security reasons, community members must always ensure they are interacting with the **correct token contracts**.\ Below are the *official and only valid* contract addresses: ### **ERC-20 Contracts (Ethereum Mainnet)** | Token | Contract Address | | - | - | | **PHA (ERC20)** | `0x6c5bA91642F10282b576d91922Ae6448C9d52f4E` | | **vPHA (ERC20)** | `0x21d6eC8fc14CaAcc55aFA23cBa66798DAB3a0ec0` | | **PHA Claim Contract** | `0x8b6d7AB0BE8d1f6AE40738C4CFF75134110a777F` | ### **Phala L2 Contracts** | Token | Contract Address | | - | - | | **PHA (Phala L2)** | `0xd63dD43678124DEb6bF38b0d7f8cf0674e85c46E` | | **vPHA (Phala L2)** | `0xFdCEBD2E111D64Fc8a682703Eac62918093ec856` | ## Transfer PHA/vPHA between Ethereum and Phala L2 [#Transfer-PHA/vPHA-between-Ethereum-and-Phala-L2](#Transfer-PHA/vPHA-between-Ethereum-and-Phala-L2) You can transfer PHA and vPHA between Ethereum and Phala L2 using [Superbridge](https://bridge.phala.network). ### Bridge from Ethereum to Phala L2 1. Go to [bridge.phala.network](https://bridge.phala.network) 2. Connect your wallet (MetaMask, Rabby, etc.) 3. Select **Ethereum → Phala L2** 4. Enter the amount of PHA or vPHA to bridge 5. Confirm the transaction and pay gas fees ### Bridge from Phala L2 to Ethereum 1. Go to [bridge.phala.network](https://bridge.phala.network) 2. Connect your wallet and switch to **Phala L2** network 3. Select **Phala L2 → Ethereum** 4. Enter the amount to bridge 5. Confirm the transaction > [!WARNING] > > **Gas fees required:** When bridging from Phala L2 to Ethereum, you need ETH on Phala L2 for gas. Bridge a small amount of ETH (\~0.001 ETH is sufficient) from Ethereum to Phala L2 first. ## Get your Phala Tokens (PHA) [#get-your-phala-tokens-pha](#get-your-phala-tokens-pha) If you do not hold any PHA, you can purchase PHA from any of the following exchanges: > [card] Binance > > ![Binance](https://mintcdn.com/phalanetwork-1606097b/RUscSf7Rplq7j02n/images/1-Binance.png?fit=max\&auto=format\&n=RUscSf7Rplq7j02n\&q=85\&s=8766d79fcb8c68b36d123d49fd58fd2b) > > [Trade PHA on Binance →](https://www.binance.com/en) > [card] Kraken > > ![Kraken](https://mintcdn.com/phalanetwork-1606097b/Y2wR1-jOsoYpAL6q/images/kraken.jpeg?fit=max\&auto=format\&n=Y2wR1-jOsoYpAL6q\&q=85\&s=6feba60b016de8b460766b08f724f775) > > [Trade PHA on Kraken →](https://www.kraken.com/prices/phala.network) > [card] OKEX > > ![OKX](https://mintcdn.com/phalanetwork-1606097b/RUscSf7Rplq7j02n/images/3-OKEx.png?fit=max\&auto=format\&n=RUscSf7Rplq7j02n\&q=85\&s=ae39cef0e72856ae77954d6edb6f7c1c) > > [Trade PHA on OKX →](https://www.okx.com/trade-spot/pha-usdt) > [card] HTX > > ![Huobi](https://mintcdn.com/phalanetwork-1606097b/RUscSf7Rplq7j02n/images/2-Huobi.png?fit=max\&auto=format\&n=RUscSf7Rplq7j02n\&q=85\&s=f104b2b54f9e68ac1936811bf91b4454) > > [Trade PHA on Huobi →](https://www.htx.com/price/pha/) > [card] KuCoin > > ![KuCoin](https://mintcdn.com/phalanetwork-1606097b/RUscSf7Rplq7j02n/images/4-KuCoin.png?fit=max\&auto=format\&n=RUscSf7Rplq7j02n\&q=85\&s=f08ff8c7f5dcab85fd412ee597ec04bd) > > [Trade PHA on KuCoin →](https://trade.kucoin.com/PHA-USDT) > [card] Gate.io > > ![Gate.io](https://mintcdn.com/phalanetwork-1606097b/RUscSf7Rplq7j02n/images/7-Gate.png?fit=max\&auto=format\&n=RUscSf7Rplq7j02n\&q=85\&s=6637cb4a04358d0c54bfe0550ea49fce) > > [Trade PHA on Gate.io →](https://www.gate.io/trade/PHA_USDT) > [!NOTE] > > Not all brokers may be available in your jurisdiction. Note that some brokers require you to have an account with them for a certain period before you can transfer your funds to another wallet, such as the [Phala Wallet](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fphala.api.onfinality.io%2Fpublic-ws#/accounts). *** ## Migrating from Phala Parachain > [!WARNING] > > The Phala/Khala parachain has been sunset. PHA tokens now exist primarily on Ethereum and Phala L2. If you have assets on the old parachain or related networks, follow the guides below to migrate them. ### Claim Assets from Khala/Phala Parachain If you had PHA staked, delegated in pools/vaults, or in your wallet on the original Khala or Phala parachain: 1. Go to the **Khala Assets Portal**: [app.phala.network/khala-assets](https://app.phala.network/khala-assets) 2. Connect your Ethereum wallet that corresponds to your old Substrate address 3. Follow the claim process to receive your assets on Phala L2 > [!NOTE] > > **Requirements for claiming:** > > * An Ethereum wallet with ETH for gas fees > * Assets will be claimed to Phala L2 > * Add Phala L2 to your wallet first (see [How to Add Phala L2](#how-to-add-phala-l2-network-to-your-wallet)) **Resources:** * [Claim System Tutorial](https://forum.phala.network/t/phala-assets-claim-system-now-alive/4002) * [Sunset Announcement](https://forum.phala.network/t/proposal-sunsetting-phala-parachain-and-migrating-to-ethereum-l2/3999) ### Migrate PHA from Hydration If your PHA is on Hydration (formerly Basilisk), a Polkadot parachain with EVM-style addresses (0x...): > [!WARNING] > > Hydration addresses look like Ethereum addresses but are NOT Ethereum accounts. The Phala snapshot did not include Hydration balances, so the claim UI will show "0 PHA". **Manual Claim Process:** Since the Phala network is sunset, the team processes Hydration claims manually: 1. **Transfer tokens to the burning address:** ``` 13UVJyLnbVp9RBZYFwFGyDvVd1y27Tt8tkntv6Q7JVPhFsTB ``` 2. **Provide verification:** * Your Hydration address (the one that held PHA) * Your Ethereum address as recipient * Signature data for ownership verification * Link to the burning transaction 3. **Alternative verification method:** Send three batches to the burning address to prove ownership: * First: 1 PHA * Second: 2 PHA * Third: All remaining PHA 4. **Contact support** via the [Phala Forum](https://forum.phala.network/t/manual-claim-guide-for-hydration-users/4003) or support channels After verification, the team will execute the claim to your Ethereum address. ### Stuck XCM Transfers (Moonbeam, etc.) If you have PHA stuck in an XCM transfer from Phala to Moonbeam or other parachains: Since the Phala parachain is sunset, XCM bridges are no longer operational. The team can help claim stuck assets manually. **Process:** 1. Verify ownership of your Phala address: [Verification Guide](https://www.notion.so/phalanetwork/How-to-verify-your-Phala-address-2bc0317e04a1809291c7eb6f3e33ad6b) 2. Provide: * Signature proving address ownership * Your Ethereum address as recipient 3. Contact support with verification proof After verification, the team will issue the transfer to your Ethereum address. ### Bridge PHA from BSC (Binance Smart Chain) For PHA on Binance Smart Chain (BEP-20), there is no direct bridge to Ethereum ERC-20. Use one of these options: **Option 1: Via Binance Exchange** 1. Deposit your BSC PHA to Binance (the centralized exchange) 2. Withdraw as ERC-20 PHA to your Ethereum wallet **Option 2: Swap on DEX** 1. Go to [PancakeSwap](https://pancakeswap.finance/?chain=bsc) 2. Swap your BSC PHA for another token (e.g., USDT, BNB) 3. Bridge that token to Ethereum using a cross-chain bridge 4. Swap back to PHA on Ethereum ### Already Have PHA on Ethereum? If your PHA tokens are already on Ethereum (ERC-20), there's nothing you need to do. Your tokens are in the correct format. You can: * [Stake PHA to receive vPHA](/network/overview/phala-staking) * Use PHA with any DeFi protocol on Ethereum * Bridge to Phala L2 for lower gas fees # Phala Governance Source: https://docs.phala.com/network/overview/phala-governance Participate in Phala Network governance using PHA tokens and democratic processes. Phala uses **Snapshot** as its off-chain governance platform, allowing community members to participate in proposals and voting without paying gas fees. Anyone holding **vPHA** (the governance token) can take part in decision-making. ## How Voting Works Snapshot takes periodic “snapshots” of wallet balances to determine voting power.\ Your **vPHA balance at the snapshot block** decides how many votes you have.\ No tokens are locked, and no transactions are sent—governance is **gas-free**. ## How to Participate 1. Go to the Phala Snapshot space:\ **[https://snapshot.box/#/s:phala-network.eth](https://snapshot.box/#/s:phala-network.eth)** 2. Connect your wallet (MetaMask, Rabby, OKX Wallet, etc.). 3. Browse active proposals:\ Each proposal includes: * Title & description * Voting options * Voting period * Impact on the network 4. Cast your vote:\ Choose an option and sign a message.\ **No gas fee** is involved, as Snapshot uses off-chain signatures. ## Creating a Proposal (for eligible members) 1. Click **New Proposal** 2. Fill in: * Title * Summary and motivation * Voting options (Yes/No/Multiple Choice) * Voting duration 3. Submit and sign—your proposal will go live instantly. ## Best Practices for Governance * Hold **vPHA** to participate effectively. * Read proposal details carefully before voting. * Participate early in case you need to switch networks or adjust your wallet. * Discuss proposals on the Discord before they go live. Phala’s Snapshot governance is designed to be open, gas-free, and accessible.\ If you hold vPHA, no matter it's on Ethereum or Phala L2, you are an active part of the network—your vote directly shapes Phala’s future. # Phala Network Source: https://docs.phala.com/network/overview/phala-network Overview of Phala Network's decentralized computing infrastructure and features. Confidential AI inference stands as a cornerstone for safeguarding sensitive data and ensuring secure AI model execution in Web3. Through the implementation of LLM models within Trusted Execution Environments (TEE), Phala Network delivers private and verifiable AI computations. This robust approach addresses fundamental challenges in the Web3 ecosystem: data privacy protection, secure execution guarantees, and computational verifiability. Such capabilities are essential for applications where the protection of user data and model integrity is paramount. ## **What Sets Phala Apart:** * **We Don't Trust Any Provider**: Our **security model** goes beyond traditional cloud solutions (e.g., AWS, Azure, GCP). **Phala does not trust any cloud platform, hardware provider, or even its users,** ensuring true zero-trust. * **User-Friendly & Affordable**: With **easy integration**, developers can migrate their **Web2 software** into a zero-trust environment. By using TEE as part of our hybrid infrastructure, developers can select the **level of proof** they need based on their use case, making the system both flexible and affordable. * **Web3 Standard Compatibility**: Phala is fully **decentralized, privacy-focused**, and auditable. Our SDK enables your programs to **easily integrate with blockchains**, providing seamless co-processing and interaction with Web3 systems. ## **How It Works** ![](https://mintcdn.com/phalanetwork-1606097b/qg5qPVMhhp3UKpah/images/phala-network-architecture.png?fit=max\&auto=format\&n=qg5qPVMhhp3UKpah\&q=85\&s=cec4ac5180ffd8b3ccc8d0c115867499) * Phala introduces a **new root-of-trust** beyond traditional hardware-based models. * We implement a combination of **TEE, MPC, ZKP (FHE)** and **blockchain game theory** to build this **new root-of-trust**. * Our system offers **auditable computation**, ensuring that anyone can verify the integrity of execution results, creating a **tamper-proof** environment. ## **The Solution** Phala provides a comprehensive suite of tools and infrastructure to make zero-trust computing **easy to access**, **build**, and **verify**: * **Easy Access to Computers**: [Phala Cloud](https://cloud.phala.com/register?invite=PHALAWIKI) provides access to TEE hardware, including **Intel TDX**, **Intel SGX**, **AMD SEV**, and **NVIDIA H100/H200 (TEE)**, offering secure and verifiable computation at scale. Phala Cloud supports deployment of any Docker application into TEE environments, making it easy to migrate existing workloads to confidential computing. * **Easy to Build**: [Dstack](/dstack/overview) is the TEE SDK developed by Phala and Flashbots jointly * **Docker / VM migration into TEE**, allowing developers to move existing workloads into a zero-trust environment. * **Serverless edge functions**: Leverage pre-built templates to create **serverless, privacy-preserving functions** that run in secure TEEs. * **Easy to Prove**: Phala offers **on-chain attestation** for auditable logs of off-chain computations, ensuring integrity and transparency. Developers can prove the correctness of their computations in a verifiable, decentralized way. ## **The Future is Here (Use Cases)** * **Web2 to Web3**: Easily transition Web2 software to **Web3 standards**, with seamless connectivity to smart contracts across blockchains. * **Intelligence-Based Economy**: Solutions like **MEV, Intent-centric applications**. Flashbots uses TEE for decentralized MEV-boost on Ethereum. Uniswap is using TEE to build a DeFi-native Ethereum L2, becoming a hub for liquidity across chains. * **Defense in Depth**: Projects like **Lit Protocol (MPC)**, **Zama (FHE)**, and **Scroll (ZKP)** use TEE to enhance their security and privacy, strengthening their defenses. * **Decentralized AI**: With **NVIDIA's GPU TEEs**, decentralized AI platforms like **NEAR AI, Sentient, Zero Gravity, Ritual, Morpheus**, and **Autonolas** use TEEs to run LLMs in secure, verifiable, and privacy-focused environments as part of their infrastructure. # phala staking Source: https://docs.phala.com/network/overview/phala-staking Stake PHA tokens to earn rewards and support network governance. ## What Is the Phala Staking Contract? The Phala Staking Contract lives on **Ethereum Mainnet** and allows users to convert **PHA to vPHA**.\ In simple terms: * You deposit **PHA** into the staking contract * The contract mints and sends you **vPHA** (an ERC-20 token) * **vPHA** is used for: * Community governance (Snapshot voting) * Staking & collateral on Phala L2 * GPU mining (required collateral + reward token) In short:\ **PHA = liquid token**,\ **vPHA = governance & staking token** for the Phala ecosystem. ## Official Contract Addresses (Verify Before Use) Always double-check that you are interacting with the correct contracts: * **PHA (ERC20)**: `0x6c5bA91642F10282b576d91922Ae6448C9d52f4E` * **vPHA (ERC20)**: `0x21d6eC8fc14CaAcc55aFA23cBa66798DAB3a0ec0` > ⚠️ Only use the addresses above.\ > Do not stake or transfer tokens to any unknown or unverified contract. ## How to Stake PHA and Receive vPHA > The process works with any EVM wallet such as MetaMask, Rabby, Safe, etc.\ > official Phala staking page: [https://app.phala.network/staking](https://app.phala.network/staking) . ### **Step 1 — Prepare Your Wallet** 1. Switch wallet to **Ethereum Mainnet** 2. Make sure your wallet has: * **PHA (ERC20)** — the tokens you want to stake * **ETH** — to pay Ethereum gas fees ### **Step 2 — Connect to the Phala Staking Page** 1. Open the official Phala staking page 2. Click **“Connect Wallet”** 3. Approve the connection in your wallet ### **Step 3 — Stake PHA → Receive vPHA** 1. Enter the amount of **PHA** you want to stake 2. First-time users must click **Approve** to allow the contract to use PHA 3. Once approved, click **Stake** 4. Confirm the transaction in your wallet After the transaction is confirmed: * Your PHA is deposited into the staking contract * You receive vPHA equal in value to the PHA you staked, based on the real-time vPHA-PHA exchange rate * As the staking contract accumulates rewards, the exchange rate increases over time, meaning vPHA represents a growing amount of PHA when you unstake. To display vPHA, manually add the ERC-20 contract address in your wallet. *** ## Unstaking vPHA to PHA Unstaking converts your vPHA back to PHA. The process takes **21 days** to complete. ### Step 1: Initiate Unstaking 1. Go to [app.phala.network/staking](https://app.phala.network/staking) 2. Connect your wallet (must be on **Ethereum Mainnet**) 3. Click **Unstake** 4. Enter the amount of vPHA to unstake 5. Confirm the transaction and pay gas fees After the transaction confirms, your vPHA enters a 21-day unlock period. ### Step 2: Wait for Unlock Period * Your tokens are locked for **21 days** * You can track the unlock countdown in the staking dashboard * You cannot cancel an unstaking request once initiated ### Step 3: Claim Your PHA After the 21-day period ends: 1. Return to [app.phala.network/staking](https://app.phala.network/staking) 2. Connect your wallet 3. You'll see your unlocked PHA available to claim 4. Click **Claim** to receive your PHA 5. Confirm the transaction > [!WARNING] > > **You must manually claim your PHA** after the unlock period. Tokens do not automatically transfer to your wallet. ### Unstaking from Phala L2 If your vPHA is on Phala L2 (not Ethereum Mainnet): 1. First, bridge your vPHA to Ethereum using [bridge.phala.network](https://bridge.phala.network) 2. You need ETH on Phala L2 for gas fees (\~0.001 ETH is sufficient) 3. Once on Ethereum, follow the unstaking steps above > [!NOTE] > > **Need ETH on Phala L2?** Bridge a small amount from Ethereum first using [bridge.phala.network](https://bridge.phala.network). ### Troubleshooting **"Insufficient ETH" error when bridging from L2:** * You need ETH on Phala L2 for gas, not just on Ethereum * Bridge \~0.001 ETH from Ethereum to Phala L2 first **Can't see vPHA in portfolio:** * Check if your vPHA is on Phala L2 or Ethereum * Add the vPHA token contract to your wallet: `0x21d6eC8fc14CaAcc55aFA23cBa66798DAB3a0ec0` **vPHA balance seems lower than expected:** * vPHA represents staked value at a conversion rate that increases over time * Check your deposit history at the bottom of the staking page * If you provided liquidity on Uniswap, your vPHA won't show in the Phala app *** ## Safety Notes Always verify: * Contract addresses before any transaction * Transaction prompts match your intended action * You are connected to **Ethereum Mainnet** > [!WARNING] > > Never send tokens to unknown addresses. Only use the official contract addresses listed in this documentation. # Phala Treasury Source: https://docs.phala.com/network/overview/phala-treasury Participate in Phala Network governance using PHA tokens and democratic processes. The Treasury is a pot of funds collected through transaction fees, slashing, Secure Worker mining rate (20%) , etc. The funds held in the Treasury can be spent by making a spending proposal that, if approved by the community, will be issued to the receipents. The Treasury attempts to spend as many proposals in the queue as it can without running out of funds. Proposals may consist of (but are not limited to): * Infrastructure deployment and continued operation. * Network security operations (monitoring services, continuous auditing). * Ecosystem provisions (collaborations with friendly chains). * Marketing activities (advertising, paid features, collaborations). * Community events and outreach (meetups, pizza parties, hackerspaces). * Software development (wallets and wallet integration, clients and client upgrades). The Treasury comes from: 70% of the PHA will be used for Secure Worker Mining, and following the progress of the Phala network, 20% of the mining rewards generated by each block will be used to fund treasury. # Attestation Fields Reference Source: https://docs.phala.com/phala-cloud/attestation/attestation-fields Reference guide for Intel TDX attestation quote fields and their meanings. This reference explains each field in an Intel TDX attestation quote. Use this when you need to understand or verify specific measurements. ## Example Quote Here's a typical attestation quote from Phala Cloud: ```json theme={"system"} { "tee_tcb_svn": "06010300000000000000000000000000", "mr_seam": "5b38e33a6487958b72c3c12a938eaa5e3fd4510c51aeeab58c7d5ecee41d7c436489d6c8e4f92f160b7cad34207b00c1", "mr_signer_seam": "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "seam_attributes": "0000000000000000", "td_attributes": "0000001000000000", "xfam": "e702060000000000", "mr_td": "c68518a0ebb42136c12b2275164f8c72f25fa9a34392228687ed6e9caeb9c0f1dbd895e9cf475121c029dc47e70e91fd", "mr_config_id": "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "mr_owner": "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "mr_owner_config": "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "rt_mr0": "85e0855a6384fa1c8a6ab36d0dcbfaa11a5753e5a070c08218ae5fe872fcb86967fd2449c29e22e59dc9fec998cb6547", "rt_mr1": "9b43f9f34a64bc7191352585be0da1774a1499e698ba77cbf6184547d53d1770d6524c1cfa00b86352f273fc272a8cfe", "rt_mr2": "7cc2dadd5849bad220ab122c4fbf25a74dc91cc12702447d3b5cac0f49b2b139994f5cd936b293e5f0f14dea4262d668", "rt_mr3": "2c482b5b34f6902293bc203696f407241bfa319d2410a04c604d1021888d6028bf4bd280ff859ee270a0429aac5f0d82", "report_data": "afab9790acb13c4c651c1933a22b5f0663ef22927120dd08cc8291d7e0912d8b1c36eb75cf661a64735042f8e81bbe42cb9ab310ca95bf8d36c44cb8835c901f" } ``` ## Hardware Fields ### tee\_tcb\_svn **Trusted Computing Base Security Version Number** Security patch level for TEE hardware components. Verify this matches the latest version to ensure no known vulnerabilities. ### mr\_seam (MRSEAM) **Measurement of TDX-Module** Cryptographic hash of the SEAM (Secure Arbitration Mode) firmware. Confirms the TDX firmware hasn't been tampered with. ### mr\_td (MRTD) **Measurement Register for Trust Domain** Hash of the initial Trust Domain memory and configuration. Proves the TD was initialized with expected contents. ### seam\_attributes **SEAM Firmware Attributes** Configuration flags for SEAM firmware. Always zeros for Intel TDX. ### td\_attributes **Trust Domain Attributes** Configuration flags for the TD. Verifies the TD has expected security settings. ### xfam **eXtended Feature Activation Mask** Controls which CPU extended features are accessible to the TD. Ensures proper security boundaries. ## Runtime Measurement Registers (RTMRs) These registers contain hash chains of boot components. ### RTMR0 **Virtual Hardware Measurement** Measures the virtual hardware environment provided to the CVM. ### RTMR1 **Linux Kernel Measurement** Hash of the Linux kernel loaded during boot. ### RTMR2 **Kernel Parameters Measurement** Measurement of kernel command line and initrd. ### RTMR3 **Application Measurement** dstack-specific measurements including: * **app-id**: Relevant for KMS key derivation * **compose-hash**: Hash of your Docker Compose configuration * **instance-id**: Unique CVM instance identifier * **key-provider**: Who distributed the root filesystem encryption keys ## RTMR3 Hash Chain RTMR3 uses a hash chain mechanism: ``` RTMR3_new = SHA384(RTMR3_old || SHA384(event)) ``` Each application component (compose-hash, instance-id, key-provider) is hashed individually, then chained together. Verify the final RTMR3 value using the [rtmr3-calculator](https://rtmr3-calculator.vercel.app/) tool. ## Application-Specific Fields ### report\_data (reportData) **User-Provided Data (64 bytes)** Custom data you attach to the quote. Common uses: * **Public keys**: Bind a public key to prove you control the private key * **Nonces**: Challenge-response protocols * **Application state**: Hash of configuration or state ### mr\_config\_id, mr\_owner, mr\_owner\_config **Configuration and Ownership** Usually all zeros for dstack deployments. Reserved for advanced attestation scenarios. ## Which Fields Should I Verify? Different verification levels require checking different fields: **Quick Verification:** * `report_data` - Your challenge or public key * Use Cloud API for hardware verification See [Quickstart](/phala-cloud/attestation/quickstart) for step-by-step guide. **Application Verification:** * `rt_mr3` (RTMR3) - Your compose-hash * `report_data` - Custom data binding * Use Cloud API for hardware and OS See [Verify Your Application](/phala-cloud/attestation/verify-your-application) for complete guide. **Complete Platform Verification:** * `mr_td` (MRTD) - OS initial state * `rt_mr0` through `rt_mr2` - OS boot chain * `rt_mr3` (RTMR3) - Application and KMS binding * `tee_tcb_svn` - Security patch level * `mr_seam` - TDX firmware measurement See [Verify the Platform](/phala-cloud/attestation/verify-the-platform) for complete guide. **Security Audit:** * All measurements above * On-chain governance verification * Reproducible OS builds * KMS attestation See [Complete Chain of Trust](/phala-cloud/attestation/chain-of-trust) for checklist. ## Resources * **[dstack Attestation Guide](https://github.com/Dstack-TEE/dstack/blob/next/docs/attestation-tdx.md)** - How dstack implements attestation * **[Intel TDX Specification](https://www.intel.com/content/www/us/en/developer/articles/technical/intel-trust-domain-extensions.html)** - Official Intel documentation * **[RTMR3 Calculator](https://rtmr3-calculator.vercel.app/)** - Verify RTMR3 values * **[Verification Script](https://github.com/Dstack-TEE/dstack-examples/blob/main/attestation/rtmr3-based/verify.py)** - Example verification code ## Next Steps > [card] [Quickstart](/phala-cloud/attestation/quickstart) > > Verify your first quote > [card] [Verify Your Application](/phala-cloud/attestation/verify-your-application) > > Prove your exact code is running > [card] [Verify the Platform](/phala-cloud/attestation/verify-the-platform) > > Verify OS, KMS, and infrastructure > [card] [Complete Security Checklist](/phala-cloud/attestation/chain-of-trust) > > Complete verification with no trust assumptions # Complete Chain of Trust Source: https://docs.phala.com/phala-cloud/attestation/chain-of-trust Complete security checklist ensuring no verification gaps exist. Hardware attestation alone isn't enough — anyone in the supply chain can still compromise your security. This guide covers every verification item needed for trustless execution and proves they're sufficient together. ## Why Complete Verification Matters Hardware attestation alone proves your code runs in genuine TEE hardware. But anyone in the supply chain could still compromise your security: **Cloud provider** could substitute OS images with backdoored versions. **Docker registry** could serve malicious container images. **Malicious KMS** could leak encryption keys and TLS certificates. **Network attacker** could impersonate your domain with fraudulent certificates. **Unauthorized developer** could deploy malicious code updates. Each of these attacks bypasses hardware attestation. You need to verify the **complete chain of trust** from source code to running CVM. ## The Complete Trust Chain ```mermaid theme={"system"} flowchart TB subgraph L1[What You Control] B[Application: compose-hash in RTMR3] G[Custom Data: reportData field] end subgraph L2[Platform Infrastructure] A[OS: MRTD, RTMR0-2] C[Keys: key-provider in RTMR3] D[Network: TLS certificate binding] end subgraph L3[Authorization] E[Governance: Smart contracts] end L1 --> Q[TDX Quote: Cryptographically signed package] L2 --> Q L3 --> Q Q --> V[Verification: Compare measurements against expected values] ``` Six independent trust chains are recorded in one cryptographically signed attestation quote. Verification confirms each measurement matches your expected values. ## Application Verification Checklist These items prove your specific application code runs unmodified: ### ☐ reportData Binding **What it prevents:** Replay attacks where old attestation quotes are reused. **How it works:** The 64-byte `reportData` field contains your custom challenge (nonce) or public key. The TEE includes this in the signed quote. **Why it's necessary:** Without reportData verification, an attacker could replay an old valid quote instead of generating a fresh one. Challenge-response proves the quote was generated specifically for you. **How to verify:** See [Quickstart: Step 2](/phala-cloud/attestation/quickstart#step-2-verify-the-challenge) ```javascript theme={"system"} // Verify reportData contains your challenge const reportData = Buffer.from(quote.quote.reportData, 'hex'); const receivedChallenge = reportData.subarray(0, 32); assert(receivedChallenge.equals(challenge)); ``` ### ☐ compose-hash Matching **What it prevents:** Code substitution attacks where different Docker images are deployed. **How it works:** Your entire docker-compose.yaml (including all image SHA256 digests) is hashed into RTMR3. The CVM verifies image digests before pulling from the registry. **Why it's necessary:** Without compose-hash verification, a compromised registry could serve malicious images. The TEE prevents this by verifying digests match the compose-hash recorded in RTMR3. **How to verify:** See [Verify Your Application: Complete Verification](/phala-cloud/attestation/verify-your-application#complete-verification-trustless) ```javascript theme={"system"} import { getComposeHash } from '@phala/dstack-sdk'; // Calculate expected hash const expectedHash = getComposeHash(JSON.parse(appCompose)); // Extract from RTMR3 event log const events = JSON.parse(quote.event_log); const attestedHash = events.find(e => e.event === 'compose-hash').event_payload; assert(expectedHash === attestedHash); ``` ### ☐ Docker Digest Pinning **What it prevents:** Image tampering where registry serves different images for the same tag. **How it works:** All images must use SHA256 digests (not tags) in docker-compose.yaml. Tags like `nginx:latest` are mutable. Digests are immutable. **Why it's necessary:** Without digest pinning, the compose-hash would be meaningless. A tag could point to different images over time, making verification impossible. **How to verify:** See [Verify Your Application: Understanding Image Digests](/phala-cloud/attestation/verify-your-application#understanding-image-digests) ```yaml theme={"system"} # Good: Immutable digest image: nginx@sha256:eee5eae48e79b2e75178328c7c585b89d676eaae616f03f9a1813aaed820745a # Bad: Mutable tag image: nginx:latest ``` ### ☐ RTMR3 Event Log Replay **What it prevents:** Event log tampering where attacker modifies compose-hash or key-provider events. **How it works:** RTMR3 uses a hash chain (RTMR3 = SHA384(RTMR3 || event)). You replay all events to recalculate RTMR3 and verify it matches the quote. **Why it's necessary:** Without replay verification, you can't trust the event payloads. An attacker could modify events and claim different compose-hash values. **How to verify:** See [Verify Your Application: Step 4](/phala-cloud/attestation/verify-your-application#step-4-replay-rtmr3-event-log) ```javascript theme={"system"} // Replay events to verify RTMR3 const rtmrs = quoteResponse.replayRtmrs(); assert(rtmrs.rtmr3 === quoteResponse.quote.rt_mr3); ``` ### ☐ Image Provenance **What it prevents:** Supply chain attacks where build infrastructure is compromised. **How it works:** Link Docker image digests back to source code using Sigstore (GitHub-endorsed builds) or reproducible builds. **Why it's necessary:** The compose-hash proves which images ran, but not whether those images came from your source code. Provenance links images to specific git commits. **How to verify:** See [Verify Your Application: Linking Images to Source Code](/phala-cloud/attestation/verify-your-application#linking-images-to-source-code) ### ☐ Application Governance **What it prevents:** Unauthorized updates where malicious developers deploy unapproved versions. **How it works:** Only compose hashes whitelisted in the `DstackApp` smart contract can boot. **Why it's necessary:** Without on-chain governance, any developer with deploy access could push malicious code. The contract enforces authorization. **How to verify:** See [Verify Your Application: Step 6](/phala-cloud/attestation/verify-your-application#step-6-verify-on-chain-governance-optional) ```bash theme={"system"} cast call "allowedComposeHashes(bytes32)" ``` ## Platform Verification Checklist These items prove Phala's infrastructure is secure: ### ☐ Hardware Measurements **What it prevents:** Fake TEE hardware or compromised firmware. **How it works:** Intel signs the TDX quote with hardware root of trust. The signature proves genuine Intel TDX hardware generated the quote. **Why it's necessary:** Without hardware verification, an attacker could fake a quote using software simulation. The cryptographic signature prevents this. **How to verify:** Use Phala Cloud API (verifies Intel signature automatically) or see [Verify the Platform: Hardware & Firmware](/phala-cloud/attestation/verify-the-platform#1-hardware--firmware-verification) ```bash theme={"system"} curl -X POST "https://cloud-api.phala.com/api/v1/attestations/verify" \ -H "Content-Type: application/json" \ -d '{"hex": "YOUR_QUOTE_HEX"}' ``` ### ☐ OS Measurements **What it prevents:** Backdoored OS images with malware or data exfiltration code. **How it works:** MRTD and RTMR0-2 contain hashes of virtual firmware, hardware config, kernel, and boot parameters. These measurements are recorded during boot. **Why it's necessary:** Without OS verification, a compromised cloud provider could substitute the OS with a backdoored version. Measurements make OS tampering detectable. **How to verify:** See [Verify the Platform: Operating System Verification](/phala-cloud/attestation/verify-the-platform#2-operating-system-verification) ```bash theme={"system"} # Calculate expected measurements cargo run --bin dstack-mr measure -c 4 -m 4G ../dstack-0.5.4/metadata.json # Compare against quote ``` ### ☐ OS Reproducibility **What it prevents:** Compromised build infrastructure injecting malicious code. **How it works:** The dstack OS is built from [meta-dstack](https://github.com/Dstack-TEE/meta-dstack) using Yocto. Anyone can rebuild from a specific git commit and get identical measurements. **Why it's necessary:** Without reproducibility, you must trust Phala's pre-built releases. Reproducible builds let you verify independently. **How to verify:** See [Verify the Platform: Step 2 Option B](/phala-cloud/attestation/verify-the-platform#step-2-download-or-build-os-image) ```bash theme={"system"} git clone https://github.com/Dstack-TEE/meta-dstack.git cd meta-dstack git checkout # Follow reproducible build instructions ``` ### ☐ OS Whitelist **What it prevents:** Unauthorized OS versions with unknown security properties. **How it works:** Only OS image hashes whitelisted in `DstackKms.allowedOsImages` can boot. **Why it's necessary:** Without on-chain governance, any OS version could run. The whitelist ensures only audited OS versions are used. **How to verify:** See [Verify the Platform: Step 5](/phala-cloud/attestation/verify-the-platform#step-5-verify-on-chain-os-whitelist) ```bash theme={"system"} cast call "allowedOsImages(bytes32)" ``` ### ☐ KMS Identity **What it prevents:** Malicious KMS instances leaking encryption keys and TLS certificates. **How it works:** The KMS root CA public key hash is recorded in RTMR3 as the `key-provider` event. This binds your app to a specific KMS instance. **Why it's necessary:** All your keys (disk encryption, TLS, signing keys) derive from the KMS root keys. A malicious KMS compromises everything. RTMR3 binding prevents silent KMS substitution. **How to verify:** See [Verify the Platform: Key Management Verification](/phala-cloud/attestation/verify-the-platform#3-key-management-verification) ```javascript theme={"system"} const events = JSON.parse(quote.event_log); const keyProvider = events.find(e => e.event === 'key-provider'); console.log('KMS ID:', JSON.parse(keyProvider.event_payload).id); ``` ### ☐ KMS Attestation **What it prevents:** Compromised KMS running malicious code. **How it works:** The KMS itself is a TEE instance with its own attestation quote. You verify the KMS's hardware, OS, and application code independently. **Why it's necessary:** Binding to a KMS in RTMR3 is meaningless if that KMS is compromised. You must verify the KMS's complete chain of trust. **How to verify:** See [Verify the Platform: Step 2](/phala-cloud/attestation/verify-the-platform#step-2-verify-the-kms-itself) ### ☐ KMS Governance **What it prevents:** Unauthorized KMS instances with unknown security properties. **How it works:** Only KMS instances with whitelisted "aggregated MR" (combined hash of all measurements) can operate. **Why it's necessary:** Without governance, any KMS instance could be used. The whitelist ensures only audited KMS instances are trusted. **How to verify:** See [Verify the Platform: Step 3](/phala-cloud/attestation/verify-the-platform#step-3-verify-kms-governance) ```bash theme={"system"} cast call "kmsAllowedAggregatedMrs(bytes32)" ``` ### ☐ TLS Certificate Binding **What it prevents:** Certificate impersonation attacks where attacker issues fraudulent certificates. **How it works:** The TEE generates TLS certificates and publishes evidence files at `/evidences/`. The quote's `reportData` contains a hash of the evidence, cryptographically binding certificate to quote. **Why it's necessary:** Without binding, anyone (domain owner, CA, cloud provider) could issue valid certificates for your domain. Binding proves the TEE controls the certificate. **How to verify:** See [Domain Attestation](/phala-cloud/networking/domain-attestation) ```javascript theme={"system"} // Verify evidence hash in reportData const evidenceHash = crypto.createHash('sha256').update(evidenceFiles).digest(); assert(quote.reportData.includes(evidenceHash)); ``` ### ☐ CAA Records **What it prevents:** Unauthorized certificate issuance even if DNS is compromised. **How it works:** CAA DNS records restrict which Certificate Authorities can issue certificates for your domain. **Why it's necessary:** Without CAA records, any CA could issue certificates. CAA records add defense-in-depth against compromised CAs or DNS attacks. **How to verify:** See [Domain Attestation: CAA Records](/phala-cloud/networking/domain-attestation) ```bash theme={"system"} dig CAA yourdomain.com ``` ## Why This Is Sufficient The verification checklist covers the complete Trusted Computing Base (TCB). Here's why no gaps exist: **Hardware root of trust:** Intel's signature proves genuine TDX hardware. All measurements are recorded by this hardware during boot before any software runs. **Measurement immutability:** Once recorded in the signed quote, measurements cannot be modified. Change one byte anywhere in the TCB, and measurements won't match. **Cryptographic binding:** Each layer binds to the next through measurements. OS binds to hardware (MRTD, RTMR0-2). Application binds to OS (RTMR3). Keys bind to KMS (key-provider). Certificates bind to quote (reportData). **Complete coverage:** The checklist covers all TCB components. Nothing runs in the CVM that isn't measured or verified. **Governance enforcement:** Smart contracts ensure only authorized versions can boot. On-chain authorization prevents malicious updates even with compromised infrastructure. **No trust assumptions:** With complete verification, you don't need to trust Phala Cloud, Docker registries, build infrastructure, or Certificate Authorities. Everything is cryptographically verified. ## Security Proof **Theorem:** If all checklist items pass, the CVM runs your exact code in genuine TEE hardware with no security gaps. **Proof by contradiction:** Assume an attacker compromises the CVM despite passing all checks. The attacker must modify at least one component (hardware, firmware, OS, application, keys, or certificates). But: 1. **Hardware/firmware tampering** changes MRTD, mr\_seam, or tee\_tcb\_svn, failing hardware verification. 2. **OS tampering** changes RTMR0-2, failing OS measurement verification. 3. **Application tampering** changes compose-hash in RTMR3, failing compose-hash verification. 4. **Image substitution** changes image digests, failing the TEE's digest check before pulling. 5. **KMS substitution** changes key-provider in RTMR3, failing KMS identity verification. 6. **Certificate impersonation** fails because evidence hash won't match reportData. 7. **Unauthorized updates** fail on-chain governance checks. Any modification causes verification to fail. Therefore, if all checks pass, no compromise is possible. QED. ## Complete Verification Checklist Use this checklist for security audits. All items must pass for complete trustless verification: **Application Layer (What You Control):** * [ ] reportData contains expected challenge/public key * [ ] compose-hash matches calculated hash * [ ] All Docker images use SHA256 digests (not tags) * [ ] RTMR3 event log replays to quoted RTMR3 * [ ] Image digests link to audited source code (Sigstore or reproducible builds) * [ ] compose-hash is whitelisted in DstackApp contract (if using governance) **Platform Layer (Infrastructure):** * [ ] TDX quote signature is valid (Intel root certificates) * [ ] `tee_tcb_svn` matches latest security patches * [ ] MRTD and RTMR0-2 match calculated OS measurements * [ ] VM config (CPU, memory, GPU) matches deployment * [ ] OS image hash is whitelisted in DstackKms contract * [ ] (Optional) OS rebuilt reproducibly from source * [ ] KMS ID from `key-provider` event is known and trusted * [ ] KMS's own attestation quote is valid * [ ] KMS aggregated MR is whitelisted in DstackKms contract **Network Layer (Custom Domains Only):** * [ ] TLS certificate fingerprint matches served certificate * [ ] Evidence files at `/evidences/` cryptographically bind to quote * [ ] CAA DNS records restrict certificate issuance **Governance Layer:** * [ ] Smart contract addresses are verified and trusted * [ ] Contract permissions match security policy * [ ] Contract ownership and upgrade mechanisms are understood ## Verification Workflow ```mermaid theme={"system"} graph TD A[Start] --> B{Need trustless execution?} B -->|No| C[Quick Verification] B -->|Yes| D[Complete Verification] C --> C1[Verify reportData] C --> C2[Verify compose-hash] C --> C3[Use Cloud API for hardware] C1 --> E[Done - Trust Phala] C2 --> E C3 --> E D --> D1[Application Verification] D --> D2[Platform Verification] D1 --> D1A[reportData + compose-hash] D1 --> D1B[RTMR3 event log replay] D1 --> D1C[Image provenance] D1 --> D1D[On-chain governance] D2 --> D2A[Hardware signature] D2 --> D2B[OS measurements] D2 --> D2C[KMS attestation] D2 --> D2D[TLS binding] D1A --> F[All checks pass?] D1B --> F D1C --> F D1D --> F D2A --> F D2B --> F D2C --> F D2D --> F F -->|Yes| G[Done - Trustless verified] F -->|No| H[Investigate failure] ``` ## Tools and Resources * **[Quickstart](/phala-cloud/attestation/quickstart)** - Quick verification (reportData + Cloud API) * **[Verify Your Application](/phala-cloud/attestation/verify-your-application)** - Complete application verification * **[Verify the Platform](/phala-cloud/attestation/verify-the-platform)** - Complete platform verification * **[Attestation Fields](/phala-cloud/attestation/attestation-fields)** - Field reference * **[Domain Attestation](/phala-cloud/networking/domain-attestation)** - TLS certificate verification * **[trust-center](https://github.com/Phala-Network/trust-center)** - Reference implementation * **[dstack SDK](https://www.npmjs.com/package/@phala/dstack-sdk)** - `getComposeHash()` and `replayRtmrs()` * **[meta-dstack](https://github.com/Dstack-TEE/meta-dstack)** - Reproducible OS builds * **[Smart Contracts](https://github.com/Dstack-TEE/dstack/tree/next/dstack/kms/auth-eth/contracts)** - DstackKms and DstackApp ## Real-World Example For a complete implementation of the full chain of trust, see how Private AI verifies: * Hardware stack (NVIDIA GPUs + Intel TDX) * OS integrity from reproducible builds * Application code via compose-hash * KMS trust for key derivation * Request/response integrity signatures Learn more: **[Private AI Verification](/phala-cloud/confidential-ai/verify/overview)** ## Next Steps > [card] [Quickstart](/phala-cloud/attestation/quickstart) > > Quick verification guide > [card] [Verify Your Application](/phala-cloud/attestation/verify-your-application) > > Prove your exact code is running > [card] [Verify the Platform](/phala-cloud/attestation/verify-the-platform) > > Verify OS, KMS, and infrastructure > [card] [Field Reference](/phala-cloud/attestation/attestation-fields) > > Understand all quote fields # Become a Featured Builder Source: https://docs.phala.com/phala-cloud/attestation/feature-builder How to become a Featured Builder on Trust Center and showcase your verified application ## What is Featured Builder? Featured Builders are highlighted applications on [trust.phala.com](https://trust.phala.com) that demonstrate excellent use cases of Phala's trusted execution environment. Being featured gives your application increased visibility and credibility within the Phala ecosystem. ![Featured Builder section on trust.phala.com homepage](https://mintcdn.com/phalanetwork-1606097b/aV-qHNM3UtPyBtK8/images/trust-center-feature-builder.png?fit=max\&auto=format\&n=aV-qHNM3UtPyBtK8\&q=85\&s=d88246838b2983d314375a2eec638e4b) Featured Builder showcase on Trust Center ## Requirements Before applying to become a Featured Builder, ensure your application: * Is deployed on Phala Cloud with passing Trust Center verification * Has a complete workspace profile with proper branding * Has enabled public listing for the application ## Step 1: Set Up Your Workspace Profile A complete workspace profile helps users understand who built the application and establishes trust. Navigate to your workspace settings in the Phala Cloud dashboard and fill in your profile information: * **Workspace Name**: Your organization or project name * **Description**: A brief description of what you do * **Logo**: Upload a clear, recognizable logo ![Workspace profile configuration page](https://mintcdn.com/phalanetwork-1606097b/aV-qHNM3UtPyBtK8/images/trust-center-workspace-profile.png?fit=max\&auto=format\&n=aV-qHNM3UtPyBtK8\&q=85\&s=ee7063c1b945744b3fc04cfbb655c0c6) Workspace profile settings in Phala Cloud dashboard ## Step 2: Enable Public Listing Public listing makes your application discoverable on the Trust Center platform. This is required for Featured Builder consideration. In your application settings, locate and enable the **Public Listing** toggle: ![Public listing toggle in application settings](https://mintcdn.com/phalanetwork-1606097b/aV-qHNM3UtPyBtK8/images/trust-center-public-listing.png?fit=max\&auto=format\&n=aV-qHNM3UtPyBtK8\&q=85\&s=77948ff90eed088132eb8cf466f9b25e) Enable public listing in application settings > [!NOTE] > > Enabling public listing makes your application's Trust Center verification report publicly accessible. This is designed for transparency and allows users to verify your deployment. ## Step 3: Apply for Featured Builder Once your workspace profile is complete and public listing is enabled, contact the Phala team to apply for Featured Builder status. Send an email to **[cloud@phala.network](mailto:cloud@phala.network)** with: * Your application name and App ID * A brief description of your application's use case * Why your application would be a good showcase for Phala Cloud The team will review your application and respond within a few business days. ## Benefits of Being Featured * **Increased Visibility**: Your application appears on the Trust Center homepage * **Credibility**: Featured status signals quality and trust to potential users * **Community Recognition**: Join the showcase of leading builders on Phala ## Next Steps * **View Trust Center**: [trust.phala.com](https://trust.phala.com) * **Understand Verification**: [Trust Center Verification](/phala-cloud/attestation/trust-center-verification) * **Deploy Your App**: [Getting Started with Phala Cloud](/phala-cloud/getting-started/overview) # Get Attestation Source: https://docs.phala.com/phala-cloud/attestation/get-attestation Learn how to get CVM attestation on Phala Cloud using dashboard or dstack SDK. Get attestation reports from your CVM to prove it's running in genuine TEE hardware. You can check the dashboard for quick verification, or use the dstack SDK to generate quotes programmatically with custom data. ## View Attestation Report on Dashboard Open the **Attestation** tab in your CVM dashboard. Click **Check Attestation** to verify the default report generated during bootstrap. ## Generate Attestation Programmatically ### Prerequisites: Configure Docker Compose Your application needs access to the dstack service to generate attestation quotes. Mount the dstack socket into your container: ```yaml theme={"system"} version: '3' services: app: image: your-app-image ports: - 8080:8080 volumes: # Mount dstack socket for TEE operations - /var/run/dstack.sock:/var/run/dstack.sock ``` ### Using dstack SDK The dstack SDK connects to `/var/run/dstack.sock` automatically. Install for your language: * **JavaScript/TypeScript:** [@phala/dstack-sdk](https://www.npmjs.com/package/@phala/dstack-sdk) * **Python:** [dstack-sdk](https://pypi.org/project/dstack-sdk/) * **Go:** [github.com/Dstack-TEE/dstack](https://github.com/Dstack-TEE/dstack/tree/master/sdk/go) ### Attaching Custom Data (reportData) The attestation quote includes a 64-byte `reportData` field for your custom data. **Important:** The SDK throws an error if you exceed 64 bytes—it does not auto-hash. **Two patterns:** 1. **Short data (≤64 bytes)**: Nonces, small challenges, or hashes—pass directly 2. **Long data (>64 bytes)**: Any arbitrary data—hash it first with SHA256 (produces 32 bytes) ```javascript TypeScript theme={"system"} import { DstackClient } from '@phala/dstack-sdk'; import crypto from 'crypto'; const client = new DstackClient(); // Pattern 1: Short data (≤64 bytes) - pass directly // Example: 32-byte nonce for challenge-response const nonce = crypto.randomBytes(32); const quote1 = await client.getQuote(nonce); // Pattern 2: Long data (>64 bytes) - hash it first // Example: JSON with arbitrary data const userData = JSON.stringify({ version: '1.0.0', timestamp: Date.now(), user_id: 'alice', public_key: '0x1234...' }); // Hash to fit in 64 bytes (SHA256 produces 32 bytes) const hash = crypto.createHash('sha256').update(userData).digest(); const quote2 = await client.getQuote(hash); console.log('Quote:', quote2.quote); console.log('Event Log:', quote2.event_log); ``` ```python Python theme={"system"} import json import time import hashlib import secrets from dstack_sdk import DstackClient client = DstackClient() # Pattern 1: Short data (≤64 bytes) - pass directly # Example: 32-byte nonce for challenge-response nonce = secrets.token_bytes(32) quote1 = client.get_quote(nonce) # Pattern 2: Long data (>64 bytes) - hash it first # Example: JSON with arbitrary data user_data = json.dumps({ "version": "1.0.0", "timestamp": time.time(), "user_id": "alice", "public_key": "0x1234..." }) # Hash to fit in 64 bytes (SHA256 produces 32 bytes) data_hash = hashlib.sha256(user_data.encode()).digest() quote2 = client.get_quote(data_hash) print('Quote:', quote2.quote) print('Event Log:', quote2.event_log) ``` > [!NOTE] > > **reportData Parameter Required** > > The `getQuote()` method requires a reportData parameter. If you don't need custom data, pass an empty value: `''` in TypeScript or `b''` in Python. Calling `getQuote()` without any parameter will fail. ### Exposing Attestation via API Expose attestation endpoints so external verifiers can validate your CVM. The `/attestation` endpoint provides the quote for hardware verification, while `/info` provides the application configuration for code verification: ```javascript TypeScript theme={"system"} import express from 'express'; import { DstackClient } from '@phala/dstack-sdk'; const app = express(); const client = new DstackClient(); app.get('/attestation', async (req, res) => { const result = await client.getQuote(''); res.json({ quote: result.quote, event_log: result.event_log, vm_config: result.vm_config // Required by dstack-verifier }); }); app.get('/info', async (req, res) => { const info = await client.info(); res.json(info); }); app.listen(8080); ``` ```python Python theme={"system"} from flask import Flask, jsonify from dstack_sdk import DstackClient app = Flask(__name__) client = DstackClient() @app.route('/attestation') def get_attestation(): result = client.get_quote(b'') return jsonify({ 'quote': result.quote, 'event_log': result.event_log, 'vm_config': result.vm_config # Required by dstack-verifier }) @app.route('/info') def get_info(): info = client.info() return jsonify(info) if __name__ == '__main__': app.run(host='0.0.0.0', port=8080) ``` These endpoints allow external verifiers to fetch attestation data and verify your CVM. See [Verify Your Application](/phala-cloud/attestation/verify-your-application) for how verifiers use these endpoints. ## Next Steps > [card] [Verify Your Application](/phala-cloud/attestation/verify-your-application) > > Prove your exact code is running > [card] [Verify the Platform](/phala-cloud/attestation/verify-the-platform) > > Verify OS, KMS, and infrastructure > [card] [Field Reference](/phala-cloud/attestation/attestation-fields) > > Understand what each field in the quote means > [card] [Complete Security Checklist](/phala-cloud/attestation/chain-of-trust) > > Complete verification with no trust assumptions # Overview Source: https://docs.phala.com/phala-cloud/attestation/overview Learn how attestation proves your CVM runs unmodified code in genuine TEE hardware. ## Why Attestation Matters Attestation proves your CVM runs in genuine TEE hardware with the exact software you expect. No one can fake it. It gives you cryptographic proof covering three layers: Intel TDX hardware, the operating system, and your application code. Anyone can independently verify this proof to confirm your CVM's security. You can verify what you control (your application code) or verify everything (including Phala's infrastructure). The choice depends on your security requirements. ## How Attestation Works Your CVM generates a cryptographic quote that includes measurements of the Intel TDX CPU, OS images, your application configuration, and optional custom data like public keys or challenge responses. The quote is signed by Intel hardware. Verifiers check this signature against Intel's root certificates to confirm authenticity. ## What You Can Verify **Your Application**: Prove your specific Docker containers and configuration run unmodified. This verifies no one substituted your code. **The Platform**: Prove the OS, key management system, and network infrastructure are secure. This verifies Phala's infrastructure integrity. **Complete Chain**: Verify everything end-to-end with no trust assumptions. This provides complete trustless execution. ## Get Started > [card] [Quickstart](/phala-cloud/attestation/quickstart) > > Generate your first quote and verify it works > [card] [Get Attestation](/phala-cloud/attestation/get-attestation) > > Generate quotes using dashboard or SDK > [card] [Verify Your Application](/phala-cloud/attestation/verify-your-application) > > Prove your exact code is running > [card] [Verify the Platform](/phala-cloud/attestation/verify-the-platform) > > Verify OS, KMS, and infrastructure > [card] [Complete Security Checklist](/phala-cloud/attestation/chain-of-trust) > > Complete verification with no trust assumptions > [card] [Field Reference](/phala-cloud/attestation/attestation-fields) > > Understand what each field in the quote means ## Next Steps New to attestation? Start with the [Quickstart](/phala-cloud/attestation/quickstart) to generate and verify your first quote. # Quickstart Source: https://docs.phala.com/phala-cloud/attestation/quickstart Get your first attestation proof using the dashboard. Get your first attestation proof using just the dashboard. No code required. ## Step 1: Open Attestation Tab Open your CVM in the [Phala Cloud dashboard](https://cloud.phala.com). Click **View Details** on your CVM card. Navigate to the **Attestations** tab. You'll see the default attestation quote that was generated during CVM bootstrap. ## Step 2: Check Attestation Click the **Check Attestation** button in the certificate chain section. This automatically opens the [TEE Attestation Explorer](https://proof.t16z.com/) in a new tab with your quote already loaded and verified. You'll see verification results showing: * ✓ Hardware signature is valid (genuine Intel TDX) * ✓ Quote measurements (MRTD, RTMR0-3) * ✓ Security status (TCB level, no known vulnerabilities) ## You're Done! You just verified your CVM runs in genuine TEE hardware. The cryptographic proof shows Intel TDX signed your quote, making it impossible to fake. You can share the proof URL with anyone who needs to verify your CVM's security. ## What You Verified **Hardware authenticity**: Intel's signature proves genuine TDX hardware generated this quote. **Measurement integrity**: The quote includes cryptographic hashes (measurements) of your OS, application, and hardware configuration. Change one byte anywhere, and the measurements won't match. **Unforgeable proof**: The signature binds all measurements together. No one can modify the quote without invalidating Intel's signature. ## What's Next? Now that you understand attestation, choose your path: ### Want Programmatic Attestation? **Generate quotes from code** instead of the dashboard. Useful for APIs, services, or automated verification. See [Get Attestation](/phala-cloud/attestation/get-attestation) for SDK examples. ### Want to Bind Custom Data? **Attach challenges, public keys, or nonces** to your quotes. This proves freshness and prevents replay attacks. See [Get Attestation: Attaching Custom Data](/phala-cloud/attestation/get-attestation#attaching-custom-data-reportdata) for reportData patterns. ### Want to Verify Your Application Code? **Prove your exact Docker images are running** unmodified. This verifies no one substituted your code. See [Verify Your Application](/phala-cloud/attestation/verify-your-application) for compose-hash verification. ### Want to Verify Platform Security? **Verify the OS, KMS, and infrastructure** end-to-end. This proves Phala's platform integrity without trust assumptions. See [Verify the Platform](/phala-cloud/attestation/verify-the-platform) for complete platform verification. ### Want Complete Security Audit? **Verify everything with no trust assumptions.** Security researchers and auditors need the complete checklist. See [Complete Chain of Trust](/phala-cloud/attestation/chain-of-trust) for necessary and sufficient verification. ### Want to Understand Quote Fields? **Learn what each measurement means** (MRTD, RTMR0-3, reportData, etc.). See [Attestation Fields Reference](/phala-cloud/attestation/attestation-fields) for field-by-field explanation. # Trust Center Verification Source: https://docs.phala.com/phala-cloud/attestation/trust-center-verification Automated verification reports for every Phala Cloud deployment with the Trust Center platform ## What is the Trust Center? The [Trust Center](https://trust.phala.com/) is an automated verification platform that generates comprehensive security reports for every application deployed on Phala Cloud. It provides cryptographic proof that your application is running in a genuine TEE with the exact code you deployed, giving you and your users confidence in the integrity and security of your deployment. > [!NOTE] > > **Automatic Verification**: Every application deployed to Phala Cloud automatically receives a Trust Center verification report. No additional configuration required. ## Why Trust Center Verification Matters Traditional cloud platforms require you to trust the provider. With Phala Cloud and Trust Center: * **Verify Hardware Authenticity**: Cryptographically prove your app runs on genuine Intel TDX and Nvidia CC hardware * **Confirm Code Integrity**: Verify the exact Docker compose configuration deployed matches your source code * **Validate OS Security**: Ensure the operating system hasn't been tampered with * **Prove Zero Trust**: For gateway deployments, verify domain certificates are managed entirely within the TEE This matters for: * **Regulatory Compliance**: Meet GDPR, HIPAA, and other privacy requirements with verifiable evidence * **Customer Trust**: Share public verification reports with users to prove data privacy * **Security Audits**: Provide auditors with cryptographic proof of deployment integrity ## Accessing Your Verification Report Every Phala Cloud application receives a unique verification report URL: ``` https://trust.phala.com/app/{your-app-id} ``` You can find your app ID in: 1. The Phala Cloud dashboard 2. The API response when creating a CVM **Example Report**: [https://trust.phala.com/app/7e0817205044eb202a590a0d236ccb4d66140197](https://trust.phala.com/app/7e0817205044eb202a590a0d236ccb4d66140197) ## Understanding Your Verification Report The Trust Center report displays comprehensive verification results across multiple security dimensions. Let's walk through each section: ### Overview Section The left column of the report shows your application's basic information and overall verification status. ![Trust Center application overview section](https://mintcdn.com/phalanetwork-1606097b/P70hyuKDoXqHI_bx/images/trust-center-overview.png?fit=max\&auto=format\&n=P70hyuKDoXqHI_bx\&q=85\&s=16b399d5541686d1e247c85fa6e6f666) Trust Center - Application Overview **What you see:** * **App Name**: Your application's identifier (e.g., "account-demo") * **Verification Status**: Overall pass/fail indicator with green checkmark when all checks succeed * **Hardware Verification**: Confirms TEE runs on genuine Intel TDX and Nvidia CC hardware * **Source Code Verification**: Validates deployed Docker Compose matches your source code repository * **Network Verification**: Checks domain certificates and network infrastructure security * **Operating System Verification**: Ensures OS image matches trusted dstack release * **Key Management Verification**: Validates cryptographic key derivation ### Hardware Verification This section proves your application runs on genuine Intel and Nvidia TEE hardware. ![Hardware attestation verification status](https://mintcdn.com/phalanetwork-1606097b/P70hyuKDoXqHI_bx/images/trust-center-hardware.png?fit=max\&auto=format\&n=P70hyuKDoXqHI_bx\&q=85\&s=73138da114caa7c2d08092497e19a40c) Trust Center - Hardware Verification **What's verified:** * **Intel TDX Quote**: Cryptographically signed attestation from Intel hardware * **(Optional) Nvidia CC Attestation Report**: Cryptographically signed attestation from Nvidia hardware * **TCB Status**: Trusted Computing Base security version (checks for known vulnerabilities) * **Platform Certificates**: Validates certificate chain back to Intel/Nvidia root CA * **Hardware Identity**: Confirms genuine Intel processor with TDX enabled and Nvidia GPU with CC enabled **Why it matters**: Ensures your application runs on real security hardware, not a simulated environment or compromised system. ### Source Code Verification This is the critical verification that your deployed application contains exactly the code you intended. ![Source code verification showing compose hash match](https://mintcdn.com/phalanetwork-1606097b/P70hyuKDoXqHI_bx/images/trust-center-source.png?fit=max\&auto=format\&n=P70hyuKDoXqHI_bx\&q=85\&s=219b101011217cd500525d8adb1f14e0) Trust Center - Source Code Verification **What's verified:** * **Compose Hash**: SHA256 hash of your configuration file containing the raw Docker compose file and other metadata * **RTMR3**: Application-specific measurement register containing: * `app-id`: Application identifier * `compose-hash`: Hash of deployment manifest * `instance-id`: Specific deployment instance * `os-image-hash`: Hash of operating system image **Why it matters**: This is the core of code integrity. Anyone can recompute the compose hash from your source code and verify it matches the deployed version. No hidden modifications possible. **How to verify yourself:** ```bash theme={"system"} # Compute the compose hash of your compose_file.json sha256sum compose_file.json # Compare with the hash shown in compose-hash Event Logs # They must match exactly ``` ### Operating System Integrity This verification confirms the OS running in your TEE matches a known trusted version. ![Operating system integrity verification](https://mintcdn.com/phalanetwork-1606097b/P70hyuKDoXqHI_bx/images/trust-center-os.png?fit=max\&auto=format\&n=P70hyuKDoXqHI_bx\&q=85\&s=85235b9142f6d0f6973a59d2fa57c70b) Trust Center - OS Integrity Verification **What's verified:** * **MRTD (Measurement Root of Trust Domain)**: Hash of the initial TD state * **RTMR0**: Virtual hardware environment measurement * **RTMR1**: Linux kernel measurement * **RTMR2**: Kernel command line and initrd measurement * **dstack Version**: Specific OS image version hash **Why it matters**: Proves the operating system hasn't been modified or backdoored. The OS matches publicly auditable dstack releases. ### Network Verification (Gateway Deployments) For applications exposed via custom domains with dstack-gateway, this verifies zero-trust HTTPS and secure traffic forwarding. ![Domain verification for zero-trust HTTPS](https://mintcdn.com/phalanetwork-1606097b/P70hyuKDoXqHI_bx/images/trust-center-network.png?fit=max\&auto=format\&n=P70hyuKDoXqHI_bx\&q=85\&s=d9e06c59624b5bb392c2f90542394565) Trust Center - Domain Verification **What's verified:** * **Gateway TEE Status**: Confirms the dstack-gateway itself runs in a TEE environment * **TLS Certificate**: Certificate private key generated entirely within TEE * **CAA Records**: DNS Certification Authority Authorization locked to TEE-controlled account * **Certificate Transparency**: All certificates logged to public CT logs * **Domain Ownership**: Cryptographic proof the domain is controlled by the TEE **Why it matters**: The gateway runs entirely within a TEE, ensuring it can safely decrypt, inspect, and forward traffic to your application without exposing it to untrusted infrastructure. Traditional HTTPS terminates at cloud load balancers where providers can access your traffic. With Phala's TEE-based gateway, even Phala cannot intercept your TLS traffic—everything stays encrypted until it reaches your application's TEE. ### Key Management Service Verification This section verifies that cryptographic keys are properly managed and derived through Phala's decentralized key management system. ![Key management service verification status](https://mintcdn.com/phalanetwork-1606097b/P70hyuKDoXqHI_bx/images/trust-center-kms.png?fit=max\&auto=format\&n=P70hyuKDoXqHI_bx\&q=85\&s=6bbf1ffc4943e19dd7ce37b184497016) Trust Center - Key Management Service Verification **What's verified:** * **Key Provider Address**: The decentralized KMS endpoint used for key derivation * **KMS Node TEE Status**: All KMS nodes run in TEE environments with program digests matching the smart contract * **App-ID Binding**: Confirms keys are uniquely derived from your application identifier * **Key Derivation Protocol**: Validates the cryptographic protocol used to generate encryption keys * **No Vendor Lock-in**: Verifies keys can be recreated on any Phala worker or dstack node with the same app-id **Why it matters**: Unlike traditional cloud platforms where encryption keys are tied to specific hardware or vendor infrastructure, Phala's decentralized key management ensures your keys are derived from your application identity, not the physical machine. This means you can migrate your application between different compute providers while maintaining access to your encrypted data. The KMS verification proves that your keys are generated securely and consistently, without giving Phala or any single party control over your encryption keys. ## Interpreting Verification Status ### ✅ Passed Verification When all checks pass: * Your app runs on genuine Intel TEE hardware * The OS matches a trusted dstack version * Your source code hash matches the deployed version * (If applicable) Domain certificates are TEE-controlled **What this means**: You have cryptographic proof your application is running securely and exactly as intended. You can share this report with users, auditors, or compliance officers. ### ⚠️ Partial Verification Some checks passed, others failed or skipped: * Check which specific verifications failed * Common causes: outdated TCB version, domain not configured, custom OS modifications **Action**: Review failed checks. Some failures may be expected (e.g., domain verification for apps without custom domains). ### ❌ Failed Verification Verification could not complete: * Hardware attestation signature invalid * Source code hash mismatch * OS image not recognized **Action**: This indicates a potential security issue. Contact Phala support or re-deploy your application. ## Sharing Your Verification Report Trust Center reports are **publicly accessible** by design. This enables: 1. **Customer Transparency**: Share your report URL in documentation or marketing 2. **Auditor Access**: Provide reports to security auditors without exposing credentials 3. **Automated Verification**: Third parties can programmatically verify your deployment Example uses: ```markdown theme={"system"} Security: [View our Trust Center report](https://trust.phala.com/app/YOUR_APP_ID) ``` ```html theme={"system"} TEE Verified ``` ## Programmatic Verification See [Trust Center Technical Documentation](/dstack/trust-center-technical) for API details and integration examples. ## Trust Center vs Manual Verification | Feature | Trust Center | Manual Verification | | - | - | - | | **Ease of Use** | ✅ Automatic, zero config | ❌ Complex, requires tooling | | **Public Auditability** | ✅ Shareable URL | ⚠️ Must share raw quote data | | **Verification Speed** | ✅ Seconds | ⚠️ Minutes to hours | | **Technical Expertise** | ✅ No expertise needed | ❌ Requires cryptography knowledge | | **Blockchain Integration** | ✅ Verifies onchain records | ⚠️ Manual registry lookup | For most users, Trust Center provides the easiest and most reliable verification. Advanced users can still perform [manual verification](/phala-cloud/attestation/verification-guide) for full control. ## Next Steps * **Learn the Technical Details**: [Trust Center Technical Architecture](/dstack/trust-center-technical) * **Understand Attestation**: [Verifying TEE Attestation](/phala-cloud/attestation/verification-guide) * **Deep Dive on Security**: [Security Architecture](/phala-cloud/security-and-privacy/security-architecture) ## Additional Resources * **Trust Center Platform**: [https://trust.phala.com](https://trust.phala.com) * **GitHub Repository**: [https://github.com/Phala-Network/trust-center](https://github.com/Phala-Network/trust-center) * **Example Report**: [account-demo verification](https://trust.phala.com/app/7e0817205044eb202a590a0d236ccb4d66140197) # End-to-End Attestation Verification Source: https://docs.phala.com/phala-cloud/attestation/verification-guide Fetch, verify, and integrate CVM attestation into your workflow — end-to-end with working code Verify that your CVM runs unmodified code on genuine TEE hardware, from fetching the attestation quote to integrating verification into your CI/CD pipeline. This guide ties together the attestation workflow end-to-end with working code examples. If you're new to attestation, start with the [Quickstart](/phala-cloud/attestation/quickstart) to understand the basics through the dashboard. This guide assumes you want programmatic verification. ## The verification flow Every CVM attestation verification follows three steps: get a quote from your running CVM, verify the quote's hardware signature, and check that the measurements match your expected application. The entire process runs in seconds from anywhere outside the CVM. ## Step 1: Get the attestation quote Your CVM must expose attestation endpoints. If you haven't set this up yet, see [Get Attestation](/phala-cloud/attestation/get-attestation) for the dstack SDK setup. Fetch the quote with a fresh challenge nonce to prevent replay attacks. ```typescript TypeScript theme={"system"} import crypto from 'crypto'; const CVM_URL = 'https://your-app.example.com'; // Generate a fresh 32-byte nonce const nonce = crypto.randomBytes(32).toString('hex'); // Fetch attestation with nonce as reportData const attestResponse = await fetch(`${CVM_URL}/attestation?reportData=${nonce}`); const attestData = await attestResponse.json(); // Fetch application info for compose verification const infoResponse = await fetch(`${CVM_URL}/info`); const appInfo = await infoResponse.json(); console.log('Quote length:', attestData.quote.length); console.log('Event log events:', JSON.parse(attestData.event_log).length); ``` ```python Python theme={"system"} import secrets import requests CVM_URL = "https://your-app.example.com" # Generate a fresh 32-byte nonce nonce = secrets.token_hex(32) # Fetch attestation with nonce as reportData attest_response = requests.get(f"{CVM_URL}/attestation?reportData={nonce}") attest_data = attest_response.json() # Fetch application info for compose verification info_response = requests.get(f"{CVM_URL}/info") app_info = info_response.json() print(f"Quote length: {len(attest_data['quote'])}") ``` ```go Go theme={"system"} package main import ( "crypto/rand" "encoding/hex" "encoding/json" "fmt" "io" "net/http" ) func main() { cvmURL := "https://your-app.example.com" // Generate a fresh 32-byte nonce nonceBytes := make([]byte, 32) rand.Read(nonceBytes) nonce := hex.EncodeToString(nonceBytes) // Fetch attestation resp, _ := http.Get(fmt.Sprintf("%s/attestation?reportData=%s", cvmURL, nonce)) body, _ := io.ReadAll(resp.Body) var attestData map[string]interface{} json.Unmarshal(body, &attestData) fmt.Printf("Quote length: %d\n", len(attestData["quote"].(string))) } ``` > [!NOTE] > > Always generate a fresh nonce per verification request. Without it, an attacker could replay an old valid quote from compromised hardware. ## Step 2: Verify the hardware signature The TDX quote is signed by Intel hardware. Verify this signature to confirm the quote came from a genuine TEE. You have two options: use Phala's verification API for convenience, or verify locally for trustless verification. ### Option A: Phala Cloud verification API The fastest approach. Sends your quote to Phala's service which checks it against Intel's root certificates. ```typescript TypeScript theme={"system"} const verifyResponse = await fetch( 'https://cloud-api.phala.com/api/v1/attestations/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ hex: attestData.quote }), } ); const result = await verifyResponse.json(); if (!result.quote.verified) { throw new Error('Hardware verification failed'); } console.log('Hardware signature: valid'); console.log('TDX version:', result.quote.body.tee_tcb_svn); ``` ```python Python theme={"system"} verify_response = requests.post( "https://cloud-api.phala.com/api/v1/attestations/verify", json={"hex": attest_data["quote"]} ) result = verify_response.json() assert result["quote"]["verified"], "Hardware verification failed" print(f"Hardware signature: valid") print(f"TDX version: {result['quote']['body']['tee_tcb_svn']}") ``` ```bash curl theme={"system"} curl -X POST "https://cloud-api.phala.com/api/v1/attestations/verify" \ -H "Content-Type: application/json" \ -d '{"hex": "YOUR_QUOTE_HEX"}' ``` ### Option B: Local verification with dcap-qvl For trustless verification without relying on Phala's API, use the open-source [dcap-qvl](https://github.com/Phala-Network/dcap-qvl) verifier. This checks Intel's signature chain locally. ```bash theme={"system"} # Install dcap-qvl cargo install dcap-qvl # Verify a quote locally dcap-qvl verify --quote-hex "YOUR_QUOTE_HEX" ``` You can also paste your quote into the [TEE Attestation Explorer](https://proof.t16z.com/) for an interactive visual breakdown of all quote fields. ## Step 3: Verify your application code Hardware verification proves the TEE is genuine. Now verify that your specific application is running inside it. The compose-hash in RTMR3 is a SHA256 hash of your entire Docker Compose configuration. ```typescript TypeScript theme={"system"} import { createHash } from 'crypto'; // Calculate the compose hash from the app info const appCompose = appInfo.tcb_info.app_compose; const calculatedHash = createHash('sha256') .update(appCompose) .digest('hex'); // Extract the attested hash from the RTMR3 event log const events = JSON.parse(attestData.event_log); const composeEvent = events.find( (e: { event: string }) => e.event === 'compose-hash' ); const attestedHash = composeEvent.event_payload; if (calculatedHash !== attestedHash) { throw new Error( `Compose hash mismatch: expected ${calculatedHash}, got ${attestedHash}` ); } console.log('Application code: verified'); console.log('Compose hash:', calculatedHash); ``` ```python Python theme={"system"} import hashlib import json # Calculate the compose hash from the app info app_compose = app_info["tcb_info"]["app_compose"] calculated_hash = hashlib.sha256(app_compose.encode()).hexdigest() # Extract the attested hash from the RTMR3 event log events = json.loads(attest_data["event_log"]) compose_event = next(e for e in events if e["event"] == "compose-hash") attested_hash = compose_event["event_payload"] assert calculated_hash == attested_hash, ( f"Compose hash mismatch: expected {calculated_hash}, got {attested_hash}" ) print(f"Application code: verified") print(f"Compose hash: {calculated_hash}") ``` ## Step 4: Verify the nonce binding Confirm that the quote contains your original nonce. This proves the attestation was freshly generated for your request. ```typescript TypeScript theme={"system"} // The reportData field in the quote should start with your nonce const reportData = attestData.report_data; if (!reportData.startsWith(nonce)) { throw new Error('Nonce mismatch: possible replay attack'); } console.log('Freshness: verified'); ``` ```python Python theme={"system"} report_data = attest_data["report_data"] assert report_data.startswith(nonce), "Nonce mismatch: possible replay attack" print("Freshness: verified") ``` ## Complete verification script Here's everything combined into a single script you can drop into your project. ```typescript TypeScript theme={"system"} import crypto from 'crypto'; import { createHash } from 'crypto'; async function verifyCVM(cvmUrl: string): Promise { // 1. Generate fresh nonce const nonce = crypto.randomBytes(32).toString('hex'); // 2. Fetch attestation and app info const [attestRes, infoRes] = await Promise.all([ fetch(`${cvmUrl}/attestation?reportData=${nonce}`), fetch(`${cvmUrl}/info`), ]); const attestData = await attestRes.json(); const appInfo = await infoRes.json(); // 3. Verify hardware signature const verifyRes = await fetch( 'https://cloud-api.phala.com/api/v1/attestations/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ hex: attestData.quote }), } ); const verifyResult = await verifyRes.json(); if (!verifyResult.quote.verified) { console.error('Hardware verification failed'); return false; } // 4. Verify compose hash const appCompose = appInfo.tcb_info.app_compose; const calculatedHash = createHash('sha256').update(appCompose).digest('hex'); const events = JSON.parse(attestData.event_log); const composeEvent = events.find( (e: { event: string }) => e.event === 'compose-hash' ); if (calculatedHash !== composeEvent.event_payload) { console.error('Compose hash mismatch'); return false; } // 5. Verify nonce freshness if (!attestData.report_data.startsWith(nonce)) { console.error('Nonce mismatch'); return false; } console.log('All checks passed'); return true; } // Usage verifyCVM('https://your-app.example.com').then(console.log); ``` ```python Python theme={"system"} import hashlib import json import secrets import requests def verify_cvm(cvm_url: str) -> bool: # 1. Generate fresh nonce nonce = secrets.token_hex(32) # 2. Fetch attestation and app info attest_data = requests.get( f"{cvm_url}/attestation?reportData={nonce}" ).json() app_info = requests.get(f"{cvm_url}/info").json() # 3. Verify hardware signature verify_result = requests.post( "https://cloud-api.phala.com/api/v1/attestations/verify", json={"hex": attest_data["quote"]}, ).json() if not verify_result["quote"]["verified"]: print("Hardware verification failed") return False # 4. Verify compose hash app_compose = app_info["tcb_info"]["app_compose"] calculated_hash = hashlib.sha256(app_compose.encode()).hexdigest() events = json.loads(attest_data["event_log"]) compose_event = next(e for e in events if e["event"] == "compose-hash") if calculated_hash != compose_event["event_payload"]: print("Compose hash mismatch") return False # 5. Verify nonce freshness if not attest_data["report_data"].startswith(nonce): print("Nonce mismatch") return False print("All checks passed") return True if __name__ == "__main__": verify_cvm("https://your-app.example.com") ``` ## Integrate verification into CI/CD Attestation verification fits naturally into deployment pipelines. Run it after every deployment to confirm your CVM booted correctly with the expected code. ### GitHub Actions example ```yaml theme={"system"} name: Verify CVM Attestation on: workflow_dispatch: schedule: - cron: '0 */6 * * *' # Every 6 hours jobs: verify: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install dependencies run: pip install requests - name: Verify attestation env: CVM_URL: ${{ secrets.CVM_URL }} run: python scripts/verify_attestation.py "$CVM_URL" - name: Alert on failure if: failure() run: | curl -X POST "${{ secrets.SLACK_WEBHOOK }}" \ -d '{"text": "CVM attestation verification failed!"}' ``` ### Continuous monitoring For production systems, run verification checks on a schedule. Here's a lightweight monitoring approach: ```python theme={"system"} import time import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger("attestation-monitor") CVM_URLS = [ "https://app1.example.com", "https://app2.example.com", ] CHECK_INTERVAL = 3600 # 1 hour while True: for url in CVM_URLS: try: result = verify_cvm(url) if result: logger.info(f"PASS: {url}") else: logger.error(f"FAIL: {url}") # Send alert to your monitoring system except Exception as e: logger.error(f"ERROR: {url} - {e}") time.sleep(CHECK_INTERVAL) ``` > [!WARNING] > > Attestation verification must always run **outside** the CVM. Verification running inside the CVM provides no security guarantees because a compromised CVM could fake its own results. ## What each check proves Here's a quick reference for what you're verifying at each step and what attack it prevents. | Check | What it proves | Attack prevented | | - | - | - | | Hardware signature | Quote came from genuine Intel TDX | Fake TEE simulation | | Compose hash | Your exact Docker images are running | Code substitution | | Nonce freshness | Quote was generated for this request | Replay of old quotes | | reportData binding | Custom data is attested by hardware | Data tampering | For advanced verification including RTMR3 event log replay, Docker digest pinning, on-chain governance, and source code provenance, see the [Complete Chain of Trust](/phala-cloud/attestation/chain-of-trust). ## Next steps > [card] [Verify Your Application](/phala-cloud/attestation/verify-your-application) > > Advanced verification including RTMR3 replay and image digest checks > [card] [Verify the Platform](/phala-cloud/attestation/verify-the-platform) > > Verify OS, KMS, and infrastructure without trust assumptions > [card] [Field Reference](/phala-cloud/attestation/attestation-fields) > > Understand every field in the attestation quote > [card] [GPU TEE Attestation](/phala-cloud/confidential-ai/verify/verify-attestation) > > Verify GPU-specific attestation for confidential AI workloads # Verify the Platform Source: https://docs.phala.com/phala-cloud/attestation/verify-the-platform Verify Phala's infrastructure integrity end-to-end. Verify Phala's infrastructure integrity end-to-end. This proves the OS, key management system, network certificates, and governance are all secure. ## Do You Need This? Prove platform integrity to your end users. Verify both your application and the infrastructure it runs on. Application verification proves your code runs in a TEE. But users still have to trust the OS, key management, network certificates, and governance. Any of these could be compromised. Verify the platform too, and you get end-to-end security with zero trust assumptions. The only thing left to trust is the TEE hardware itself. ## What is TCB (Trusted Computing Base)? The Trusted Computing Base (TCB) represents all components critical for security. In dstack, the TCB consists of cryptographic measurements that prove integrity across three layers. A **measurement** is a cryptographic hash (like a fingerprint) of a component. TEE hardware records these measurements in the remote attestation report during boot. Once recorded in the cryptographically signed quote, measurements cannot be modified. This makes them unforgeable proof of what code is running. Change even one byte in any component, and the measurements won't match your expected values. **Hardware & Firmware** use MRTD for virtual firmware and RTMR0 for hardware configuration like CPU count and memory size. **Operating System** uses RTMR1 for the Linux kernel and RTMR2 for kernel parameters and initrd. **Application** uses RTMR3 for your compose hash and runtime info. All RTMRs (0-3) use the same hash chain structure. Each starts at zero and is "extended" by hashing in events during boot (RTMR = SHA384(RTMR || event)). For verification, only RTMR3 event logs matter. RTMR0-2 event logs contain low-level hardware/firmware details you can ignore. Just use dstack-mr to reproduce the final RTMR0-2 values directly. ## Prerequisites Your application must expose an `/attestation` endpoint that returns the quote, event log, and VM configuration. This endpoint is what dstack-verifier calls to get the data it needs. See [Get Attestation](/phala-cloud/attestation/get-attestation) for how to set this up inside your CVM. ## Using dstack-verifier The dstack-verifier tool automates complete platform verification. It validates hardware, firmware, OS, key management, and event log integrity in one operation. Run it as an HTTP service: ```bash theme={"system"} # Via Docker docker run -p 8080:8080 dstacktee/dstack-verifier:latest # Or via cargo cargo run --bin dstack-verifier ``` Verify a quote: ```bash theme={"system"} # Get quote from your app curl https://your-app.example.com/attestation -o quote.json # Verify it curl -d @quote.json localhost:8080/verify | jq ``` The verifier checks: * **Hardware & firmware**: MRTD, RTMR0, TCB status, debug mode disabled * **Operating system**: RTMR1, RTMR2, OS image hash matches known build * **Key management**: KeyProviderInfo extracted from RTMR3 events * **Event log integrity**: Replays events to verify RTMR values match quote Response shows `is_valid: true` when all checks pass. See [dstack-verifier README](https://github.com/Dstack-TEE/dstack/tree/next/dstack/verifier) for API details and configuration. ### What the Verifier Checks Automatically dstack-verifier automates cryptographic verification by fetching reference values and comparing them against your quote. **Automatically fetched and verified**: * OS images downloaded from dstack releases (if not cached locally) * Expected MRTD and RTMR0-2 calculated using dstack-mr from the OS image + VM config * Quote signature validated using Intel root certificates via dcap-qvl * RTMR3 recalculated by replaying the event log * TCB status checked for security patches and debug mode disabled **You provide** (from your app's `/attestation` endpoint): * TDX quote (hex string) * Event log (hex-encoded JSON) * VM configuration (JSON with CPU, memory, os\_image\_hash) **You verify separately**: * Governance policies via smart contracts - see [5. Governance Verification](#5-governance-verification) * KMS instance attestation - see [3. Key Management Verification](#3-key-management-verification) * Network certificate binding - see [4. Network Security Verification](#4-network-security-verification) The verifier handles all cryptographic verification. You handle policy and governance verification. ## 1. Hardware & Firmware Verification ### Attack Vector Modified firmware can compromise the entire boot sequence. An attacker who controls the virtual firmware (OVMF) can load a malicious OS that appears legitimate to your application. The firmware is the trust anchor - if it's compromised, everything that follows is suspect. ### How It's Secured **MRTD** measures the virtual firmware (OVMF). This is the first code executed after CVM startup and serves as your trust anchor. **RTMR0** measures the virtual hardware configuration - CPU count, memory size, and device setup. This ensures the CVM runs with expected hardware resources. **mr\_seam** must be all zeros for TDX TD 1.0. This verifies the SEAM firmware signature is correct. **Debug mode** must be disabled. The TCB validation checks this to prevent debugging interfaces from exposing secrets. Intel signs the quote containing these measurements with their hardware root of trust. ### How to Verify Use dstack-verifier to verify hardware and firmware automatically. It validates the quote signature, checks TCB status, and ensures debug mode is disabled. **Implementation details**: See [`verify_quote` function](https://github.com/Dstack-TEE/dstack/blob/next/dstack/verifier/src/verification.rs) in verifier/src/verification.rs for the complete TCB validation logic. ## 2. Operating System Verification ### Attack Vector Anyone in the cloud compute supply chain (cloud provider, network operator, data center staff, or compromised infrastructure) could substitute the dstack OS image with a modified version containing backdoors or data exfiltration code. ### How It's Secured The dstack OS is built from the [meta-dstack](https://github.com/Dstack-TEE/meta-dstack) repository using Yocto. This means you can reproduce it from any specific git commit. The OS produces four measurements (MRTD, RTMR0-2) that cryptographically prove firmware, hardware config, kernel, and boot parameters. Only OS images with approved hashes can boot, enforced by the `DstackKms.allowedOsImages` smart contract. ### How to Verify Use dstack-verifier to verify OS integrity automatically. It downloads the OS image, calculates MRTD and RTMR0-2 using the VM configuration, and compares them against the quote. For reproducible builds, you can independently build the OS from [meta-dstack](https://github.com/Dstack-TEE/meta-dstack) source and verify it produces identical measurements. **Implementation details**: See [`verify_os_image_hash` function](https://github.com/Dstack-TEE/dstack/blob/next/dstack/verifier/src/verification.rs) in verifier/src/verification.rs for the OS verification logic. ## 3. Key Management Verification ### Attack Vector A malicious KMS could leak all keys used by your application: disk encryption keys, TLS private keys, and signing keys. This would compromise your application even if everything else was verified. ### How It's Secured Your application uses multiple keys: disk encryption, TLS certificates, and signing keys. All of these derive from two KMS root key pairs using deterministic Key Derivation Functions (KDFs). The Root CA Key (P256) derives your TLS certificates and disk encryption keys. The Root K256 Key (secp256k1) derives Ethereum-compatible signing keys. Each derived key combines your app's unique ID with a purpose string for cryptographic separation. Verify the KMS is trustworthy, and you've automatically verified all derived keys too. The KMS root CA public key is recorded in RTMR3 as the `key-provider` event. This binds your app to a specific KMS instance. You can't silently swap to a different KMS without changing the attestation. ### How to Verify Use dstack-verifier to extract the key provider information from RTMR3 events automatically. The verifier returns the KMS ID and name in the verification response. **Important**: dstack-verifier only extracts which KMS instance your app uses. It does not verify the KMS itself. The KMS is a separate TEE instance that requires its own complete verification: 1. **Hardware verification**: Validate the KMS's TDX quote against Intel root CAs 2. **OS integrity verification**: Verify the KMS's MRTD and RTMR0-2 match expected values for the dstack OS version 3. **Source code verification**: Verify the KMS's compose hash matches known trustworthy KMS configurations 4. **Governance verification**: Check the KMS's aggregated MR is whitelisted in the `DstackKms.kmsAllowedAggregatedMrs` smart contract For production deployments, use [trust-center](https://github.com/Phala-Network/trust-center) which automates complete KMS verification including all reference value comparisons. **Implementation details**: See [`decode_app_info` method](https://github.com/Dstack-TEE/dstack/blob/next/dstack/verifier/src/verification.rs) in verifier/src/verification.rs for key provider extraction logic. ## 4. Network Security Verification ### Attack Vector Anyone could issue a valid TLS certificate for your domain and impersonate your TEE. This includes the domain owner, cloud provider, or a compromised Certificate Authority. Without verification, users can't tell the legitimate TEE-controlled certificate from a fraudulent one used for man-in-the-middle attacks. ### How It's Secured Your TLS certificates are generated and controlled entirely within the TEE. For custom domains, the TEE creates its own ACME account and TLS private keys inside encrypted memory. The private keys never leave the TEE. Evidence files published at `/evidences/` prove the TEE controls the certificate through cryptographic binding. The TEE puts a hash of the certificate evidence into the TDX quote's `report_data` field. This proves the TEE created both the quote and the certificate evidence at the same time. CAA (Certification Authority Authorization) DNS records add another layer of protection. They restrict which Certificate Authorities can issue certificates for your domain, preventing unauthorized issuance even if DNS is compromised. ### How to Verify The verification process differs based on your domain type. #### For custom domains Verify the evidence files: 1. Download evidence files from `https://your-domain.com/evidences/` 2. Verify the certificate fingerprint matches what's being served 3. Check that the TDX quote contains the hash of the evidence files 4. Confirm CAA records restrict certificate issuance to the TEE's ACME account See **[Domain Attestation](/phala-cloud/networking/domain-attestation)** for complete step-by-step verification. #### For Phala Cloud domains `*.phala.network` domains use the gateway TEE for TLS termination. The gateway performs mutual attestation with your CVM to establish a secure tunnel. You don't need to verify TLS certificates for these domains. The gateway's attestation is verified separately. ## 5. Governance Verification ### Attack Vector Without governance verification, a malicious developer could update the application at any time to introduce backdoors. This could happen even if the previous version was fully attested, verified, and trusted by users. ### How It's Secured The `DstackApp` and `DstackKms` contracts define which compose hashes (application versions), OS images (system versions), and KMS instances are allowed. Code updates pushed to Phala Cloud must pass contract authorization. The new compose-hash must be whitelisted on-chain before deployment. ### How to Verify #### Application governance Check which application versions are authorized: ```bash theme={"system"} # Check if your app's compose-hash is whitelisted cast call "allowedComposeHashes(bytes32)" # Monitor for new authorized versions cast logs --event "ComposeHashAdded(bytes32,address)" ``` #### Platform governance The `DstackKms` contract controls platform-level security: ```bash theme={"system"} # Check allowed OS images cast call "allowedOsImages(bytes32)" # Check allowed KMS instances cast call "kmsAllowedAggregatedMrs(bytes32)" # Monitor governance changes cast logs ``` Understanding who controls these contracts and how they're governed is critical for assessing platform trustworthiness. ## Complete Platform Verification Checklist Verify the full platform integrity by checking each component: **Hardware & Firmware:** * [ ] TDX quote signature is valid (Intel's root certificates) * [ ] `tee_tcb_svn` matches latest security patches * [ ] `mr_seam` matches known TDX firmware **Operating System:** * [ ] OS version from `appInfo.tcb_info.os_version` is known * [ ] MRTD and RTMR0-2 match calculated values * [ ] VM config (CPU, memory, GPU) matches `appInfo.vm_config` * [ ] OS image hash is whitelisted in `DstackKms.allowedOsImages` * [ ] (Optional) OS built reproducibly from source **Key Management:** * [ ] KMS ID from RTMR3 `key-provider` event is known * [ ] KMS's own attestation quote is valid * [ ] KMS aggregated MR is whitelisted in `DstackKms.kmsAllowedAggregatedMrs` **Network Security:** * [ ] TLS certificate fingerprint matches served certificate * [ ] Evidence files at `/evidences/` are cryptographically bound to quote * [ ] CAA DNS records restrict certificate issuance **Governance:** * [ ] Smart contract addresses are verified * [ ] Contract permissions match security policy * [ ] Contract ownership and upgrade mechanisms are understood ## Attack Scenarios Prevented **Compromised OS:** OS measurements in RTMR0-2 and on-chain whitelist prevent unauthorized OS versions from booting. **Malicious KMS:** KMS binding in RTMR3 and on-chain governance prevent unauthorized KMS instances from providing keys. **Certificate impersonation:** Evidence files and CAA records prevent unauthorized TLS certificates from being issued. **Supply chain attacks:** Reproducible OS builds and governance contracts prevent compromised build infrastructure from injecting malicious code. **Unauthorized updates:** On-chain governance ensures only authorized OS versions, KMS instances, and application updates can run. ## Tools and Resources * **[dstack-verifier](https://github.com/Dstack-TEE/dstack/tree/next/dstack/verifier)** - Automated platform verification tool * **[meta-dstack](https://github.com/Dstack-TEE/meta-dstack)** - Reproducible OS builds * **[dstack SDK](https://www.npmjs.com/package/@phala/dstack-sdk)** - Application info and quote retrieval * **[Smart Contracts](https://github.com/Dstack-TEE/dstack/tree/next/dstack/kms/auth-eth/contracts)** - DstackKms and DstackApp source * **[trust-center](https://github.com/Phala-Network/trust-center)** - Complete reference implementation ## Real-World Example: Private AI For a complete implementation of platform verification, see how Private AI verifies: * Hardware stack (NVIDIA GPUs + Intel TDX) * OS integrity from reproducible builds * Application code via compose-hash * KMS trust for key derivation * Request/response integrity signatures Learn more: **[Private AI Verification](/phala-cloud/confidential-ai/verify/overview)** ## Next Steps > [card] [Verify Your Application](/phala-cloud/attestation/verify-your-application) > > Verify your application code and Docker images > [card] [Complete Security Checklist](/phala-cloud/attestation/chain-of-trust) > > Security audit checklist for 100% verification > [card] [Field Reference](/phala-cloud/attestation/attestation-fields) > > Understand all quote fields and measurements > [card] [Domain Attestation](/phala-cloud/networking/domain-attestation) > > Verify TLS certificate binding for custom domains # Verify Your Application Source: https://docs.phala.com/phala-cloud/attestation/verify-your-application Prove your exact Docker containers run unmodified in the TEE. Prove your exact Docker containers run unmodified in the TEE. Verify no one substituted different code. ## What Should You Verify? **Basic verification:** Confirm your application code (reportData and compose-hash) runs in genuine TEE hardware. Suitable for most use cases. **Advanced verification:** Everything from Basic, plus RTMR3 event log replay, on-chain governance checks, and source code provenance. Required for high-assurance applications (DeFi, confidential AI, sensitive data). ## Basic Verification Verify your application code runs in genuine TEE hardware. This verification confirms: * Your specific data (reportData) is present in the quote * Your application configuration (compose-hash) matches what's deployed * The quote comes from genuine Intel TDX hardware > [!NOTE] > > This code runs on the **verifier side** (end users or auditors checking your CVM), not inside the CVM itself. ### Prerequisites Your application must expose attestation endpoints. See [Get Attestation](/phala-cloud/attestation/get-attestation) for how to set this up inside your CVM. Fetch all required data from your CVM: ```javascript TypeScript theme={"system"} // Fetch attestation quote const attestResponse = await fetch('https://your-app.example.com/attestation'); const attestData = await attestResponse.json(); const quote = attestData.quote; const eventLog = attestData.event_log; const reportData = attestData.report_data; // Fetch application configuration const infoResponse = await fetch('https://your-app.example.com/info'); const appInfo = await infoResponse.json(); const appComposeConfig = appInfo.tcb_info.app_compose; ``` ```python Python theme={"system"} import requests # Fetch attestation quote attest_response = requests.get('https://your-app.example.com/attestation') attest_data = attest_response.json() quote = attest_data['quote'] event_log = attest_data['event_log'] report_data = attest_data['report_data'] # Fetch application configuration info_response = requests.get('https://your-app.example.com/info') app_info = info_response.json() app_compose_config = app_info['tcb_info']['app_compose'] ``` ### Step 1: Verify reportData Check that reportData contains the expected challenge or public key: ```javascript TypeScript theme={"system"} import assert from 'assert'; const expectedChallenge = 'your-expected-challenge-hex'; assert(reportData.startsWith(expectedChallenge), 'reportData mismatch'); ``` ```python Python theme={"system"} expected_challenge = 'your-expected-challenge-hex' assert report_data.startswith(expected_challenge), 'reportData mismatch' ``` ### Step 2: Verify compose-hash The compose-hash is a SHA256 hash of your app-compose.json configuration file (which includes your docker-compose.yaml plus metadata). This hash proves which exact Docker images are running. Verify the configuration you fetch from the CVM matches what's attested in RTMR3: ```javascript TypeScript theme={"system"} import assert from 'assert'; import { createHash } from 'crypto'; // Calculate SHA-256 hash of app-compose const calculatedHash = createHash('sha256') .update(appComposeConfig) .digest('hex'); // Extract attested hash from RTMR3 event log const events = JSON.parse(eventLog); const composeEvent = events.find(e => e.event === 'compose-hash'); const attestedHash = composeEvent.event_payload; // Verify hashes match assert.strictEqual(calculatedHash, attestedHash, 'compose-hash mismatch'); ``` ```python Python theme={"system"} import hashlib import json # Calculate SHA-256 hash of app-compose calculated_hash = hashlib.sha256(app_compose_config.encode()).hexdigest() # Extract attested hash from RTMR3 event log events = json.loads(event_log) compose_event = next(e for e in events if e['event'] == 'compose-hash') attested_hash = compose_event['event_payload'] # Verify hashes match assert calculated_hash == attested_hash, 'compose-hash mismatch' ``` ### Step 3: Verify quote signature Verify the TDX quote was signed by genuine Intel hardware. This uses Phala Cloud's verification API (alternatively, you can use [dcap-qvl](https://github.com/Phala-Network/trust-center) locally for trustless verification): ```javascript TypeScript theme={"system"} import assert from 'assert'; const verifyResponse = await fetch('https://cloud-api.phala.com/api/v1/attestations/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ hex: quote }) }); const result = await verifyResponse.json(); assert(result.quote.verified, 'Hardware verification failed'); ``` ```python Python theme={"system"} import requests verify_response = requests.post( 'https://cloud-api.phala.com/api/v1/attestations/verify', json={'hex': quote} ) result = verify_response.json() assert result['quote']['verified'], 'Hardware verification failed' ``` You've verified your application code runs in genuine TEE hardware. ## Advanced Verification For high-assurance applications, verify additional security properties beyond Basic Verification: * **RTMR3 event log replay**: Cryptographically prove the boot sequence * **Docker image digests**: Ensure images are pinned to specific versions * **On-chain governance**: Verify only authorized configs can run * **Source code provenance**: Link images back to audited source code > [!NOTE] > > All verification steps **must run outside the CVM**. Only verification that happens outside the TEE provides security guarantees. ### Prerequisites Complete [Basic Verification](#basic-verification) first. You'll need the same data (quote, event\_log, app\_compose, calculated hash). ### Step 1: Verify RTMR3 event log replay RTMR3 uses a hash chain where each event extends the previous value. The event log records three events during boot: 1. `compose-hash` - Your application configuration 2. `instance-id` - Unique CVM instance identifier 3. `key-provider` - KMS that distributed encryption keys The hash chain mechanism ensures no one can modify the event log without breaking the chain. Each new value is computed as: `RTMR3_new = SHA384(RTMR3_old || SHA384(event))`. To verify this: 1. Parse the event log and extract all RTMR3 events (where `imr === 3`) 2. Start with initial RTMR3 value (48 zero bytes) 3. For each event digest in order: * Pad digest to 48 bytes if needed * Compute: `RTMR3 = SHA384(RTMR3 || digest)` 4. Compare final replayed RTMR3 with the `rtmr3` value from the quote > [!NOTE] > > **TODO**: The dstack SDK does not currently export a `replayRtmrs()` utility function for external verifiers. For production use, refer to the [Rust verification implementation](https://github.com/Dstack-TEE/dstack/blob/d3275d1e0a0f4e2191273f0d9df62986f3d6acca/verifier/src/verification.rs#L26-L149) or use [trust-center](https://github.com/Phala-Network/trust-center) for complete RTMR3 replay verification. ### Step 2: Verify Docker image digests Docker images must be pinned by SHA256 digest, not mutable tags. Tags like `nginx:latest` can point to different images over time, breaking verification. Verify all images in your app-compose use immutable digests: ```javascript TypeScript theme={"system"} import assert from 'assert'; // Parse app-compose and extract docker-compose const appCompose = JSON.parse(appComposeConfig); const dockerComposeYaml = appCompose.docker_compose_file; // Check all image lines use @sha256 digests const imageLines = dockerComposeYaml.split('\n').filter(line => line.trim().startsWith('image:') ); for (const line of imageLines) { assert( line.includes('@sha256:'), `Image not pinned by digest: ${line.trim()}` ); } ``` ```python Python theme={"system"} import json import yaml # Parse app-compose and extract docker-compose app_compose = json.loads(app_compose_config) docker_compose = yaml.safe_load(app_compose['docker_compose_file']) # Check all services use @sha256 digests for service_name, service in docker_compose.get('services', {}).items(): image = service.get('image', '') assert '@sha256:' in image, f'Image not pinned by digest: {service_name}' ``` Example of proper image pinning: ```yaml theme={"system"} services: app: # BAD: Mutable tag image: nginx:latest # GOOD: Immutable digest image: nginx@sha256:eee5eae48e79b2e75178328c7c585b89d676eaae616f03f9a1813aaed820745a ``` Get the digest for any image: ```bash theme={"system"} docker pull nginx:latest docker inspect nginx:latest | grep -A 1 RepoDigests ``` ### Step 3: Verify on-chain governance (optional) If your application uses on-chain governance, verify the compose-hash is whitelisted. This ensures only authorized application versions can boot: ```bash theme={"system"} # Check if compose-hash is authorized in DstackApp contract cast call "allowedComposeHashes(bytes32)" # Returns true if whitelisted, false otherwise # Monitor for new authorized versions cast logs --event "ComposeHashAdded(bytes32,address)" ``` ### Step 4: Verify source code provenance Link Docker image digests back to audited source code using cryptographic build provenance. **Recommended: Sigstore for GitHub builds** Sigstore cryptographically links container images to specific GitHub commits and workflows. When you build images via GitHub Actions, Sigstore automatically signs the build with GitHub's identity, creating unforgeable proof. Platform components use Sigstore: * [dstack-gateway releases](https://github.com/Dstack-TEE/dstack/releases?q=%22dstack-gateway%22\&expanded=true) * [dstack-kms releases](https://github.com/Dstack-TEE/dstack/releases?q=%22dstack-kms%22\&expanded=true) * [dstack-verifier releases](https://github.com/Dstack-TEE/dstack/releases?q=%22dstack-verifier%22\&expanded=true) Set up Sigstore signing in your GitHub Actions workflow to provide the same cryptographic build provenance for your applications. **Alternative: Reproducible builds** For maximum verifiability, use reproducible builds where anyone can rebuild from source and get identical digests. Publish your Dockerfile and build instructions. This requires careful environment control but removes the need to trust any build service. ## Attack Scenarios Prevented **Compromised Docker registry:** The TEE verifies image digests against compose-hash before pulling. Even if the registry serves malicious images, digest verification fails. **Code substitution:** The compose-hash in RTMR3 is recorded by TEE hardware during boot. No one can modify it without invalidating the attestation quote signature. **Unauthorized updates:** On-chain governance (if enabled) ensures only whitelisted compose hashes can boot. Malicious developers cannot deploy unapproved versions. **Event log tampering:** RTMR3 event log replay cryptographically proves the events are authentic. Modification causes replay to produce different RTMR3 that won't match the quote. ## Verification Checklist Complete application verification requires checking: * [ ] All Docker images use SHA256 digests (not tags) * [ ] Calculated compose-hash matches expected value * [ ] RTMR3 event log replays to quoted RTMR3 value * [ ] Attested compose-hash matches calculated hash * [ ] compose-hash is whitelisted on-chain (if using governance) * [ ] reportData contains expected challenge/public key * [ ] Image digests link to audited source code (Sigstore or reproducible builds) ## Tools and Resources * **[dstack SDK](https://www.npmjs.com/package/@phala/dstack-sdk)** - `getComposeHash()` and `replayRtmrs()` methods * **[RTMR3 Calculator](https://rtmr3-calculator.vercel.app/)** - Web tool for compose-hash calculation * **[Verification Script](https://github.com/Dstack-TEE/dstack-examples/blob/main/attestation/rtmr3-based/verify.py)** - Complete Python example * **[trust-center](https://github.com/Phala-Network/trust-center)** - Reference implementation ## Next Steps > [card] [Verify the Platform](/phala-cloud/attestation/verify-the-platform) > > Verify OS, KMS, and infrastructure security > [card] [Complete Security Checklist](/phala-cloud/attestation/chain-of-trust) > > Security audit checklist for 100% verification > [card] [Field Reference](/phala-cloud/attestation/attestation-fields) > > Understand all quote fields and measurements > [card] [API Reference](/phala-cloud/phala-cloud-api/attestations) > > Complete verification service documentation # Cases Explorer Source: https://docs.phala.com/phala-cloud/cases/best-practices-and-successful-case Explore real-world use cases showing how Phala Cloud enables secure, verifiable AI and trustless applications using TEE technology. Explore how Phala Cloud enables secure, verifiable AI and trustless applications using TEE technology. [https://cloud.phala.com/cases](https://cloud.phala.com/cases) # Overview Source: https://docs.phala.com/phala-cloud/cases/overview Explore real-world applications and use cases for TEE technology. TEE provide hardware-based isolation for sensitive computations, ensuring data confidentiality and integrity. This document explores various use cases where TEEs can be combined with other technologies to create powerful, secure solutions. ## Industry Success Stories Explore real-world implementations across different sectors: * [Financial Services](https://phala.com/success-stories/financial-services) - confidential AI for banking and trading * [Healthcare & Research](https://phala.com/success-stories/healthcare-research) - HIPAA-compliant AI and medical data privacy * [B2B SaaS Platforms](https://phala.com/success-stories/ai-saas-platform) - Enterprise AI privacy and multi-tenant security * [Decentralized AI](https://phala.com/success-stories/decentralized-ai) - Web3 and blockchain AI applications ## TEE + AI TEEs can protect AI model training and inference, preserving both model privacy and data confidentiality. This combination enables secure machine learning on sensitive data while preventing unauthorized access to proprietary models. TEE also can be used to build unruggable AI Agents that operate with the same level of trustworthiness as smart contracts, check [the article by Phala CEO Marvin Tong](https://x.com/marvin_tong/status/1866319231350100330) to see why we get there. Check out [Building confidential AI with TEE](/phala-cloud/cases/tee_with_ai) ## TEE + FHE/MPC TEEs can complement Fully Homomorphic Encryption (FHE) and Multi-Party Computation (MPC) to create hybrid systems with enhanced performance and security guarantees. These combinations allow for secure computation on encrypted data with reduced overhead. Check out [TEE with FHE and MPC](/phala-cloud/cases/tee_with_fhe_and_mpc) ## Private Proving with TEE **Private Proving** runs zero-knowledge provers inside TEE to protect sensitive data during proof generation. While ZK proofs verify computation correctness, they don't prevent the prover from accessing your private data. Running ZK provers in TEE solves this critical problem - your transaction data, API keys, AI models, and business logic stay hardware-encrypted even during proving. Phala Cloud provides production-ready infrastructure for private proving with GPU TEE (H100/H200), enabling developers to generate ZK proofs at hardware speed while keeping sensitive inputs encrypted at the silicon level. Check out [Private Proving with TEE](/phala-cloud/cases/tee_with_zk_and_zkrollup) # Building confidential AI Source: https://docs.phala.com/phala-cloud/cases/tee_with_ai Build confidential AI applications with Trusted Execution Environment technology. > [!NOTE] > > Check Phala Network's [2025 dAGI report](https://phala.com/reports/2025RealCodeForRealdAGI.pdf) to see how TEE is used in AI full stack. ## Introduction ![Phala Network 2025 dAGI report cover showing AI robot building with data structures and partner ecosystem logos](https://mintcdn.com/phalanetwork-1606097b/Z_xV6g4Cdei2rfqm/images/tee-ai-banner.png?fit=max\&auto=format\&n=Z_xV6g4Cdei2rfqm\&q=85\&s=62fb03b5a95d4039525d462b4c2a9b98) AI has become a transformative force across industries, but its widespread adoption faces significant challenges related to data privacy, model security, and computational trust. As AI systems process increasingly sensitive information and make critical decisions, ensuring the confidentiality and integrity of both the data and the AI models themselves has become paramount. TEE offer a compelling solution to these challenges by providing hardware-enforced isolation for AI workloads. By running AI models and AI agents programs within TEE, organizations can protect sensitive data, prevent unauthorized access to proprietary models, and provide verifiable guarantees about the execution environment. ## The Need for TEE in AI Systems The integration of TEE technology with AI addresses several critical challenges: * **Data Privacy Concerns**: AI training and inference often require access to sensitive personal, financial, or proprietary data. TEEs ensure this data remains encrypted and protected even during processing. * **Model Protection**: Valuable AI models represent significant intellectual property that needs protection from theft, tampering, or unauthorized access. TEEs can safeguard these assets throughout their lifecycle. * **Verifiable Computation**: Users need assurance that AI computations are performed correctly and that results haven't been manipulated. TEE attestation provides cryptographic proof of the execution environment's integrity. * **Preventing Data Leakage**: Even in systems designed for privacy, subtle information leakage can occur through side channels or model outputs. TEEs provide an additional layer of protection against such vulnerabilities. ![Diagram of confidential AI inference showing data flow through a TEE-protected environment](https://mintcdn.com/phalanetwork-1606097b/416gZMDMREnPDd33/images/confidential-ai-inference-overview.png?fit=max\&auto=format\&n=416gZMDMREnPDd33\&q=85\&s=78dfccdf90de5da01774dd04459c4e79) ## Key Benefits of TEE for AI Applications 1. **Confidential AI inference**: Run inference on sensitive data without exposing either the data or the model to the host system or service provider. 2. **Secure Model Training**: Protect training data and emerging model parameters during the training process, preventing data poisoning or model extraction attacks. 3. **Trustless AI Marketplaces**: Enable secure sharing and monetization of AI models without risking intellectual property theft. 4. **Verifiable AI Results**: Provide cryptographic proof that AI outputs were generated by specific models running in secure environments, enhancing trust in critical applications. 5. **Regulatory Compliance**: Meet stringent data protection requirements by ensuring data remains encrypted throughout the AI pipeline. 6. **Autonomous AI Agents**: Enable AI agents to securely manage cryptographic keys and digital assets without exposing sensitive credentials. ## Case Studies ### TEE in Agent Frameworks
🤖 Eliza: Secure AI Agent Framework with TEE Integration[tee\_eliza.png](/images/tee_eliza.png)[Eliza TEE Plugin](https://eliza.how/packages/plugins/tee)
🎮 Virtuals: Game Agents Running in Secure TEE Environment[tee\_game\_agents.png](/images/tee_game_agents.png)[Virtuals Game Agent](https://github.com/game-by-virtuals/game-node/tree/main/game-starter#to-run-project-in-phala-tee)
### Other TEE-AI Integrations
📡 Vana Network: Decentralized Data Privacy with TEE[tee\_vana.png](/images/tee_vana.png)[Phala x Vana](https://phala.com/posts/phala-network-and-vana-network-join-forces-to-usher-in-new-era-for-decentralized-data-privacy)
🌐 0G: Confidential AI Computing in Decentralized Networks[tee\_0g.png](/images/tee_0g.png)[Phala x 0G](https://phala.com/posts/phala-network-and-0g-partner-for-enhanced-confidential-ai-computing)
💰 Fairblock: Unruggable AI with MPC-TEE Hybrid Architecture[tee\_fairblock.png](/images/fairblock_tee_registry.png)[Phala x Fairblock](https://phala.com/posts/phala-x-fairblock-a-blueprint-for-unruggable-ai-with-an-mpctee-hybrid-architecture)
🌱 Spore.fun: Autonomous AI Evolution in Secure Environments[tee\_spore.png](/images/tee_spore.png)[Spore.fun](https://www.spore.fun/blog/wtf)
# 2FA for FHE/MPC Systems Source: https://docs.phala.com/phala-cloud/cases/tee_with_fhe_and_mpc Combine TEE with FHE and MPC for enhanced privacy-preserving computations. ## Introduction Fully Homomorphic Encryption (FHE) and Multi-Party Computation (MPC) are foundational technologies for privacy-preserving computation, enabling operations on encrypted data without decryption. However, their adoption in real-world systems, particularly blockchain and decentralized networks, faces challenges such as computational overhead, key management risks, and trust assumptions. This chapter explores how Phala Network's TEE can act as a 2FA mechanism to enhance the security and practicality of FHE/MPC workflows. Check out earlier thoughts on **[SGX as 2FA for FHE/MPC](https://ethresear.ch/t/sgx-as-2fa-for-fhe-mpc/19780)** and **[Drawbacks in FHE Blockchain and how TEE can help](https://collective.flashbots.net/t/drawbacks-in-fhe-blockchain-and-how-tee-can-help-it/3642)** ## Challenges in FHE/MPC Systems **Key Management Risks** * Secure key generation, storage, and usage are critical vulnerabilities * Key compromise threatens data confidentiality and computation integrity * Software-based solutions remain susceptible to memory attacks and insider threats **Performance Limitations** * FHE introduces significant computational overhead, impractical for time-sensitive applications * MPC reduces individual computation but increases network communication and coordination costs * Both technologies face scalability challenges in high-throughput environments **Trust Vulnerabilities** * Systems rely on honest-majority assumptions that weaken with participant count * Collusion attacks become feasible when economic incentives align for malicious actors * Lack of accountability mechanisms when malicious behavior occurs * Threshold schemes vulnerable to withholding attacks that prevent result finalization ## TEE as a 2FA Mechanism: Architectural Overview TEEs provide hardware-enforced isolation for sensitive operations, combining the benefits of TEE with cryptographic protocols. When integrated with FHE/MPC, TEEs act as a secondary trust layer, ensuring: * **Secure Key Generation/Storage**: Cryptographic keys are generated and stored within the TEE, isolated from the host OS or untrusted applications. * **Computation Integrity**: Critical operations (e.g., decryption of FHE results or MPC coordination) are verified within the TEE. * **Attestation**: Remote parties can cryptographically verify that computations were executed in a genuine TEE. ### Workflow Example * MPC nodes build a docker image and deploy it to [Phala Cloud](https://cloud.phala.com/register?invite=PHALAWIKI), see the [tutorial](/phala-cloud/cvm/create-with-docker-compose). 1. A master key is generated inside an TEE and never exposed externally. 2. The MPC node signs a public verification key, which is shared with the network. 3. The MPC node generate a attestation proof that prove the key generation and storage are done in a genuine TEE. For FHE Computation: 4. Users encrypt data using FHE and send to FHE server. 5. FHE finished the computation and encrypt the result with the MPC key. 6. The MPC nodes in TEE decrypting intermediate results and return the result to users. ## Case Studies
🔐 Fairblock: Building Unruggable AI with an MPC-TEE Hybrid Architecture[fairblock\_tee\_registry.png](/images/fairblock_tee_registry.png)[Fairblock GitHub](https://github.com/Fairblock/Unruggable-AI)
🗳️ Mind Network: Leverage TEE and FHE Build Blind Voting[fhe\_tee\_voting.png](/images/fhe_blind_voting.png)[Mind Network Case Study](https://phala.com/posts/fhepowered-aifi-with-mind-network)
# Private Proving with TEE Source: https://docs.phala.com/phala-cloud/cases/tee_with_zk_and_zkrollup Private Proving - Running ZK provers inside TEE to protect sensitive data during proof generation. ## What is Private Proving? **Private Proving** is a method of generating cryptographic proofs inside a Trusted Execution Environment (TEE) that ensures input data (the witness) remains completely confidential during proof generation. This means neither the verifier nor the prover can see an application's input data. ![Private Proving Overview - Source: Succinct Labs](https://mintcdn.com/phalanetwork-1606097b/W_CrYRGQOR7Ch9JM/images/succinct-private-proving-overview.jpeg?fit=max\&auto=format\&n=W_CrYRGQOR7Ch9JM\&q=85\&s=57d8762c4f1e99bdf7d5a9e95fa3fd14) ### The Problem: Witness Data Exposure in Traditional ZK Proving Traditional zero-knowledge proving systems verify computation correctness, but the witness data (private inputs) is exposed to the prover operator during proof generation: * **Privacy-focused rollups**: Prover operators can see user transaction amounts, recipients, and trading strategies * **Private DeFi protocols**: Witness data includes sensitive positions, balances, and trading logic * **Confidential identity systems**: User credentials and personal data are exposed to prover infrastructure * **Private payments**: Transaction amounts and sender/receiver information visible to prover **The core issue**: Zero-knowledge proofs hide data from the verifier, but they don't protect data from the prover. The prover sees all witness data during proof generation. ### The Solution: Run ZK Provers Inside TEE Private proving runs the proof generation process inside hardware-isolated environments, ensuring witness data never leaves the secure enclave: ``` Witness Data (Private) → TEE [zkVM Prover] → ZK Proof (Public) ``` **How it works**: * Witness data enters the TEE and remains hardware-encrypted throughout proving * The zkVM (like SP1) executes inside the TEE to generate the proof * Only the final proof leaves the TEE - witness data stays protected * TEE attestation proves the proving environment was secure **Key benefits**: 1. **Complete Witness Privacy**: No one, including the prover operator, can see witness data 2. **Hardware-Level Security**: Data encrypted at the silicon level (Intel TDX, AMD SEV, AWS Nitro) 3. **Developer-Friendly**: Write private applications in Rust using familiar zkVM frameworks 4. **Performance**: GPU TEE (H200) provides hardware acceleration for fast proof generation 5. **Verifiable Security**: Remote attestation cryptographically proves the secure execution environment **Impact**: Private proving transforms privacy from a specialized technical challenge into a standard feature. As Succinct states: "With Succinct, privacy will be a standard rather than an exception." > [!NOTE] > > Learn more about Private Proving from Succinct Labs' [Private Proving announcement](https://blog.succinct.xyz/private-proving/). ## Benefits vs Traditional ZK | Feature | Traditional ZK | Private Proving (ZK in TEE) | | - | - | - | | **Proof Correctness** | ✅ Cryptographic | ✅ Cryptographic | | **Witness Privacy** | ❌ Exposed to prover | ✅ Hardware encrypted | | **Verifiable Execution** | ❌ No guarantees | ✅ TEE attestation | | **Developer Experience** | Circuit development | ✅ No code changes (Rust/zkVM) | | **Performance** | Fast | Minimal overhead with GPU TEE | | **GPU Acceleration** | ✅ Yes | ✅ Yes (H100/H200) | | **Trust Assumptions** | Cryptography only | Cryptography + hardware | ## Private Proving in Production ### Phala Cloud: Hardware-Accelerated Private Proving Phala Cloud provides production-ready infrastructure for private proving with GPU TEE:
🚀 Phala Network: Run zk-Rollup STF (state transition function) in TEE [Use-Cases-Multi-Proof.png](/images/Use-Cases-Multi-Proof.png) [Phala SGXProver](https://phala.com/posts/introducing-phala-sgxprover-a-twofactor-authentication-solution-for-zkrollups)
🔒 Primus: Build Trustless zkTLS with TEE [tee\_zktls.png](/images/tee_zktls.png) [Primus zkTLS](https://medium.com/@primuslabs/primus-x-phala-network-build-trustless-zktls-with-tee-332a26d48c83)
💾 Running SP1 zkVM in TEE H200 with Low Overhead [zkvm-sp1-in-gpu-tee.jpg](/images/zkvm-sp1-in-gpu-tee.jpg) [SP1 zkVM in TEE](https://phala.com/posts/performance-benchmark-running-sp1-zkvm-in-tee-h200-with-low-overhead)
## Multi-Proof Systems: Defense-in-Depth (SP1-2FA) While private proving protects data privacy, some applications require maximum security through defense-in-depth. **Multi-proof systems** like [Succinct's SP1-2FA](https://blog.succinct.xyz/sp1-2fa/) generate both ZK and TEE proofs in parallel: ![SP1-2FA Multi-Proof Architecture - Source: Succinct Labs](https://mintcdn.com/phalanetwork-1606097b/W_CrYRGQOR7Ch9JM/images/succinct-sp1-2fa-architecture.jpg?fit=max\&auto=format\&n=W_CrYRGQOR7Ch9JM\&q=85\&s=bc5b753b528829a4f8aad63dd87482f4) **How it differs from private proving**: * **Private Proving**: ZK prover runs *inside* TEE (focus: data privacy) * **SP1-2FA**: ZK and TEE run in *parallel* (focus: maximum security) **When to use SP1-2FA**: * Critical infrastructure (blockchain consensus, bridges) * High-value DeFi protocols (significant TVL at risk) * Defense against undiscovered ZK circuit bugs * Regulatory requirements for multiple independent proofs **Trade-off**: SP1-2FA provides stronger security guarantees but doesn't specifically protect data privacy during ZK proving. For most applications requiring data privacy, private proving is the right choice. > [!NOTE] > > Learn more about SP1-2FA from [Succinct's blog post](https://blog.succinct.xyz/sp1-2fa/). **Resources**: * [Getting Started Guide](/phala-cloud/getting-started/overview) * [Performance Benchmarks](/phala-cloud/references/performance-report) * [TEE Attestation](/phala-cloud/attestation/overview) * [Deploy with Docker](/phala-cloud/cvm/overview) ## References and Further Reading * **Succinct Labs**: [Private Proving Blog Post](https://blog.succinct.xyz/private-proving/) | [SP1-2FA Technical Details](https://blog.succinct.xyz/sp1-2fa/) * **Vitalik Buterin**: [Multi-Proof Systems Presentation](https://hackmd.io/@vbuterin/zk_slides_20221010#/) * **Justin Drake**: [2FA ZK-Rollups with SGX](https://ethresear.ch/t/2fa-zk-Rollups-using-sgx/14462) * **Phala Network**: [SP1 zkVM Performance Benchmark](https://phala.com/posts/performance-benchmark-running-sp1-zkvm-in-tee-h200-with-low-overhead) # Claude Code Source: https://docs.phala.com/phala-cloud/confidential-ai/agents/claude-code Run Claude Code on Phala through Private AI Proxy, or configure it by hand. Claude Code speaks the Anthropic Messages protocol. Private AI Proxy configures it automatically. ## With Private AI Proxy 1. Install [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy), choose a **Phala** profile, sign in, and turn on **Protected**. 2. On the **Agents** screen, connect **Claude Code**. 3. Start `claude`. The app writes the Messages provider into Claude Code's settings with an agent-scoped token for its local API, and restores the previous settings when you disconnect or stop Protected. From the CLI, the same connection is: ```bash theme={"system"} pap agents connect claude-code ``` ## Without the Proxy Create a key under **Private AI → API Keys** in the [Phala dashboard](https://cloud.phala.com/dashboard). Set the base URL to the host without `/v1`; Claude Code appends `/v1/messages` itself. ```bash theme={"system"} export PHALA_AI_API_KEY="YOUR_PHALA_API_KEY" export ANTHROPIC_BASE_URL="https://inference.phala.com" export ANTHROPIC_AUTH_TOKEN="$PHALA_AI_API_KEY" export ANTHROPIC_API_KEY="" export ANTHROPIC_MODEL="z-ai/glm-5.3" export ANTHROPIC_DEFAULT_OPUS_MODEL="z-ai/glm-5.3" export ANTHROPIC_DEFAULT_SONNET_MODEL="z-ai/glm-5.3" export ANTHROPIC_DEFAULT_HAIKU_MODEL="z-ai/glm-5.3" claude ``` `ANTHROPIC_AUTH_TOKEN` sends the key as a bearer token; clearing `ANTHROPIC_API_KEY` stops an existing Anthropic key from adding a conflicting `x-api-key` header. Phala model IDs do not appear in the `/model` picker; set the model with `ANTHROPIC_MODEL` or `/model z-ai/glm-5.3`. The alias variables send plan mode and background work to a Phala model. This path does not verify attestation locally; use [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy) or the [TypeScript ACI Verifier](/phala-cloud/confidential-ai/verify/typescript-sdk). Every model on this endpoint runs in a TEE. ## Check the Connection Run `/status` in Claude Code. With the Proxy, the base URL is `http://127.0.0.1:4180`; without it, `https://inference.phala.com`. Confirm the bearer credential source and the selected model. ## Troubleshooting | Symptom | Check | | - | - | | Claude Code ignores the Proxy | Confirm **Connected** in the app and that Protected is on, then restart `claude`. | | Request path contains `/v1/v1/messages` | Remove `/v1` from `ANTHROPIC_BASE_URL`. | | Authentication fails | Use `ANTHROPIC_AUTH_TOKEN` and clear `ANTHROPIC_API_KEY`. | ## Related * [Claude Code gateway configuration](https://code.claude.com/docs/en/llm-gateway-connect) * [Claude Code gateway model discovery](https://code.claude.com/docs/en/llm-gateway-protocol#model-discovery) * [Claude Code model configuration](https://code.claude.com/docs/en/model-config) * [Phala Messages API](/phala-cloud/confidential-ai/confidential-model/api-reference/messages) * [Phala model catalog](/phala-cloud/confidential-ai/confidential-model/api-reference/models) # Cline Source: https://docs.phala.com/phala-cloud/confidential-ai/agents/cline Run Cline on Private AI through Private AI Proxy, or configure it by hand. Cline uses Chat Completions through its **OpenAI Compatible** provider. Private AI Proxy does not configure it automatically; enter the app's Local API values by hand. ## With Private AI Proxy 1. Install [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy), choose a Phala profile, sign in, and turn on **Protected**. 2. Open Cline's settings (gear icon), select **OpenAI Compatible** under **API Provider**, and enter the Local API values: | Field | Value | | - | - | | Base URL | `http://127.0.0.1:4180/v1` | | API Key | The client key from the app's Overview screen | | Model ID | `z-ai/glm-5.3`, or another chat model from the app's verified catalog | 3. Start a task. Requests succeed only while Protected is on. From the CLI, `pap token show` prints the client key and `pap models list` lists the catalog. Keep the client key private. ## Without the Proxy Create a key under **Private AI → API Keys** in the [Phala dashboard](https://cloud.phala.com/dashboard). Open Cline's settings (gear icon) and select **OpenAI Compatible** under **API Provider**, then enter the following [provider settings](https://docs.cline.bot/provider-config/openai-compatible): ```text theme={"system"} Base URL: https://inference.phala.com/v1 API Key: Your Phala API key Model ID: z-ai/glm-5.3 ``` Choose another chat model from [`/v1/models`](https://inference.phala.com/v1/models) and copy its context and output limits when entering a model by hand. This path does not verify attestation locally; use [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy) or the [TypeScript ACI Verifier](/phala-cloud/confidential-ai/verify/typescript-sdk). Every model on this endpoint runs in a TEE. ## Check the Connection Use Cline's **Verify** action, then run a read-only request in a disposable repository and confirm the selected provider and model. ## Troubleshooting | Symptom | Check | | - | - | | Verify fails with the Proxy | Protected must be on; copy the client key again. | | Verify fails without the Proxy | Keep `/v1` in the base URL and check the API key. | | Tool calls fail | Choose a model that declares `tools` in the live catalog and repeat Verify. | ## Related * [Cline OpenAI-Compatible Providers](https://docs.cline.bot/provider-config/openai-compatible) * [Phala Model Catalog](/phala-cloud/confidential-ai/confidential-model/api-reference/models) # Codex CLI Source: https://docs.phala.com/phala-cloud/confidential-ai/agents/codex Run Codex CLI on Phala through Private AI Proxy, or configure it by hand. Codex speaks the Responses protocol. Private AI Proxy configures it automatically. ## With Private AI Proxy 1. Install [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy), choose a **Phala** profile, sign in, and turn on **Protected**. 2. On the **Agents** screen, connect **Codex** and pick a model from the verified catalog. 3. Start `codex`. The app adds a custom model provider to `~/.codex/config.toml` that points at its local API with an agent-scoped token, and restores the file when you disconnect or stop Protected. From the CLI, the same connection is: ```bash theme={"system"} pap agents connect codex ``` ## Without the Proxy Create a key under **Private AI → API Keys** in the [Phala dashboard](https://cloud.phala.com/dashboard). Add Phala as a custom provider in the user-level configuration; Codex ignores `model_provider` and `model_providers` in a project-local `.codex/config.toml`. ```bash theme={"system"} export PHALA_AI_API_KEY="YOUR_PHALA_API_KEY" ``` ```toml ~/.codex/config.toml theme={"system"} model = "z-ai/glm-5.3" model_provider = "phala" [model_providers.phala] name = "Phala" base_url = "https://inference.phala.com/v1" env_key = "PHALA_AI_API_KEY" wire_api = "responses" ``` Pick the model from [`GET /v1/models`](/phala-cloud/confidential-ai/confidential-model/api-reference/models); choose one that declares `tools`. This path does not verify attestation locally; use [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy) or the [TypeScript ACI Verifier](/phala-cloud/confidential-ai/verify/typescript-sdk). Every model on this endpoint runs in a TEE. ## Check the Connection Start `codex` and run one bounded tool task. With the Proxy, the provider in `config.toml` points at `http://127.0.0.1:4180/v1`; without it, at `https://inference.phala.com/v1`. ## Troubleshooting | Symptom | Check | | - | - | | Codex ignores the Proxy | Confirm **Connected** in the app and that Protected is on, then restart `codex`. | | Codex still uses the default provider | Confirm `model_provider = "phala"` is at the top level of the user-level file. | | Chat works but tools fail | Choose a model that declares `tools` in the live catalog. | ## Related * [Codex custom model providers](https://learn.chatgpt.com/docs/config-file/config-advanced#custom-model-providers) * [Phala Responses API](/phala-cloud/confidential-ai/confidential-model/api-reference/responses) * [Phala model catalog](/phala-cloud/confidential-ai/confidential-model/api-reference/models) # Hermes Source: https://docs.phala.com/phala-cloud/confidential-ai/agents/hermes Run Hermes Agent on Phala through Private AI Proxy, or configure it by hand. Hermes speaks Chat Completions. Private AI Proxy configures it automatically. ## With Private AI Proxy 1. Install [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy), choose a **Phala** profile, sign in, and turn on **Protected**. 2. On the **Agents** screen, connect **Hermes**. 3. Start a new Hermes session; existing sessions stay on their original provider. The app writes the provider into `~/.hermes/config.yaml` with an agent-scoped token for its local API, and restores the file when you disconnect or stop Protected. From the CLI, the same connection is: ```bash theme={"system"} pap agents connect hermes ``` ## Without the Proxy Create a key under **Private AI → API Keys** in the [Phala dashboard](https://cloud.phala.com/dashboard). Define and select a named provider. Hermes reads the key from its process environment or `~/.hermes/.env`; do not put it in `config.yaml`. ```bash theme={"system"} export PHALA_AI_API_KEY="YOUR_PHALA_API_KEY" ``` ```yaml ~/.hermes/config.yaml theme={"system"} providers: phala: api: https://inference.phala.com/v1 key_env: PHALA_AI_API_KEY transport: chat_completions default_model: z-ai/glm-5.3 discover_models: true model: provider: custom:phala default: z-ai/glm-5.3 ``` This changes the main text and tool-calling loop only; image, speech, embedding, search, and browser providers stay separate. This path does not verify attestation locally; use [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy) or the [TypeScript ACI Verifier](/phala-cloud/confidential-ai/verify/typescript-sdk). Every model on this endpoint runs in a TEE. ## Check the Connection Start `hermes`, run `/model`, and confirm the active provider, then run one harmless tool task. ## Troubleshooting | Symptom | Check | | - | - | | Hermes ignores the Proxy | Confirm **Connected** in the app and that Protected is on, then start a new session. | | Provider is not selected | Start a new session and choose `custom:phala` with `/model`. | | Authentication fails | Export `PHALA_AI_API_KEY` in the Hermes process environment. | ## Related * [Hermes model providers](https://hermes-agent.nousresearch.com/docs/integrations/providers) * [Phala model catalog](/phala-cloud/confidential-ai/confidential-model/api-reference/models) # OpenClaw Source: https://docs.phala.com/phala-cloud/confidential-ai/agents/openclaw Run OpenClaw on Phala through Private AI Proxy, or configure it by hand. OpenClaw speaks Chat Completions. Private AI Proxy configures it automatically. ## With Private AI Proxy 1. Install [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy), choose a **Phala** profile, sign in, and turn on **Protected**. 2. On the **Agents** screen, connect **OpenClaw**. 3. Restart OpenClaw; it reads the native-host provider and local token on start. The app writes a native-host provider into OpenClaw's gateway configuration with an agent-scoped token for its local API, and restores the file when you disconnect or stop Protected. From the CLI, the same connection is: ```bash theme={"system"} pap agents connect openclaw ``` ## Without the Proxy Create a key under **Private AI → API Keys** in the [Phala dashboard](https://cloud.phala.com/dashboard). Merge a named provider into the gateway configuration and keep your existing agent, channel, tool, and provider settings. Export the key where the OpenClaw gateway process can read it. ```bash theme={"system"} export PHALA_AI_API_KEY="YOUR_PHALA_API_KEY" ``` ```json5 ~/.openclaw/openclaw.json theme={"system"} { agents: { defaults: { model: { primary: "phala/z-ai/glm-5.3" } } }, models: { mode: "merge", providers: { phala: { baseUrl: "https://inference.phala.com/v1", apiKey: "${PHALA_AI_API_KEY}", api: "openai-completions", models: [ { id: "z-ai/glm-5.3", name: "GLM 5.3", reasoning: true, input: ["text"], contextWindow: 1048576, maxTokens: 1048576 }, ], }, }, }, } ``` This changes the main model loop only; image, speech, embedding, search, and browser providers stay separate. This path does not verify attestation locally; use [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy) or the [TypeScript ACI Verifier](/phala-cloud/confidential-ai/verify/typescript-sdk). Every model on this endpoint runs in a TEE. ## Check the Connection Run `openclaw config validate` and `openclaw models list`, confirm the Phala model is listed, then run one harmless tool task. ## Troubleshooting | Symptom | Check | | - | - | | OpenClaw ignores the Proxy | Confirm **Connected** in the app and that Protected is on, then restart OpenClaw. | | Configuration is rejected | Run `openclaw config validate` and preserve JSON5 syntax. | | Key is unavailable | Export `PHALA_AI_API_KEY` for the gateway process, not only an interactive shell. | ## Related * [OpenClaw model providers](https://docs.openclaw.ai/concepts/model-providers/custom-providers) * [OpenClaw configuration](https://docs.openclaw.ai/gateway/configuration) * [Phala model catalog](/phala-cloud/confidential-ai/confidential-model/api-reference/models) # OpenCode Source: https://docs.phala.com/phala-cloud/confidential-ai/agents/opencode Run OpenCode on Phala through Private AI Proxy, or configure it by hand. OpenCode speaks Chat Completions. Private AI Proxy configures it automatically. ## With Private AI Proxy 1. Install [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy), choose a **Phala** profile, sign in, and turn on **Protected**. 2. On the **Agents** screen, connect **OpenCode**. 3. Restart OpenCode. The app writes the provider into `~/.config/opencode/opencode.json` with an agent-scoped token for its local API, and restores the file when you disconnect or stop Protected. From the CLI, the same connection is: ```bash theme={"system"} pap agents connect opencode ``` ## Without the Proxy Create a key under **Private AI → API Keys** in the [Phala dashboard](https://cloud.phala.com/dashboard). Export your Phala API key, then add a custom provider to `opencode.json` in your project: ```bash theme={"system"} export PHALA_AI_API_KEY="YOUR_PHALA_API_KEY" ``` ```json opencode.json theme={"system"} { "$schema": "https://opencode.ai/config.json", "provider": { "phala": { "npm": "@ai-sdk/openai-compatible", "name": "Phala", "options": { "baseURL": "https://inference.phala.com/v1", "apiKey": "{env:PHALA_AI_API_KEY}" }, "models": { "z-ai/glm-5.3": { "name": "GLM 5.3", "limit": { "context": 1048576, "output": 1048576 } } } } } } ``` Start OpenCode, run `/models`, and select the Phala model. The key is read from the process environment. For another model, use its ID and limits from the [model catalog](/phala-cloud/confidential-ai/confidential-model/api-reference/models). This path does not verify attestation locally; use [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy) or the [TypeScript ACI Verifier](/phala-cloud/confidential-ai/verify/typescript-sdk). Every model on this endpoint runs in a TEE. ## Check the Connection Run `/models` and confirm a `phala/` model is selected, then run one bounded tool task. ## Troubleshooting | Symptom | Check | | - | - | | OpenCode ignores the Proxy | Confirm **Connected** in the app and that Protected is on, then restart OpenCode. | | Phala is absent from `/models` | Confirm `provider.phala` and its `models` entry are in the project's `opencode.json`. | | No models appear | Run `opencode models phala` and read the provider error. | ## Related * [OpenCode providers](https://opencode.ai/docs/providers/) * [Phala model catalog](/phala-cloud/confidential-ai/confidential-model/api-reference/models) # Other Tools Source: https://docs.phala.com/phala-cloud/confidential-ai/agents/other-tools Connect coding assistants and chat apps to Private AI with your Phala API key. For tools that support an OpenAI-compatible provider, use: | Setting | Value | | - | - | | Provider type | OpenAI compatible | | Base URL | `https://inference.phala.com/v1` | | API key | Your Phala API key | | Model | `z-ai/glm-5.3`, or another chat model from [`/v1/models`](https://inference.phala.com/v1/models) | Create a key under **Private AI → API Keys** in the Phala dashboard. For the shell examples below, set `PHALA_AI_API_KEY` in your local environment. Every model on this endpoint runs in a TEE. These clients do not verify attestation locally; use [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy#local-api) when you need a verified channel on your machine. ## Continue Add a model to your local `~/.continue/config.yaml` using Continue's [OpenAI-compatible configuration](https://docs.continue.dev/customize/model-providers/top-level/openai). Keep any other models already in the file: ```yaml theme={"system"} name: Phala version: 0.0.1 schema: v1 models: - name: Phala GLM 5.3 provider: openai model: z-ai/glm-5.3 apiBase: https://inference.phala.com/v1 apiKey: YOUR_PHALA_API_KEY ``` ## Zed Add this provider under `language_models` in your settings file using Zed's [OpenAI-compatible endpoint configuration](https://zed.dev/docs/ai/use-api-access#openai-compatible). Enter your Phala API key through **Settings → AI → LLM Providers**: ```json theme={"system"} { "language_models": { "openai_compatible": { "phala": { "api_url": "https://inference.phala.com/v1", "available_models": [ { "name": "z-ai/glm-5.3", "max_tokens": 1048576 } ] } } } } ``` ## GitHub Copilot (VS Code BYOK) Run **Chat: Manage Language Models**, choose **Add Models → Custom Endpoint**, name the group `Phala`, enter your Phala API key, and select **Chat Completions**. In the generated `chatLanguageModels.json`, keep the API-key input reference created by VS Code and configure the model as below. See the [Custom Endpoint documentation](https://code.visualstudio.com/docs/agent-customization/language-models#_add-a-custom-endpoint-model). This example uses the model's context window from the catalog and reserves 65,536 tokens for output, within the model's 1,048,576-token output maximum: ```json theme={"system"} [ { "name": "Phala", "vendor": "customendpoint", "apiKey": "${input:phalaApiKey}", "models": [ { "id": "z-ai/glm-5.3", "name": "Phala GLM 5.3", "url": "https://inference.phala.com/v1/chat/completions", "toolCalling": true, "contextWindow": 1048576, "maxOutputTokens": 65536 } ] } ] ``` Select the model in chat. For Copilot Business or Enterprise, your administrator can disable this with the *Bring Your Own Language Model Key in VS Code* policy. ## Aider Use Aider's [OpenAI-compatible endpoint](https://aider.chat/docs/llms/openai-compat.html) support. The `openai/` prefix tells Aider which API format to use: ```bash theme={"system"} export OPENAI_API_BASE="https://inference.phala.com/v1" export OPENAI_API_KEY="$PHALA_AI_API_KEY" aider --model openai/z-ai/glm-5.3 ``` ## Goose Save the following as `phala.json` in Goose's [`custom_providers` directory](https://goose-docs.ai/docs/getting-started/providers/#configure-custom-provider): `~/.config/goose/custom_providers/` on macOS/Linux, or `%APPDATA%\Block\goose\config\custom_providers\` on Windows. If you set `GOOSE_PATH_ROOT`, use `/config/custom_providers/` instead. Create the directory if needed: ```json theme={"system"} { "name": "phala", "engine": "openai", "display_name": "Phala", "description": "OpenAI-compatible confidential inference from Phala.", "api_key_env": "PHALA_AI_API_KEY", "base_url": "https://inference.phala.com/v1", "dynamic_models": true, "models": [], "supports_streaming": true, "model_doc_link": "https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/confidential-ai-api", "setup_steps": [ "Sign in to the Phala dashboard", "Open Private AI, then API Keys, and create an API key", "Copy the key and paste it above" ] } ``` With `PHALA_AI_API_KEY` set, run `goose configure`, choose **Configure Providers → Phala**, and select `z-ai/glm-5.3`. Dynamic discovery also lists the non-chat `jaredpalmer/kev-4b` decision model; choose a chat model. ## AnythingLLM In **Settings → AI Providers → LLM**, select **Generic OpenAI** and enter these [provider settings](https://docs.anythingllm.com/setup/llm-configuration/cloud/openai-generic), then select **Save changes**. Use the model's `context_length` from the catalog when choosing another model: ```text theme={"system"} Base URL: https://inference.phala.com/v1 API Key: Your Phala API key Selected Model: z-ai/glm-5.3 Model context window: 1048576 ``` ## Cherry Studio Open **Settings → Model Services → + Add Provider** and add a [custom provider](https://docs.cherryai.com.cn/docs/en-us/pre-basic/providers/zi-ding-yi-fu-wu-shang) with the values below. Enter the base URL in the OpenAI-compatible endpoint/API address row. Select **Add**, then **Get model list** and add `z-ai/glm-5.3`: ```text theme={"system"} Provider Name: Phala API Key: Your Phala API key Base URL: https://inference.phala.com/v1 ``` ## LobeHub Open **App Settings → AI Providers** and create a [custom AI provider](https://lobehub.com/changelog/2025-01-22-new-ai-provider) with the values below. Enable the provider and fetch or add `z-ai/glm-5.3` in its model list, then select it in your Agent settings: ```text theme={"system"} Provider ID: phala Provider Name: Phala Request Format: openai Proxy URL: https://inference.phala.com/v1 API Key: Your Phala API key ``` ## Jan In [Jan Desktop](https://docs.jan.ai/desktop/remote-models/custom-endpoint), open **Settings → Model Providers → Add Provider**, choose **OpenAI-compatible**, and set **Provider name** to `Phala`, **Base URL** to `https://inference.phala.com/v1`, and **API key** to your Phala key. Select **Create**, then select `z-ai/glm-5.3` from the model list. For tool use, edit the model and enable **Tools** under **Capabilities**. For [Jan Agent CLI](https://docs.jan.ai/agent/providers), save a provider and start Jan with it: ```bash theme={"system"} jan config set --provider phala \ --api-key "$PHALA_AI_API_KEY" \ --base-url https://inference.phala.com/v1 \ --model z-ai/glm-5.3 jan --provider phala --model z-ai/glm-5.3 ``` # Use in Agents Source: https://docs.phala.com/phala-cloud/confidential-ai/agents/overview Connect coding agents to Private AI through Private AI Proxy, or configure an OpenAI-compatible endpoint directly. [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy) verifies the Phala gateway on your machine and connects your agents to a local API. Agents receive a local token instead of your Phala credential. Tools can also connect to Phala directly. ## Connect an Agent **1. Install Private AI Proxy and Sign In** [Install the desktop app or CLI](/phala-cloud/confidential-ai/agents/private-ai-proxy#install). Add a profile and choose **Phala**. Sign in with a Phala account or paste a key from **Private AI → API Keys** in the [Phala dashboard](https://cloud.phala.com/dashboard). **2. Turn On Protected** The app verifies the gateway's attestation and pins the channel before sending model traffic. Signed response receipts are audited after delivery. **3. Connect the Agent** On the **Agents** screen, connect the agent and restart it. The app writes its Local API into the agent's provider settings; disconnecting restores the previous settings. | Agent | What Changes | Guide | | - | - | - | | Claude Code | Messages provider in `~/.claude/settings.json` | [Claude Code](/phala-cloud/confidential-ai/agents/claude-code) | | Codex | Custom Responses provider in `~/.codex/config.toml` | [Codex CLI](/phala-cloud/confidential-ai/agents/codex) | | DeepSeek Harness | `~/.dsh/cordis.patch.yml` and `.credentials.yaml` | | | OpenCode | Provider in `~/.config/opencode/opencode.json` | [OpenCode](/phala-cloud/confidential-ai/agents/opencode) | | Pi | Provider in `~/.pi/agent/models.json` | [Pi](/phala-cloud/confidential-ai/agents/pi) | | Hermes | Provider in `~/.hermes/config.yaml` | [Hermes](/phala-cloud/confidential-ai/agents/hermes) | | OpenClaw | Native-host provider; restart required | [OpenClaw](/phala-cloud/confidential-ai/agents/openclaw) | | Oh My Pi | Local token and models file; restart `omp` | | From the CLI, sign in and start protection before connecting an agent: ```bash theme={"system"} pap profiles login work --provider phala pap start --profile work pap agents connect codex ``` See [Private AI Proxy CLI](/phala-cloud/confidential-ai/agents/private-ai-proxy#cli) for API-key profiles and other commands. ## Other Tools Tools with an OpenAI-compatible provider setting, such as [Cline](/phala-cloud/confidential-ai/agents/cline), can use the Proxy's Local API while Protected is on: | Field | Value | | - | - | | Base URL | `http://127.0.0.1:4180/v1` | | API Key | The client key from the app's Overview screen | | Model | `z-ai/glm-5.3`, or another chat model from the app's verified catalog | See [Other Tools](/phala-cloud/confidential-ai/agents/other-tools) for Continue, Zed, Copilot, Aider, Goose, and chat apps. ## Without the Proxy On servers, in CI, or in frameworks, point the client at Phala directly. Every model on this endpoint runs in a TEE, but a base-URL configuration does not verify attestation locally. Use the [TypeScript ACI Verifier](/phala-cloud/confidential-ai/verify/typescript-sdk) to enforce a verified channel in Node.js or Bun applications. | Client | Protocol | Base URL | | - | - | - | | OpenAI clients and agent frameworks | Chat Completions | `https://inference.phala.com/v1` | | Codex CLI and other Responses clients | Responses | `https://inference.phala.com/v1` | | Claude Code and Anthropic clients | Messages | `https://inference.phala.com` (the client appends `/v1/messages`) | For direct connections, create a key under **Private AI → API Keys** and export it in the client's shell: ```bash theme={"system"} export PHALA_AI_API_KEY="YOUR_PHALA_API_KEY" curl -s https://inference.phala.com/v1/models \ | jq -r '.data[] | select((.supported_features // []) | index("tools")) | .id' ``` Use an exact chat-model ID such as `z-ai/glm-5.3` from [`/v1/models`](https://inference.phala.com/v1/models). For SDKs, observability tools, and gateways, see [Migration and Integrations](/phala-cloud/confidential-ai/confidential-model/migration-and-integrations). # Pi Source: https://docs.phala.com/phala-cloud/confidential-ai/agents/pi Run Pi on Phala through Private AI Proxy, or configure it by hand. Pi speaks Chat Completions. Private AI Proxy configures it automatically. ## With Private AI Proxy 1. Install [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy), choose a **Phala** profile, sign in, and turn on **Protected**. 2. On the **Agents** screen, connect **Pi**. 3. Start `pi`. The app writes the provider into Pi's settings with an agent-scoped token for its local API, and restores the previous settings when you disconnect or stop Protected. From the CLI, the same connection is: ```bash theme={"system"} pap agents connect pi ``` ## Without the Proxy Create a key under **Private AI → API Keys** in the [Phala dashboard](https://cloud.phala.com/dashboard). Export your Phala API key, then add a custom provider to `~/.pi/agent/models.json`: ```bash theme={"system"} export PHALA_AI_API_KEY="YOUR_PHALA_API_KEY" ``` ```json ~/.pi/agent/models.json theme={"system"} { "providers": { "phala": { "baseUrl": "https://inference.phala.com/v1", "api": "openai-completions", "apiKey": "$PHALA_AI_API_KEY", "models": [{ "id": "z-ai/glm-5.3", "contextWindow": 1048576, "maxTokens": 1048576 }] } } } ``` Start `pi`, run `/model`, and select the model under `phala`. Opening `/model` reloads the file; press Ctrl+S on the model to save it as the default. The key is read from the process environment. This path does not verify attestation locally; use [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy) or the [TypeScript ACI Verifier](/phala-cloud/confidential-ai/verify/typescript-sdk). Every model on this endpoint runs in a TEE. ## Check the Connection Run `/model` in Pi, confirm the provider and model, then send a short prompt. With the Proxy, the provider points at `http://127.0.0.1:4180/v1`; without it, at `https://inference.phala.com/v1`. ## Troubleshooting | Symptom | Check | | - | - | | Pi ignores the Proxy | Confirm **Connected** in the app and that Protected is on, then restart `pi`. | | The custom model is absent from `/model` | Check `providers.phala` in `~/.pi/agent/models.json` and export `PHALA_AI_API_KEY` in Pi's shell. | | Authentication fails | Check for a stale `phala` credential in `auth.json`; stored credentials take precedence over `models.json`. | ## Related * [Pi model configuration](https://pi.dev/docs/latest/models) * [Phala model catalog](/phala-cloud/confidential-ai/confidential-model/api-reference/models) # Private AI Proxy Source: https://docs.phala.com/phala-cloud/confidential-ai/agents/private-ai-proxy The desktop app and CLI that verifies the Phala gateway on your machine and connects your agents to a verified local API. Private AI Proxy runs on your computer. It signs in to your Phala account, verifies the gateway's attestation before any prompt leaves your machine, and gives your agents a local API so they never hold your Phala credential. It is open source in [Dstack-TEE/private-ai-gateway](https://github.com/Dstack-TEE/private-ai-gateway/tree/main/apps/desktop) and published by dstack TEE. ```text theme={"system"} your agent → Local API on 127.0.0.1:4180 (agent-scoped token) → Private AI Proxy, verified and pinned channel → Phala gateway (attested), signed receipt per response ``` The sections below follow the app's screens: Profiles, Privacy, Agents, Local API, Usage, and Settings, then the CLI. ## Install ### Desktop App Download an installer for macOS, Windows, or Linux from [GitHub Releases](https://github.com/Dstack-TEE/private-ai-gateway/releases). On macOS, you can also use Homebrew: ```bash theme={"system"} brew install --cask dstack-tee/private-ai/private-ai-proxy ``` Linux requires glibc 2.35 or newer. Windows Desktop is currently Preview. ### Command-Line Tool Install the CLI with Homebrew or npm: ```bash Homebrew theme={"system"} brew install dstack-tee/private-ai/private-ai-proxy ``` ```bash npm theme={"system"} npm install --global private-ai-proxy ``` Do not use `--omit=optional` with npm; it selects the native package through an optional dependency. Standalone packages, release signatures, and checksums are also available from [GitHub Releases](https://github.com/Dstack-TEE/private-ai-gateway/releases). On Homebrew 6+, the fully qualified commands above automatically tap the repository and trust the item being installed. Homebrew and npm manage their own upgrades and removal. Verify the installation: ```bash theme={"system"} pap --version pap doctor ``` ## Profiles and Sign-In Add a profile and choose **Phala**. A Phala profile holds one account's inference credential. Choose either: * **Account login**: sign in with a Phala account. The app shows a device code and opens your browser to approve it. This uses device authorization (RFC 8628), with no workspace picker or local callback. The sign-in token stays in memory; if saving fails, **Retry** reuses the approval. * **API key**: **Get API key** opens the [Phala dashboard](https://cloud.phala.com/dashboard). Create a key under **Private AI → API Keys** and paste it into the **Phala API key** field. Credentials live in an owner-only, plaintext `credentials.toml` file in the app's settings directory. The operating system's credential store is used only to migrate old installations; profile exports never contain credentials. Sign in again or paste a new key to replace one, and revoke old keys in the dashboard. ## Privacy: What Protected Does Switching on **Protected** runs the ACI relying-party checks against the gateway with a fresh nonce: 1. the hardware quote verifies to the TEE vendor root and binds the report data; 2. the attested keyset digest matches the statement for that nonce; 3. the keyset has not expired; 4. source provenance is present and the app compose matches its measured hash; and 5. the TLS key actually used for the connection is in the attested keyset. On success the app pins the channel to that keyset for the session and enables inference through the Local API. A verification failure or network loss keeps connected agents pointed at the Local API, which refuses requests until protection is verified again. Stopping Protected, choosing **Stop All and Quit**, stopping the service, or disconnecting an agent restores its previous configuration. Quitting only the desktop app leaves the backend running. Verification is never restored from disk after a restart; it is redone. ## Agents The **Agents** screen lists the agents the app can configure. **Connect** writes Phala into the agent's own provider settings, in the protocol the agent speaks, with an agent-scoped token for the Local API. **Disconnect** restores the file you had before; edits you made in the meantime are preserved, and an incomplete restore stays retryable. | Agent | Protocol | Where the app writes | After connecting | | - | - | - | - | | Claude Code | Messages | `~/.claude/settings.json` | Restart `claude` | | Codex | Responses | Custom model provider in `~/.codex/config.toml` | Restart `codex` | | DeepSeek Harness | Chat Completions | `~/.dsh/cordis.patch.yml` and `.credentials.yaml` | New session; restart headless/ACP processes | | OpenCode | Chat Completions | `~/.config/opencode/opencode.json` | Restart OpenCode | | Pi | Chat Completions | `~/.pi/agent/models.json` | Restart Pi | | Hermes | Chat Completions | `~/.hermes/config.yaml` | Restart Hermes | | OpenClaw | Chat Completions | Native-host provider with a local token reference | Restart OpenClaw | | Oh My Pi | Chat Completions | Local token and models file | Restart `omp` | Only agents that are both connected and currently protected are authorized on the Local API. Connecting from the CLI previews the change first and applies it with a revision, so a file that changed in between is rejected rather than overwritten. ## Local API While Protected is on, the app serves an OpenAI-compatible API on your machine: | Field | Value | | - | - | | Base URL | `http://127.0.0.1:4180/v1` | | API key | The client key shown on the Overview and Local API screens (`sk-pap-…`) | | Models | The verified catalog for the active profile | Any tool that accepts an OpenAI-compatible endpoint can use it, for example [Cline](/phala-cloud/confidential-ai/agents/cline). The Local API is plain HTTP on loopback by default; send ordinary request bodies. It rejects end-to-end encryption headers because the app already owns the verified channel. Its listener runs with the backend, but inference is refused without verified protection. Rotate the client key from Local API settings or `token rotate`. ## Usage Responses stream to the agent immediately. The app fetches the signed receipt for each response afterwards and audits it against the attestation. **Usage** records every request with the agent, model, tokens, estimated cost, and the audit result; an audit failure is recorded but cannot recall bytes the agent already received. The Overview screen shows the current session's totals. Usage can be filtered, exported to CSV, and cleared. ## Settings * **Protect on launch** starts protection when the background service starts. * **Open at Login** is an operating system preference set from the desktop app. * **Advanced > Reset settings** stops protection, disconnects agents, restores defaults, generates a new web UI password, and disables Open at Login. Profiles, API keys, the local client key, and usage history are kept. * Closing the window or choosing **Quit** from the tray or menu leaves the backend running. **Stop All and Quit** stops protection, restores agent configuration, and stops the backend. ## CLI `pap` drives the same background service without a window. It comes with the desktop app or [on its own](#command-line-tool). The macOS app registers it automatically; add `~/.local/bin` to your terminal's PATH if needed. The Windows installer registers it on the user PATH, and Linux packages install it system-wide. Settings > Advanced > **pap command** manages registration in the desktop app. `private-ai-proxy` and `aci` are the same executable. ```bash theme={"system"} pap doctor # local installation, settings, and backend diagnostics pap profiles login work --provider phala pap start --profile work # verify the gateway and turn on Protected pap agents connect codex # add --model MODEL to pick a model yourself pap status --json pap stop # stop Protected and restore agent configuration ``` For an API-key profile instead of account sign-in, run this command and paste the key at its hidden prompt: ```bash theme={"system"} pap profiles add --id work --name Phala \ --url https://inference.phala.com --provider phala pap start --profile work ``` | Task | Command | | - | - | | Service and protection | `service start`, `start`, `stop`, `status --watch` | | Profiles and credentials | `profiles login/list/show/add/edit/verify/use/remove`, `token clear-credential` | | Agents | `agents list/connect/disconnect/disconnect-all` | | Catalog and usage | `models list --refresh`, `usage list/show/export/clear` | | Local API settings and token | `settings show/set`, `token show/rotate` | | Verify any ACI service | `verify `, `sessions `, `serve ` | Credentials are entered through a hidden prompt or `--key-stdin`, never as an argument. For scripts, `--json --non-interactive` returns data and `--yes` approves a change; agent changes are previewed with `--dry-run` and applied with the returned `--revision`. Exit status is `0` on success, `2` for invalid arguments, `1` for operation failures. `verify`, `sessions`, and `serve` work against any ACI service without a profile; `serve` refuses to start unless verification passes. ## Troubleshooting | Symptom | Check | | - | - | | Protected will not turn on | Run `pap doctor`; it reports local installation, settings, and backend checks separately, with warnings for credentials other users can read or profiles without a saved key. | | An agent still uses its old provider | Confirm it shows **Connected**, that Protected is on, and restart the agent. | | A tool cannot reach `127.0.0.1:4180` | Confirm the backend is running and check Settings > Local API; inference requires verified protection. | | Settings look wrong after an update | Settings > Advanced > Reset settings. | # Benchmark Source: https://docs.phala.com/phala-cloud/confidential-ai/benchmark Performance benchmarks and metrics for LLM inference in GPU TEE environments. ## Key Results **TEE mode on H100/H200 GPUs runs up to 99% efficiency, nearly matching native performance.** This means you get confidential computing with minimal performance penalty. The efficiency improves as your workload grows. Larger models and longer sequences see even better performance relative to native execution. ## What We Tested We benchmarked LLM inference in GPU TEE mode using NVIDIA H100 and H200 GPUs. TEE mode encrypts your data and computation while it runs on the GPU. ![Performance comparison table showing TPS and QPS metrics for LLama-3.1-8B, Phi3-14B-128k, and LLama-3.1-70B models on H100 and H200 GPUs with TEE-on vs TEE-off overhead percentages](https://mintcdn.com/phalanetwork-1606097b/416gZMDMREnPDd33/images/confidential-ai/benchmark_result.png?fit=max\&auto=format\&n=416gZMDMREnPDd33\&q=85\&s=1b5be9a4726c40eb5a788785e958786f) Benchmark Results ## Performance Insights * **Larger models perform better in TEE mode.** Models like Phi3-14B-128k and Llama3.1-70B show higher efficiency because they spend more time computing and less time on I/O operations. * **Longer sequences boost efficiency.** When you process more tokens (input + output), the computation-to-I/O ratio improves. This makes TEE overhead less noticeable. * **The sweet spot: High-computation workloads.** TEE mode shines when your GPU is doing heavy lifting. The encryption/decryption overhead becomes trivial compared to the actual computation time. ## Resources For detailed metrics and analysis, check our [benchmark paper](https://arxiv.org/pdf/2409.03992). See detailed [GPU TEE performance specifications](https://phala.com/gpu-tee) for production deployments, including [H100 TEE](https://phala.com/gpu-tee/h100) and [H200 TEE](https://phala.com/gpu-tee/h200) configurations. # Deploy and Verify GPU TEE Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-gpu/deploy-and-verify Deploy or fine-tune AI models with hardware-level security using TEE-protected GPUs and verify they run in genuine TEE hardware GPU TEE gives you dedicated H200 or B300 GPUs running inside trusted execution environments for custom AI workloads. You get full control over your environment with Docker container support, and you can verify hardware authenticity using NVIDIA's local verification tools. This option works when you need to train, fine-tune, or run inference on proprietary datasets with custom code. For standard LLM inference, the [Private AI API](/phala-cloud/confidential-ai/confidential-model/confidential-ai-api) is a simpler alternative. Each instance comes with the NVIDIA driver and CUDA toolkit pre-installed, with 1 or 8 GPUs. ## Prerequisites * Phala Cloud account with enough Balance * Basic understanding of Jupyter notebooks * Familiarity with command-line tools ## Step 1: Deploy GPU TEE instance ### Launch the deployment wizard Sign in to [cloud.phala.com](https://cloud.phala.com), click **GPU TEE** in the navigation bar, then click **Start Building** to open the Launch GPU Instance wizard. > [!NOTE] > > Check your Balance on the Billing page. GPU instances incur hourly charges, so confirm your Balance before launching. ### Choose GPU hardware Select your GPU type based on your compute needs. ![GPU TEE hardware selection interface showing H200 and B300 GPU options with specifications](https://mintcdn.com/phalanetwork-1606097b/416gZMDMREnPDd33/images/confidential-ai/confidential-gpu/gpu-tee-01.png?fit=max\&auto=format\&n=416gZMDMREnPDd33\&q=85\&s=b89176cc1bffa8cc92d72001c2c3e042) GPU Device Selection Available options include: | GPU type | Region | vCPU cores | VRAM | RAM | Storage | | - | - | - | - | - | - | | H200 (1 GPU) | US | 24 | 141 GB | 192 GB | 1 TB | | H200 (8 GPUs) | US | 192 | 1128 GB | 1536 GB | 1 TB | Check the [pricing page](https://cloud.phala.com/about/pricing) for current rates. Click your preferred GPU card to highlight it in green. ### Configure GPU count Choose the number of GPUs for your instance: **1 or 8 GPUs** per instance. The UI updates resource totals dynamically: | GPU count | Example: H200 | Total vCPU | Total VRAM | Total RAM | Total storage | | - | - | - | - | - | - | | 1 GPU | Single | 24 cores | 141 GB | 192 GB | 1 TB | | 8 GPUs | Multi | 192 cores | 1128 GB | 1536 GB | 1 TB | ### Configure deployment Give your deployment a name or use the auto-generated name like `gpu-tee-1p1qp`. For the template, choose **Jupyter Notebook (PyTorch)** to get a GPU-accelerated JupyterLab environment with PyTorch and CUDA pre-installed. This template works well for running verification scripts and custom experiments. You can also choose vLLM for an inference server or Custom Configuration to provide your own Docker Compose file. For this tutorial, we'll use Jupyter Notebook because it gives us terminal access to run verification commands. > [!TIP] > > You can always deploy different containers later. Your initial template choice isn't permanent. ### Select pricing plan Choose a commitment period: | Plan | Notes | | - | - | | 6-month commitment | Lowest rate, long-term commitment | | 1-month commitment | Short-term commitment | | On-Demand | Pay-as-you-go, no commitment | Check the [pricing page](https://cloud.phala.com/about/pricing) for current rates. Review the **Pricing Summary** showing estimated costs per hour, day, and month. ### Launch instance Before launching, review the **Instance Summary** to confirm your GPU model and count, VRAM, RAM, and storage allocations, plus your total estimated costs. ![GPU TEE order summary showing selected hardware configuration, pricing breakdown, and submit order button](https://mintcdn.com/phalanetwork-1606097b/416gZMDMREnPDd33/images/confidential-ai/confidential-gpu/gpu-tee-02.png?fit=max\&auto=format\&n=416gZMDMREnPDd33\&q=85\&s=ac4cb0bb08bb8c56d6dc43cfcb7894e0) Order Review Click **Launch Instance** when you're ready to proceed. > [!WARNING] > > Launching creates hourly charges. Confirm your configuration and budget before proceeding. Provisioning takes approximately 1 day. ## Step 2: Access your GPU TEE instance After provisioning completes, your instance appears under the **GPU TEE** tab with connection details including the JupyterLab URL. Navigate to the **GPU TEE** tab in your dashboard and find your instance in the GPU Instances list. Click **View Details** to see the JupyterLab URL, then open that URL in your browser to access your instance. > [!NOTE] > > Monitor provisioning status in the GPU Instances list. Instances progress from **Preparing** → **Starting** → **Running**. ## Step 3: Verify GPU TEE attestation Open a terminal in JupyterLab (**File** → **New** → **Terminal**) to verify your instance runs on genuine TEE hardware. ### Check GPU and TEE status First, confirm your GPU is detected and confidential compute mode is active. Run `nvidia-smi` to check GPU status: ```bash theme={"system"} nvidia-smi ``` Look for your GPU model (H200/B300) and confirm the driver and CUDA versions are loaded. Then check confidential compute status: ```bash theme={"system"} nvidia-smi conf-compute -q ``` Expected output: ``` # nvidia-smi conf-compute -q ==============NVSMI CONF-COMPUTE LOG============== CC State : ON Multi-GPU Mode : None CPU CC Capabilities : INTEL TDX GPU CC Capabilities : CC Capable CC GPUs Ready State : Ready ``` The key indicators are `CC State: ON` and `CPU CC Capabilities: INTEL TDX`, confirming your instance runs in TEE mode. ### Run attestation verification Install NVIDIA's attestation verification tools: ```bash theme={"system"} pip install nv-local-gpu-verifier nv_attestation_sdk ``` Run the verifier to get cryptographic proof of hardware authenticity: ```bash theme={"system"} python -m verifier.cc_admin ``` The verifier confirms your GPUs are genuine NVIDIA devices, checks confidential compute mode is enabled, verifies driver and firmware versions, and generates cryptographic evidence of your TEE status. Successful verification means your GPU hardware is authentic, confidential compute mode is active, and the driver version matches the expected TEE-enabled version. > [!WARNING] > > If verification fails, do not use the instance for confidential workloads. Contact [Phala Support](/phala-cloud/support) with the error details. ## Step 4: Confirm GPU functionality Verify GPU functionality with PyTorch. Open a new notebook in JupyterLab (**File** → **New** → **Notebook**) and run: ```python theme={"system"} import torch print(f"CUDA available: {torch.cuda.is_available()}") print(f"GPU: {torch.cuda.get_device_name(0)}") ``` This confirms PyTorch can detect and access the GPU. ## Next steps You've deployed and verified a GPU TEE instance! Now you can: > [card] [Programmatic verification](/phala-cloud/confidential-ai/verify/verify-attestation) > > Learn how to fetch and verify attestations programmatically > [card] [Bind GPU and CPU attestations](/phala-cloud/confidential-ai/verify/overview) > > Understand how GPU and CPU attestations create a complete trust chain > [card] [Expose services](/phala-cloud/networking/expose-http-service) > > Make your GPU TEE workloads accessible over HTTPS # Troubleshooting Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-gpu/troubleshooting Common issues and warnings when running GPU TEE workloads ## Serial Output Warnings These warnings appear in serial output but are safe to ignore. ### NVIDIA Fabric Manager Service Failed ``` [FAILED] Failed to start NVIDIA fabric manager service. ``` Safe to ignore for single-GPU instances. The fabric manager service is only needed for multi-GPU NVLink configurations. ### NVRM Assertion Error ``` NVRM: nvAssertFailed: Assertion failed: 0 @ g_kern_gmmu_nvoc.h:2256 ``` Safe to ignore. This is a known warning that doesn't affect GPU functionality. # Anthropic SDK Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/anthropic-sdk Use the official Anthropic Python or TypeScript SDK with Phala's Messages API. The Anthropic SDK can call Phala's compatible [`/v1/messages`](/phala-cloud/confidential-ai/confidential-model/api-reference/messages) endpoint directly. Set the Phala host without `/v1` because the SDK appends `/v1/messages`. > [!WARNING] > > Use `auth_token` in Python or `authToken` in TypeScript. The `api_key` option sends `x-api-key`, > while Phala expects `Authorization: Bearer`. ## Install ```bash Python theme={"system"} pip install anthropic ``` ```bash TypeScript theme={"system"} npm install @anthropic-ai/sdk ``` ## Send a message ```python Python theme={"system"} import os from anthropic import Anthropic client = Anthropic( auth_token=os.environ["PHALA_AI_API_KEY"], base_url="https://inference.phala.com", ) message = client.messages.create( model="z-ai/glm-5.3", max_tokens=128, messages=[{"role": "user", "content": "Explain attestation in one sentence."}], ) for block in message.content: if block.type == "text": print(block.text) ``` ```typescript TypeScript theme={"system"} import Anthropic from '@anthropic-ai/sdk'; const authToken = process.env.PHALA_AI_API_KEY; if (!authToken) throw new Error('PHALA_AI_API_KEY is required'); const client = new Anthropic({ authToken, baseURL: 'https://inference.phala.com', }); const message = await client.messages.create({ model: 'z-ai/glm-5.3', max_tokens: 128, messages: [{ role: 'user', content: 'Explain attestation in one sentence.' }], }); for (const block of message.content) { if (block.type === 'text') console.log(block.text); } ``` ## Choose a model Use a model ID from the live Phala catalog; the Messages format also works with supported non-Anthropic models: ```bash theme={"system"} curl -s https://inference.phala.com/v1/models \ | jq -r '.data[] | .id' ``` Model availability and supported fields change. Test streaming or tool use with the selected model before depending on it in production. ## Privacy boundary Every request enters through Phala's attested gateway. This TEE-only endpoint requires a verified upstream; evidence coverage varies by provider. Ordinary Anthropic SDK clients do not verify the gateway, pin its TLS key, or audit response receipts. Use the [TypeScript ACI verifier](/phala-cloud/confidential-ai/verify/typescript-sdk) or [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy) for client-side verification. ## Troubleshooting | Symptom | Check | | - | - | | `401` authentication error | Pass the Phala key as `auth_token` or `authToken`, not `api_key` or `apiKey`. | | Request path contains `/v1/v1/messages` | Set the base URL to `https://inference.phala.com`, without `/v1`. | | Model not found | Refresh `GET /v1/models` and use the exact model ID. | | Unsupported field returns `400` | Update the SDK, then remove beta-only fields not accepted by the selected model. | ## Related * [Anthropic Python SDK](https://github.com/anthropics/anthropic-sdk-python) * [Anthropic TypeScript SDK](https://github.com/anthropics/anthropic-sdk-typescript) * [Phala Messages API](/phala-cloud/confidential-ai/confidential-model/api-reference/messages) # Attestation report Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/api-reference/attestation GET /aci/attestation The gateway TEE attestation report, bound to a caller-supplied nonce. Returns the gateway's attestation report: the hardware-backed proof of which TEE workload is serving the API, plus the public keys it signs with. Verify this report before trusting any [receipt](/phala-cloud/confidential-ai/confidential-model/api-reference/receipts). For what each field proves, see [Attestation report](/phala-cloud/confidential-ai/verify/verify-attestation). ```http theme={"system"} GET /v1/aci/attestation?nonce={nonce} ``` ## Request **nonce** `string` Exactly 64 lowercase hex characters (32 random bytes). The gateway binds it into the quote's `report_data` so you can prove the report is not a replay. ## Response `200 OK`, `application/json`. The bare attestation report. ### Top-level fields | Field | Type | Description | | - | - | - | | `api_version` | string | ACI version token, for example `aci/1`. | | `workload_keyset_digest` | string | `sha256:…` digest over the published keyset. | | `attestation` | object | The attestation evidence and keyset (below). | | `service_capabilities` | object | `supported_e2ee_versions` and the `serving` mode. | ### `attestation` object | Field | Type | Description | | - | - | - | | `tee_type` | string | TEE technology, for example `tdx`. | | `report_data` | string | Value bound into the quote. Commits to your `nonce` and the keyset. | | `source_provenance` | object | Workload-declared `repo_url`, `repo_commit`, `image_digest`, and `image_provenance` labels. | | `workload_keyset` | object | `subject`, `not_after`, `receipt_signing_keys`, `e2ee_public_keys`, and `tls_public_keys`. | | `evidence` | object | `quote`, `quote_report_data`, `event_log`, `vm_config`, `app_compose`, `key_custody`, and `downstream_tls_binding`. | ### Example (long values truncated) For brevity, the example shows a subset of the E2EE/TLS keys and omits custody entries. Recompute digests over the complete report returned by the service. ```json theme={"system"} { "api_version": "aci/1", "workload_keyset_digest": "sha256:3eff0836cd104d8cb5f8e8ee361789cf9…", "attestation": { "tee_type": "tdx", "report_data": "7b7daf62d7e9e31f5d17e70d32c010bda9ead273…", "source_provenance": { "repo_url": "https://github.com/Dstack-TEE/private-ai-gateway.git", "repo_commit": "", "image_digest": null, "image_provenance": null }, "workload_keyset": { "subject": null, "not_after": 1795221116, "receipt_signing_keys": [ { "key_id": "dstack-kms-receipt-ed25519-v1", "algo": "ed25519", "public_key": "211c…" } ], "e2ee_public_keys": [ { "key_id": "dstack-kms-e2ee-v1", "algo": "secp256k1-aes-256-gcm-hkdf-sha256", "public_key": "0494…" } ], "tls_public_keys": [ { "spki_sha256": "943c…", "domain": "inference.phala.com" } ] }, "evidence": { "quote": "040002008100…", "quote_report_data": "7b7daf…", "event_log": "[{…}]", "vm_config": "{…}", "app_compose": "{…}", "downstream_tls_binding": { "domain": "inference.phala.com", "spki_sha256": "943c…" }, "key_custody": { "provider": "dstack-kms", "keys": [] } } }, "service_capabilities": { "supported_e2ee_versions": ["2"], "serving": "aggregator" } } ``` ## Verifying the report 1. Verify `attestation.evidence.quote` against Intel DCAP collateral, and confirm its report data binds your `nonce` and the `workload_keyset`. 2. Recompute the JCS digest of `workload_keyset` and compare it with `workload_keyset_digest`. 3. Confirm `workload_keyset_digest` matches the receipts you verify. 4. Confirm `workload_keyset.not_after` is in the future. 5. Replay the event log to RTMR3 and confirm the measured compose hash equals `sha256(app_compose)`. 6. For reviewed-release enforcement, require that compose hash in an independently obtained allowlist. Do not treat `source_provenance` as the trust anchor. The full verification procedure is in [Verify a response](/phala-cloud/confidential-ai/verify/verify-signature). ## Legacy alias `GET /v1/attestation/report?nonce=…` returns the same gateway attestation for clients written against earlier API versions, with two differences: top-level `signing_address`, `signing_algo`, and `signing_public_key` derived from the gateway keyset (`?signing_algo=ecdsa`, the default, or `ed25519` selects the key), and `all_attestations` collapsed to a single entry. Earlier API versions returned the upstream model's attestation here; the upstream verification for a response is now in the [receipt](/phala-cloud/confidential-ai/confidential-model/api-reference/receipts) and the [attested session](/phala-cloud/confidential-ai/confidential-model/api-reference/sessions). New integrations should use `/v1/aci/attestation`. ## Related > [card] [Get receipt](/phala-cloud/confidential-ai/confidential-model/api-reference/receipts) > > The signed per-response receipt. > [card] [Attestation report concept](/phala-cloud/confidential-ai/verify/verify-attestation) > > What each field proves. # Audio Transcription Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/api-reference/audio POST /audio/transcriptions Transcribe audio with multipart uploads and billing per started second through the attested gateway. ## Endpoint ```bash theme={"system"} POST https://inference.phala.com/v1/audio/transcriptions ``` Transcribe an audio file using `multipart/form-data`. Responses are buffered JSON with an `x-receipt-id` header for verification. ## Models and Pricing The live [model catalog](/phala-cloud/confidential-ai/confidential-model/api-reference/models) lists transcription models with `transcription` in `output_modalities` and USD-per-second rates in `pricing.audio_transcription`. | Model ID | Provider | Response formats | Current price per second | | - | - | - | - | | `openai/whisper-large-v3` | NEAR AI | `json`, `verbose_json` | \$0.0001 | | `mistralai/voxtral-small-24b-2507` | Tinfoil | `json` only | \$0.00005 | Check the catalog for current availability and pricing. Audio is billed per started second: `2.965` seconds is billed as `3` seconds. ## Request Body **model** `string` *required* Transcription model ID: `openai/whisper-large-v3` or `mistralai/voxtral-small-24b-2507`. **file** `file` *required* Exactly one nonempty file, up to 25 MiB (26,214,400 bytes). The filename must include a supported extension: `flac`, `mp3`, `mp4`, `mpeg`, `mpga`, `m4a`, `ogg`, `wav`, or `webm`. **language** `string` Language code of 2–3 lowercase ASCII letters, for example `en`. **prompt** `string` Optional context for transcription, up to 4,096 Unicode characters. **temperature** `number` Sampling temperature from `0` through `1`. **response\_format** `string` `json` by default. Whisper also accepts `verbose_json`; Voxtral supports `json` only and returns `400 invalid_request_error` for `verbose_json`. Text and subtitle formats are not supported. **timestamp\_granularities\[]** `string[]` Accepted values are `word` and/or `segment`, once each, with Whisper and `response_format=verbose_json`. Repeat the form field for both. The spelling `timestamp_granularities` is also accepted; do not mix spellings. Word-level timestamps are not returned; segments can be absent. **stream** `boolean` Omit this field or send the literal form value `false`. Streaming is not supported; other values return `400`. **user** `string` Accepted for SDK compatibility but removed before forwarding upstream. Duplicate scalar fields, malformed multipart, and invalid UTF-8 text return `400`. Unknown form fields, including `provider`, `chunking_strategy`, `include[]`, and speaker fields, return `400 unknown_parameter`. ACI E2EE is not supported on this endpoint. The upload must complete within 60 seconds; oversized files or request bodies return `413`. ## Routing Constraints The Phala TEE-only endpoint requires verified serving for audio requests. A `provider` form field is not accepted. **X-ACI-Provider** `string` Optional JSON object with the same routing constraints as the JSON [provider field](/phala-cloud/confidential-ai/confidential-model/api-reference/chat-completions#param-provider), for example `{"aci_verified":true}`. The gateway consumes this header and does not forward it upstream. The header must appear once, contain only ASCII bytes, and be at most 8,192 bytes. Before sending explicit multipart constraints, verify the gateway and confirm that its attestation report lists `/v1/audio/transcriptions` in `service_capabilities.supported_multipart_constraint_endpoints`. Refuse the upload if support is absent. Session pins must intersect locally accepted sessions; verify the receipt's cited session against the effective policy. Receipt body hashes do not commit to this header. See [Attested Routing](/phala-cloud/confidential-ai/confidential-model/attested-routing). ## Examples Let the client set the multipart `Content-Type` boundary. Node SDK uploads need an explicit filename: `toFile(buf)` alone uses `unknown_file`, which has no supported extension and returns `400 invalid_parameter` with `param: file`. ```bash cURL theme={"system"} curl --fail-with-body --silent --show-error \ https://inference.phala.com/v1/audio/transcriptions \ -H "Authorization: Bearer $PHALA_AI_API_KEY" \ -D audio-headers.txt \ -F 'model=openai/whisper-large-v3' \ -F 'file=@audio.wav' \ -F 'response_format=json' ``` ```python Python theme={"system"} import os from openai import OpenAI client = OpenAI( api_key=os.environ["PHALA_AI_API_KEY"], base_url="https://inference.phala.com/v1", ) with open("audio.wav", "rb") as audio: response = client.audio.transcriptions.create( model="openai/whisper-large-v3", file=audio, response_format="json", ) print(response.text) ``` ```typescript TypeScript theme={"system"} import { readFile } from "node:fs/promises"; import OpenAI, { toFile } from "openai"; const client = new OpenAI({ apiKey: process.env.PHALA_AI_API_KEY, baseURL: "https://inference.phala.com/v1", }); const buf = await readFile("audio.wav"); const response = await client.audio.transcriptions.create({ model: "openai/whisper-large-v3", file: await toFile(buf, "audio.wav"), response_format: "json", }); console.log(response.text); ``` ```bash Private AI Proxy theme={"system"} pap curl https://inference.phala.com/v1/audio/transcriptions -- \ --fail-with-body --silent --show-error \ -H @auth-headers.txt \ -D audio-headers.txt \ -F 'model=openai/whisper-large-v3' \ -F 'file=@audio.wav' \ -F 'response_format=json' ``` For Voxtral, replace the model with `mistralai/voxtral-small-24b-2507` and keep `response_format=json`. For the [Private AI Proxy example](https://github.com/Dstack-TEE/private-ai-gateway/blob/main/apps/desktop/docs/cli.md#one-pinned-curl-request), create `auth-headers.txt` containing `Authorization: Bearer `, restrict its permissions to your user, and remove it after use. No manual `X-ACI-Provider` header is needed for this request on the Phala TEE-only endpoint. `pap curl` verifies the gateway and pins its TLS channel; it does not audit response receipts. Use `pap serve` or an ACI verifier SDK for receipt audits. Ordinary cURL and OpenAI SDK clients do not verify the gateway or audit receipts. ## Response Example JSON response for three billable seconds of Whisper audio at the current rate: ```json theme={"system"} { "text": "Hello, world.", "usage": { "type": "duration", "seconds": 3, "cost": 0.0003 } } ``` `json` returns `text`, `usage`, and optional `languages: [{"code":"en"}]`. Whisper's `verbose_json` response includes `duration` and `language` alongside `text` and `usage`. Word-level timestamps are not returned. With `verbose_json`, Whisper responses may include `segments`; they can be absent. A segment's `no_speech_prob` field may also be missing. `usage.seconds` is an integer rounded up to the next whole second; verbose `duration` retains the raw value. The gateway adds `usage.cost` in USD when audio pricing is available: billable seconds times the model's `pricing.audio_transcription` rate. Without a valid duration, the transcript is withheld with `502` and no audio is billed. ## Verification Capture `x-receipt-id` and fetch `GET /v1/aci/receipts/{id}` with the same bearer token. Audio receipts have `chat_id: null`; use the receipt ID. See [Get Receipt](/phala-cloud/confidential-ai/confidential-model/api-reference/receipts) and [Verify a Response](/phala-cloud/confidential-ai/verify/verify-signature). ## Errors Errors use a JSON `error` object, with `error.code` and `error.param` where applicable. | Status | Error field | Condition | | - | - | - | | 400 | `code: unknown_parameter` | Unrecognized form field; `param` names the field. | | 400 | `code: invalid_parameter` | Missing or invalid required fields, filename extension, response format, timestamp options, duplicate scalar fields, invalid UTF-8, malformed multipart, or exceeded multipart metadata limits. | | 400 | `type: invalid_request_error`, `code: null`, `param: null` | Voxtral with `verbose_json`: `Currently do not support verbose_json for voxtral-small-24b`. | | 400 | `type: invalid_request_error` | Invalid or duplicate `X-ACI-Provider` header, including malformed constraints. | | 400 | `type: e2ee_unsupported_endpoint` | E2EE headers are present. | | 404 | `type: model_not_found` | No eligible route supports transcription for the model. | | 408 | `code: upload_timeout` | Upload exceeds the 60-second deadline; the connection closes. | | 413 | `code: request_too_large` | File or whole-body limit exceeded; the connection closes. | | 429 | `type: rate_limit_error`, `code: rate_limit_exceeded` | Capacity is full or a rate limit is reached; respect `Retry-After` when present. | | 502 | `type: upstream_error` | Upstream failure, response over 8 MiB, missing string `text`, or invalid duration. | Authentication, budget, and other routing errors follow [Error Handling](/phala-cloud/confidential-ai/confidential-model/error-handling). ## Related > [card] [List Models](/phala-cloud/confidential-ai/confidential-model/api-reference/models) > [card] [Get Receipt](/phala-cloud/confidential-ai/confidential-model/api-reference/receipts) # Chat Completions Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/api-reference/chat-completions Create OpenAI-compatible chat completion responses with Private AI models. ## Endpoint ```bash theme={"system"} POST https://inference.phala.com/v1/chat/completions ``` Creates a response for a chat conversation. Use the same OpenAI-compatible request shape you already use with the OpenAI SDK, then set the base URL to `https://inference.phala.com/v1`. ## Request Body **model** `string` *required* Model ID to use for completion. Example: `z-ai/glm-5.3`. Use an id returned by [List Models](/phala-cloud/confidential-ai/confidential-model/api-reference/models). **messages** `array` *required* Conversation messages. Each message includes `role` and `content`. ```json theme={"system"} [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Explain GPU TEE in one paragraph."} ] ``` **temperature** `number` Sampling temperature. Typical range is `0` to `2`. **max\_tokens** `integer` Maximum number of output tokens for most open models and GPU TEE models. **max\_completion\_tokens** `integer` Maximum output tokens for newer OpenAI reasoning models that do not accept `max_tokens`. **stream** `boolean` Set to `true` to receive server-sent event chunks. **tools** `array` Function/tool definitions that supported models can call. **tool\_choice** `string | object` Controls whether the model may call tools. Common values are `auto`, `none`, or a specific tool selection object. **response\_format** `object` Requests structured output from supported models, including JSON schema mode. **provider** `object` Routing constraints for this request. Fields are applied together, and the request is served only by a route that satisfies all of them. **`zdr`** (boolean): set `true` to route only to providers that operate under zero data retention, meaning they do not retain prompt or completion content after serving the request. `false`, or omitting the field, applies no retention constraint. ```json theme={"system"} {"provider": {"zdr": true}} ``` If no route for the model satisfies the constraint, the request returns `404` and no prompt is sent. The constraint is enforced for the whole request, including failover, so a retry cannot fall back to a route that does not satisfy it. Find models that can satisfy `zdr` ahead of time with [`GET /v1/models?zdr=true`](/phala-cloud/confidential-ai/confidential-model/api-reference/models#query-parameters). See [Zero Data Retention](/phala-cloud/confidential-ai/confidential-model/zero-data-retention). **`aci_verified`** (boolean): set `true` to route only to an upstream the gateway verified inside the TEE before sending the prompt. `false`, or omitting the field, adds no request-level constraint; the Phala TEE-only endpoint still requires verified serving. ```json theme={"system"} {"provider": {"aci_verified": true}} ``` If no upstream for the model is both classified as attested and currently verified, the request returns `503` (`upstream_verification_failed`) and no prompt is sent. Nothing in the request can relax this constraint once it is set. **`aci_session_ids`** (array of strings): restrict the request further to specific attested channels, identified by the session ids from [`GET /v1/aci/sessions`](/phala-cloud/confidential-ai/confidential-model/api-reference/sessions). Any one of the listed ids may serve the request; if none matches a currently verified channel, the request returns `412` (`session_not_accepted`). Refresh the session list before pinning; example ids are snapshots, not permanent accepted channels. ```json theme={"system"} {"provider": {"aci_verified": true, "aci_session_ids": ["50b1e4ac17b1f10906595d322269b69e75ba15e03adb147490fa28eba4de8fc1"]}} ``` Session ids imply `aci_verified`. Passing them with `"aci_verified": false` returns `400`, as does an empty array or a non-string entry. Both fields are read by the gateway and removed before the request reaches a provider. See [Attested Routing](/phala-cloud/confidential-ai/confidential-model/attested-routing). ## Examples ```bash cURL theme={"system"} curl https://inference.phala.com/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{ "model": "z-ai/glm-5.3", "messages": [ {"role": "user", "content": "What privacy guarantees does GPU TEE provide?"} ] }' ``` ```python Python theme={"system"} from openai import OpenAI client = OpenAI( api_key="", base_url="https://inference.phala.com/v1", ) response = client.chat.completions.create( model="z-ai/glm-5.3", messages=[ {"role": "user", "content": "What privacy guarantees does GPU TEE provide?"} ], ) print(response.choices[0].message.content) ``` ```typescript TypeScript theme={"system"} import OpenAI from "openai"; const client = new OpenAI({ apiKey: "", baseURL: "https://inference.phala.com/v1", }); const response = await client.chat.completions.create({ model: "z-ai/glm-5.3", messages: [ { role: "user", content: "What privacy guarantees does GPU TEE provide?" }, ], }); console.log(response.choices[0].message.content); ``` ## Response ```json theme={"system"} { "id": "chatcmpl-123", "object": "chat.completion", "created": 1677652288, "model": "z-ai/glm-5.3", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "GPU TEE protects inference by..." }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 16, "completion_tokens": 48, "total_tokens": 64 } } ``` Raw HTTP responses include verification headers. Use `x-receipt-id` with [Get Receipt](/phala-cloud/confidential-ai/confidential-model/api-reference/receipts) when you need cryptographic proof for this specific response. The response `id` can also be used as a receipt lookup id. | Header | Meaning | | - | - | | `x-receipt-id` | Signed receipt id for this response. | | `x-aci-identity` | Attested gateway workload identity. | | `x-aci-keyset-digest` | Digest of the attested gateway keyset. | ## Feature Notes * Streaming uses the same `stream: true` option as the OpenAI API. * Vision models accept multimodal `content` arrays with `image_url` entries. * Tool calling uses OpenAI-compatible `tools`, `tool_choice`, assistant `tool_calls`, and tool response messages. * Structured output uses `response_format` on supported models. ## Next Steps > [card] [List Models](/phala-cloud/confidential-ai/confidential-model/api-reference/models) > > Discover available Private AI models and capabilities > [card] [Verify Responses](/phala-cloud/confidential-ai/confidential-model/api-reference/receipts) > > Fetch the receipt for a chat completion response # Completions Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/api-reference/completions POST /completions Create a legacy text completion through the attested Private AI gateway. > [!WARNING] > > This endpoint is legacy. Use [Chat Completions](/phala-cloud/confidential-ai/confidential-model/api-reference/chat-completions) or [Responses](/phala-cloud/confidential-ai/confidential-model/api-reference/responses) for new applications. ## Endpoint ```bash theme={"system"} POST https://inference.phala.com/v1/completions ``` ## Request ```json theme={"system"} { "model": "z-ai/glm-5.3", "prompt": "Say this is a test", "max_tokens": 7, "temperature": 0 } ``` This endpoint accepts the same `provider` routing block as chat completions, including `zdr`, `aci_verified`, and `aci_session_ids`. See [Chat Completions](/phala-cloud/confidential-ai/confidential-model/api-reference/chat-completions#param-provider). ## Response ```json theme={"system"} { "id": "cmpl-123", "object": "text_completion", "created": 1677652288, "model": "z-ai/glm-5.3", "choices": [ { "text": "\n\nThis is a test.", "index": 0, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 5, "completion_tokens": 7, "total_tokens": 12 } } ``` Like other inference endpoints, raw HTTP responses include `x-receipt-id` for verification. ## Related > [card] [Chat Completions](/phala-cloud/confidential-ai/confidential-model/api-reference/chat-completions) > [card] [Get Receipt](/phala-cloud/confidential-ai/confidential-model/api-reference/receipts) # List Embedding Models Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/api-reference/embedding-models List embedding-capable models available through the Private AI API. ## Endpoint ```bash theme={"system"} GET https://inference.phala.com/v1/embeddings/models ``` Returns models designed for vector embeddings. Use this endpoint when selecting embedding models for retrieval, RAG, clustering, or similarity search. No API key is required. ## Query Parameters **zdr** `string` Set to `true` to return only embedding models that can be served under zero data retention. `true` is the only accepted value. Any other value returns `400`. Omit the parameter to list the full embedding catalog. ```bash theme={"system"} curl "https://inference.phala.com/v1/embeddings/models?zdr=true" ``` **tee** `string` Set to `true` to return only embedding models that are offered confidentially, meaning the model carries `is_tee: true`. To require attestation for a specific request, send `provider: {"aci_verified": true}`. See [Attested Routing](/phala-cloud/confidential-ai/confidential-model/attested-routing). `true` is the only accepted value. Any other value returns `400`. Omit the parameter to list the full embedding catalog. ```bash theme={"system"} curl "https://inference.phala.com/v1/embeddings/models?tee=true" ``` Response entries have the same shape as the unfiltered catalog. There is no `zdr` field on a model object. ## Examples ```bash theme={"system"} curl https://inference.phala.com/v1/embeddings/models ``` ## Response Fields | Field | Description | | - | - | | `id` | Model identifier for `POST /v1/embeddings` | | `name` | Human-readable model name | | `input_modalities` | Input types accepted by the model | | `output_modalities` | Output types produced by the model | | `context_length` | Maximum input context length | | `max_output_length` | Embedding dimensions or max output size | | `pricing.prompt` | Input price per token | | `description` | Model description and use case | # Embeddings Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/api-reference/embeddings Create vector embeddings with OpenAI-compatible embedding models. ## Endpoint ```bash theme={"system"} POST https://inference.phala.com/v1/embeddings ``` Generate vector embeddings for retrieval, semantic search, clustering, and similarity workloads. ## Request Body **model** `string` *required* Embedding model ID. Examples: `qwen/qwen3-embedding-8b`, `sentence-transformers/all-minilm-l6-v2`. **input** `string | array` *required* Input text or list of inputs to embed. **encoding\_format** `string` Embedding encoding format. Common values are `float` and `base64`. **dimensions** `integer` Requested output dimensions, when supported by the selected model. **provider** `object` Routing constraints for this request. Embedding requests accept the same `provider` routing block as chat completions, including `zdr`, `aci_verified`, and `aci_session_ids`. Set `provider: {"zdr": true}` to route only to serving routes that operate under zero data retention. If no route for the selected embedding model satisfies the constraint, the request fails before input text is sent. See [Zero Data Retention](/phala-cloud/confidential-ai/confidential-model/zero-data-retention) and [Attested Routing](/phala-cloud/confidential-ai/confidential-model/attested-routing). ## Examples ```bash cURL theme={"system"} curl https://inference.phala.com/v1/embeddings \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "model": "qwen/qwen3-embedding-8b", "input": "Private AI keeps inference data private." }' ``` ```python Python theme={"system"} from openai import OpenAI client = OpenAI( api_key="", base_url="https://inference.phala.com/v1", ) response = client.embeddings.create( model="qwen/qwen3-embedding-8b", input="Private AI keeps inference data private.", ) vector = response.data[0].embedding print(len(vector)) ``` ```typescript TypeScript theme={"system"} import OpenAI from "openai"; const client = new OpenAI({ apiKey: "", baseURL: "https://inference.phala.com/v1", }); const response = await client.embeddings.create({ model: "qwen/qwen3-embedding-8b", input: "Private AI keeps inference data private.", }); console.log(response.data[0].embedding.length); ``` ## Response ```json theme={"system"} { "object": "list", "data": [ { "object": "embedding", "index": 0, "embedding": [0.0023, -0.0015, 0.0042] } ], "model": "qwen/qwen3-embedding-8b", "usage": { "prompt_tokens": 8, "total_tokens": 8 } } ``` Use [List Embedding Models](/phala-cloud/confidential-ai/confidential-model/api-reference/embedding-models) for the live embedding catalog. # Images Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/api-reference/images POST /images/generations Generate images with inline base64 output and per-image billing through the attested gateway. ## Endpoint ```bash theme={"system"} POST https://inference.phala.com/v1/images/generations ``` Generate images from a text prompt. Responses are buffered JSON with inline base64 image data and an `x-receipt-id` header for verification. ## Models and Pricing The live [model catalog](/phala-cloud/confidential-ai/confidential-model/api-reference/models) lists image models with `image` in `output_modalities`. It currently offers `black-forest-labs/flux.2-klein-4b` at **\$0.015 per returned image**, published as `pricing.image_generation` in USD per image. Check the catalog for current availability and pricing. ## Request Body **model** `string` *required* Image model ID, for example `black-forest-labs/flux.2-klein-4b`. **prompt** `string` *required* Text describing the image, up to 32,000 Unicode characters. **n** `integer` Maximum number of images to generate, from `1` through `10`. Defaults to `1`. Providers may return fewer images; billing uses the returned count. **size** `string` Image dimensions, for example `512x512`, or `auto` if supported by the model. **quality** `string` Model-specific quality setting. **background** `string` Model-specific background setting. **output\_format** `string` Requested image encoding, subject to model support. The current FLUX route returns JPEG bytes even when `png` is requested. Save its output as `.jpg`; do not infer the encoding from this parameter. **output\_compression** `integer` Compression setting from `0` through `100`, if supported by the model and encoding. **moderation** `string` Model-specific moderation setting. **response\_format** `string` Omit this field or set it to `b64_json`. The gateway requests inline base64 output. Image URLs are not supported. **safety\_identifier** `string` Accepted for SDK compatibility but removed before forwarding upstream. **provider** `object` The same routing constraints as [Chat Completions](/phala-cloud/confidential-ai/confidential-model/api-reference/chat-completions#param-provider), including `zdr`, `aci_verified`, and `aci_session_ids`. The Phala endpoint requires verified serving independently of request-level constraints. The gateway validates option types; supported values and defaults depend on the model. `user` and `style` are accepted as strings but removed before forwarding. Unknown fields, including `seed`, are rejected. Omit `stream` and `partial_images` entirely, including `stream: false`. Streaming and ACI E2EE are not supported on this endpoint. ## Examples Both examples save the first FLUX image as `image.jpg`. The cURL example also saves the raw response and headers, including the receipt ID. ```bash cURL theme={"system"} curl --fail-with-body --silent --show-error \ https://inference.phala.com/v1/images/generations \ -H "Authorization: Bearer $PHALA_AI_API_KEY" \ -H "Content-Type: application/json" \ -D image-headers.txt -o image-response.json \ -d '{ "model": "black-forest-labs/flux.2-klein-4b", "prompt": "A blue circle on a white background.", "size": "512x512" }' && \ python3 - <<'PY' import base64 import json from pathlib import Path response = json.loads(Path("image-response.json").read_text()) image = base64.b64decode(response["data"][0]["b64_json"], validate=True) Path("image.jpg").write_bytes(image) PY ``` ```python Python theme={"system"} import base64 import os from pathlib import Path from openai import OpenAI client = OpenAI( api_key=os.environ["PHALA_AI_API_KEY"], base_url="https://inference.phala.com/v1", ) response = client.images.generate( model="black-forest-labs/flux.2-klein-4b", prompt="A blue circle on a white background.", size="512x512", ) if not response.data or not response.data[0].b64_json: raise ValueError("The response did not contain an inline image") image = base64.b64decode(response.data[0].b64_json, validate=True) Path("image.jpg").write_bytes(image) ``` ## Response Example for one FLUX image at the current rate. The base64 data is shortened. ```json theme={"system"} { "created": 1793859850, "data": [ { "b64_json": "/9j/4AAQSkZJRg...", "revised_prompt": "A blue circle on a white background." } ], "usage": { "input_tokens": 0, "output_tokens": 0, "total_tokens": 0, "input_tokens_details": { "text_tokens": 0, "image_tokens": 0 }, "cost": 0.015 } } ``` `created` is a Unix timestamp in seconds. `data` is a nonempty array of images with `b64_json`; an item may also contain `revised_prompt` as a string or `null`. The current FLUX response does not include top-level `size` or `output_format` fields. When present, `usage` includes integer token counts, with missing counts filled with `0`. The gateway adds `usage.cost` in USD when pricing is available: returned image count times the per-image rate, plus token charges if token usage and rates are available. Zero token counts do not imply free image generation. ## Verification Capture `x-receipt-id` from the response headers and fetch `GET /v1/aci/receipts/{id}` with the same bearer token. Image receipts have `chat_id: null`; use the receipt ID. See [Get Receipt](/phala-cloud/confidential-ai/confidential-model/api-reference/receipts) and [Verify a Response](/phala-cloud/confidential-ai/verify/verify-signature). Ordinary cURL and OpenAI SDK clients do not verify the gateway or audit receipts. ## Errors Errors use a JSON `error` object, with `error.code` and `error.param` where applicable. | Status | Error field | Condition | | - | - | - | | 400 | `code: unknown_parameter` | Unrecognized field, such as `seed`; `param` names the field. | | 400 | `code: invalid_parameter` | Missing required strings, invalid option types or ranges, `n` outside `1`–`10` or not an integer, `response_format: "url"`, any `stream` or `partial_images` field, or a prompt over 32,000 characters. | | 400 | `type: invalid_request_error` | Invalid JSON or malformed routing constraints. | | 400 | `type: e2ee_unsupported_endpoint` | E2EE headers are present. | | 404 | `type: model_not_found` | No eligible route supports image generation for the model. | | 429 | `type: rate_limit_error`, `code: rate_limit_exceeded` | Capacity is full or a rate limit is reached; respect `Retry-After` when present. | | 502 | `type: upstream_error` | Upstream failure, buffered response over 64 MiB, or malformed response, including empty `data`, too many images, or missing inline image data. | Authentication, budget, and other routing errors follow [Error Handling](/phala-cloud/confidential-ai/confidential-model/error-handling). ## Related > [card] [List Models](/phala-cloud/confidential-ai/confidential-model/api-reference/models) > [card] [Get Receipt](/phala-cloud/confidential-ai/confidential-model/api-reference/receipts) # Messages Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/api-reference/messages POST /messages Create a model response using the Anthropic Messages API format through the attested Private AI gateway. Creates a model response using the Anthropic Messages request and response format. Requests are served through the attested gateway and return an `x-receipt-id` header for verification. ## Endpoint ```bash theme={"system"} POST https://inference.phala.com/v1/messages ``` ## Request Body **model** `string` *required* Model id returned by [List Models](/phala-cloud/confidential-ai/confidential-model/api-reference/models). **max\_tokens** `integer` *required* Maximum number of tokens to generate. **messages** `array` *required* Conversation turns. Each item has a `role` (`user` or `assistant`) and `content`. **system** `string` System prompt, sent as a top-level field. **temperature** `number` Sampling temperature. **stream** `boolean` Stream the response as server-sent events. **provider** `object` Routing constraints for this request, applied together. `zdr` restricts routing to providers that do not retain content; `aci_verified` restricts it to an upstream verified inside the TEE; `aci_session_ids` pins it to specific attested channels. ```json theme={"system"} {"provider": {"aci_verified": true}} ``` If no provider satisfies the constraints the request fails before the prompt is sent, and failover retries stay inside the allowed set. Field reference: [Chat Completions](/phala-cloud/confidential-ai/confidential-model/api-reference/chat-completions#param-provider). See [Attested Routing](/phala-cloud/confidential-ai/confidential-model/attested-routing) and [Zero Data Retention](/phala-cloud/confidential-ai/confidential-model/zero-data-retention). ## Example ```bash theme={"system"} curl https://inference.phala.com/v1/messages \ -H "Authorization: Bearer $PHALA_AI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "z-ai/glm-5.3", "max_tokens": 100, "messages": [ {"role": "user", "content": "Say hello in three words."} ] }' ``` ## Response ```json theme={"system"} { "id": "msg_01ABC...", "type": "message", "role": "assistant", "model": "z-ai/glm-5.3", "content": [ { "type": "text", "text": "Hello, howdy, hi!" } ], "stop_reason": "end_turn", "stop_sequence": null, "usage": { "input_tokens": 14, "output_tokens": 8 } } ``` Read assistant text from `content[].text` on blocks with `type: "text"`. `stop_reason` is usually `end_turn`, `max_tokens`, `stop_sequence`, or `tool_use`. ## Verification Use the response `x-receipt-id` header with [Get Receipt](/phala-cloud/confidential-ai/confidential-model/api-reference/receipts). A confidential response has `upstream.verified.result = verified` and `required = true`. ## Related > [card] [Responses](/phala-cloud/confidential-ai/confidential-model/api-reference/responses) > [card] [Trust Boundary](/phala-cloud/confidential-ai/confidential-model/trust-boundary) # List Models Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/api-reference/models List available Private AI models, modalities, context windows, and pricing metadata. ## Endpoints ```bash theme={"system"} GET https://inference.phala.com/v1/models ``` Use the live model catalog before hardcoding model IDs. The catalog returns model IDs, context windows, pricing, serving metadata, modalities, supported parameters, and whether a model can be served confidentially. No API key is required. ## Query Parameters **zdr** `string` Set to `true` to return only models that can be served under zero data retention, meaning the upstream serving route does not retain prompt or completion content. A model is included when at least one route that can serve it operates under zero data retention. Listing a model here means a request for it with `provider: {"zdr": true}` can be routed. See [Zero Data Retention](/phala-cloud/confidential-ai/confidential-model/zero-data-retention). `true` is the only accepted value. Any other value, including `false`, returns `400`. Omit the parameter to list the full catalog. ```bash theme={"system"} curl "https://inference.phala.com/v1/models?zdr=true" ``` **tee** `string` Set to `true` to return only models that are offered confidentially, meaning the model object carries `is_tee: true`. This filter reports a model's own capability. It does not promise that a given request will reach an attested provider, which depends on the deployment serving it. To require attestation for a request, send `provider: {"aci_verified": true}`. See [Attested Routing](/phala-cloud/confidential-ai/confidential-model/attested-routing). `true` is the only accepted value. Any other value, including `false`, returns `400`. Omit the parameter to list the full catalog. ```bash theme={"system"} curl "https://inference.phala.com/v1/models?tee=true" ``` Both filters compose. Combining them returns models that satisfy each constraint. Response entries have the same shape as the unfiltered catalog. There is no `zdr` field on a model object: the filter is the way to read this property. An invalid value returns `400`: ```json theme={"system"} { "error": { "message": "Invalid 'zdr' query parameter. The only accepted value is 'true'; omit it for unfiltered results.", "type": "invalid_request_error" } } ``` ## Examples ```bash theme={"system"} curl https://inference.phala.com/v1/models ``` ## Model Object Fields | Field | Description | | - | - | | `id` | Model identifier for API calls | | `name` | Human-readable model name | | `is_tee` | `true` if the model can be served confidentially by a verified TEE provider | | `created` | Unix timestamp when the model was added | | `description` | Model or provider description | | `context_length` | Maximum context window | | `max_output_length` | Maximum output length | | `pricing.prompt` | Input token price per token; multiply by 1,000,000 for per-million-token pricing | | `pricing.completion` | Output token price per token; multiply by 1,000,000 for per-million-token pricing | | `pricing.input_cache_read` | Cached input price per token when the model exposes cache pricing | | `providers` | Serving routes available for the model. | | `input_modalities` | Supported input types, such as `text` or `image` | | `output_modalities` | Supported output types, such as `text`, `embeddings`, or `decisions` | | `supported_parameters` | Request parameters accepted by the model | | `supported_features` | Higher-level capabilities declared by the model, such as `tools`, `reasoning`, or `structured_outputs` | ## Decision models Models with `"decisions"` in `output_modalities`, such as `jaredpalmer/kev-4b`, answer typed questions through [`POST /v1/systemone`](/phala-cloud/confidential-ai/confidential-model/api-reference/systemone). They do not serve chat completions and do not stream. ## Find Verifiable TEE Models Filter for models that can be served confidentially: ```bash theme={"system"} curl "https://inference.phala.com/v1/models?tee=true" | \ jq -r '.data[].id' ``` `is_tee: true` means the model can be served confidentially. To require attestation for a specific request rather than reading the catalog flag, use [Attested Routing](/phala-cloud/confidential-ai/confidential-model/attested-routing). The receipt remains the per-response proof: read the `x-receipt-id` header, then verify it with [Attestation Report](/phala-cloud/confidential-ai/confidential-model/api-reference/attestation) and [Get Receipt](/phala-cloud/confidential-ai/confidential-model/api-reference/receipts). ## Find Zero-Data-Retention Models `is_tee` and `zdr` describe different properties. `is_tee` says a model can run inside a verified TEE, which constrains who can read memory during execution. Zero data retention says the upstream serving route does not keep prompt or completion content after serving the request. Filter for it with the query parameter rather than inferring it from `is_tee`: ```bash theme={"system"} curl -s "https://inference.phala.com/v1/models?zdr=true" | \ jq -r '.data[].id' ``` To route a request under the same constraint, send `provider: {"zdr": true}` in the request body. See [Zero Data Retention](/phala-cloud/confidential-ai/confidential-model/zero-data-retention). # Receipt Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/api-reference/receipts GET /aci/receipts/{id} The signed receipt for a response, with the full transparency event log. Returns the signed receipt for a response: a transparency event log that binds the request and response hashes to the attested gateway, signed by a key from the attested [keyset](/phala-cloud/confidential-ai/confidential-model/api-reference/attestation). This is the canonical per-response proof. Look up a receipt by the `x-receipt-id` header on the inference response, or by the response `id`. For how to read the event log, see [Receipts](/phala-cloud/confidential-ai/confidential-model/receipts-and-sessions). ```http theme={"system"} GET /v1/aci/receipts/{id} ``` ## Request **id** `string` *required* A receipt id (`rcpt-…`) or the response `id` (chat id). The receipt id is returned in the `x-receipt-id` response header on `/v1/chat/completions`. ## Response `200 OK`, `application/json`. The bare canonical receipt. Use the same API key that made the inference request; a different key returns `404`, and a missing key returns `401` for a credential-bound receipt: | Field | Type | Description | | - | - | - | | `api_version` | string | ACI version token, for example `aci/1`. | | `receipt_id` | string | The receipt id (`rcpt-…`). | | `chat_id` | string or null | The response/chat id, when the upstream returns one. | | `workload_keyset_digest` | string | Must match the attestation report. | | `model` | string or null | Model requested by the client. | | `endpoint` | string | The route served, for example `/v1/chat/completions`. | | `method` | string | HTTP method. | | `served_at` | number | Unix seconds. | | `event_log` | array | Ordered transparency events (below). | | `key_id` | string | Selects a receipt-signing key from the attested keyset. | | `signature` | string | Signature over the receipt, by a key in the attested keyset. | ### `event_log` entries | `type` | Key fields | | - | - | | `request.received` | `body_hash` | | `middleware.forwarded` | `body_hash` | | `route.selected` | `target_route_id` | | `request.forwarded` | `body_hash` | | `upstream.verified` | `model_id`, `result`, `required`, `session_id` | | `response.received` | `body_hash` | | `response.returned` | `body_hash` | ### Example (truncated) ```json theme={"system"} { "api_version": "aci/1", "receipt_id": "rcpt-e0eefe63b3673e2a5984951f", "chat_id": "d3ad808b20a444c29e798db35f112033", "workload_keyset_digest": "sha256:3eff0836…", "model": "z-ai/glm-5.3", "endpoint": "/v1/chat/completions", "method": "POST", "served_at": 1781588857, "event_log": [ { "type": "request.received", "body_hash": "sha256:111d08a5…" }, { "type": "route.selected", "target_route_id": "" }, { "type": "upstream.verified", "model_id": "z-ai/glm-5.3", "result": "verified", "required": true, "session_id": "3681736b…" }, { "type": "response.returned", "body_hash": "sha256:07703fb4…" } ], "key_id": "dstack-kms-receipt-ed25519-v1", "signature": "…" } ``` ## Verifying the receipt 1. Confirm `workload_keyset_digest` matches a verified [attestation report](/phala-cloud/confidential-ai/confidential-model/api-reference/attestation). 2. Resolve `key_id` in the attested `receipt_signing_keys` and verify `signature` over the JCS (RFC 8785) form of the receipt with only `signature` removed. The baseline is a hex-encoded Ed25519 signature. 3. Confirm `request.received.body_hash` matches the request you sent and `response.returned.body_hash` matches the response you received. 4. On this TEE-only endpoint, upstream verification is required (`required: true`). A failed check refuses forwarding instead of returning unverified inference. Read `upstream.verified`: `result = verified` and `required = true` indicate a confidential model served from a verified, channel-bound upstream. Follow `session_id` to the [attested session](/phala-cloud/confidential-ai/confidential-model/api-reference/sessions). See [Verify a response](/phala-cloud/confidential-ai/verify/verify-signature) for the full walkthrough. ## Legacy alias `GET /v1/signature/{id}` returns the same receipt wrapped in a legacy envelope, for clients written against earlier API versions. `{id}` is a receipt id or a response id. | Field | Description | | - | - | | `api_version` | ACI version token, for example `aci/1`. | | `signing_algo` | Signature algorithm, for example `ecdsa`. | | `signing_address` | Address that signed `text`. | | `text` | `":"`, the signed message. | | `signature` | Signature over `text`. | | `receipt` | The full receipt object, identical to this endpoint's response. | New integrations should use `/v1/aci/receipts/{id}`. ## Related > [card] [Get attestation report](/phala-cloud/confidential-ai/confidential-model/api-reference/attestation) > [card] [Get session](/phala-cloud/confidential-ai/confidential-model/api-reference/sessions) # Responses Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/api-reference/responses POST /responses Create a model response using the Responses API format through the attested Private AI gateway. Creates a model response using the Responses API request and response format. Like other inference endpoints, requests are served through the attested gateway and return an `x-receipt-id` header for verification. ## Endpoint ```bash theme={"system"} POST https://inference.phala.com/v1/responses ``` ## Request Body **model** `string` *required* Model id, for example `z-ai/glm-5.3` or another id returned by [List Models](/phala-cloud/confidential-ai/confidential-model/api-reference/models). **input** `string | array` *required* Input prompt. This can be a string or an array of input items. **tools** `array` Tool definitions the model may call. **temperature** `number` Sampling temperature. **top\_p** `number` Nucleus sampling. **provider** `object` Routing constraints for this request, applied together. `zdr` restricts routing to providers that do not retain content; `aci_verified` restricts it to an upstream verified inside the TEE; `aci_session_ids` pins it to specific attested channels. ```json theme={"system"} {"provider": {"aci_verified": true}} ``` If no provider satisfies the constraints the request fails before the prompt is sent, and failover retries stay inside the allowed set. Field reference: [Chat Completions](/phala-cloud/confidential-ai/confidential-model/api-reference/chat-completions#param-provider). See [Attested Routing](/phala-cloud/confidential-ai/confidential-model/attested-routing) and [Zero Data Retention](/phala-cloud/confidential-ai/confidential-model/zero-data-retention). ## Example ```bash theme={"system"} curl https://inference.phala.com/v1/responses \ -H "Authorization: Bearer $PHALA_AI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "z-ai/glm-5.3", "input": "Explain attestation in one sentence." }' ``` ## Response ```json theme={"system"} { "id": "resp_023cda4f5e268c44006a30f3e0b6f4819b87536574ae6ecd14", "object": "response", "status": "completed", "model": "z-ai/glm-5.3", "output": [ { "type": "message", "role": "assistant", "content": [ { "type": "output_text", "text": "Attestation proves which trusted workload served a request.", "annotations": [] } ] } ], "usage": { "input_tokens": 12, "output_tokens": 10, "total_tokens": 22 } } ``` Read assistant text from `output[].content[].text` on `message` items. Reasoning models may also return `reasoning` items. ## Verification Capture `x-receipt-id` from the HTTP response and verify it with [Get Receipt](/phala-cloud/confidential-ai/confidential-model/api-reference/receipts). The receipt proves the response bytes and records whether the upstream provider was verified. ## Related > [card] [Chat Completions](/phala-cloud/confidential-ai/confidential-model/api-reference/chat-completions) > [card] [Verify a Response](/phala-cloud/confidential-ai/verify/verify-signature) # Session Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/api-reference/sessions GET /aci/sessions/{session_id} The immutable attested-session record behind a confidential response. Returns an [attested session](/phala-cloud/confidential-ai/confidential-model/receipts-and-sessions#attested-sessions): the immutable, content-addressed record of the verified TEE channel a confidential request was bound to. A receipt's `upstream.verified.session_id` references it, so you can trace any confidential response back to the exact verified security context, with its typed claims and channel binding. ```http theme={"system"} GET /v1/aci/sessions/{session_id} GET /v1/aci/sessions?upstream_name={upstream_name}&model={model} ``` ## Get one session **session\_id** `string` *required* The bare 64-character lowercase hex id (no prefix) from a receipt's `upstream.verified.session_id`. ### Response | Field | Type | Description | | - | - | - | | `api_version` | string | ACI version token. | | `upstream_name` | string | The service-chosen upstream label for this channel. | | `endpoint` | string | The verified upstream origin. | | `verifier_id` | string | The verifier that produced this result. | | `established_at` | number | When the material was verified (Unix seconds). | | `expires_at` | number | Retention deadline (Unix seconds). | | `identity` | object | Verified upstream identity keys (for example a signing address). | | `channel_binding` | array | The enforceable binding(s): TLS SPKI, E2EE public key, or measured co-deployed proxy image/credential. | | `claims` | object | Typed claims (below). | | `evidence` | object | Byte-preserving evidence the verifier checked (`digest` + data URI). | ### Binding types | Type | Meaning | | - | - | | `tls_spki_sha256` | Pins the upstream TLS public key. | | `e2ee_public_key_sha256` | Binds provider-facing encryption to a verified key. | | `proxy_image_sha256` | Binds Privatemode forwarding to the co-deployed proxy's measured image (`proxy_image_digest`) and startup-checked shared credential digest (`credential_sha256`); plaintext is sent only to its configured internal origin. | ### Typed claims Each claim carries a `status` (`asserted` / `refuted` / `unknown`), a `source` (`hardware_proven` / `verifier_derived` / `provider_asserted` / `operator_asserted`), and a `reason`. The claim set: `tee_attested`, `tcb_up_to_date`, `os_known_good`, `serving_software_known_good`, `gpu_attested`, `model_weights_provenance`, plus provider-specific entries in `extra`. See [Claims](/phala-cloud/confidential-ai/confidential-model/tcb-and-claims). ```json theme={"system"} { "api_version": "aci/1", "upstream_name": "near-ai", "endpoint": "https://cloud-api.near.ai", "verifier_id": "private-ai-verifier/near-ai-gateway/v1", "established_at": 1781588840, "expires_at": 1781589140, "channel_binding": [ { "type": "tls_spki_sha256", "origin": "https://cloud-api.near.ai", "spki_sha256": "…" } ], "claims": { "tee_attested": { "status": "asserted", "source": "hardware_proven", "reason": "verified TDX quote" }, "tcb_up_to_date": { "status": "asserted", "source": "hardware_proven" }, "gpu_attested": { "status": "unknown" } }, "evidence": { "digest": "sha256:…", "data": "data:application/json;base64,…" } } ``` ## List current sessions `GET /v1/aci/sessions?upstream_name={upstream_name}&model={model}` returns current attested sessions. The endpoint is public. `upstream_name` is a service-chosen route label such as `chutes` or `phala-267`, rather than a catalog provider id. Use it as a preflight survey: inspect the verified identity, channel binding, and claims for a model before sending a prompt. ```bash theme={"system"} curl "https://inference.phala.com/v1/aci/sessions?upstream_name=chutes" ``` Returns `{ "api_version": "aci/1", "sessions": [...] }`. Each list entry includes its `session_id` but omits the bulky `evidence.data`; fetch the full record before verifying its content hash. ## Why content-addressed The full session document does not contain its own id. `session_id` is the bare SHA-256 of the full session document in canonical JCS form. Any change produces a new id, and sessions are never updated in place. Recompute the id after fetching the full record to confirm it is exactly the document cited by the receipt. ## Related > [card] [Verified upstreams](/phala-cloud/confidential-ai/confidential-model/receipts-and-sessions#attested-sessions) > [card] [Get receipt](/phala-cloud/confidential-ai/confidential-model/api-reference/receipts) # Signature Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/api-reference/signature GET /signature/{id} Use the legacy receipt wrapper for older Private AI clients. `GET /v1/signature/{id}` is a legacy compatibility endpoint. It returns the same proof as the canonical [Get Receipt](/phala-cloud/confidential-ai/confidential-model/api-reference/receipts) endpoint, but wrapped in the older `text`, `signature`, and `signing_address` envelope. New integrations should use `GET /v1/aci/receipts/{id}`. ## Endpoint ```bash theme={"system"} GET https://inference.phala.com/v1/signature/{id}?signing_algo=ecdsa ``` ## Parameters **id** `string` *required* Receipt id (`rcpt-...`) or response id from `POST /v1/chat/completions`. **signing\_algo** `string` (default: ecdsa) Legacy wrapper signature algorithm: `ecdsa` (default) or `ed25519`. This selects the wrapper signer; the canonical receipt retains its own `key_id` and Ed25519 signature. ## Example ```bash theme={"system"} curl "https://inference.phala.com/v1/signature/$RECEIPT_OR_RESPONSE_ID" \ -H "Authorization: Bearer " ``` ## Response | Field | Description | | - | - | | `api_version` | ACI version token, for example `aci/1`. | | `signing_algo` | Signature algorithm, for example `ecdsa`. | | `signing_address` | Address that signed `text`. | | `text` | `":"`. | | `signature` | Signature over `text`. | | `receipt` | Full receipt object, identical to the canonical `/v1/aci/receipts/{id}` response. | ```json theme={"system"} { "api_version": "aci/1", "signing_algo": "ecdsa", "signing_address": "0xffb22d95...", "text": "111d08a5...:07703fb4...", "signature": "0xd0cd266a...", "receipt": { "receipt_id": "rcpt-...", "event_log": ["..."], "signature": "..." } } ``` ## Verification For new clients, verify the `receipt` object directly: 1. Fetch a fresh [Attestation Report](/phala-cloud/confidential-ai/confidential-model/api-reference/attestation). 2. Confirm `receipt.workload_keyset_digest` matches the report. 3. Resolve `receipt.key_id` in the attested `receipt_signing_keys` and verify `receipt.signature` over the JCS receipt with `signature` removed. The canonical receipt uses `ed25519` (`dstack-kms-receipt-ed25519-v1`), independently of the wrapper's `signing_algo`. 4. Confirm `request.received.body_hash` and `response.returned.body_hash` match the exact bytes you sent and received. On this TEE-only endpoint, require `upstream.verified.result: verified`, `required: true`, and a verified cited session. For legacy clients that verify the wrapper, also verify `signature` over `text`, then bind `signing_address` back to a fresh attestation report. ## Related > [card] [Get Receipt](/phala-cloud/confidential-ai/confidential-model/api-reference/receipts) > [card] [Verify a Response](/phala-cloud/confidential-ai/verify/verify-signature) # System One Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/api-reference/systemone POST /systemone Ask a model typed questions about a state and get structured decisions. System One models answer typed questions about a piece of content instead of generating text. Each answer is a calibrated probability, a choice among options, or a level on a scale, so software can act on it directly. The endpoint follows the TypeSafe System One protocol, so the official TypeSafe SDKs work with Phala by changing the base URL. System One models list `decisions` in `output_modalities` in [`GET /v1/models`](/phala-cloud/confidential-ai/confidential-model/api-reference/models). They do not serve chat: a chat completion request to one returns `404 model_not_found`. Responses are never streamed. ```bash theme={"system"} POST https://inference.phala.com/v1/systemone ``` ## Request body **model** `string` *required* Id of a model whose `output_modalities` include `decisions`, for example `jaredpalmer/kev-4b`. **state** `string | object | array` *required* The content the questions are about: a message, a document, or any JSON value. **questions** `object` *required* Questions keyed by an id you choose. Each answer is returned under the same id. Every question has a `type` and usually `instructions` that state the question. **question types** **noul** `object` A yes/no question. `criteria` optionally describes what `true` and `false` mean. ```json theme={"system"} { "type": "noul", "instructions": "Is this about billing?" } ``` **choice** `object` Pick one option. `criteria` maps each option to a description, or to `null`. ```json theme={"system"} { "type": "choice", "instructions": "What is the tone?", "criteria": { "calm": null, "upset": null } } ``` **score** `object` Rate on an ordered scale. `criteria` lists the levels from lowest to highest. ```json theme={"system"} { "type": "score", "instructions": "How urgent is it?", "criteria": ["low", "medium", "high"] } ``` **provider** `object` The same `provider` routing block as chat completions. It is used for routing and is not sent to the upstream. Other fields are not forwarded. ## Example ```bash cURL theme={"system"} curl https://inference.phala.com/v1/systemone \ -H "Authorization: Bearer $PHALA_AI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "jaredpalmer/kev-4b", "state": "I was charged twice this month. Please fix it today.", "questions": { "billing": { "type": "noul", "instructions": "Is this about billing?" }, "tone": { "type": "choice", "instructions": "What is the tone?", "criteria": { "calm": null, "upset": null } }, "urgency": { "type": "score", "instructions": "How urgent is it?", "criteria": ["low", "medium", "high"] } } }' ``` ```python Python theme={"system"} import os from typesafe_sdk import Choice, Noul, Score, TypeSafeClient client = TypeSafeClient( api_key=os.environ["PHALA_AI_API_KEY"], base_url="https://inference.phala.com", model="jaredpalmer/kev-4b", ) result = client.system_one( state="I was charged twice this month. Please fix it today.", questions={ "billing": Noul(instructions="Is this about billing?"), "tone": Choice(instructions="What is the tone?", criteria={"calm": None, "upset": None}), "urgency": Score(instructions="How urgent is it?", criteria=["low", "medium", "high"]), }, ) print(result.nouls["billing"].noul, result.choices["tone"].choice, result.scores["urgency"].score) ``` ```javascript JavaScript theme={"system"} import { TypeSafeClient, choice, noul, score } from "@typesafe-ai/sdk"; const client = new TypeSafeClient({ baseURL: "https://inference.phala.com", apiKey: process.env.PHALA_AI_API_KEY, }); const result = await client.systemOne({ model: "jaredpalmer/kev-4b", state: "I was charged twice this month. Please fix it today.", questions: { billing: noul("Is this about billing?"), tone: choice("What is the tone?", { calm: null, upset: null }), urgency: score("How urgent is it?", ["low", "medium", "high"]), }, }); console.log(result.answers.billing.noul, result.answers.tone.choice, result.answers.urgency.score); ``` The SDKs append `/v1/systemone` themselves, so set their base URL to `https://inference.phala.com` without `/v1`. Install them with `pip install typesafe-sdk` or `npm install @typesafe-ai/sdk`. ## Response ```json theme={"system"} { "model": "jaredpalmer/kev-4b", "answers": { "billing": { "type": "noul", "noul": 0.8828 }, "tone": { "type": "choice", "choice": "upset", "confidence": 0.4882, "probabilities": { "calm": 0.2559, "upset": 0.7441 } }, "urgency": { "type": "score", "score": 1.4055, "legend": { "0": "low", "1": "medium", "2": "high" }, "probabilities": { "0": 0.1268, "1": 0.3408, "2": 0.5323 }, "confidence": 0.1083 } }, "usage": { "input_tokens": 57, "output_tokens": 167, "cost": 0.000002394 } } ``` **answers** `object` One answer per question id, in the same type as the question: * `noul`: `noul` is the probability that the answer is `true`. * `choice`: `choice` is the most likely option, with `probabilities` per option and a 0 to 1 `confidence`. * `score`: `score` is the probability-weighted level index, with `probabilities` per level, `legend` mapping each index to its level, and a 0 to 1 `confidence`. **usage** `object` `input_tokens`, `output_tokens`, and `cost`, the charge for this request in USD. The response carries `x-typesafe-request-id`, which the SDKs read, and the gateway's `x-receipt-id` for [receipt verification](/phala-cloud/confidential-ai/confidential-model/api-reference/receipts). Errors use the same error format as the other endpoints. # Attested Routing Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/attested-routing Restrict a request to an upstream the gateway verified inside the TEE, and pin it to a specific attested channel. Attested routing restricts a request to an upstream that the gateway verified before sending the prompt. Verification runs inside the TEE, produces an enforceable channel binding, and fails closed: if no eligible upstream verifies, the prompt is never forwarded. Use it when a prompt must not reach a provider whose execution environment you cannot check. The examples below use a confidential model; see [List the models you can use](#list-the-models-you-can-use) to find one. Two levels of constraint are available: | Constraint | What it selects | | - | - | | `provider: {"aci_verified": true}` | Any upstream that is currently verified and channel bound. | | `provider: {"aci_session_ids": [...]}` | One specific attested channel, by session id. | The Phala endpoint is TEE-only: upstream verification is required even when this block is omitted. `aci_verified` can express that requirement explicitly, and `aci_session_ids` narrows it to specified verified channels. No request option disables the endpoint policy. See [Provider Verification](/phala-cloud/confidential-ai/confidential-model/providers). ## Require an attested upstream Add the `provider` block to the request. Every inference endpoint accepts it: `/v1/chat/completions`, `/v1/messages`, `/v1/responses`, `/v1/embeddings`, and `/v1/completions`. ```bash theme={"system"} curl https://inference.phala.com/v1/chat/completions \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "model": "z-ai/glm-5.3", "messages": [{"role": "user", "content": "Summarize this patient note."}], "provider": {"aci_verified": true} }' ``` If no upstream for the requested model is both classified as attested and currently verified, the request fails before the prompt is sent. For example, an unavailable verified route can return: ```json theme={"system"} { "error": { "message": "upstream verification failed: no attested upstream available for model z-ai/glm-5.3", "type": "upstream_verification_failed" } } ``` The status is `503` (`upstream_verification_failed`). Failover retries stay inside the attested set, so a plaintext upstream never receives the prompt as a fallback. Setting `"aci_verified": false`, or omitting the field, adds no request-level constraint. The endpoint still requires verified serving. > [!NOTE] > > A request that requires an attested upstream cannot also opt out of the attestation. No request header or option relaxes this constraint once `aci_verified` is set. ## Pin a request to one attested channel `aci_verified` accepts any upstream that is verified right now. To require one specific attested channel, pass its session id. This is useful when you have already inspected a session's evidence and want subsequent requests to reach that exact channel or fail. List the sessions that can serve your model. The unfiltered list covers every upstream the gateway has verified, so filter it: a session belonging to another upstream will never match your request. ```bash theme={"system"} curl -s "https://inference.phala.com/v1/aci/sessions?model=z-ai/glm-5.3" \ -H "Authorization: Bearer " \ | jq -r '.sessions[] | "\(.session_id) \(.upstream_name) \(.endpoint)"' ``` Each entry carries a `session_id` as a bare 64-character lowercase hex digest with no prefix, the verifier that produced it, its channel binding, and an `expires_at` timestamp. `?upstream_name=` filters the same list by upstream. See [Get Session](/phala-cloud/confidential-ai/confidential-model/api-reference/sessions). The most reliable id is the one that already served you. Every response's receipt names the session that served it, so a client can pin follow-up requests to the channel it just used. Pin a request to one or more of them. The example id below was obtained from the live sessions endpoint; replace it with a currently accepted id before sending: ```bash theme={"system"} curl https://inference.phala.com/v1/chat/completions \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "model": "z-ai/glm-5.3", "messages": [{"role": "user", "content": "Summarize this patient note."}], "provider": { "aci_verified": true, "aci_session_ids": ["50b1e4ac17b1f10906595d322269b69e75ba15e03adb147490fa28eba4de8fc1"] } }' ``` Listing several ids means any one of them may serve the request. If none of them matches a currently verified channel, the request fails with `412` (`session_not_accepted`) and no prompt is sent: ```json theme={"system"} { "error": { "message": "upstream verification failed: none of the requested attested sessions is available for model z-ai/glm-5.3", "type": "session_not_accepted" } } ``` A session id is tied to one verified channel, and the gateway re-verifies periodically. When it re-verifies, the evidence changes and the id changes with it. Read a current id shortly before you pin it, and expect a pinned id to stop matching. A pin that stops matching is a failure, never a silent fallback to a different channel. `aci_session_ids` implies `aci_verified`. Passing session ids together with `"aci_verified": false` is rejected as a contradiction rather than resolved in either direction. ## List the models you can use ```bash theme={"system"} curl -s "https://inference.phala.com/v1/models?tee=true" \ | jq -r '.data[].id' ``` Embedding models have their own catalog, which takes the same parameter: ```bash theme={"system"} curl -s "https://inference.phala.com/v1/embeddings/models?tee=true" \ | jq -r '.data[].id' ``` `true` is the only accepted value. Any other value, including `false`, returns `400`. Omit the parameter for the full catalog. > [!WARNING] > > `?tee=true` and `provider: {"aci_verified": true}` read different properties. The catalog filter reports a model's own `is_tee` capability flag. The routing constraint is enforced against the provider actually serving the request. > > A model listed under `?tee=true` can still return `503` for an attested request when none of its live deployments is on an attested provider. The catalog tells you which models are offered confidentially. Only the gateway decides what a given request may reach. ## Request validation The gateway parses the attestation fields itself and rejects anything it cannot read, rather than treating it as an absent constraint. Every case below returns `400` with type `invalid_request_error` and forwards nothing. | Request | Result | | - | - | | `"provider": {"aci_verified": true}` | Constraint applied. | | `"provider": {"aci_verified": false}` | No extra request constraint; endpoint policy still applies. | | `"provider": {"aci_verified": "yes"}` | `400`, expected a boolean. | | `"provider": {"aci_session_ids": []}` | `400`, must not be empty. | | `"provider": {"aci_session_ids": [""]}` | `400`, expected non-empty strings. | | `"provider": {"aci_verified": false, "aci_session_ids": ["<64 lowercase hex>"]}` | `400`, contradictory. | | `"provider": ["aci_verified"]` | `400`, the block must be an object. | `aci_verified` and `aci_session_ids` are read by the gateway and removed before the request reaches a provider. They compose with the other `provider` fields, such as [`zdr`](/phala-cloud/confidential-ai/confidential-model/zero-data-retention). ## What the constraint guarantees The check runs before any prompt bytes leave the gateway: 1. The route is classified as an attested provider. 2. Verification is required for that route and cannot be waived by the request. 3. Verification returns a verified result and an enforceable channel binding. 4. The request is forwarded over the bound channel. Verification evidence is cached for a short interval and refreshed in the background, so a verified result may come from a recent check rather than one performed at that instant. The channel binding is enforced on every connection. If the upstream presents a key or certificate that does not match the binding, the gateway re-verifies and retries, then fails. A request is never served over a channel that does not match the evidence it was verified against. This constraint applies per request. There is no session to establish and reuse: every request is evaluated on its own, and each failover candidate is evaluated independently. ## Verify that it held A successful attested request returns `x-receipt-id`. Fetch that receipt and read its `upstream.verified` event: ```bash theme={"system"} curl -s "https://inference.phala.com/v1/aci/receipts/$RECEIPT_ID" \ -H "Authorization: Bearer " \ | jq '.event_log[] | select(.type == "upstream.verified")' ``` ```json theme={"system"} { "type": "upstream.verified", "model_id": "z-ai/glm-5.3", "result": "verified", "required": true, "session_id": "50b1e4ac17b1f10906595d322269b69e75ba15e03adb147490fa28eba4de8fc1" } ``` These fields record the gateway's assertion that the constraint held. Inspection alone does not verify it; verify the receipt signature, hashes, and cited session with the [TypeScript SDK](/phala-cloud/confidential-ai/verify/typescript-sdk) or [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy). `session_id` names the channel that served the request, and is the id to pin for follow-up requests. The cited session holds `channel_binding`, typed claims, and evidence; inspect its `upstream_name` rather than assuming a catalog provider name. See [Verify a Response](/phala-cloud/confidential-ai/verify/verify-signature). The request you sent is bound into the same receipt through `request.received.body_hash`, so you can prove which constraint you asked for alongside the result you got. ## Related > [card] [Receipts and Sessions](/phala-cloud/confidential-ai/confidential-model/receipts-and-sessions) > > What a session id identifies and how long it lives. > [card] [Channel Binding](/phala-cloud/confidential-ai/confidential-model/channel-binding) > > How a verified channel is enforced on the wire. > [card] [Zero Data Retention](/phala-cloud/confidential-ai/confidential-model/zero-data-retention) > > The retention constraint, which composes with this one. > [card] [Chat Completions](/phala-cloud/confidential-ai/confidential-model/api-reference/chat-completions) > > The full `provider` routing block. # Channel Binding Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/channel-binding Learn how the gateway binds confidential upstream verification to the actual request channel. Verifying an upstream's attestation is not enough by itself. The gateway must also prove it sends the prompt to the same verified endpoint. Channel binding closes that gap. For a confidential response, gateway verification and binding are one fact: if the provider cannot be verified and bound, the prompt is not forwarded. ## Binding Types | Binding | What it is | How it is enforced | | - | - | - | | `tls_spki_sha256` | SHA-256 digest of the upstream TLS public key (SPKI). | The gateway pins the HTTPS connection to that key before forwarding. | | `e2ee_public_key_sha256` | SHA-256 digest of the upstream E2EE public key. | The gateway encrypts the provider-facing request to the verified enclave key. | | `proxy_image_sha256` | Privatemode proxy image digest and startup-checked shared credential digest. | The gateway requires the binding to match the measured co-deployed proxy and sends plaintext only to its configured internal origin; the proxy handles provider-facing encryption. | The binding type depends on the provider. See [Providers](/phala-cloud/confidential-ai/confidential-model/providers). ## Fail-Closed Forwarding When `upstream.verified.required` is `true`, the gateway must verify the upstream and enforce the binding before forwarding. If verification fails, or if the binding cannot be enforced on the live connection, the gateway rejects instead of sending the prompt. ```mermaid theme={"system"} flowchart TD A[Confidential request] --> B{Upstream verified and binding enforceable?} B -->|Yes| C[Forward over bound channel] B -->|No| D[Reject before forwarding] ``` On the Phala TEE-only endpoint, `required` is `true` for every routed request. A failed verification refuses forwarding; it does not fall back to an unverified provider. ## How to Confirm Binding You do not enforce the provider binding from your client. You verify that the gateway did: 1. Verify the [Attestation Report](/phala-cloud/confidential-ai/confidential-model/api-reference/attestation). 2. Fetch the [Receipt](/phala-cloud/confidential-ai/confidential-model/api-reference/receipts). 3. Verify the receipt signature and exact request/response `body_hash` values; require `upstream.verified.result: verified`, `required: true`, and a `session_id`. 4. Fetch the full [Session](/phala-cloud/confidential-ai/confidential-model/api-reference/sessions), verify its content address and evidence, and inspect `channel_binding` under your policy. The [TypeScript SDK](/phala-cloud/confidential-ai/verify/typescript-sdk) and [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy) implement client-side checks. cURL inspection alone does not establish channel binding. ## Related > [card] [Trust Boundary](/phala-cloud/confidential-ai/confidential-model/trust-boundary) > [card] [TCB and Claims](/phala-cloud/confidential-ai/confidential-model/tcb-and-claims) # Compliance and Open Source Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/compliance-and-open-source Understand the technical controls, source provenance, and audit evidence behind Private AI. Phala Private AI is designed so privacy and integrity claims can be checked with technical evidence: attestation reports, source provenance, signed receipts, and provider verification records. > [!NOTE] > > Read [Trust Boundary](/phala-cloud/confidential-ai/confidential-model/trust-boundary) first. The gateway is attested and receipts do not retain request bodies, but plaintext is visible inside the attested gateway after TLS termination or E2EE (end-to-end encryption) decryption. ## Technical Controls | Control | How Private AI provides it | | - | - | | Data isolation | Gateway and confidential providers run in TEEs. | | Hardware-backed identity | The gateway publishes an attestation report with a TEE quote. | | Per-response auditability | Receipts bind request and response hashes to the attested workload. | | No body retention in receipts | Receipts store hashes and facts, not prompt or response text. | | Upstream zero data retention | `provider: {"zdr": true}` restricts routing to providers that do not retain prompt or completion content. Enforced fail-closed, including on failover. See [Zero Data Retention](/phala-cloud/confidential-ai/confidential-model/zero-data-retention). | | Confidential upstreams | For confidential responses, the upstream is verified and channel-bound before forwarding. | | Encryption in transit | TLS for all requests, with optional [E2EE](/phala-cloud/confidential-ai/confidential-model/e2ee-encryption). | ## Regulatory Fit | Requirement | How the architecture helps | | - | - | | Data minimization | Gateway receipts avoid storing request and response bodies. Request `zdr` to extend the constraint to the upstream provider. | | Storage limitation | Zero-data-retention providers do not keep prompt or completion content after serving a request. | | Confidential processing | TEE isolation and attestation provide verifiable runtime identity. | | Audit evidence | Attestation reports, receipts, sessions, and source provenance can be retained by the customer. | | Provider separation | Receipts cite the verified upstream session; its claims describe provider-specific evidence coverage. | For regulated data, use confidential responses and verify `upstream.verified.result = verified`, `required = true`, and the provider claims your policy requires. ## Source Provenance Every gateway attestation report includes `attestation.source_provenance`: ```json theme={"system"} { "repo_url": "https://github.com/Dstack-TEE/private-ai-gateway.git", "repo_commit": "9d45c7e3d48d2f74c31cd85f1fb5c6cee1435ef3", "image_digest": null, "image_provenance": null } ``` These are workload-declared inspection labels, not a trust root. Replay the measured event log to RTMR3, match `sha256(app_compose)` to the measured compose hash, and require an independently obtained compose allowlist for reviewed-release enforcement. See [Verify Attestation](/phala-cloud/confidential-ai/verify/verify-attestation). ## Relevant Repositories > [card] [private-ai-gateway](https://github.com/Dstack-TEE/private-ai-gateway) > > ACI gateway, attestation reports, receipts, and provider verification. > [card] [dstack](https://github.com/Dstack-TEE/dstack) > > TEE runtime and KMS used for workload identity and quote generation. ## What to Audit * Attestation report generation and nonce binding. * JCS keyset digest, expiry, key custody, and receipt signing keys. * Provider verification and channel binding. * Receipt event log construction. * Fail-closed behavior when confidential upstream verification is required. * Source provenance and image provenance for production releases. ## Enterprise Documentation Compliance reports, enterprise security reviews, DPAs, BAAs, and certification scope can change over time. Request current documents from Phala through your account or enterprise support channel. ## Related > [card] [Attestation Report](/phala-cloud/confidential-ai/confidential-model/api-reference/attestation) > [card] [Receipts and Sessions](/phala-cloud/confidential-ai/confidential-model/receipts-and-sessions) # On-demand API Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/confidential-ai-api Make your first OpenAI-compatible Private AI request through Phala, then confirm it was served through an attested gateway. ## Overview The on-demand Private AI API provides an OpenAI-compatible interface for confidential inference. Requests go through Phala's ACI gateway at `https://inference.phala.com/v1`. The gateway runs in a TEE, publishes an attestation report, and signs a per-response receipt that you can verify. ## Prerequisites Private AI is paid from your workspace Balance, the same Balance that pays for CVMs and GPU instances. There is no separate top-up and no minimum: if your Balance has money, the API works. Gifted credits do not pay for Private AI. In the dashboard, go to **Private AI** → **API Keys** and create your first API key. Click the key to copy it. ![GPU TEE API Generate Key](https://mintcdn.com/phalanetwork-1606097b/416gZMDMREnPDd33/images/confidential-ai/confidential-model/api-keys.png?fit=max\&auto=format\&n=416gZMDMREnPDd33\&q=85\&s=74fe03c7de5d4e99800da48f5c3e5cb9) Once you get the API Key, you can start making requests to the Private AI API. ## Make Your First Request Replace `` with your actual API key. The examples below use `z-ai/glm-5.3`; use [List Models](/phala-cloud/confidential-ai/confidential-model/api-reference/models) to choose a model for your workload. ```python Python theme={"system"} # Install OpenAI SDK: `pip3 install openai` from openai import OpenAI client = OpenAI( api_key="", base_url="https://inference.phala.com/v1", ) response = client.chat.completions.create( model="z-ai/glm-5.3", messages=[ {"role": "system", "content": "You are a helpful assistant"}, {"role": "user", "content": "What is your model name?"}, ], ) print(response.choices[0].message.content) ``` ```typescript TypeScript theme={"system"} import OpenAI from 'openai'; const client = new OpenAI({ baseURL: 'https://inference.phala.com/v1', apiKey: '', }); async function main() { const completion = await client.chat.completions.create({ model: 'z-ai/glm-5.3', messages: [ { role: 'user', content: 'What is the meaning of life?', }, ], }); console.log(completion.choices[0].message); } main(); ``` ```bash CLI theme={"system"} curl -X 'POST' \ 'https://inference.phala.com/v1/chat/completions' \ -H 'accept: application/json' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ -d '{ "messages": [ { "content": "You are a helpful assistant.", "role": "system" }, { "content": "What is your model name?", "role": "user" } ], "model": "z-ai/glm-5.3" }' ``` The response is a standard OpenAI chat completion. In raw HTTP responses, Phala also returns verification headers: | Header | Meaning | | - | - | | `x-receipt-id` | Receipt id for this response. Use it with `GET /v1/aci/receipts/{id}`. | | `x-aci-keyset-digest` | Digest of the gateway keyset used for receipt verification. | ## Inspect the Response Receipt Fetch the receipt with the `x-receipt-id` header: ```bash theme={"system"} curl -s "https://inference.phala.com/v1/aci/receipts/$RECEIPT_ID" \ -H "Authorization: Bearer " | \ jq '.event_log[] | select(.type=="upstream.verified") | {model_id, result, required, session_id}' ``` On this TEE-only endpoint, successful upstream verification records `result: verified` and `required: true`; a failed required check refuses forwarding. This command only inspects the receipt. Ordinary SDK clients and cURL do not verify the gateway or each response. For client-side verification, use the [TypeScript ACI verifier](/phala-cloud/confidential-ai/verify/typescript-sdk) or [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy). ## Choose a Model The live catalog is authoritative; query it before hardcoding model IDs: ```bash theme={"system"} curl https://inference.phala.com/v1/models ``` The catalog is public and authoritative for availability, pricing, context limits, modalities, and capabilities. Embedding models are listed separately at `GET /v1/embeddings/models`. > [!NOTE] > > Every model served at this Phala endpoint uses the TEE-only policy. Provider evidence covers different boundaries; inspect the cited session and apply the claims your policy requires. The catalog describes capabilities, while a verified receipt and session bind a specific exchange. > [!NOTE] > > Confidential inference and zero data retention are separate properties. `is_tee` constrains who can read memory during execution. `zdr` constrains whether the upstream stores prompt or completion content after serving. Use [`GET /v1/models?zdr=true`](/phala-cloud/confidential-ai/confidential-model/api-reference/models#query-parameters) and `provider: {"zdr": true}` when retention is part of your policy. ## Verify Your AI is Running Securely The verification client checks a fresh [attestation report](/phala-cloud/confidential-ai/confidential-model/api-reference/attestation), recomputes the JCS keyset digest, checks its expiry and measured compose, and pins TLS before traffic. After the response it checks the [receipt](/phala-cloud/confidential-ai/confidential-model/api-reference/receipts) signature, `workload_keyset_digest`, exact request/response `body_hash` values, and cited upstream session. See [Verify a Response](/phala-cloud/confidential-ai/verify/verify-signature). The legacy [Signature](/phala-cloud/confidential-ai/confidential-model/api-reference/signature) endpoint remains available for older clients, but new integrations should use `GET /v1/aci/receipts/{id}`. ## Billing Private AI usage is charged to your workspace Balance. The response's `usage.cost` reports the request charge in USD when present. Token prices are published in the live catalog. Cached input tokens are charged at `pricing.input_cache_read` when a model exposes that rate, otherwise at its normal prompt rate; see [Prompt Caching](/phala-cloud/confidential-ai/confidential-model/prompt-caching). [Image generation](/phala-cloud/confidential-ai/confidential-model/api-reference/images) is charged per returned image at the catalog's `pricing.image_generation` rate in USD per image. [Audio transcription](/phala-cloud/confidential-ai/confidential-model/api-reference/audio) is charged per started second of input audio at `pricing.audio_transcription` in USD per second: `2.965` seconds is billed as `3` seconds. Zero token counts do not imply that image or audio requests are free. ## Next Steps Use the API reference and feature guides for the next step: * [Chat Completions](/phala-cloud/confidential-ai/confidential-model/api-reference/chat-completions) documents the core request and response shape. * [List Models](/phala-cloud/confidential-ai/confidential-model/api-reference/models) shows how to discover models programmatically. * [Get Receipt](/phala-cloud/confidential-ai/confidential-model/api-reference/receipts) documents the canonical per-response proof. * [Embeddings](/phala-cloud/confidential-ai/confidential-model/api-reference/embeddings) covers embedding model calls. * [Tool Calling](/phala-cloud/confidential-ai/confidential-model/tool-calling) helps you call tools from your AI models. * [Images and Vision](/phala-cloud/confidential-ai/confidential-model/images-and-vision) helps you use image-capable models. * [Structured Output](/phala-cloud/confidential-ai/confidential-model/structured-output) helps you get JSON responses. * [Streaming](/phala-cloud/confidential-ai/confidential-model/streaming) helps you consume streaming responses. * [Zero Data Retention](/phala-cloud/confidential-ai/confidential-model/zero-data-retention) helps you route requests only to serving routes that do not retain prompt or completion content. * [Playground](/phala-cloud/confidential-ai/confidential-model/playground) helps you test models in a private environment. # End-to-End Encryption Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/e2ee-encryption Add field-level encryption to Private AI requests with keys published in the attested gateway keyset. End-to-end encryption (E2EE) adds field-level encryption between your client and the attested gateway, on top of TLS. TLS still protects the HTTP connection. E2EE additionally encrypts selected request and response fields to a public key that comes from the gateway's verified attestation report. E2EE is useful when you want the encryption key itself to be cryptographically tied to the TEE workload you verified. > [!NOTE] > > E2EE decrypts inside the attested gateway so the gateway can process the request. It proves the decryption key belongs to the verified gateway; it does not hide plaintext from that gateway. Use confidential models when the upstream model provider must also be attested. ## Get the Gateway E2EE Key Fetch and verify the gateway attestation report, then read the E2EE key from the attested keyset: ```bash theme={"system"} curl -s "https://inference.phala.com/v1/aci/attestation?nonce=$(openssl rand -hex 32)" \ -H "Authorization: Bearer $PHALA_AI_API_KEY" \ | jq -r '.attestation.workload_keyset.e2ee_public_keys[] | select(.key_id=="dstack-kms-e2ee-v1") | .public_key' ``` The key algorithm is `secp256k1-aes-256-gcm-hkdf-sha256`. The gateway advertises supported E2EE versions in `service_capabilities.supported_e2ee_versions`. ## Request Headers Include these headers when sending an E2EE request: | Header | Value | | - | - | | `X-E2EE-Version` | `2` | | `X-Client-Pub-Key` | Your secp256k1 public key, hex encoded. | | `X-Model-Pub-Key` | The gateway E2EE public key from the attested keyset. | | `X-E2EE-Nonce` | Unique per-request nonce. | | `X-E2EE-Timestamp` | Unix seconds, close to gateway time. | Do not send `X-Signing-Algo` with E2EE. That header selects the legacy signature compatibility path. ## Ciphertext Format Each encrypted field is lowercase hex encoding of: ```text theme={"system"} ephemeral_uncompressed_secp256k1_public_key || aes_gcm_nonce || ciphertext_tag ``` The AEAD associated data binds ciphertext to the protocol version, direction, algorithm, model, field path, nonce, timestamp, and response identity. If any of those values change, decryption fails. > [!WARNING] > > Do not build this manually unless you are implementing a client library. Use official client or verifier helpers when available, because AAD construction and field selection must match the gateway exactly. ## Receipts with E2EE Receipts work the same way for E2EE requests. The response still includes `x-receipt-id`, and you still verify the receipt with [Get Receipt](/phala-cloud/confidential-ai/confidential-model/api-reference/receipts). For E2EE, `request.received.body_hash` is the hash of the gateway-observed decrypted body, not the encrypted wire body. Compare it with the decrypted request body your client holds. ## Related > [card] [Trust Boundary](/phala-cloud/confidential-ai/confidential-model/trust-boundary) > [card] [Verify a Response](/phala-cloud/confidential-ai/verify/verify-signature) # Error Handling Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/error-handling Handle Private AI API errors, retries, unsupported parameters, and upstream failures. ## Error Response Format Errors return a JSON body with an `error` object and an HTTP status code: ```json theme={"system"} { "error": { "message": "Invalid API key provided", "type": "authentication_error", "code": null, "param": null } } ``` The `type` field is the machine-readable discriminator. | `type` | Meaning | | - | - | | `authentication_error` | Missing or invalid API key. | | `invalid_request_error` | Malformed request body or unsupported parameter. | | `model_not_found` | The requested model id is unavailable. | | `not_found_error` | The model exists but no serving route can satisfy the request constraints, for example `provider: {"zdr": true}`. | | `session_not_accepted` | None of the requested attested session ids is currently accepted (`412`); refresh and verify the session before retrying. | | `upstream_verification_failed` | Required upstream verification failed or no eligible attested upstream is available (`503`); no prompt is forwarded. | | `upstream_error` | The upstream provider failed or timed out. | ## Status Codes | Status | Meaning | | - | - | | `400` | Bad request, unknown model, or invalid parameter. | | `401` | Missing or invalid API key. | | `403` | Forbidden, for example your Balance is too low to fund Private AI. Top up, and calls work again within about 5 minutes. | | `404` | No eligible route under the request constraints, or an unknown/expired receipt or session. | | `412` | No requested attested session is currently accepted (`session_not_accepted`). | | `429` | Rate limited. | | `500` | Gateway server error. | | `502` | Upstream provider unavailable. | | `503` | Service temporarily unavailable, including required upstream verification failure (`upstream_verification_failed`). | ## SDK Handling ```python theme={"system"} import os import time from openai import OpenAI, AuthenticationError, RateLimitError, APIError client = OpenAI( base_url="https://inference.phala.com/v1", api_key=os.environ["PHALA_AI_API_KEY"], ) try: response = client.chat.completions.create( model="z-ai/glm-5.3", messages=[{"role": "user", "content": "Hello"}], ) except AuthenticationError: print("Invalid API key") except RateLimitError: print("Rate limited; retry with backoff") except APIError as e: print(f"API error {e.status_code}: {e.message}") ``` ## Retry Policy Retry only transient errors: * Retry `429`, `500`, `502`, and `503` with exponential backoff. * Do not retry `400` or `401` until you fix the request or key. * For `412 session_not_accepted`, refresh and verify an accepted session before retrying; do not retry the same stale pin. * If a confidential upstream verification fails, treat it as a failed security condition, not a normal retry loop, unless the API response documents it as transient. ```python theme={"system"} from openai import RateLimitError, APIError def with_retry(call, max_retries=3): for attempt in range(max_retries): try: return call() except (RateLimitError, APIError) as e: status = getattr(e, "status_code", 500) if status in (429, 500, 502, 503) and attempt < max_retries - 1: time.sleep(2 ** attempt) continue raise ``` ## Common Cases > [accordion] Invalid API key > > Confirm the `Authorization: Bearer ` header, check for whitespace, and create a fresh key from the Phala dashboard if needed. > [accordion] Unknown model > > List valid model ids with [`GET /v1/models`](/phala-cloud/confidential-ai/confidential-model/api-reference/models). Do not assume a model id exists until it appears in the catalog. > [accordion] No zero-data-retention route > > A request with `provider: {"zdr": true}` returns `404` when the selected model has no available zero-data-retention route. Query [`GET /v1/models?zdr=true`](/phala-cloud/confidential-ai/confidential-model/api-reference/models#query-parameters) before sending sensitive prompts that require this property. > [accordion] Unsupported parameter > > Some models support `max_tokens`; others require `max_completion_tokens`. Check `supported_parameters` in `/v1/models`. > [accordion] Rate limited > > Back off and retry. For sustained high volume, use dedicated GPU TEE capacity. > [accordion] Upstream unavailable > > Retry after backoff or choose another model. For sensitive prompts, confirm the replacement model returns `upstream.verified.result = verified`. ## Best Practices * Branch on HTTP status and `error.type`, not message text. * Keep API keys in environment variables or a secret manager. * Never log request bodies for sensitive prompts. * Verify `x-receipt-id` when the response is security-sensitive. # Images and Vision Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/images-and-vision Learn how to use images and vision models in Private AI. ## Images and Vision in Private AI Private AI supports various images and vision models, enabling you to leverage the power of visual data in a secure and confidential manner. ## Analyze images You can use vision models to analyze images, including image recognition, object detection, and image classification. Replace `` with your actual API key in the examples below. ```python theme={"system"} from openai import OpenAI client = OpenAI( base_url="https://inference.phala.com/v1", api_key="", ) response = client.chat.completions.create( model="qwen/qwen3-vl-30b-a3b-instruct", messages=[{ "role": "user", "content": [ { "type": "text", "text": "What is in this image?" }, { "type": "image_url", "image_url": { "url": "https://upload.wikimedia.org/wikipedia/commons/6/67/Giant_Pandas_having_a_snack.jpg" } } ] }], ) print(response.choices[0].message.content) ``` > [accordion] Sample output of image analysis request > > ```text theme={"system"} > Here's what I see in the image: > > * **Giant Pandas:** There are four young giant pandas in the image. They are black and white and appear to be playful. > * **Bamboo:** The scene is full of lush, green bamboo. The pandas are among the bamboo and seemingly eating it. > * **Greenery:** Besides the bamboo, there is other green vegetation surrounding the pandas. > * **Dirt mound:** The pandas are partially sitting on a raised earth mound. > * **Outdoor Setting:** It appears to be a natural or zoo-like outdoor enclosure. > > The overall impression is of a cute and peaceful scene with baby pandas enjoying their habitat. > ``` ### Find Compatible Models ```bash theme={"system"} curl -s https://inference.phala.com/v1/models \ | jq -r '.data[] | select((.input_modalities // []) | index("image")) | .id' ``` # Migration and Integrations Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/migration-and-integrations Migrate from OpenAI or OpenRouter and connect SDKs, observability tools, and gateways. Phala Private AI is OpenAI-compatible. Most integrations require changing only the base URL and API key: ```text theme={"system"} https://inference.phala.com/v1 ``` After migration, responses can be verified with `x-receipt-id`, [Attestation Report](/phala-cloud/confidential-ai/confidential-model/api-reference/attestation), and [Get Receipt](/phala-cloud/confidential-ai/confidential-model/api-reference/receipts). ## Migrate from OpenAI ```python theme={"system"} from openai import OpenAI # Before openai_client = OpenAI(api_key="sk-...") # After phala_client = OpenAI( api_key="YOUR_PHALA_API_KEY", base_url="https://inference.phala.com/v1", ) ``` Everything else stays familiar: chat completions, streaming, tool calling, vision, structured output, and embeddings use OpenAI-compatible request shapes. ## Migrate from OpenRouter ```python theme={"system"} from openai import OpenAI client = OpenAI( base_url="https://inference.phala.com/v1", api_key="YOUR_PHALA_API_KEY", ) ``` Model ids use the provider/model format returned by `/v1/models`. Verify the actual response receipt when you need evidence for an exchange. ## OpenAI SDK ```python Python theme={"system"} from openai import OpenAI client = OpenAI( api_key="YOUR_PHALA_API_KEY", base_url="https://inference.phala.com/v1", ) response = client.chat.completions.create( model="z-ai/glm-5.3", messages=[{"role": "user", "content": "Explain TEE privacy."}], ) print(response.choices[0].message.content) ``` ```typescript TypeScript theme={"system"} import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.PHALA_AI_API_KEY, baseURL: "https://inference.phala.com/v1", }); const response = await client.chat.completions.create({ model: "z-ai/glm-5.3", messages: [{ role: "user", content: "Explain TEE privacy." }], }); ``` ## LangChain ```python theme={"system"} from langchain_openai import ChatOpenAI chat = ChatOpenAI( model="z-ai/glm-5.3", api_key="YOUR_PHALA_API_KEY", base_url="https://inference.phala.com/v1", ) response = chat.invoke("Explain confidential inference in one paragraph.") print(response.content) ``` ## Vercel AI SDK ```typescript theme={"system"} import { generateText } from "ai"; import { createOpenAI } from "@ai-sdk/openai"; const phala = createOpenAI({ apiKey: process.env.PHALA_AI_API_KEY, baseURL: "https://inference.phala.com/v1", }); const { text } = await generateText({ model: phala("z-ai/glm-5.3"), prompt: "Explain attestation.", }); ``` ## Langfuse ```python theme={"system"} import os from langfuse.openai import OpenAI os.environ["LANGFUSE_PUBLIC_KEY"] = "pk-lf-..." os.environ["LANGFUSE_SECRET_KEY"] = "sk-lf-..." os.environ["LANGFUSE_HOST"] = "https://cloud.langfuse.com" client = OpenAI( api_key="YOUR_PHALA_API_KEY", base_url="https://inference.phala.com/v1", ) ``` > [!WARNING] > > Observability tools may store prompts, responses, metadata, or traces. For sensitive data, configure redaction or self-hosting before sending production traffic. For custom Node.js or Bun applications, use the [TypeScript ACI Verifier](/phala-cloud/confidential-ai/verify/typescript-sdk) to inject a pinned `fetch` and audit signed receipts in code. ## Gateways ### Cloudflare AI Gateway In **Compute & AI → AI Gateway → Custom Providers → Add Custom Provider**, set **Provider Name** to `Phala`, **Provider Slug** to `phala`, and **Base URL** to `https://inference.phala.com`, then save and enable the provider. Cloudflare's [custom-provider routing](https://developers.cloudflare.com/ai-gateway/configuration/custom-providers/) appends the path after `custom-phala/`, so the request includes `/v1/chat/completions`. For authenticated gateways, also send `cf-aig-authorization`: ```bash theme={"system"} curl "https://gateway.ai.cloudflare.com/v1/$CLOUDFLARE_ACCOUNT_ID/$CLOUDFLARE_GATEWAY_ID/custom-phala/v1/chat/completions" \ -H "Authorization: Bearer $PHALA_AI_API_KEY" \ -H "cf-aig-authorization: Bearer $CF_AIG_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "model": "z-ai/glm-5.3", "messages": [{"role": "user", "content": "Hello!"}] }' ``` ### LiteLLM Add this model to your LiteLLM proxy `config.yaml` using its [generic OpenAI-compatible route](https://docs.litellm.ai/docs/providers/openai_compatible). Set `PHALA_AI_API_KEY` in the proxy's environment and start it with `litellm --config config.yaml`: ```yaml theme={"system"} model_list: - model_name: phala-glm litellm_params: model: openai/z-ai/glm-5.3 api_base: https://inference.phala.com/v1 api_key: os.environ/PHALA_AI_API_KEY ``` Clients of the proxy use `phala-glm` as their model name; LiteLLM sends `z-ai/glm-5.3` to Phala. ## Migration Checklist * [ ] Create a Phala API key. * [ ] Change the base URL to `https://inference.phala.com/v1`. * [ ] List models with `GET /v1/models`. * [ ] Use a catalog model; every model on this endpoint runs in a TEE. * [ ] Capture `x-receipt-id` in raw HTTP responses when you need verification. * [ ] Verify one representative response before production rollout. ## Related > [card] [Use in Agents](/phala-cloud/confidential-ai/agents/overview) > [card] [On-demand API](/phala-cloud/confidential-ai/confidential-model/confidential-ai-api) > [card] [Error Handling](/phala-cloud/confidential-ai/confidential-model/error-handling) # Playground Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/playground Learn how to use Open-WebUI to play with Private AI models ## How to setup playground environment If you want to interact with Private AI models with web UI instead of command line tools, we recommend using Open-WebUI. It is a web-based interface for Private AI models. It allows you to play with models, test prompts, and visualize the results in real-time. ## Deploy Open-WebUI You could deploy Open-WebUI on your local machine or Phala Cloud. It is recommended to deploy Open-WebUI on Phala Cloud with this [Open-WebUI one-click deploy template](https://cloud.phala.com/templates/open-webui). Or if you prefer try it locally, you could deploy it on your local machine with this [docker compose file](https://github.com/Phala-Network/phala-cloud/blob/main/templates/prebuilt/openwebui/docker-compose.yml). If you deploy Open-WebUI on Phala Cloud, once it is deployed, you could access it by opening the `Endpoint #1` in Network tab of CVM instance details. ![Open-WebUI Endpoint](https://mintcdn.com/phalanetwork-1606097b/YlUFrX-O4VDGXMEg/images/confidential-ai/confidential-model/open-webui-01.png?fit=max\&auto=format\&n=YlUFrX-O4VDGXMEg\&q=85\&s=6289abaecec9755539bee144ac4f327f) ## Configure Open-WebUI Open-WebUI need to be configured with API key and base URL to connect to Private AI API. 1. Click right top user icon, and click `Admin Panel` to open Settings page. 2. Click `Connection` navigation item to open Connection settings page. 3. In Connection settings page, click setting icon to fill in the `URL` with `https://inference.phala.com/v1`, input Bearer token with your API key, and then click `Save` button. 4. Once the connection is saved, you could start using Open-WebUI to play with Private AI models. ![Open-WebUI Connection Settings](https://mintcdn.com/phalanetwork-1606097b/YlUFrX-O4VDGXMEg/images/confidential-ai/confidential-model/open-webui-02.png?fit=max\&auto=format\&n=YlUFrX-O4VDGXMEg\&q=85\&s=74da3c156c6893344b20e742975cbccd) In this private playground environment, you could play with Private AI models with highly secure and private data without any data leakage. # Prompt caching Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/prompt-caching Providers that cache a repeated prompt prefix report cached tokens in usage, and Phala bills them at the model's cache rate. Prompt caching happens at the provider and needs nothing in the request. When a provider serves part of a prompt from its cache, the response reports it in `usage`, and the cached tokens are billed at `pricing.input_cache_read` when the model lists one, otherwise at the normal prompt rate. ```json theme={"system"} { "usage": { "prompt_tokens": 1905, "prompt_tokens_details": {"cached_tokens": 1792}, "completion_tokens": 64 } } ``` To benefit, keep the stable part of a prompt, such as the system message and reference material, at the start, and vary only the end. Cache eligibility and prefix thresholds depend on the provider. Which models expose a cache rate is visible in the catalog: look for `input_cache_read` in `pricing`. ## Related > [card] [Billing](/phala-cloud/confidential-ai/confidential-model/confidential-ai-api#billing) > [card] [Models](/phala-cloud/confidential-ai/confidential-model/api-reference/models) # Provider Verification Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/providers Understand the evidence and channel bindings for each provider in Phala's live catalog. Every model served at `https://inference.phala.com/v1` uses the TEE-only policy. The Phala gateway requires upstream verification and an enforceable channel binding before forwarding your prompt. Evidence coverage varies by provider: a verified router, a model instance, and a provider broker prove different boundaries. The public [model catalog](/phala-cloud/confidential-ai/confidential-model/api-reference/models) lists serving providers in `providers`. The receipt identifies the session that actually served a response; inspect that session's `upstream_name`, `verifier_id`, `channel_binding`, `claims`, and `evidence`. A route label such as `phala-267` is distinct from the catalog provider `phala`. ## Provider evidence These are the providers in the live catalog. Availability changes; the catalog and each response's verified session remain authoritative. | Catalog provider | What the gateway verifier checks and binds | Evidence boundary | | - | - | - | | `phala` | dstack TDX quote, nonce and signing-address/TLS-SPKI report-data binding, measured compose, and available GPU evidence; pins upstream TLS. | A Phala dstack model CVM. GPU claims depend on verified, nonce-bound evidence. | | `chutes` | Instance TDX evidence and verified instance encryption keys; binds forwarding to a verified ML-KEM E2EE key. | Model instance. Inspect the session for GPU evidence and claim status rather than assuming a CPU-to-GPU binding. | | `tinfoil` | The official verifier checks enclave evidence, release/code measurements, and router TLS SPKI. | The confidential model router. The gateway does not independently attest each model worker through this verifier. | | `near-ai` | Nonce-bound gateway TDX evidence and TLS SPKI; pins the verified gateway channel. | The NEAR AI gateway. Per-model backend verification is delegated to that gateway. | | `privatemode` | The official proxy is co-deployed in the gateway's measured compose. Its readiness follows initial Contrast verification and secret exchange; requests and successful responses use Privatemode OAE protection. | The measured proxy and its Contrast-attested secret path. The observed dynamic manifest is not bound to the active inference secret and is not proof of a particular serving manifest. | | `fortanix` | The `armet-ai` verifier checks nonce-bound TDX evidence, TLS SPKI, model-id/GPU-evidence report-data commitments, NRAS GPU verification, and an operator-pinned TD measurement profile. | The per-model Armet AI TD. Matching a configured measurement pin does not independently establish model-weight provenance. | | `0g-private-computer` | Native verifier checks provider-broker TDX evidence, a pinned boot chain, and report-data-bound encryption/signing keys; forwarding uses the verified E2EE key. | The provider broker TEE. `plaintext_destination_verified: false` means the evidence does not independently establish the plaintext inference destination. | The implementation is public in the [gateway provider verifiers](https://github.com/Dstack-TEE/private-ai-gateway/tree/main/src/aci/verifier) and [provider evidence bridges](https://github.com/Dstack-TEE/private-ai-gateway/tree/main/scripts/provider_verifier). ## Binding methods | Binding | Meaning | | - | - | | `tls_spki_sha256` | Pins the provider-facing HTTPS connection to a verified TLS key. | | `e2ee_public_key_sha256` | Encrypts the provider-facing request to a verified key. | | `proxy_image_sha256` | Binds Privatemode forwarding to the co-deployed proxy's measured image (`proxy_image_digest`) and startup-checked shared credential digest (`credential_sha256`); plaintext is sent only to its configured internal origin. | Bindings and typed claims are in the **session**, referenced by the receipt's `upstream.verified.session_id`. The receipt event records `model_id`, `result`, `required`, and `session_id`; do not assume it embeds all verification details. ## Claim coverage Claims have lowercase statuses `asserted`, `refuted`, or `unknown`, and a source that distinguishes hardware proof, verifier derivation, and provider/operator assertions. * `tee_attested` describes the verified TEE boundary above. Check its `source` as well as its `status`: Privatemode reports `verifier_derived`, based on the measured proxy and its Contrast-attested secret path, rather than `hardware_proven`. * `tcb_up_to_date` can be `refuted` for a stale TCB; successful verification does not silently turn it into an up-to-date claim. * `serving_software_known_good` depends on the verifier's measurement/provenance policy. * `gpu_attested` depends on provider evidence. A genuine GPU attestation alone does not establish its binding to the serving CPU TEE. * `model_weights_provenance` is not generally proven. Treat `unknown` as unproven. Zero data retention is a separate property. Send `provider: {"zdr": true}` when the provider must not keep prompt or completion content after serving. See [Zero Data Retention](/phala-cloud/confidential-ai/confidential-model/zero-data-retention). Ordinary clients do not verify each response. Use the [TypeScript ACI verifier](/phala-cloud/confidential-ai/verify/typescript-sdk) or [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy) for client-side verification. ## Related > [card] [TCB and Claims](/phala-cloud/confidential-ai/confidential-model/tcb-and-claims) > [card] [Receipts and Sessions](/phala-cloud/confidential-ai/confidential-model/receipts-and-sessions) # Reasoning Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/reasoning Control how much a model thinks before it answers, and whether the reasoning text is returned. Reasoning models think before they answer. Ask for more or less of it with the `reasoning` object, and choose whether the reasoning text comes back. A model supports it when its `supported_features` in [`GET /v1/models`](/phala-cloud/confidential-ai/confidential-model/api-reference/models) include `reasoning`. Supported effort levels and token budgets depend on the selected model and serving route. ## Set the effort ```json theme={"system"} { "model": "z-ai/glm-5.3", "messages": [{"role": "user", "content": "What is 17 * 23?"}], "reasoning": {"effort": "low"} } ``` `effort` is one of `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max`. The OpenAI-style `reasoning_effort` field is accepted as an alias; if both are sent they must match. Instead of an effort, `reasoning.max_tokens` sets a token budget for thinking. The two are mutually exclusive, and a model that cannot express a budget returns `400`. ## Read or hide the reasoning Models that return their reasoning put it in `message.reasoning_content`, or `delta.reasoning_content` while streaming. Reasoning text availability depends on the model and provider. When reported, `usage.completion_tokens_details.reasoning_tokens` counts the thinking, and it is billed as completion tokens. To keep the reasoning out of the response, send `"reasoning": {"exclude": true}` or `"include_reasoning": false`. The tokens are still generated and billed. ## Related > [card] [Chat completions](/phala-cloud/confidential-ai/confidential-model/api-reference/chat-completions) > [card] [Billing](/phala-cloud/confidential-ai/confidential-model/confidential-ai-api#billing) # Receipts and Sessions Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/receipts-and-sessions Learn how per-response receipts and attested sessions prove what happened to a Private AI request. Receipts and sessions are the two response-level artifacts you use after verifying the gateway attestation report. * A **receipt** is the signed record for one response. * A **session** is the immutable verified security context for a confidential upstream channel. ## Receipt Lifecycle A completed inference response identifies its receipt with `x-receipt-id`. A stream whose headers were committed before the id was allocated may instead require lookup by response id after completion. Fetch it with [Get Receipt](/phala-cloud/confidential-ai/confidential-model/api-reference/receipts): ```bash theme={"system"} curl "https://inference.phala.com/v1/aci/receipts/$RECEIPT_ID" \ -H "Authorization: Bearer $PHALA_AI_API_KEY" ``` The receipt records ordered events with hashes and facts, not prompt text. | Event | What it records | | - | - | | `request.received` | Hash of the request body observed by the gateway. | | `route.selected` | Selected backend route. | | `request.forwarded` | Hash of the provider-facing request. | | `upstream.verified` | `model_id`, `result`, `required`, and the `session_id` for verification details. | | `response.received` | Hash of the provider response before post-processing. | | `response.returned` | Hash of the final wire response. | ## What a Receipt Proves A verified receipt proves: 1. The receipt was signed by a key in the attested gateway keyset. 2. `workload_keyset_digest` matches the verified attestation report. 3. The exact request bytes match `request.received.body_hash`, and the returned response bytes match `response.returned.body_hash`. 4. The required upstream verification result is recorded. On this TEE-only endpoint `required` is `true`; a failed check refuses forwarding. Receipt signatures cover the JCS form of the full receipt with `signature` removed. Resolve `key_id` in the verified keyset's `receipt_signing_keys`; the Phala key is `dstack-kms-receipt-ed25519-v1` (`ed25519`). Hash comparisons alone do not verify the signature or attestation. Use the [TypeScript SDK](/phala-cloud/confidential-ai/verify/typescript-sdk) or [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy). ## Streaming Responses For streaming, `x-receipt-id` can arrive before the stream ends. Fetch the receipt after the stream completes because `response.returned.body_hash` covers the full response body. ## Attested Sessions When the gateway verifies a confidential upstream, it records an attested session. A receipt references it from `upstream.verified.session_id`. A session captures: * Verified upstream identity and endpoint. * Enforced channel binding. * Typed claims and reasons. * Evidence digest and evidence payload. The `session_id` is the bare 64-character lowercase SHA-256 digest of the complete session document in JCS form, with no prefix. It is not a field in the full document. If the material changes, the id changes. The list endpoint returns `{ "api_version": "aci/1", "sessions": [...] }`; entries include `session_id` but omit `evidence.data`. Fetch the full record before checking the content address. Filter the list with `?upstream_name=chutes` or `?model=z-ai/glm-5.3`. ## Trace a Response ```text theme={"system"} response -> x-receipt-id receipt -> upstream.verified.session_id session -> provider identity, binding, claims, evidence ``` The receipt records the attested gateway's assertion about the upstream. Independent upstream auditing also verifies the cited session's evidence and binding. Coverage varies by provider; apply the claims your policy requires. ## Related > [card] [Verify a Response](/phala-cloud/confidential-ai/verify/verify-signature) > [card] [TCB and Claims](/phala-cloud/confidential-ai/confidential-model/tcb-and-claims) # Streaming Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/streaming Learn how to use streaming in Private AI API ## Streaming in Private AI API Private AI API supports streaming, enabling you to receive responses in a streaming fashion. This is particularly useful for applications that require real-time data processing or integration with other systems. ### Example of Streaming Replace `` with your actual API key in the examples below. ```python Python theme={"system"} from openai import OpenAI client = OpenAI( api_key="", base_url="https://inference.phala.com/v1", ) stream = client.chat.completions.create( model="z-ai/glm-5.3", messages=[ { "role": "user", "content": "say `Hello` 2 times fast, no other output", }, ], stream=True, ) for chunk in stream: content = chunk.choices[0].delta.content if content: print(content, end="") ``` ```typescript TypeScript theme={"system"} import OpenAI from "openai"; const client = new OpenAI({ apiKey: "", baseURL: "https://inference.phala.com/v1", }); const stream = await client.chat.completions.create({ model: "z-ai/glm-5.3", messages: [ { role: "user", content: "say `Hello` 2 times fast, no other output" }, ], stream: true, }); for await (const chunk of stream) { process.stdout.write(chunk.choices[0]?.delta?.content || ""); } ``` > [accordion] Sample output of streaming request > > ```text theme={"system"} > HelloHello > ``` ### Supported Models All models support streaming. # Structured Output Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/structured-output Learn how to use structured output in Private AI ## Structured Output in Private AI Private AI supports structured output, enabling you to receive responses in specific formats such as JSON structures. This is particularly useful for applications that require data to be processed or integrated into other systems. ### Example of Structured Output Replace `` with your actual API key in the examples below. ```python theme={"system"} import requests response = requests.post( "https://inference.phala.com/v1/chat/completions", headers={ "Authorization": "Bearer ", "Content-Type": "application/json", }, json={ "model": "z-ai/glm-5.3", "messages": [ {"role": "user", "content": "What is the weather like in Los Angeles?"}, ], "response_format": { "type": "json_schema", "json_schema": { "name": "weather", "strict": True, "schema": { "type": "object", "properties": { "location": { "type": "string", "description": "City or location name", }, "temperature": { "type": "number", "description": "Temperature in Celsius", }, "conditions": { "type": "string", "description": "Weather conditions description", }, }, "required": ["location", "temperature", "conditions"], "additionalProperties": False, }, }, }, }, ) data = response.json() info = data["choices"][0]["message"]["content"] print(info) ``` > [accordion] Sample output of structured output > > ```json theme={"system"} > { > "location":"Los Angeles", > "temperature":75, > "conditions":"Sunny with a few clouds" > } > ``` ### Find Compatible Models ```bash theme={"system"} curl -s https://inference.phala.com/v1/models \ | jq -r '.data[] | select((.supported_features // []) | index("structured_outputs")) | .id' ``` # TCB and Claims Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/tcb-and-claims Interpret typed claims in receipts and attested sessions, including source, status, and TCB freshness. Confidential responses carry typed claims about the upstream that served the request, including TCB (Trusted Computing Base) freshness. Claims appear in the attested session referenced by the receipt's `upstream.verified.session_id`; the canonical receipt event does not embed the full claim set. A claim is not just a boolean. It has a status, a source, and often a reason. ```json theme={"system"} { "tee_attested": { "status": "asserted", "source": "hardware_proven", "reason": "verified TEE quote and bound request channel" } } ``` ## Claim Status | Status | Meaning | | - | - | | `asserted` | Evidence backs this claim. | | `refuted` | Evidence contradicts this claim, such as a stale TCB. | | `unknown` | The verifier did not establish this claim. Treat it as not proven. | ## Claim Source | Source | Assurance | | - | - | | `hardware_proven` | Comes from verified TEE quote or collateral. | | `verifier_derived` | Computed by the verifier from checked evidence. | | `provider_asserted` | Published by the provider, not independently proven. | | `operator_asserted` | Declared by the gateway operator. | ## Common Claims | Claim | Meaning | | - | - | | `tee_attested` | An attested TEE identity is bound to the channel, directly or through the measured proxy; inspect `source`. | | `tcb_up_to_date` | The platform Trusted Computing Base is current. | | `os_known_good` | The OS or platform image maps to reviewed source or known measurements. | | `serving_software_known_good` | Serving software maps to reviewed source or build provenance. | | `gpu_attested` | NVIDIA confidential-computing GPU evidence was verified and nonce-bound. | | `model_weights_provenance` | Model weights and quantization match a reviewed provenance chain. | Privatemode reports `tee_attested: asserted` with `source: verifier_derived` under verifier `privatemode-proxy/co-deployed-contrast/v1`. It relies on the measured co-deployed proxy and its Contrast-attested secret path, rather than a provider quote verified directly by the gateway. Its other common claims are `unknown`. ## TCB Freshness `tcb_up_to_date` is intentionally tri-state: * Up-to-date evidence asserts the claim. * Stale evidence refutes the claim and records the stale status. * Missing evidence leaves the claim `unknown`. Your verifier policy decides whether a refuted TCB is acceptable. The receipt's job is to expose the fact. ## GPU Attestation `gpu_attested` proves a confidential-computing GPU attestation was verified for the provider's evidence. It does not by itself prove model weights, serving software, or CPU-to-GPU binding for every provider. Read it as supplemental evidence unless your policy says otherwise. ## Suggested Policy 1. For direct hardware proof, require `tee_attested: asserted` from `hardware_proven`. This policy excludes Privatemode's `verifier_derived` sessions. 2. Require `upstream.verified.result = verified` and `required = true` for sensitive prompts. 3. Treat `unknown` as not proven. 4. Decide whether to reject `tcb_up_to_date: refuted`. 5. Use `serving_software_known_good` and `gpu_attested` to increase assurance when available. ## Related > [card] [Providers](/phala-cloud/confidential-ai/confidential-model/providers) > [card] [Get Session](/phala-cloud/confidential-ai/confidential-model/api-reference/sessions) # Tool Calling Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/tool-calling Quick guide for how to tool calling (or function calling) of Private AI API. ## Tool Calling in Private AI Tool calling, also known as function calling, enables AI models to interact with external systems by invoking predefined functions or APIs. This allows the model to access up-to-date information, perform specific actions, or integrate with other services, extending its capabilities beyond static knowledge. Deploy [custom fine-tuned models](https://phala.com/solutions/fine-tuned-models) with proprietary tool definitions for specialized use cases. Here we provide a simple example of tool calling. ## Define the Tool Use following request to create a function named `get_weather`. ```bash theme={"system"} curl -s -X POST 'https://inference.phala.com/v1/chat/completions' \ -H 'Authorization: Bearer sk-xx' \ -H 'Content-Type: application/json' \ -d '{ "messages": [ { "content": "What is the weather like in New York?", "role": "user" } ], "tools": [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather in a specified city", "parameters": { "type": "object", "properties": { "city": {"type": "string"}, "metric": {"type": "string", "enum": ["celsius", "fahrenheit"]} }, "required": ["city"] } } } ], "tool_choice": "auto", "stream": false, "model": "z-ai/glm-5.3" }' ``` > [accordion] Example response of tool calling request > > ```json theme={"system"} > { > "id": "chatcmpl-28f745c2b7ee44f2ba36a8b4b409c74a", > "object": "chat.completion", > "created": 1754381277, > "model": "z-ai/glm-5.3", > "choices": [ > { > "index": 0, > "message": { > "role": "assistant", > "content": null, > "refusal": null, > "annotations": null, > "audio": null, > "function_call": null, > "tool_calls": [ > { > "id": "chatcmpl-tool-471f2c795ab64a27ab671a9e302c94db", > "type": "function", > "function": { > "name": "get_weather", > "arguments": "{\"city\": \"New York\", \"metric\": \"celsius\"}" > } > } > ], > "reasoning_content": null > }, > "logprobs": null, > "finish_reason": "tool_calls", > "stop_reason": null > } > ], > "service_tier": null, > "system_fingerprint": null, > "usage": { > "prompt_tokens": 319, > "total_tokens": 353, > "completion_tokens": 34, > "prompt_tokens_details": null > }, > "prompt_logprobs": null, > "kv_transfer_params": null > } > ``` Extract the tool id from the response, and in this example it would be `chatcmpl-tool-471f2c795ab64a27ab671a9e302c94db`. ## Invoke the Tool Use the tool id extracted from previouse request to call the tool. ```bash theme={"system"} curl -s -X POST 'https://inference.phala.com/v1/chat/completions' \ -H 'Authorization: Bearer sk-xx' \ -H 'Content-Type: application/json' \ -d '{ "messages": [ {"role": "user", "content": "What is the weather like in New York?"}, { "role": "assistant", "content": null, "tool_calls": [ { "id": "chatcmpl-tool-471f2c795ab64a27ab671a9e302c94db", "type": "function", "function": { "name": "get_weather", "arguments": "{\"city\": \"New York\", \"metric\": \"celsius\"}" } } ] }, { "role": "tool", "content": "{\"city\": \"New York\", \"temperature\": 15, \"description\": \"clear sky\", \"metric\": \"celsius\"}", "tool_call_id": "chatcmpl-tool-471f2c795ab64a27ab671a9e302c94db" } ], "tools": [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather in a specified city", "parameters": { "type": "object", "properties": { "city": {"type": "string"}, "metric": {"type": "string", "enum": ["celsius", "fahrenheit"]} }, "required": ["city"] } } } ], "tool_choice": "auto", "stream": false, "model": "z-ai/glm-5.3" }' ``` > [accordion] Example response of invoke the tool > > ```json theme={"system"} > { > "id": "chatcmpl-a46eff3d335c42c39bbe4ea69fc97462", > "object": "chat.completion", > "created": 1754381325, > "model": "z-ai/glm-5.3", > "choices": [ > { > "index": 0, > "message": { > "role": "assistant", > "content": "The current weather in New York is clear sky with a temperature of 15°C.", > "refusal": null, > "annotations": null, > "audio": null, > "function_call": null, > "tool_calls": [], > "reasoning_content": null > }, > "logprobs": null, > "finish_reason": "stop", > "stop_reason": null > } > ], > "service_tier": null, > "system_fingerprint": null, > "usage": { > "prompt_tokens": 394, > "total_tokens": 413, > "completion_tokens": 19, > "prompt_tokens_details": null > }, > "prompt_logprobs": null, > "kv_transfer_params": null > } > ``` ## Find Compatible Models ```bash theme={"system"} curl -s https://inference.phala.com/v1/models \ | jq -r '.data[] | select((.supported_features // []) | index("tools")) | .id' ``` # Trust Boundary Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/trust-boundary Understand Phala's attested gateway, provider evidence coverage, and where plaintext exists. Every model on `https://inference.phala.com/v1` uses the TEE-only serving policy. The Phala gateway requires upstream verification and channel binding before forwarding; if that fails, it refuses the request. The evidence covers different boundaries for different [providers](/phala-cloud/confidential-ai/confidential-model/providers). ## What the gateway protects * **Gateway identity**: A fresh [attestation report](/phala-cloud/confidential-ai/confidential-model/api-reference/attestation) binds the gateway keyset to hardware evidence. * **Per-response integrity**: A signed [receipt](/phala-cloud/confidential-ai/confidential-model/api-reference/receipts) binds request and response hashes to that keyset. * **No body retention in receipts**: Receipts contain hashes and verification facts rather than prompt or response bodies. * **Required upstream verification**: The gateway verifies the provider boundary and enforces channel binding before forwarding. * **Optional retention constraint**: `provider: {"zdr": true}` restricts routing to serving routes that do not retain prompt or completion content. See [Zero Data Retention](/phala-cloud/confidential-ai/confidential-model/zero-data-retention). ## Limits * **Plaintext is processed in the gateway TEE**: TLS terminates there. Field-level [E2EE](/phala-cloud/confidential-ai/confidential-model/e2ee-encryption) encrypts to an attested gateway key and decrypts inside that gateway. * **Upstream coverage varies**: Some verifiers cover a model CVM, others a router or broker. Read the cited session's claims; gateway attestation does not independently attest every upstream model worker, GPU link, or model weight. * **Client verification is explicit**: Ordinary clients do not verify the quote, pin TLS to the attested key, or audit receipts. Use the [TypeScript SDK](/phala-cloud/confidential-ai/verify/typescript-sdk) or [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy). * **Receipts are not a permanent public log**: Fetch them promptly and archive them if durable evidence is required. * **Local tools remain separate**: Agent tools, MCP servers, browser automation, and telemetry can expose data outside the inference boundary. ## Where plaintext exists | Stage | Plaintext boundary | | - | - | | Client to gateway | TLS protects transit; optional E2EE protects selected fields to the gateway's attested key. | | Inside gateway TEE | The attested workload processes the request after TLS termination or E2EE decryption. | | Gateway to provider | Pinned TLS, provider-specific E2EE, or a measured co-deployed proxy binding enforces the provider path. | | Inside provider | Depends on the verified model-instance, router, or broker boundary and the session's evidence. | ## Upstream binding boundaries | Binding | Boundary | | - | - | | `tls_spki_sha256` | The verified upstream TLS key. | | `e2ee_public_key_sha256` | The verified provider encryption key. | | `proxy_image_sha256` | Binds Privatemode forwarding to the co-deployed proxy's measured image (`proxy_image_digest`) and startup-checked shared credential digest (`credential_sha256`); plaintext is sent only to its configured internal origin. | The Privatemode proxy owns Contrast verification, secret exchange, and body encryption after that internal hop. Its dynamic manifest observation is not bound to the active inference secret. ## Apply a policy Verify the receipt and its session, then require the claims your workload needs. Add a compose allowlist from authenticated release metadata when you need reviewed gateway releases. Add zero data retention when post-request storage matters. Use a custom GPU TEE deployment when you need control over the complete serving workload. ## Related > [card] [Providers](/phala-cloud/confidential-ai/confidential-model/providers) > [card] [Channel Binding](/phala-cloud/confidential-ai/confidential-model/channel-binding) # Zero Data Retention Source: https://docs.phala.com/phala-cloud/confidential-ai/confidential-model/zero-data-retention Restrict requests to serving routes that do not retain prompt or completion content, and list models that support that constraint. Zero data retention (ZDR) means the upstream serving route that handles your request does not keep the prompt or completion after returning it. Use it when a prompt carries data you cannot leave on a third party's disk. Two API surfaces implement ZDR: * [`GET /v1/models?zdr=true`](/phala-cloud/confidential-ai/confidential-model/api-reference/models#query-parameters) lists the models a ZDR request can reach. * `provider: {"zdr": true}` in a request body restricts routing for that request. The two agree by construction. A model listed under `?zdr=true` is one that `provider: {"zdr": true}` can route. ## Route a request under zero data retention Add the `provider` block to the request. Every inference endpoint accepts it: `/v1/chat/completions`, `/v1/messages`, `/v1/responses`, `/v1/embeddings`, and `/v1/completions`. ```bash theme={"system"} curl https://inference.phala.com/v1/chat/completions \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "model": "", "messages": [{"role": "user", "content": "Summarize this contract clause."}], "provider": {"zdr": true} }' ``` If no route for that model operates under zero data retention, the request fails before the prompt is sent: ```json theme={"system"} { "error": { "message": "No zero-data-retention providers are available for the selected model.", "type": "not_found_error" } } ``` The status is `404`. This is a fail-closed check: the gateway does not fall back to a non-ZDR route, and failover retries stay inside the ZDR set. Setting `"zdr": false`, or omitting the field, applies no retention constraint and behaves like a request with no `provider` block. ## List models you can use ```bash theme={"system"} curl -s "https://inference.phala.com/v1/models?zdr=true" \ | jq -r '.data[].id' ``` Embedding models have their own catalog, which takes the same parameter: ```bash theme={"system"} curl -s "https://inference.phala.com/v1/embeddings/models?zdr=true" \ | jq -r '.data[].id' ``` `true` is the only accepted value. Any other value, including `false`, returns `400`. Omit the parameter for the full catalog. Rejecting other values is deliberate: a typo cannot silently return an unfiltered list that looks filtered. A model object has no `zdr` field. The filter is how you read this property, so query the filtered catalog rather than inspecting individual model objects. ## ZDR is different from confidential inference These are different properties and you may need either, or both. | | What it constrains | How to select it | How to verify it | | - | - | - | - | | Confidential inference (`is_tee`) | Who can read memory while the model runs. The upstream is attested and the channel is bound before the prompt is sent. | `is_tee: true` on a model object | The per-response [receipt](/phala-cloud/confidential-ai/confidential-model/api-reference/receipts) records `upstream.verified.result`. | | Zero data retention (`zdr`) | Whether the upstream stores prompt and completion content after serving. | `?zdr=true`, `provider: {"zdr": true}` | Provider contract and published policy. | The distinction matters because a TEE constrains execution, not storage. A provider could run a model inside an enclave and still write request logs to disk. > [!WARNING] > > Do not infer ZDR from `is_tee`. Filter with `?zdr=true` when you need the retention property, and route with `provider: {"zdr": true}` when a specific request must stay inside the ZDR set. Zero data retention is a property of the upstream serving route, backed by its contract or published policy. It is not proven by the attestation report or the receipt, which cover workload identity and response integrity. Confidential inference is the property the receipt proves. See [Verify a Response](/phala-cloud/confidential-ai/verify/verify-signature). ## Gateway retention The gateway does not store request or response bodies for ZDR or non-ZDR requests. Receipts hold hashes and verification facts, not content. See [Trust Boundary](/phala-cloud/confidential-ai/confidential-model/trust-boundary). Setting `zdr` changes which upstream route serves the request. It does not change gateway behavior. ## Related > [card] [List Models](/phala-cloud/confidential-ai/confidential-model/api-reference/models) > > The `zdr` query parameter and model object fields. > [card] [Chat Completions](/phala-cloud/confidential-ai/confidential-model/api-reference/chat-completions) > > The `provider` routing block. > [card] [Provider Verification](/phala-cloud/confidential-ai/confidential-model/providers) > > How upstream serving environments are verified. > [card] [Compliance and Open Source](/phala-cloud/confidential-ai/confidential-model/compliance-and-open-source) > > How retention maps to compliance requirements. # FAQs Source: https://docs.phala.com/phala-cloud/confidential-ai/faqs Frequently asked questions about Private AI. > [accordion] What is the relationship between dstack Private ML SDK, and what's the vllm-proxy doing there? > > The Private ML SDK leverages the TEE features provided by Intel and NVIDIA GPUs to support running any GPU workload as a Docker container in a GPU TEE. In the Private ML SDK, dstack is a framework that can run Docker containers, while vllm-proxy is a specific container within it. The vllm-proxy container operates as a server that forwards requests to a vllm container (hosting a large language model) and generates quotes to attach to responses. This separation allows vllm to remain unmodified and compatible with its latest versions. > [accordion] Do I need CUDA or NVIDIA drivers on the host for Private ML SDK with GPU support? > > No, CUDA and NVIDIA drivers are not required on the host for the Private ML > SDK with GPU support. The host should not have NVIDIA drivers installed to > avoid conflicts with TDX and VFIO passthrough. Drivers (e.g., 550.54.15) and > CUDA (e.g., 12.4) are loaded inside the guest CVM via Docker containers (e.g., > kvin/cuda-notebook). The vllm and vllm-proxy services also run entirely within > the TEE guest, not on the host. > [accordion] Is CUDA directly accessible in Phala GPU TEE? > > Yes, CUDA works in the GPU TEE environment. By default, you don't need to > install it on the host environment when using private-ml-sdk to create a CVM. > If you want to use CUDA in your CVM, you can install it manually inside the > CVM. You can refer to our benchmark analysis with Succinct, where the SP1 VM > also involves CUDA. > [accordion] Can I run my app in a docker container with access to GPU TEE under Intel TDX? Is this similar to Google Cloud's Confidential Space? > > Yes, you can build your application into a docker image and prepare a > docker-compose file. The SDK will create a TDX-based virtual machine to launch > your application. However, unlike Google Cloud's Confidential Space, which > uses virtual machines, dstack and private-ml-sdk require a bare-metal > environment. > [accordion] Is dstack-based including private-ml-sdk's CVM running on bare metal or a hypervisor? > > dstack is launched on a bare-metal environment. However, for CVMs created by dstack, a hypervisor (qemu) is used to launch the VM with TDX enabled. # Deploy AI Models in GPU TEE Source: https://docs.phala.com/phala-cloud/confidential-ai/gpu-tee-deployment-guide End-to-end guide for deploying custom LLMs on GPU TEE with vLLM and accessing them via OpenAI-compatible API Deploy a custom LLM on Phala Cloud GPU TEE and serve it through an OpenAI-compatible API. This guide walks you through the full workflow from choosing hardware to making your first inference request with verified TEE attestation. For pre-deployed models that don't require infrastructure setup, use the [On-demand API](/phala-cloud/confidential-ai/confidential-model/confidential-ai-api) instead. ## Prerequisites * Phala Cloud account with enough Balance for GPU instances * A model you want to deploy (Hugging Face model ID or custom weights) * Basic familiarity with Docker Compose and LLM serving ## Choose your GPU hardware Pick a GPU based on your model's VRAM requirements. Larger models need more VRAM, and you can scale up to 8 GPUs per instance for models that support tensor parallelism. | GPU type | VRAM per GPU | Best for | | - | - | - | | H200 | 141 GB | Most 70B+ models, long context | | B300 | 288 GB | Largest models, maximum throughput | A 7B model fits comfortably on a single GPU. A 70B model typically needs 2-4 GPUs depending on quantization. Check your model's documentation for exact VRAM requirements. > [!NOTE] > > GPU instances incur hourly charges starting from provisioning. Check current pricing on the [GPU TEE](https://cloud.phala.com) dashboard before launching. ## Deploy your instance **1. Launch the GPU TEE wizard** Sign in to [cloud.phala.com](https://cloud.phala.com), click **GPU TEE** in the navigation bar, then click **Start Building**. Select your GPU type and count. **2. Choose the vLLM template** In the deployment configuration, select **vLLM** as your template. This gives you a production-ready inference server with OpenAI-compatible API endpoints out of the box. If you prefer full control, choose **Custom Configuration** and provide your own Docker Compose file. See the [custom vLLM compose example](#custom-vllm-docker-compose) below. **3. Configure your model** Set the model you want to serve. For Hugging Face models, use the model ID directly (e.g., `meta-llama/Llama-3.1-70B-Instruct`). Add any required environment variables like `HUGGING_FACE_HUB_TOKEN` as encrypted secrets if your model needs authentication. **4. Launch and wait for provisioning** Review the pricing summary and click **Launch Instance**. GPU provisioning takes approximately 1 day. Monitor the status in your dashboard as it progresses through **Preparing**, **Starting**, and **Running**. ## Custom vLLM Docker Compose If you chose Custom Configuration, here's a Docker Compose file for serving a model with vLLM. This example serves Qwen 2.5 7B on a single GPU. ```yaml theme={"system"} services: vllm: image: vllm/vllm-openai:v0.8.5@sha256:abc123... # Pin to digest for attestation ports: - "8000:8000" environment: - HUGGING_FACE_HUB_TOKEN=${HF_TOKEN} command: > --model qwen/Qwen2.5-7B-Instruct --tensor-parallel-size 1 --max-model-len 32768 --trust-remote-code deploy: resources: reservations: devices: - driver: nvidia count: 1 capabilities: [gpu] ``` For multi-GPU serving, increase `--tensor-parallel-size` to match your GPU count. For example, with 4 GPUs: ```yaml theme={"system"} command: > --model meta-llama/Llama-3.1-70B-Instruct --tensor-parallel-size 4 --max-model-len 65536 deploy: resources: reservations: devices: - driver: nvidia count: 4 capabilities: [gpu] ``` > [!WARNING] > > Pin your Docker images by SHA256 digest (not tags) for attestation verification. Tags like `vllm/vllm-openai:latest` are mutable and break the chain of trust. See [Verify Your Application](/phala-cloud/attestation/verify-your-application) for details. ## Access the OpenAI-compatible API Once your instance is running, vLLM exposes an OpenAI-compatible API. Find your instance's URL in the dashboard under your GPU TEE instance details. ```bash curl theme={"system"} curl https:///v1/chat/completions \ -H "Content-Type: application/json" \ -d '{ "model": "qwen/Qwen2.5-7B-Instruct", "messages": [ {"role": "user", "content": "What is confidential computing?"} ], "max_tokens": 256 }' ``` ```python Python theme={"system"} from openai import OpenAI client = OpenAI( base_url="https:///v1", api_key="not-needed" # No auth by default; add if configured ) response = client.chat.completions.create( model="qwen/Qwen2.5-7B-Instruct", messages=[ {"role": "user", "content": "What is confidential computing?"} ], max_tokens=256 ) print(response.choices[0].message.content) ``` ```typescript TypeScript theme={"system"} import OpenAI from 'openai'; const client = new OpenAI({ baseURL: 'https:///v1', apiKey: 'not-needed', }); const response = await client.chat.completions.create({ model: 'qwen/Qwen2.5-7B-Instruct', messages: [ { role: 'user', content: 'What is confidential computing?' } ], maxTokens: 256, }); console.log(response.choices[0].message.content); ``` You can also check the available models and server health: ```bash theme={"system"} # List loaded models curl https:///v1/models # Health check curl https:///health ``` ## Verify TEE attestation Your GPU TEE instance runs on genuine Intel TDX + NVIDIA confidential compute hardware. Verify this to confirm your model is actually running inside a trusted execution environment. **1. Check GPU TEE status** Open JupyterLab (if using the Jupyter template) or SSH into your instance and run: ```bash theme={"system"} nvidia-smi conf-compute -q ``` Confirm `CC State: ON` and `CPU CC Capabilities: INTEL TDX` in the output. **2. Run local GPU verification** Install NVIDIA's attestation tools and run the verifier: ```bash theme={"system"} pip install nv-local-gpu-verifier nv_attestation_sdk python -m verifier.cc_admin ``` Successful output confirms your GPUs are genuine NVIDIA hardware with confidential compute enabled. **3. Verify the Intel TDX quote** Fetch and verify the CPU attestation through Phala's verification API: ```bash theme={"system"} # Get the attestation quote from your instance curl https:///attestation -o attestation.json # Verify through Phala's API curl -X POST https://cloud-api.phala.com/api/v1/attestations/verify \ -H "Content-Type: application/json" \ -d @attestation.json ``` You can also paste the quote into the [TEE Attestation Explorer](https://proof.t16z.com/) for a visual breakdown. For programmatic attestation verification in your application, see [Verify Attestation](/phala-cloud/confidential-ai/verify/verify-attestation). ## Add a custom domain Expose your model API on your own domain by adding dstack-ingress to your Docker Compose. This handles DNS and TLS certificates automatically. ```yaml theme={"system"} services: dstack-ingress: image: dstacktee/dstack-ingress:2.2@sha256:d05a7b343c37c1cca1bba8dbf7e8f3c6d2118158af2d41c455103796db4f67f0 ports: - "443:443" environment: - DOMAIN=ai.mycompany.com - TARGET_ENDPOINT=vllm:8000 - CLOUDFLARE_API_TOKEN=${CLOUDFLARE_API_TOKEN} - GATEWAY_DOMAIN=gateway.${DSTACK_GATEWAY_DOMAIN} - CERTBOT_EMAIL=${CERTBOT_EMAIL} - SET_CAA=true volumes: - /var/run/dstack.sock:/var/run/dstack.sock - /var/run/tappd.sock:/var/run/tappd.sock - cert-data:/etc/letsencrypt - evidences:/evidences vllm: image: vllm/vllm-openai:v0.8.5 # ... your vLLM config from above volumes: cert-data: evidences: ``` See [Set Up a Custom Domain](/phala-cloud/networking/setup-custom-domain) for the full guide including DNS provider configuration and troubleshooting. ## Next steps > [card] [Verify attestation](/phala-cloud/confidential-ai/verify/verify-attestation) > > Programmatically verify your GPU TEE hardware and software stack > [card] [Verify responses](/phala-cloud/confidential-ai/verify/verify-signature) > > Confirm inference responses are authentic using signed receipts > [card] [Performance benchmark](/phala-cloud/confidential-ai/benchmark) > > See how TEE mode performs compared to native GPU execution > [card] [Networking guides](/phala-cloud/networking/overview) > > Expose services, set up gRPC, and configure TCP endpoints # Overview Source: https://docs.phala.com/phala-cloud/confidential-ai/overview Use Private AI through an OpenAI-compatible API, or rent GPU TEE servers for your own confidential AI, with attestation reports and signed receipts you can verify. ![Private AI overview - run AI models with hardware-level privacy in GPU TEEs](https://mintcdn.com/phalanetwork-1606097b/416gZMDMREnPDd33/images/confidential-ai/confidential-ai-overview.jpeg?fit=max\&auto=format\&n=416gZMDMREnPDd33\&q=85\&s=7078e43ac11a53f8be6d0d9626fa9941) ## Why Private AI? Traditional cloud AI deployments ask you to trust the platform operator and the upstream model provider. Phala Private AI runs inference through an attested gateway and verified TEE providers, then gives you cryptographic evidence for each response. The on-demand API is OpenAI-compatible and served through an Attested Confidential Inference (ACI) gateway. Every response includes a signed receipt, and the gateway publishes an attestation report that proves which TEE workload served the request. Confidential model responses additionally show, in the receipt, that the upstream provider was verified and channel-bound before your prompt was forwarded. Phala Cloud offers pre-deployed **Models** through an API for quick integration, and **GPU TEE** for custom infrastructure. See [available models](https://phala.com/confidential-ai-models) for supported models, use cases, and deployment options. > [card] [API Access](/phala-cloud/confidential-ai/confidential-model/confidential-ai-api) > > **Pre-deployed models, pay per request** > > Best for quick integration. 5 minute setup with OpenAI-compatible API and no infrastructure management. > [card] [GPU TEE](/phala-cloud/confidential-ai/confidential-gpu/deploy-and-verify) > > **Custom infrastructure, full control** > > Best for custom models. Rent dedicated GPU TEE servers for training, fine-tuning, or any custom workload. ## Quick Tour of Private AI ### Models: API Access **API Access** provides pre-deployed models through an OpenAI-compatible API at `https://inference.phala.com/v1`. Pay per request with no infrastructure to manage. Start with [API Access](/phala-cloud/confidential-ai/confidential-model/confidential-ai-api). For advanced API features, explore [Tool Calling](/phala-cloud/confidential-ai/confidential-model/tool-calling) to enable LLMs to interact with external tools and APIs securely within TEE. ### GPU TEE: Custom Infrastructure For complete infrastructure control beyond pre-deployed models, use [GPU TEE](/phala-cloud/confidential-ai/confidential-gpu/deploy-and-verify) to rent dedicated GPU servers. Run any workload including custom models for inference, training, or fine-tuning. Configure GPU, CPU, RAM, and storage to match your exact needs. ### Verify Attestation and Receipts To verify the API path, fetch a fresh [Attestation Report](/phala-cloud/confidential-ai/confidential-model/api-reference/attestation) from `GET /v1/aci/attestation`. It proves the gateway workload identity, TEE quote, source provenance, and public keyset used to sign receipts. Then use the response `x-receipt-id` header to fetch the [Receipt](/phala-cloud/confidential-ai/confidential-model/api-reference/receipts). The receipt binds request and response hashes to the attested workload and records whether the upstream provider was verified. See [Verify a Response](/phala-cloud/confidential-ai/verify/verify-signature) for the full flow. ### Benchmark Our [benchmark](/phala-cloud/confidential-ai/benchmark) shows GPU TEE mode achieves 99% of native performance on H100/H200 GPUs. ### FAQs Check [FAQs](/phala-cloud/confidential-ai/faqs) for frequently asked questions about Private AI. ## What makes Phala Cloud Private AI Different? * **Drop-in compatibility**: OpenAI-compatible API with popular models (DeepSeek, Llama, GPT-OSS, Qwen) ready for immediate use * **Verifiable security**: Gateway attestation, signed per-response receipts, and upstream verification events you can check yourself * **Flexible deployment**: Choose from API access (pay per request) or GPU TEE (full infrastructure control) ## Open Source Foundation Our underlying technology is open source. Check out the [dstack](https://github.com/Dstack-TEE/dstack) repository to see how LLMs run securely in GPU TEEs. # Overview Source: https://docs.phala.com/phala-cloud/confidential-ai/verify/overview Verify Phala gateway attestation, pinned TLS, signed receipts, and upstream evidence. Private AI verification connects the gateway's hardware evidence to the exact request and response bytes. The attestation report identifies the **Phala gateway**. The response receipt cites a verified upstream session, whose evidence coverage varies by provider. Every model on `https://inference.phala.com/v1` uses the TEE-only serving policy: upstream verification and channel binding are required before forwarding. A failed check refuses the request. Ordinary clients still need a verification client to check this from their own machine. ## Start with a verification client * For Node.js or Bun, use the [TypeScript ACI verifier](/phala-cloud/confidential-ai/verify/typescript-sdk): `connectAci()`, the scoped `aci.fetch`, and `verifyReceipt()` after each response. * For coding agents, use [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy): attestation and pinned TLS before traffic, receipt audits after delivery. * Use [Verify a Response](/phala-cloud/confidential-ai/verify/verify-signature) to understand the checks and inspect existing artifacts. cURL and `jq` inspection alone does not verify them. ## Verification workflow **1. Verify the gateway before traffic** Generate a fresh nonce, verify the TDX quote and JCS keyset digest, check `not_after`, replay RTMR3 and the measured compose hash, and apply your release policy. Source labels alone are not a trust root. **2. Pin the request channel** Use hostname-validated TLS pinned to the SPKI listed for `inference.phala.com` in the verified keyset. **3. Verify the receipt** Match `workload_keyset_digest`, verify the receipt signature under its `key_id`, and compare `request.received.body_hash` and `response.returned.body_hash` with the exact bytes exchanged. **4. Audit the cited upstream session** Require `upstream.verified.result: verified` and `required: true`. Recompute the full session's content address and verify its evidence, channel binding, and claims under your policy. A passing audit proves the exchange used the attested gateway and cited upstream channel. It proves a reviewed release only with an independently obtained compose allowlist. It does not imply that every provider proves GPU binding, model-weight provenance, or the same software measurements. ## Canonical and legacy endpoints | Purpose | Canonical endpoint | Legacy alias | | - | - | - | | Gateway attestation | `GET /v1/aci/attestation?nonce=` | `GET /v1/attestation/report` | | Per-response proof | `GET /v1/aci/receipts/{id}` | `GET /v1/signature/{id}` | | Upstream security context | `GET /v1/aci/sessions/{session_id}` | None | Use the canonical `/v1/aci/*` endpoints for new integrations. > [card] [Attestation](/phala-cloud/confidential-ai/verify/verify-attestation) > [card] [Verify a Response](/phala-cloud/confidential-ai/verify/verify-signature) > [card] [TypeScript ACI Verifier](/phala-cloud/confidential-ai/verify/typescript-sdk) > [card] [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy) # TypeScript ACI Verifier Source: https://docs.phala.com/phala-cloud/confidential-ai/verify/typescript-sdk Use the official TypeScript SDK to verify Phala Private AI attestation, pin the TLS channel, and audit signed response receipts. `@phala/aci-verifier` is the official TypeScript implementation of the ACI client checks. Node.js and Bun applications can use it to establish an instance-scoped, SPKI-pinned connection before sending model traffic. The package is ESM-only and supports Node.js 20.18.1 or newer and Bun 1.4.0 or newer. ## Install ```bash theme={"system"} npm install @phala/aci-verifier openai ``` ## Create a verified connection ```typescript theme={"system"} import OpenAI from "openai"; import { connectAci } from "@phala/aci-verifier/runtime"; const apiKey = process.env.PHALA_AI_API_KEY; if (!apiKey) throw new Error("PHALA_AI_API_KEY is required"); const aci = await connectAci({ baseURL: "https://inference.phala.com/v1", serving: { requireVerified: true, requireReceipt: true, }, }); try { const client = new OpenAI({ baseURL: aci.baseURL, apiKey, fetch: aci.fetch, }); const response = await client.chat.completions.create({ model: "z-ai/glm-5.3", messages: [{ role: "user", content: "Explain attestation." }], }); const audit = await aci.verifyReceipt(); if (!audit.transcript.verdict.verified) { throw new Error(audit.transcript.verdict.line); } console.log(response.choices[0].message.content); } finally { await aci.close(); } ``` `connectAci()` verifies a fresh nonce-bound workload report and creates a hostname-validated TLS transport pinned to the attested SPKI. Its scoped `fetch` rejects non-HTTPS and cross-origin requests, expired workload identities, TLS key mismatches, and missing receipt ids, and requires verified serving in JSON inference requests. ## Receipt auditing The runtime records the exact request and response wire digests while the body is consumed. Call `verifyReceipt()` after the response finishes to fetch and verify the latest signed receipt, including its signature, request and response `body_hash` values, verified upstream status, and cited session. Pass a receipt id returned by `aci.receipts()` to audit another retained exchange. The default local history is the latest 32 receipt-bearing requests and exists only for the current process. Gateway receipts and sessions follow the deployment's server-side retention policy. > [!WARNING] > > The low-level SDK does not automatically call `verifyReceipt()` for every > response. Applications must make that call before accepting a result. > Private AI Proxy audits every receipt automatically after delivery. ## Browser use The browser export can verify attestation and receipt documents, but browser JavaScript cannot observe the server certificate SPKI. It therefore cannot enforce the same pinned transport by itself. Use the Node.js or Bun runtime export when the application must bind model traffic to the attested TLS key. ## Release policy The SDK does not check whether the gateway runs a production or development dstack OS image. For OS-image assurance, verify the same quote, event log, and VM configuration with an independent [dstack verifier](https://github.com/Dstack-TEE/dstack/tree/next/dstack/verifier) and require `is_valid: true`. Attestation proves which compose hash was measured, but not that your organization reviewed that release. When you have an authenticated allowlist, pass its hashes as `policy.acceptedComposeHashes`. Never copy a hash from the endpoint and trust it on first use. Each production release of the gateway at `inference.phala.com` is published as a `gateway-prod-` release in [`Dstack-TEE/private-ai-gateway`](https://github.com/Dstack-TEE/private-ai-gateway/releases). It lists the compose hash, OS and KMS values, and TLS keys, and attaches the exact measured `app_compose.json` so you can recompute the compose hash yourself. A change to these values is published as a prerelease at least 3 days before the rollout, or sooner for an urgent change, with the reason in the release. KMS values are the exception: `mr-kms` is recorded when a replica boots and can change without notice, so pin the KMS root key instead. The [release measurements page](https://docs.redpill.ai/guides/release-measurements) lists the current values and the full notice policy. Without a compose allowlist, the client verifies that the measured compose ran in a genuine TDX workload. It does not claim that Phala reviewed that release. For a production security decision, pair compose appraisal with a dstack verifier result for the same quote, event log, and VM configuration, and require `is_valid: true`. For the complete API and security limits, see the [`@phala/aci-verifier` package documentation](https://github.com/Dstack-TEE/private-ai-gateway/tree/main/clients/verifier-ts). > [card] [Verify Attestation](/phala-cloud/confidential-ai/verify/verify-attestation) > [card] [Verify a Response](/phala-cloud/confidential-ai/verify/verify-signature) # Attestation Source: https://docs.phala.com/phala-cloud/confidential-ai/verify/verify-attestation Verify the Phala gateway's TDX evidence, nonce-bound keyset, expiry, and measured compose. The attestation report describes the **Phala gateway**, rather than every upstream model's execution environment. It publishes the gateway's receipt-signing, TLS, and E2EE keys. Upstream evidence is in the [attested session](/phala-cloud/confidential-ai/confidential-model/api-reference/sessions) cited by a response receipt, and its coverage varies by provider. ## Inspect the report The endpoint is public. Generate a fresh 32-byte nonce, encoded as exactly 64 lowercase hex characters: ```bash theme={"system"} NONCE=$(openssl rand -hex 32) curl --fail-with-body -sS "https://inference.phala.com/v1/aci/attestation?nonce=$NONCE" \ -o report.json jq '{api_version, workload_keyset_digest, report_data: .attestation.report_data, not_after: .attestation.workload_keyset.not_after, provenance: .attestation.source_provenance}' report.json ``` These commands inspect the document. They do not verify a hardware quote, the nonce binding, or a receipt signature. Applications should use [`connectAci()`](/phala-cloud/confidential-ai/verify/typescript-sdk); agent tools can use [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy). ## Report fields | Field | Meaning | | - | - | | `api_version` | `aci/1`. | | `workload_keyset_digest` | `sha256:` digest of the RFC 8785 JCS form of the complete published keyset. | | `attestation.tee_type` | TEE technology, currently `tdx` for this gateway. | | `attestation.workload_keyset` | `subject`, `not_after`, `receipt_signing_keys`, `e2ee_public_keys`, and `tls_public_keys`. | | `attestation.report_data` | Digest of the nonce/keyset statement bound into the quote. | | `attestation.evidence` | Quote, report data, boot event log, VM configuration, `app_compose`, key custody, and downstream TLS binding. | | `attestation.source_provenance` | Workload-declared source/build labels; these are not a trust root. | | `service_capabilities` | Supported E2EE extension versions and `serving: "aggregator"`. | The published receipt key uses `algo: "ed25519"` and `key_id: "dstack-kms-receipt-ed25519-v1"`. Select the key from the verified report rather than hardcoding its public key. ## Verification procedure 1. **Verify the TDX quote.** Verify `attestation.evidence.quote` against Intel DCAP collateral, inspect TCB status, and apply your OS and key-custody policy. A local verifier such as [dcap-qvl](https://github.com/Phala-Network/dcap-qvl) can verify Intel evidence. The [ACI SDK](/phala-cloud/confidential-ai/verify/typescript-sdk) verifies the quote but does not check whether the dstack OS image is production or development. For OS-image assurance, verify the same quote, event log, and VM configuration with an independent [dstack verifier](https://github.com/Dstack-TEE/dstack/tree/next/dstack/verifier) and require `is_valid: true`. 2. **Recompute the keyset digest.** Canonicalize the complete `attestation.workload_keyset` with JCS (RFC 8785), hash those bytes with SHA-256, prefix the lowercase hex digest with `sha256:`, and require equality with `workload_keyset_digest`. Sorting keys with `jq` is not a general JCS implementation. 3. **Check nonce binding.** Build this exact statement with the recomputed digest and your nonce, without whitespace and in this field order: ```text theme={"system"} {"keyset_digest":"sha256:","nonce":"<64 lowercase hex>","purpose":"aci.report_data.v1"} ``` Require its SHA-256 digest to equal `attestation.report_data` and the quote's first 32 report-data bytes, with the remaining 32 bytes zero. A report fetched without a nonce does not establish freshness. 4. **Check expiry.** Require `attestation.workload_keyset.not_after` to be a future Unix timestamp under your policy. Reject implausibly distant expiry. Receipts must cite this verified `workload_keyset_digest` and a receipt key in this keyset. 5. **Replay measured evidence.** Replay the boot event log to the quote's RTMR3. Confirm the measured `compose-hash` equals `sha256(app_compose)`. Inspect the measured launcher/configuration path that selects the gateway release. 6. **Apply release policy.** For reviewed-release enforcement, compare the measured compose hash against an independently obtained, authenticated allowlist. `source_provenance.repo_url` and `repo_commit` are inspection labels; trusting them without measured corroboration does not establish a reviewed release. Pair compose appraisal with the independent OS verification in step 1. 7. **Bind the client channel before sending traffic.** Pin hostname-validated TLS to the SPKI listed for `inference.phala.com` in the attested keyset. The TypeScript SDK and Private AI Proxy implement this step. A valid hardware quote alone does not verify a particular response. Continue with [Verify a Response](/phala-cloud/confidential-ai/verify/verify-signature). ## Legacy compatibility `GET /v1/attestation/report?nonce=…` returns the gateway report with compatibility signer fields. `signing_algo=ecdsa` (default) or `ed25519` selects the legacy signer. New integrations should use `/v1/aci/attestation` and the keyset directly. # Verify a Response Source: https://docs.phala.com/phala-cloud/confidential-ai/verify/verify-signature Verify a Phala response with a pinned client transport, signed receipt, and cited upstream session. `https://inference.phala.com/v1` requires confidential routing through Phala's attested gateway. Ordinary HTTP clients do not verify its attestation, pin its TLS key, or verify each response receipt. `curl` and `jq` can inspect the artifacts; client-side verification requires the [TypeScript ACI verifier](/phala-cloud/confidential-ai/verify/typescript-sdk) or [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy). ## Choose a verification client | Client | Verification | | - | - | | Node.js or Bun application | Call `connectAci()` before traffic, use `aci.fetch`, and call `verifyReceipt()` after consuming the response. See the [TypeScript example](/phala-cloud/confidential-ai/verify/typescript-sdk). | | Coding agent through Private AI Proxy | The proxy verifies attestation and pins the channel before traffic, then audits receipts after delivery. See [Private AI Proxy](/phala-cloud/confidential-ai/agents/private-ai-proxy). | | Ordinary OpenAI/Anthropic SDK or cURL | Base-URL configuration alone does not perform client-side verification. | Agent tools, MCP servers, browser automation, and telemetry remain separate trust boundaries. ## What the verifier checks 1. Verify a fresh nonce-bound gateway quote, recompute the JCS keyset digest, check `not_after`, and replay the measured compose evidence. See [Attestation](/phala-cloud/confidential-ai/verify/verify-attestation). 2. Before sending model traffic, use hostname-validated TLS pinned to a key in the attested keyset. 3. Fetch the receipt named by `x-receipt-id` using the same credential that made the request. Require `workload_keyset_digest` to match the verified keyset. Resolve `key_id` in `receipt_signing_keys` and verify the Ed25519 signature over the JCS receipt with `signature` removed. 4. Match `request.received.body_hash` and `response.returned.body_hash` to the exact request and response bytes. For SSE, the response hash includes the complete in-order stream framing. E2EE request hashes follow the transport extension's restored-plaintext rules. 5. Require a successful `upstream.verified` event with `result: "verified"`, `required: true`, and a `session_id`. Fetch the full session, recompute its bare SHA-256 JCS content address, verify its evidence and binding, and apply your claim policy. The receipt's serving time must fall within that session's validity interval. A receipt event by itself is an assertion by the attested gateway. Verifying the cited session's evidence provides the independent upstream audit; coverage varies by provider. ## Inspect existing artifacts The following commands only display documents for a request you already made. They do not produce a verification verdict. ```bash theme={"system"} # Set RECEIPT_ID to the x-receipt-id header from your inference response. curl --fail-with-body -sS "https://inference.phala.com/v1/aci/receipts/$RECEIPT_ID" \ -H "Authorization: Bearer $PHALA_AI_API_KEY" -o receipt.json jq '{receipt_id, workload_keyset_digest, key_id, endpoint, upstream: [.event_log[] | select(.type == "upstream.verified")]}' receipt.json # Stop if the receipt does not cite a successful upstream session. SESSION_ID=$(jq -er '.event_log[] | select(.type == "upstream.verified" and .result == "verified") | .session_id | select(type == "string" and test("^[0-9a-f]{64}$"))' receipt.json) && \ curl --fail-with-body -sS "https://inference.phala.com/v1/aci/sessions/$SESSION_ID" \ | jq '{upstream_name, endpoint, channel_binding, claims}' ``` The session uses `upstream_name` (for example `chutes` or `phala-267`). The list endpoint accepts `?upstream_name=` and `?model=`; it omits `evidence.data`, so fetch the full record for a content-address check. ## Release policy and limits A passing audit binds the exact exchange to a genuine attested gateway, pinned TLS channel, signed receipt, and verified upstream session. It establishes a reviewed release only when you enforce an independently obtained compose allowlist. Workload-declared `source_provenance` is not a trust root. See the [SDK release policy](/phala-cloud/confidential-ai/verify/typescript-sdk#release-policy). ## Legacy signature endpoint `GET /v1/signature/{id}` wraps the same canonical receipt for older clients. New integrations should verify `/v1/aci/receipts/{id}` directly. # Advanced CVM Settings Source: https://docs.phala.com/phala-cloud/cvm/advanced-settings Init scripts, ephemeral data disks, annotations, other runners and raw app-compose input for CVMs created or updated through the API. These settings are set through the API, on the create request (`POST /cvms`) or with [`PATCH /cvms/{cvm_id}`](/phala-cloud/update/update-cvm-configuration), or with the matching [`phala deploy`](/phala-cloud/phala-cloud-cli/deploy) flags. Some of them sit behind a feature flag and are available on request: [contact support](/phala-cloud/support) to turn them on for your workspace. ## Init scripts Init scripts are small scripts Phala Cloud provides. The CVM runs them on every boot, before your containers start. You pick them by name. Today there is one: | Name | What it does | Needs | | - | - | - | | `docker_cleanup` | Erases every local container store on each boot: images, volumes and all containerd namespaces. Each boot pulls images again and starts with empty Docker volumes. | dstack OS 0.6.x, `ext4` storage, the `docker-compose` runner | ### How do I choose init scripts? Send the full list. It replaces the scripts the CVM runs now, and `[]` removes them all: ```json theme={"system"} { "init_scripts": ["docker_cleanup"] } ``` With the CLI, use `phala deploy --init-script docker_cleanup` on create, or `phala cvms init-scripts on|off` to turn one script on or off on an existing CVM. See [`cvms init-scripts`](/phala-cloud/phala-cloud-cli/cvms/init-scripts). Use the same field on create and on `PATCH /cvms/{cvm_id}`. The create request still accepts the older form `enabled_init_scripts_docker_cleanup`. Storage is fixed when you create a CVM, and the default is `zfs`. To use `docker_cleanup`, create the CVM with `ext4` storage. ### Why does turning on docker\_cleanup ask for confirmation? Because the next boot erases your images and Docker volumes, and every boot after that does it again. On an existing CVM, the update fails with `ERR-03-048` unless you also send `"confirm_data_wipe": true`. Back up any data in Docker volumes before you turn it on. ### Does each CVM have its own init scripts? Yes. Init scripts are part of each CVM's compose. Changing them is a compose change: the CVM gets a new compose hash and restarts, and on Onchain KMS the new hash must be registered. Redeploying an older revision brings back that revision's init scripts. To see what a CVM runs and what you could pick, call `GET /cvms/{cvm_id}/init-scripts`. Each item says whether the CVM runs the script (`selected`), whether you can pick it (`selectable`) and, if not, why (`reason`). ## Ephemeral data disk With `requirements.ephemeral_data_disk` set to `true`, the CVM starts every boot with an empty data disk. The guest formats the disk before any app code runs, so nothing from earlier boots is left. Use it for workloads that must not keep data between boots. It needs dstack OS 0.6.3 or newer. To turn it on at create, put it in `compose_file.requirements`. To turn it on for an existing CVM, confirm the wipe: ```json theme={"system"} { "compose": { "requirements": { "ephemeral_data_disk": true } }, "confirm_data_wipe": true } ``` Without `confirm_data_wipe`, the update fails with `ERR-03-048`. Turning it off needs no confirmation. ## Annotations Annotations sit behind a feature flag and are available on request. Without it, every annotations request, and a create request that carries annotations, fails with `403` and `ERR-03-049`. Annotations are key/value labels for tools on the host, for example a wrapper that reads the VM's settings to place its memory or pin its vCPUs. The node keeps them with the VM. They are host configuration, not part of your app. They never reach the CVM, are not measured and are not part of the compose hash, so attestation does not cover them. Do not rely on them for security. ### How do I set annotations? * At create: add an `annotations` map to the create request. * On an existing CVM: `PUT /cvms/{cvm_id}/annotations` with `{"annotations": {"memory_tier": "fast"}}`. This replaces all annotations. To clear them, send `{"annotations": {}}`. * To read them: `GET /cvms/{cvm_id}/annotations`. * From the CLI: [`phala annotations`](/phala-cloud/phala-cloud-cli/annotations) shows them, and `phala annotations memory_tier=fast` sets a key and keeps the others. Keys must not be empty. The node must run dstack VMM 0.6.1 or newer, or the request fails with `ERR-03-050`. Setting annotations does not restart the CVM. Some host tools read them only when the VM starts. For those, restart the CVM after you change them. ### Do annotations follow the CVM? Phala Cloud does not keep annotations as part of the CVM's state and never restores them. The node holds them. The audit record of a create request may include the annotations it carried. * A replica starts without annotations. Set them again on the replica. * A CVM moved to another node keeps whatever its VM settings on the node carry. * Other updates to the CVM never change them. ## Other runners The runner is the program that starts your app inside the CVM. The default is `docker-compose`, and it is the only runner open to everyone. These two sit behind a feature flag and are available on request. Without it, a create request that picks one fails with `ERR-03-045`. * `nerdctl-compose` runs your Docker Compose YAML with nerdctl. It needs dstack OS 0.6.0 or newer. It cannot build images, so the YAML must not have `build:` sections. It is the only runner that accepts `snapshotter`. * `bash` runs the script in `bash_script` instead of Docker Compose YAML. There are no containers, so the CVM has no container list or container logs, and `docker_cleanup` is not available. If you turn on `requirements.health_check`, you must also set `requirements.health_status_file`. To change the script later, send `{"compose": {"bash_script": "..."}}` with `PATCH /cvms/{cvm_id}`. Set the runner in `compose_file.runner` when you create the CVM. It cannot change afterwards. ### Why does my bash CVM stay in processing? Because your script has not exited. The CVM runs `bash_script` in the foreground and finishes booting only after the script returns. Until then, the CVM stays in `processing` with the boot step "running main script", and it never reaches `running`. A script such as `while true; do sleep 300; done` keeps the CVM booting forever. Start long-running work in the background and let the script return: ```bash theme={"system"} (my-server --port 8080) >/dev/null 2>&1 & ``` A bash CVM has no containers, so `phala ps` lists none and there are no container logs. The script's output is in the CVM's service journal. ## Raw app-compose input Raw app-compose input sits behind the same feature flag as the other runners. Without it, the create request fails with `ERR-03-045`. Instead of `compose_file`, a create request can send `compose_file_raw`: a whole app-compose JSON file as one string. Send one or the other, not both. Phala Cloud reads the file with the same rules as `compose_file` and rejects fields it does not know. It then writes the compose the same way it writes any other. The bytes the CVM runs, and the compose hash, come from that output, not from the bytes you sent. After create, the CVM is like any other. Update it with [`PATCH /cvms/{cvm_id}`](/phala-cloud/update/update-cvm-configuration). # CVM with Docker Compose Source: https://docs.phala.com/phala-cloud/cvm/create-with-docker-compose Deploy a CVM from a docker-compose.yml file using the Phala Cloud dashboard. ## Prerequisites * [Phala Cloud account](/phala-cloud/getting-started/sign-up-for-cloud-account) * Basic understanding of Docker Compose syntax * A valid `docker-compose.yml` for your application ## Deploy in Advanced Mode Phala Cloud supports standard Docker Compose syntax in a secure TEE environment. 1. Go to the deployment section in the dashboard. 2. Switch to the **Advanced** tab. 3. Edit and validate your Docker Compose content in the built-in editor. ## What You Can Configure With Docker Compose deployment, you can: * Specify Docker image names and versions * Configure port mappings for public services * Define environment variables * Configure volume mounts for persistence * Deploy multiple services in one CVM ## Multi-Service Deployments All services in one compose file run inside the same CVM, enabling secure service-to-service communication within the trusted environment. ## Private Container Registry For proprietary or restricted images, Phala Cloud supports private registries including **Docker Hub**, **GHCR (GitHub Container Registry)**, and **AWS ECR (Elastic Container Registry)**. ➡️ [Learn more about private registry deployment](/phala-cloud/cvm/create-with-private-docker-image) ## Example Interface ![Docker Compose deployment interface](https://mintcdn.com/phalanetwork-1606097b/416gZMDMREnPDd33/images/cloud-compose-deployment.png?fit=max\&auto=format\&n=416gZMDMREnPDd33\&q=85\&s=124f65c43374913e000a551151d379ef) Docker Compose deployment interface The built-in editor provides syntax highlighting to help you review configuration before deployment. ## Next Steps * [Set secure environment variables](/phala-cloud/cvm/set-secure-environment-variables) * [Use a private container registry](/phala-cloud/cvm/create-with-private-docker-image) * [Expose your service over HTTPS](/phala-cloud/networking/expose-http-service) # Private Container Registry Source: https://docs.phala.com/phala-cloud/cvm/create-with-private-docker-image Configure private container registry access for CVM deployments on Phala Cloud. ## Prerequisites * [Phala Cloud account](/phala-cloud/getting-started/sign-up-for-cloud-account) * Credentials for one of the supported registries: * Docker Hub * GitHub Container Registry (GHCR) * AWS ECR (Elastic Container Registry) ## Overview Phala Cloud supports private image pulls during CVM startup. Registry credentials are passed as encrypted environment variables and only used at runtime inside the trusted boot flow. ## Method 1: Configure from the Dashboard 1. Open CVM creation and go to **Advanced Features**. 2. Open **Private Container Registry**. 3. Select one provider: * **No private registry** * **Docker Hub** * **GHCR (GitHub Container Registry)** * **AWS ECR (Elastic Container Registry)** 4. Fill in credentials for the selected provider. 5. Submit deployment. ![Private container registry provider selection](https://mintcdn.com/phalanetwork-1606097b/zBs-xYTNPLuVglvj/images/cloud-private-registry-providers.png?fit=max\&auto=format\&n=zBs-xYTNPLuVglvj\&q=85\&s=5a671bb072656bbbcbb59053a93eadbf) Private Container Registry providers > [!NOTE] > > All registry credentials are encrypted before submission and consumed only at runtime. ## Method 2: Configure with Encrypted Secrets Set the following environment variables for CLI or API workflows. ### Docker Hub Use your Docker Hub username and password (or [access token](https://docs.docker.com/security/for-developers/access-tokens/)). Image paths follow the format `username/image:tag` or `docker.io/username/image:tag`. See [Docker Hub documentation](https://docs.docker.com/docker-hub/) for account and repository setup. | Variable | Required | Description | | - | - | - | | `DSTACK_DOCKER_USERNAME` | Yes | Docker Hub username | | `DSTACK_DOCKER_PASSWORD` | Yes | Docker Hub password or access token | Docker Hub is the default registry — you do **not** need to set `DSTACK_DOCKER_REGISTRY`. ### GHCR ![GHCR credential fields](https://mintcdn.com/phalanetwork-1606097b/zBs-xYTNPLuVglvj/images/cloud-private-registry-ghcr.png?fit=max\&auto=format\&n=zBs-xYTNPLuVglvj\&q=85\&s=f8fc8027f0ac00aa431844af3c65be18) GHCR credential form Use your GitHub username and a PAT (Personal Access Token) with `read:packages` scope. Image paths follow the format `ghcr.io/OWNER/IMAGE:TAG`. With [GitHub CLI](https://cli.github.com/), check your token scopes, add `read:packages` if missing, and print the token: ```bash theme={"system"} gh auth status # check current scopes gh auth refresh -s read:packages # add read:packages if missing gh auth token # print token for DSTACK_DOCKER_PASSWORD ``` You can also create a PAT manually at [GitHub Settings → Personal access tokens](https://github.com/settings/tokens). See [GHCR documentation](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry) for package visibility and permission details. | Variable | Required | Description | | - | - | - | | `DSTACK_DOCKER_USERNAME` | Yes | GitHub username | | `DSTACK_DOCKER_PASSWORD` | Yes | GitHub PAT (Personal Access Token) | | `DSTACK_DOCKER_REGISTRY` | Yes | Must be `ghcr.io` | ### AWS ECR ![AWS ECR credential fields](https://mintcdn.com/phalanetwork-1606097b/zBs-xYTNPLuVglvj/images/cloud-private-registry-aws-ecr.png?fit=max\&auto=format\&n=zBs-xYTNPLuVglvj\&q=85\&s=cd350b818b81224a1ce2824aaad32101) AWS ECR credential form Use an IAM access key with `ecr:GetAuthorizationToken` and `ecr:BatchGetImage` permissions. Image paths follow the format `ACCOUNT_ID.dkr.ecr.REGION.amazonaws.com/REPO:TAG`. With [AWS CLI](https://aws.amazon.com/cli/): ```bash theme={"system"} aws sts get-caller-identity # verify current identity aws ecr describe-repositories --region # list repos to confirm access aws iam create-access-key --user-name # create a new access key ``` Verify registry login: ```bash theme={"system"} aws ecr get-login-password --region | docker login --username AWS --password-stdin .dkr.ecr..amazonaws.com ``` See [Amazon ECR documentation](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html) for repository creation and IAM policy setup. | Variable | Required | Description | | - | - | - | | `DSTACK_AWS_ACCESS_KEY_ID` | Yes | AWS access key ID | | `DSTACK_AWS_SECRET_ACCESS_KEY` | Yes | AWS secret access key | | `DSTACK_AWS_REGION` | Yes | ECR region | | `DSTACK_AWS_ECR_REGISTRY` | Yes | Full ECR registry URL | ## Deploy with Phala Cloud CLI You can deploy with [`phala` CLI](/phala-cloud/phala-cloud-cli/overview) and pass secrets via `-e .env`. ### GHCR example `.env`: ```bash theme={"system"} DSTACK_DOCKER_USERNAME=your_github_username DSTACK_DOCKER_PASSWORD=your_github_pat DSTACK_DOCKER_REGISTRY=ghcr.io ``` `docker-compose.yml`: ```yaml theme={"system"} version: '3.8' services: app: image: ghcr.io/your-org/your-image:v1.0.0 ports: - "3000:3000" environment: - DSTACK_DOCKER_USERNAME=${DSTACK_DOCKER_USERNAME} - DSTACK_DOCKER_PASSWORD=${DSTACK_DOCKER_PASSWORD} - DSTACK_DOCKER_REGISTRY=${DSTACK_DOCKER_REGISTRY} ``` Deploy: ```bash theme={"system"} phala deploy -n my-private-app -c docker-compose.yml -e .env ``` ### AWS ECR example `.env`: ```bash theme={"system"} DSTACK_AWS_ACCESS_KEY_ID=AKIA... DSTACK_AWS_SECRET_ACCESS_KEY=... DSTACK_AWS_REGION=us-east-1 DSTACK_AWS_ECR_REGISTRY=123456789012.dkr.ecr.us-east-1.amazonaws.com ``` ## Deploy with Phala Cloud API When using the API, set the same environment variables listed above. See [Phala Cloud API docs](/phala-cloud/phala-cloud-api/overview) for endpoint details. ## Pull Rate Limits Each registry enforces pull rate limits. During frequent debugging and redeployment cycles, these limits can block image pulls and cause CVM startup failures. ### Docker Hub | Account type | Limit | | - | - | | Unauthenticated | 100 pulls / 6 hours per IP | | Docker Personal (free, authenticated) | 200 pulls / 6 hours | | Docker Pro / Team / Business | Unlimited | > [!WARNING] > > CVM instances pull images on every startup. If you are iterating quickly on a public Docker Hub image **without** setting `DSTACK_DOCKER_USERNAME` / `DSTACK_DOCKER_PASSWORD`, pulls are unauthenticated and share the 100-pull limit across the host IP. Always configure Docker Hub credentials during active development to get the higher authenticated limit. See [Docker Hub pull usage and limits](https://docs.docker.com/docker-hub/usage/pulls/) for details. ### GHCR GitHub does not publish hard pull rate limits for GHCR. Public image pulls are effectively unlimited. Private image pulls are subject to your GitHub plan's data transfer quota. See [GitHub billing for Packages](https://docs.github.com/en/billing/managing-billing-for-github-packages/about-billing-for-github-packages) for details. ### AWS ECR Private ECR (Elastic Container Registry) does not impose per-image pull rate limits. API calls (e.g. `GetAuthorizationToken`) are throttled at \~20 TPS per region per account. See [Amazon ECR service quotas](https://docs.aws.amazon.com/AmazonECR/latest/userguide/service-quotas.html) for details. ## Troubleshooting If private image deployment fails: 1. Verify credentials are valid and not expired. 2. Ensure image path and tag exist. 3. Confirm pull permissions for the account used. 4. Check CVM serial logs for pre-launch errors. ### GHCR-specific checks * `DSTACK_DOCKER_REGISTRY` is set to `ghcr.io` * PAT (Personal Access Token) contains at least `read:packages` * The package visibility and permission settings allow this account to pull For additional assistance, join support groups: 🌍 [Global](https://t.me/+nbhjx1ADG9EyYmI9), 🇨🇳 [Chinese](https://t.me/+4PcAE9qTZ1kzM2M9). # Deployment Cheat Sheet Source: https://docs.phala.com/phala-cloud/cvm/deployment-cheat-sheet Common gotchas and quick fixes when deploying CVMs, including cross-architecture image builds and Docker log sizing. ## Platform Compatibility ### Build Docker Images on x86 Linux When developing on Mac ARM (M1/M2/M3), build your Docker images for `linux/amd64` before deploying. Phala Cloud runs x86\_64 — ARM images will fail to start. **Resources:** * [Docker Multi-platform Builds](https://docs.docker.com/build/building/multi-platform/) * [Building x86 Docker Images on M1 Macs](https://blog.jaimyn.dev/how-to-build-multi-architecture-docker-images-on-an-m1-mac/) * [Running x86\_64 Docker Images on Apple Silicon](https://nesin.io/blog/x86-x86-amd64-docker-mac) ## Performance Optimization ### Limit Docker Log Size Configure logging options for all services to prevent excessive disk usage: ```yaml theme={"system"} x-common: &common-config restart: always logging: driver: "json-file" options: max-size: "100m" max-file: "5" services: example: <<: *common-config image: example:0.1.0 container_name: example ports: - "8000:8000" ``` # OS Image Source: https://docs.phala.com/phala-cloud/cvm/image/overview Deploy confidential applications with dstack - a TEE-based infrastructure platform. > [Phala Cloud](/) is the managed version of dstack deployment that enables developers to deploy programs to CVM (Confidential VM), and to follow the security best practices by default. The dstack SDK is designed to simplify the steps for developers to deploy programs to CVM (Confidential VM), and to follow the security best practices by default. The main features include: * Deploy any docker containers to a CVM on supported TEEs * Remote Attestation API and a chain-of-trust visualization on Web UI * Automatic RA-HTTPS wrapping with content addressing domain on `0xABCD.dstack.host` * Decouple the app execution and state persistent from specific hardware with decentralized Root-of-Trust Now we use an example to show how dstack works. We assume user application constitutes multiple docker container services, and is configured with tools like docker compose. ![Confidential Virtual Machine architecture overview showing multiple Docker containers running inside TEE](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/dstack-cvm%20\(1\).png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=83135271ccb857f0fe97dc3b11789f94) As the architecture shown below, multiple docker containers can run inside one single CVM. The underlying infrastructure we provide is to make sure the application is secure and verifiable. The container uses dstack API to communicate with the underlying `dstack-guest-agent`. `dstack-guest-agent` is the component that is responsible to setup the CVM environment, do remote attestation, and manage the whole lifecycle of docker containers, running inside CVM. `dstack-guest-agent` communicates with a decentralized Key Management Service (KMS), that derives deterministic encryption keys for the application. The keys will be utilized to encrypt storage specific to the application and to protect the its data integrity. With KMS operating independently from any specific TEE instance, your applications avoid vendor lock-in and can be securely migrated between different hardware environments without any data loss. ![dstack CVM architecture diagram showing dstack API, dstack-guest-agent components, and decentralized KMS integration](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/dstack-cvm-arch.png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=8193a9bc12e6245b55facbfbe8aed007) ## Verify If An Application is Running Inside a TEE When the application launched successfully, the RA Report can be exported with specific interfaces provide `dstack`. The RA Report is bound with the application runtime information, such as the docker image hash, the initial arguments passed to the container, and the environment variables. In addition to signature signed by the key hardcoded in the TEE hardware, the RA report will also be signed with a specific key that bond to the application. Anyone can verify the report with tools supports TEE RA report verification. For applications deployed on Phala Intel TDX workers, their RA report will default be exported and verified, a [TEE Attestation Explorer](https://proof.t16z.com/) is provided for people to check. ## Conclusion Now that there is an introduction to the dstack, we can begin the fun part of building on the SDK. There are a few ways to get started depending on your starting point. Let's take a look at the options in [Getting Started](/phala-cloud/getting-started/overview). Or if you are interested in building on Phala Cloud without runing dstack at your own hardware, you can check out the [Phala Cloud](/) page. # Launch Token Source: https://docs.phala.com/phala-cloud/cvm/launch-token Require a secret token before a CVM can boot your app and get its keys, and learn what the token does and does not protect against. A launch token is a secret your CVM must have before it can boot your app. On every boot, the guest OS checks the token against a hash in your compose. If they do not match, the CVM stops before it gets any keys. Launch tokens need dstack OS 0.6.0 or newer. ## What does a launch token protect against? Your compose is public. Anyone can read it, and it holds only the token's hash, not the token. Someone who has your compose but not the token cannot start a CVM that boots it, because the boot check fails. The token does not change your app's keys, app ID or instance ID. It only decides whether the CVM may start. ## What does it not protect against? The token does not hide anything from the host. Phala Cloud passes the token to the CVM through its user config, which Phala Cloud and the node operator can read. Do not treat it as a secret the host cannot see. ## How do I create a CVM with a launch token? Add one of these fields to the create request (`POST /cvms`): * `"launch_token": ""` to use your own token. It must be at least 32 bytes long. * `"generate_launch_token": true` to have Phala Cloud make one. Phala Cloud writes the token's hash into `compose_file.requirements.launch_token_hash` for you. When the create stores a new token on the app, the response that creates the CVM returns it once, in `launch_token`. Save it. With the CLI, use `phala deploy --launch-token ` or `phala deploy --generate-launch-token`. The token belongs to the app, not to one CVM. If the app already has a token, a create uses it. Sending a different token fails with `ERR-03-044`. ## Do replicas need their own token? No. Every CVM of an app shares the app's token, and Phala Cloud gives it to each replica. A replica of a CVM whose compose requires a token fails if the app has no token. ## How do I see the token later? Call `GET /cvms/{cvm_id}/user_config`. When the CVM's compose requires a token, the response includes `launch_token`. Any workspace member who can read the CVM can see it. CVM lists never show it. ## How do I add a token to an app that already runs? 1. Set the app's token with `POST /apps/{app_id}/launch-token`. Send `{"launch_token": ""}`, or an empty body to have Phala Cloud make one. The response returns `launch_token` and `launch_token_hash` once. With the CLI: [`phala apps launch-token set `](/phala-cloud/phala-cloud-cli/apps/launch-token). 2. Update each CVM of the app to require it, with [`PATCH /cvms/{cvm_id}`](/phala-cloud/update/update-cvm-configuration): ```json theme={"system"} { "compose": { "requirements": { "launch_token_hash": "" } } } ``` With the CLI: `phala deploy --cvm-id --launch-token-hash `. The update restarts a running CVM. A stopped CVM stays stopped and checks the token at its next start. A hash that does not match the app's token fails with `ERR-03-043`. ## How do I rotate the token? Rotation works the same way: set a new token on the app with `POST /apps/{app_id}/launch-token`, then update each CVM's `launch_token_hash` to the new hash. Between those two steps, a CVM that restarts fails to boot. It gets the new token, but its compose still has the old hash. Update every CVM right after you set the new token, and avoid restarting CVMs until you are done. ## How do I remove the token? Remove it in two steps, in this order: 1. Update each CVM to drop the hash: ```json theme={"system"} { "compose": { "requirements": { "launch_token_hash": null } } } ``` With the CLI: `phala deploy --cvm-id --launch-token-hash ""`. 2. Clear the app's token with `DELETE /apps/{app_id}/launch-token`, or `phala apps launch-token clear `. If you clear the app's token first, every CVM whose compose still has the hash fails at its next boot. ## Does this work with Onchain KMS? Yes. Adding, changing or removing the hash is a compose change, so it gives the CVM a new compose hash. Register that hash on your app contract as for any other update. See [What changes for a CVM on Onchain KMS?](/phala-cloud/update/update-cvm-configuration#what-changes-for-a-cvm-on-onchain-kms) # Scale with Multiple Replicas Source: https://docs.phala.com/phala-cloud/cvm/multi-replica-scaling Understand when replicas make sense, what you get from them, and where they fall short. For concrete replication steps, see Replicating CVMs. Replicas let you run several copies of the same application side by side on Phala Cloud. This page covers the concepts and the decision criteria. For concrete dashboard and CLI steps, see [Replicating CVMs](/phala-cloud/cvm/replicating-cvms). ## What a Replica Is A replica is an independent CVM instance provisioned from an existing source CVM. Replicas of the same app share an `app_id` and the same compose hash, but each replica has its own: * `vm_uuid`, endpoint URL, and internal IP * TEE attestation report * Process state, memory, and local disk * Billing meter Replicas are created one at a time from an existing source, not as an atomic group. If you ask for three replicas, Phala Cloud creates three independent CVMs whose only formal relationship is the shared `app_id`. ## What Replicas Give You **Horizontal capacity.** More replicas serve more concurrent traffic, assuming your workload is stateless or has a shared data layer behind it. **Failure isolation.** If one replica's node goes down for maintenance, the others keep serving. A single CVM has no such fallback. **Regional placement.** You can pin replicas to physical nodes in different regions using the `node` name when you replicate, which reduces latency for geographically distributed users. **Independent attestation.** Each replica produces its own TDX quote. A relying party can verify any individual replica without trusting the others, which matters when the attestation is part of your security story. ## What Replicas Do Not Give You **Load balancing.** Phala Cloud does not distribute traffic across replicas. Each replica gets its own public endpoint. You need an external load balancer, DNS round-robin, or service mesh to split traffic. **Shared state.** Replicas do not share filesystems, memory, or any in-process state. Two replicas writing to their local disks write to two separate disks. If your app keeps state locally, replicating it will cause divergence. **Automatic propagation of compose updates.** Updating the compose of one replica does not update the others. Each replica is its own CVM and must be updated individually. See [Upgrade Application](/phala-cloud/update/upgrade-application) for the update flow. **Linear performance scaling.** Two replicas do not automatically serve twice the throughput. The upstream bottleneck (database, queue, external API) often dominates. Measure before assuming. ## When to Use Replicas Use replicas when: * The workload is **stateless**, or reads and writes go to a shared backing store (managed Postgres, object storage, an external queue). * You need **high availability** and one CVM outage would be unacceptable. * You want to **distribute traffic geographically** and you have a way to route users to the nearest replica. * The attestation model assumes **independent instances** — each replica must be verifiable on its own. Avoid replicas when: * The workload keeps **state on local disk** and you have no replication layer. Two divergent copies of the same database do not make a cluster. * The workload assumes it is the **only writer** to an external resource (a singleton job scheduler, a leader-elected worker). * You are trying to solve a **vertical scaling** problem. If one replica is slow because it is CPU- or memory-bound, bigger instance types often help more than more copies. See [Resize Resources](/phala-cloud/update/resize-resource). ## Cost Model Each replica is billed as an independent CVM at the full rate of its instance type. Three `tdx.medium` replicas cost three times one `tdx.medium`. There is no bulk discount for adding replicas. Factor this into your scaling budget before raising the replica count. Stopping a replica pauses compute billing but keeps its disk allocation, which is billed separately. Deleting a replica releases both. ## How to Create Replicas The concrete steps live in [Replicating CVMs](/phala-cloud/cvm/replicating-cvms), which covers: * The dashboard **Scale** dialog on the app detail page * The `phala cvms replicate` CLI command * Onchain KMS workflows for contract-governed apps * The replicate API for custom integrations ## Related Documentation * [Replicating CVMs](/phala-cloud/cvm/replicating-cvms) — concrete dashboard, CLI, and API steps. * [Upgrade Application](/phala-cloud/update/upgrade-application) — how to update compose or environment, including across replicas. * [Resize Resources](/phala-cloud/update/resize-resource) — vertical scaling when more replicas is not the answer. * [Deploy Your First CVM](/phala-cloud/getting-started/deploy-first-cvm) — single-CVM getting started. # CVM Overview Source: https://docs.phala.com/phala-cloud/cvm/overview Landing page for CVM creation and management on Phala Cloud. Links to deployment methods, scaling, and lifecycle operations. ## Choose Your Deployment Method Phala Cloud offers multiple ways to create and deploy a Confidential Virtual Machine (CVM). Learn about [Confidential Virtual Machine technology](https://phala.com/confidential-vm) and its enterprise applications. ### Option 1: Phala Cloud dashboard The dashboard walks you through CVM creation with a visual interface. Use it if you are new to Phala Cloud, prefer graphical tooling, or want to deploy without touching the command line. [**Create with Docker Compose →**](/phala-cloud/cvm/create-with-docker-compose) ### Option 2: `phala` CLI The CLI is the right tool for automated deployments, CI/CD pipelines, and scriptable infrastructure. Use it if you are comfortable in a terminal and want reproducible deployments. [**Follow the CLI Guide →**](/phala-cloud/phala-cloud-cli/start-from-cloud-cli) ## CVM Management Features After deployment, manage your CVMs from the dashboard or the API. ### Monitoring * **CVM status** — track the health and status of your CVMs * **Resource usage** — monitor CPU, memory, and storage consumption * **Logs** — view application logs and system messages ### Upgrades * **Environment variables** — update your application's encrypted secrets * **Docker images** — upgrade your application's Docker image * **Resource allocation** — adjust CPU, memory, and storage ### Scaling * **Horizontal scaling** — run multiple replicas of the same CVM for availability and regional distribution. See [Scale with Multiple Replicas](/phala-cloud/cvm/multi-replica-scaling) for concepts and [Replicating CVMs](/phala-cloud/cvm/replicating-cvms) for concrete steps. * **Vertical scaling** — [resize a single CVM's CPU, memory, or disk](/phala-cloud/update/resize-resource) to handle more load per instance. ### Security * **Data protection** — end-to-end encryption of sensitive data at rest * **Access control** — restrict who can reach your CVMs and their logs ## CVM Management API Phala Cloud provides an [API](/phala-cloud/phala-cloud-api/overview) for managing CVMs programmatically. ## Next Steps After creating your CVM, you probably want to: * [Set secure environment variables](/phala-cloud/cvm/set-secure-environment-variables) * [Expose an HTTP service](/phala-cloud/networking/expose-http-service) * [Set up monitoring](/phala-cloud/monitoring/public-logs) * [Replicate the CVM for scale or availability](/phala-cloud/cvm/replicating-cvms) # Replicating CVMs Source: https://docs.phala.com/phala-cloud/cvm/replicating-cvms Scale an existing CVM by creating replicas on the same or different nodes. Covers the dashboard flow, the phala CLI, Cloud KMS, and Onchain KMS approval workflows. Replication creates a new CVM instance with the same configuration as an existing source CVM. Use it to scale out, move a workload to a different node, or split traffic across replicas in different regions. This guide focuses on the two workflows most users should use: the Phala Cloud dashboard and the `phala` CLI. An API reference is included at the end for programmatic integrations. ## Mental Model A replica is a **new, independent CVM instance** provisioned from a **source CVM**. It gets its own `vm_uuid`, endpoint, and attestation. It does not share storage, memory, or running state with the source. **Copied from source (you do not re-specify these):** * The compose file and pre-launch script (same `compose_hash`) * The application ID (all replicas of an app share one `app_id`) * The KMS type and chain * The encrypted environment variables **Things you can change at replication time:** * The target node (pin the replica to a specific node, or let the platform pick one) * The encrypted environment variables (optional override — pass a new encrypted blob to replace the inherited one) **Not carried over:** * Running processes, in-memory state * Contents of persistent volumes and any data written at runtime * Active network connections ### The three replication workflows Which workflow applies depends on the source CVM's KMS setup. You do not pick it — it is determined by how the source was deployed. | Workflow | Applies when | What you do | | - | - | - | | **Simple** | Source uses Cloud KMS or no KMS | One step: request the replica and wait for it to come up. | | **Onchain, auto-registered** | Source uses Onchain KMS and the DstackApp owner is an EOA with an accessible private key | The CLI detects missing on-chain registrations, signs `addComposeHash` / `addDevice` with the provided key, then creates the replica. | | **Onchain, manual approval** | Source uses Onchain KMS and the DstackApp owner is a Safe, timelock, or DAO | Prepare the replica, collect the on-chain payload, obtain multisig approval, then commit. | Onchain KMS adds gates because the DstackApp contract — not Phala Cloud — decides which compose hashes and devices are allowed to run under the app's identity. If the new replica lands on a node whose device is not already allowlisted, someone has to sign `addDevice` before the KMS will release keys. See [Deploying with Onchain KMS](/phala-cloud/key-management/deploying-with-onchain-kms) for the full model. ## Prerequisites Before replicating: * The **source CVM** exists in your current workspace. It can be running or stopped. * The **target node** (if you pin one) is deployable for your workspace, has the required OS image, and has enough vCPU, memory, and disk. * Your **workspace has enough Balance** to cover the new instance. Replicas are billed like any other CVM. For Onchain KMS workflows only: * **Gas** in your signing wallet on the chain the DstackApp lives on (typically Base — 0.001 ETH is plenty for the first few transactions). * **An RPC URL** for that chain. The CLI uses a default public endpoint, or you can pass `--rpc-url` / set `ETH_RPC_URL`. * **Either a private key** (for auto-registration) **or a multisig wallet** (for manual approval). ## Replicate from the Dashboard The dashboard wraps replication in a single "Scale" action on the app detail page. It is the fastest way to add replicas interactively. ### Steps 1. Open the app detail page for the application you want to scale. 2. Click **Scale** to open the Scale dialog. The dialog shows the current list of replicas and lets you add or remove instances. 3. **Pick a source configuration.** If your app has multiple live configurations (different compose hashes), choose the one you want to replicate. If there is only one, the dashboard selects it automatically. 4. **Choose a target node.** Leave it on **Auto** to let the platform schedule the replica, or pick a specific node from the list. The list is filtered to nodes your workspace can deploy to. 5. **Set the number of replicas to add.** Use the `+` / `−` controls, then click the add button. 6. The dashboard creates replicas one by one and shows their status as they provision. ### When the dashboard prompts for on-chain action If the source uses Onchain KMS and the target node's device is not yet allowlisted, the Scale dialog warns you before creating the replica. You then have two options: * **Approve from the dashboard with a connected wallet.** The dashboard walks you through signing `addDevice` (and `addComposeHash` if needed) using the wallet connected to the app. This is the recommended path when the DstackApp owner is an EOA you control. * **Approve externally.** If the owner is a Safe or another contract, use the CLI's manual workflow described below to obtain a commit token, sign on-chain through your multisig, then commit the replica. ## Replicate with the CLI The CLI is the right tool for scripting, CI/CD, and any workflow that does not start from the dashboard. It also exposes the lower-level prepare / commit flow used for multisig-gated apps. Install or update the CLI before starting: ```bash theme={"system"} npm install -g phala phala login ``` ### Basic replication Replicate a CVM to a specific node: ```bash theme={"system"} phala cvms replicate --node prod6 ``` `--node` accepts a physical node name, for example `prod6`, `prod7`, or `use2`. Run `phala nodes` to see the node names your workspace can use. > [!NOTE] > > `--node-id` and `--teepod-id` no longer exist. Use `--node` with the node name instead. Omit `--node` to let the backend schedule the replica on any node with capacity and a compatible image: ```bash theme={"system"} phala cvms replicate ``` `` can be a CVM UUID, an `app_id`, or a unique CVM name. Prefer UUIDs in scripts — names can collide and `app_id` is ambiguous when an app has more than one live configuration (see [Multi-instance apps](#multi-instance-apps) below). On success the CLI prints the new replica's UUID, node, and dashboard URL: ```text theme={"system"} Source CVM ID: app_abc123 Team: my-workspace CVM UUID: 550e8400-e29b-41d4-a716-446655440000 App ID: 0x1234567890abcdef1234567890abcdef12345678 Name: my-app-replica-1 Status: provisioning Node: prod6 (ID: 5) vCPUs: 2 Memory: 4096 MB Disk Size: 40 GB App URL: https://cloud.phala.com/my-workspace/apps/0x1234567890abcdef1234567890abcdef12345678/instances/550e8400-e29b-41d4-a716-446655440000 ``` ### Replicating with new environment variables By default the replica inherits the source CVM's encrypted environment. See [Environment Variables](/phala-cloud/cvm/set-secure-environment-variables) for the full encryption model and the rules around `allowed_envs`. To change an env var on the replica — for example, to give a staging replica a different database URL — pass `--env-file`: ```bash theme={"system"} phala cvms replicate --node prod6 --env-file .env.prod ``` The CLI: 1. Parses the env file locally. 2. Fetches the CVM's per-application encryption public key from the backend. 3. Encrypts each env var with that key. 4. Sends only the ciphertext to the replicate endpoint. Plaintext env values never leave your machine. Only the running CVM, after the KMS releases its keys, can decrypt them. Env var names you pass with `--env-file` must already appear in the app's `allowed_envs` list — the list is fixed by the compose hash, so replication cannot introduce new names. ### Multi-instance apps When an app has multiple live CVMs with different compose hashes — for example, a canary deployment alongside the stable version — the CLI needs to know which configuration you want to replicate. Running the basic command with just the `app_id` fails: ```text theme={"system"} $ phala cvms replicate app_abc123 Error: ERR-03-009 — This app has multiple live CVM instances. Please specify compose_hash to choose which revision to replicate. ``` Two ways to fix it: * **Point at a specific source instance** by UUID. The UUID uniquely identifies one compose hash. ```bash theme={"system"} phala cvms replicate 550e8400-e29b-41d4-a716-446655440000 --node prod6 ``` * **Pass `--compose-hash` explicitly.** Look up the compose hash of the configuration you want (from the dashboard or `phala cvms list`), set `COMPOSE_HASH` to that value, and pass it on the command line: ```bash theme={"system"} phala cvms replicate app_abc123 --compose-hash "$COMPOSE_HASH" --node prod6 ``` ### Onchain KMS: auto-registration When the source CVM uses Onchain KMS and you own the DstackApp through an EOA, you can register and replicate in one command by passing a private key. The CLI detects whether the target node's device and the compose hash are already allowlisted and only writes the transactions that are missing. ```bash theme={"system"} # Set PRIVATE_KEY securely before running this command. export ETH_RPC_URL=https://base-mainnet.example.com phala cvms replicate \ --node prod6 \ --private-key $PRIVATE_KEY \ --rpc-url $ETH_RPC_URL ``` The sequence is: 1. The backend prepares the replica and computes the `compose_hash` and the target node's `device_id`. 2. The CLI reads the DstackApp contract to see which registrations are missing. 3. If the device is not allowlisted, the CLI calls `addDevice` and waits for confirmation. 4. If the compose hash is not allowlisted, the CLI calls `addComposeHash` and waits for confirmation. 5. The CLI commits the prepared replica, the backend creates the instance, and the replica boots. If everything is already registered, the CLI skips straight to step 5 and the replica comes up immediately. ### Onchain KMS: manual approval (multisig) When the DstackApp owner is a Safe, a timelock, or any other contract that cannot sign from the CLI, use the prepare + commit flow. **Step 1. Prepare.** Ask the backend to reserve the replica and emit the on-chain payload: ```bash theme={"system"} phala cvms replicate --node prod6 --prepare-only ``` The command does not create the replica. It prints a commit token, compose hash, app ID, device ID, and their on-chain registration status. Save the complete values for the next steps. The commit token is valid for 14 days. Save it somewhere your approvers can reach. **Step 2. Sign on-chain.** From your Safe (or whichever contract owns the DstackApp), call the missing writes on the DstackApp address printed above. Typically: * `addComposeHash` with the returned compose hash — if it is not registered. * `addDevice` with the returned device ID — if it is not registered. Submit the transaction(s) through the Safe UI and wait for execution. Record the final transaction hash. **Step 3. Commit.** Set `COMMIT_TOKEN` and `COMPOSE_HASH` to the values returned by the prepare step, and `TRANSACTION_HASH` to the executed transaction hash. Pass them back to the CLI: ```bash theme={"system"} phala cvms replicate \ --commit \ --token "$COMMIT_TOKEN" \ --compose-hash "$COMPOSE_HASH" \ --transaction-hash "$TRANSACTION_HASH" ``` If both writes are already on-chain and you just want to finalize, pass `--transaction-hash already-registered`. The backend re-reads the contract, verifies the state, and creates the replica. See [Multisig and Governance](/phala-cloud/key-management/multisig-governance) for guidance on structuring the Safe ownership itself. ## API Reference For programmatic integrations — custom portals, CI systems, or orchestration that cannot shell out to the CLI — Phala Cloud exposes the replicate endpoints directly. Prefer the dashboard or CLI for interactive use; the raw API gives you no convenience on top of what the CLI already does. ### POST `/cvms/{cvm_id}/replicas` Create a replica from a source CVM. | Field | Location | Required | Description | | - | - | - | - | | `cvm_id` | path | yes | Source CVM identifier. UUID, `app_id`, or unique name. | | `node` | body | no | Physical target node name, such as `prod6`. Omit to let the backend pick. | | `compose_hash` | body | no | Explicit compose hash. Required when the source app has more than one live configuration. | | `encrypted_env` | body | no | Hex-encoded encrypted env blob. Omit to inherit the source's env. | | `X-Prepare-Only` | header | no | Set to `true` to prepare the replica without creating it, for the manual approval flow. | On success the response is a `VM` object representing the new replica. On Onchain KMS prerequisites failure the response is HTTP 465 with a structured body containing `commit_token`, `compose_hash`, `device_id`, and `onchain_status`; use those fields as inputs to the commit endpoint after completing on-chain approval. ### POST `/apps/{app_id}/cvms/{vm_uuid}/replicas` Alternative form that takes the app and source instance UUIDs in the URL. Same request body and response shape as the CVM-scoped endpoint. Use this when your integration already tracks `(app_id, vm_uuid)` pairs. ### POST `/cvms/{vm_uuid}/commit-replica` Finalize a replica prepared with `X-Prepare-Only: true`. | Field | Required | Description | | - | - | - | | `token` | yes | Commit token from the prepare response. | | `compose_hash` | yes | The same compose hash returned during prepare. | | `transaction_hash` | yes | On-chain transaction hash for the registration write, or `"already-registered"` when the prerequisites were met before commit. | The response is the same `VM` object you would get from a direct replicate call. ## Errors Replicate calls share the same structured error envelope as the rest of the Phala Cloud API. Common codes you may hit during replication: | Code | Meaning | | - | - | | `ERR-01-005` | Onchain KMS requires compose hash or device registration (HTTP 465). Use auto-registration or the prepare + commit flow. | | `ERR-02-003` / `ERR-02-004` / `ERR-02-005` | Target node is out of vCPU, memory, or slots. Drop `--node` or pick a different node. | | `ERR-03-006` | The source CVM's OS image is not available on the target node. | | `ERR-03-008` | The source instance is not visible in the current workspace. | | `ERR-03-009` | The source app has multiple live instances; pass `--compose-hash` or use a specific source UUID. | | `ERR-04-001` | Workspace Balance is too low. | See [Error Codes](/phala-cloud/references/error-codes) for the full catalog, HTTP status mappings, and the exception class behind each code. ## Related Documentation * [Scale with Multiple Replicas](/phala-cloud/cvm/multi-replica-scaling) — When replicas help and when they do not. * [Environment Variables](/phala-cloud/cvm/set-secure-environment-variables) — Encrypted secrets model, `allowed_envs`, and update semantics. * [Deploying with Onchain KMS](/phala-cloud/key-management/deploying-with-onchain-kms) — First-deploy workflow for contract-governed CVMs. * [Multisig and Governance](/phala-cloud/key-management/multisig-governance) — Transferring DstackApp ownership to a Safe and running updates through it. * [Device Management](/phala-cloud/key-management/device-management) — How device IDs are derived and allowlisted. * [Error Codes](/phala-cloud/references/error-codes) — Full error reference. # Environment Variables Source: https://docs.phala.com/phala-cloud/cvm/set-secure-environment-variables Manage encrypted secrets and built-in environment variables for your CVM. ## Encrypted Secrets When your application requires environment variables, **never set them directly in the Docker Compose file**. Instead, use the **Encrypted Secrets** section to ensure your sensitive data remains secure. All encrypted secrets are **encrypted locally on the client side** (using X25519 + AES-256-GCM) before being sent to the server. The Phala Cloud server never sees the plaintext values — only the CVM's TEE can decrypt them at boot time. Encrypted secrets are a list of key-value pairs that are passed into the docker compose file in the same way as the variables defined in `.env` files. You should first define the encrypted secrets in the dashboard (or CLI), and then reference them in the docker compose file using the `${KEY}` syntax. A typical use case is passing secrets to your containers via environment variables, using the `environment:` Docker Compose directive. > [!WARNING] > > Updating encrypted secrets is a **full replacement** operation. You cannot update a single variable > — every update requires submitting the complete set of all variables. This applies to both the > dashboard and the CLI. 1. **Declare Environment Variables in Docker Compose** Define your environment variables in the Docker Compose file using variable substitution: ```yaml theme={"system"} services: your-service: environment: - OPENAI_API_KEY=${OPENAI_API_KEY} - TWITTER_API_KEY=${TWITTER_API_KEY} ``` > **Important:** Do not use double quotation marks around variables:\ > ❌ `OPENAI_API_KEY="${OPENAI_API_KEY_IN_ENV}"` 2. **Set Values in Encrypted Secrets** Configure the actual values in the **Encrypted Secrets** section of the dashboard. ![Setting environment variables in Encrypted Secrets](https://mintcdn.com/phalanetwork-1606097b/416gZMDMREnPDd33/images/cloud-set-env.png?fit=max\&auto=format\&n=416gZMDMREnPDd33\&q=85\&s=c28c9c712ac10392ce1510e5937945da) Encrypted Secrets configuration interface > [!NOTE] > > Secret names don't need to match your Docker Compose environment variable names. You can name > secrets anything in the UI, then reference them in Docker Compose using `${KEY}` syntax. > > Besides the environment variables, you can also reference the encrypted secrets in any other place > like the `command:` docker compose directive. However, you should be careful to not leak the secret > values in the logs or other places. > > Learn more about Docker .env files [here](https://docs.docker.com/compose/how-tos/environment-variables/set-environment-variables/). We recommend using **Text** type for environment variables if you have many variables to set. ## Set Secrets via CLI The CLI encrypts variables locally before sending them, just like the dashboard does. ```bash theme={"system"} # Pass individual variables phala deploy -e OPENAI_API_KEY=sk-xxx -e DATABASE_URL=postgres://... # Or pass a .env file phala deploy -e .env ``` To update secrets on an existing CVM, redeploy with the new values. Remember that this is a full replacement, so include all variables every time. ## Set Secrets via SDKs Each SDK provides methods to update environment variables programmatically. The encryption happens client-side before the API call. ```typescript JavaScript theme={"system"} import { createClient } from "@phala/cloud"; const client = createClient({ apiKey: process.env.PHALA_CLOUD_API_KEY }); await client.updateCvmEnvs({ id: "app_abc123", envs: { OPENAI_API_KEY: "sk-xxx", DATABASE_URL: "postgres://user:pass@host:5432/db", }, }); ``` ```python Python theme={"system"} from phala_cloud import create_client client = create_client() client.update_cvm_envs({ "id": "app_abc123", "envs": { "OPENAI_API_KEY": "sk-xxx", "DATABASE_URL": "postgres://user:pass@host:5432/db", }, }) ``` ```go Go theme={"system"} package main import ( "context" "log" phala "github.com/Phala-Network/phala-cloud/go" ) func main() { client, _ := phala.NewClient() err := client.UpdateCVMEnvs(context.Background(), "app_abc123", &phala.UpdateCVMEnvsRequest{ Envs: map[string]string{ "OPENAI_API_KEY": "sk-xxx", "DATABASE_URL": "postgres://user:pass@host:5432/db", }, }) if err != nil { log.Fatal(err) } } ``` ## Set Secrets via Terraform The Terraform provider supports auto-encryption mode where you provide plaintext values and the provider handles encryption. ```hcl theme={"system"} resource "phala_app" "web" { name = "my-app" size = "tdx.medium" region = "US-WEST-1" disk_size = 40 env = { OPENAI_API_KEY = var.openai_api_key DATABASE_URL = var.database_url } docker_compose = <<-YAML services: app: image: myregistry/my-app:latest ports: - "80:80" environment: - OPENAI_API_KEY=${OPENAI_API_KEY} - DATABASE_URL=${DATABASE_URL} YAML } ``` > [!WARNING] > > Even in auto-encryption mode, plaintext values are stored in your Terraform state file. Use a remote backend with encryption at rest, or switch to manual encrypted mode for maximum security. ## Best Practices **Never put secrets in the compose file.** Always use encrypted secrets and reference them with `${KEY}` syntax. The compose file is stored on the server, but encrypted secrets are only decryptable inside the TEE. **Use a `.env` file locally for development.** Keep a `.env.example` in your repo with placeholder values and add `.env` to `.gitignore`. This makes it easy for teammates to set up their own credentials. **Rotate secrets by redeploying.** When you update encrypted secrets, the CVM restarts to pick up the new values. Plan for brief downtime, or run [multiple replicas](/phala-cloud/cvm/replicating-cvms) and rotate them one at a time to maintain availability. **Keep secret names consistent.** Use the same key names in your compose file and encrypted secrets to avoid confusion. While Phala Cloud allows different names, matching them makes your configuration easier to audit. ## What happens to secrets when I roll back? Nothing changes. A rollback restores the Docker Compose file from the earlier revision, but your CVM keeps the encrypted secrets it has now. We do this so a rollback never brings back an old secret you already rotated. This matters after a failed update. If the update changed your secrets, the rollback keeps those new values. If the bad secrets caused the failure, fix them in the same step. Rolling back can also fail to start if the earlier compose file needs a variable your current secrets do not have. In that case, send a full set of secrets along with the rollback, encrypted the same way as at deploy time. With the API or SDKs, pass the encrypted blob as `encrypted_env`. If you roll back several CVMs of one app at once, they all get the same blob. ## Built-in Environment Variables Phala Cloud attaches a [default pre-launch script](https://github.com/Dstack-TEE/dstack-examples/tree/main/phala-cloud-prelaunch-script) to every CVM deployment. This script runs before your Docker Compose services start, handling private registry authentication, root access setup, and injecting environment variables you can reference in your `docker-compose.yml`. The built-in variables documented below are provided by the **default pre-launch script**. If you replace it with a custom script via [`--pre-launch-script`](/phala-cloud/phala-cloud-cli/deploy#deploy-with-pre-launch-script), these variables will no longer be available unless your script implements them. > [!NOTE] > > The pre-launch script is versioned (currently **v0.0.14**). New deployments always use the latest > version, but existing CVMs keep the version they were deployed with — there is no automatic update. > To use a newer version, you need to redeploy your CVM. ### Private Docker Registry Authentication Set the following encrypted secrets to pull images from a private Docker registry (Docker Hub, GHCR (GitHub Container Registry), etc.): | Variable | Required | Description | | - | - | - | | `DSTACK_DOCKER_USERNAME` | Yes | Registry username | | `DSTACK_DOCKER_PASSWORD` | Yes | Registry password or access token | | `DSTACK_DOCKER_REGISTRY` | No | Registry URL. Defaults to `docker.io`. Set to `ghcr.io` for GHCR, etc. | The pre-launch script logs in to the registry before pulling your images. If login fails, the CVM boot is aborted. ### AWS ECR Authentication Set the following encrypted secrets to pull images from Amazon ECR (Elastic Container Registry): | Variable | Required | Description | | - | - | - | | `DSTACK_AWS_ACCESS_KEY_ID` | Yes | AWS access key ID | | `DSTACK_AWS_SECRET_ACCESS_KEY` | Yes | AWS secret access key | | `DSTACK_AWS_REGION` | Yes | AWS region of your ECR repository | | `DSTACK_AWS_ECR_REGISTRY` | Yes | Your ECR registry URL | | `DSTACK_AWS_SESSION_TOKEN` | No | For temporary AWS credentials (e.g. assumed roles). If expired, the CVM continues to boot but may fail to pull images. | > [!NOTE] > > The AWS CLI is installed inside the CVM when ECR credentials are detected — you do not need to > include it in your Docker image. ### Root Access | Variable | Required | Description | | - | - | - | | `DSTACK_ROOT_PASSWORD` | No | Linux root password inside the CVM. Since dstack 0.5.6, SSH rejects password logins, so this does not get you an SSH session. If you do not set it, a random 32-character password is generated. | | `DSTACK_ROOT_PUBLIC_KEY` | No | SSH public key added to `/home/root/.ssh/authorized_keys` | | `DSTACK_AUTHORIZED_KEYS` | No | SSH authorized keys for `/home/root/.ssh/authorized_keys`. Overwrites `DSTACK_ROOT_PUBLIC_KEY` if both are set. | > [!WARNING] > > For security, `DSTACK_ROOT_PASSWORD`, `DSTACK_ROOT_PUBLIC_KEY`, and `DSTACK_AUTHORIZED_KEYS` are > **unset** from the environment immediately after they are applied. They will **not** be visible to > your Docker Compose services. ### App Metadata The following variables are automatically injected by the pre-launch script. You do not need to set them — they are available in your `docker-compose.yml`. | Variable | Description | | - | - | | `DSTACK_APP_ID` | Unique identifier for the CVM app | | `DSTACK_GATEWAY_DOMAIN` | Gateway domain for accessing the app | | `DSTACK_APP_DOMAIN` | Default app domain. Equals `${DSTACK_APP_ID}.${DSTACK_GATEWAY_DOMAIN}`, routes to port 80. | You can reference these in your Docker Compose file: ```yaml theme={"system"} services: my-app: environment: - APP_ID=${DSTACK_APP_ID} - PUBLIC_URL=https://${DSTACK_APP_DOMAIN} ``` > [!NOTE] > > `DSTACK_APP_DOMAIN` points to port 80 by default. To access a different port, use the pattern > `${DSTACK_APP_ID}-.${DSTACK_GATEWAY_DOMAIN}`. For example, to access port 3000: > `${DSTACK_APP_ID}-3000.${DSTACK_GATEWAY_DOMAIN}`. # FAQ Source: https://docs.phala.com/phala-cloud/faqs Deploy confidential applications with Phala Cloud's managed TEE infrastructure. ## Frequently Asked Questions ### What is Phala Cloud? Phala Cloud is a platform that provides TEE virtual machines. These VMs offer hardware-level isolation through Intel TDX technology, allowing for secure and private computation. ### How are the VMs provisioned? Each application gets one CVM (Confidential Virtual Machine), which is one TDX. TDX is a VM technology that provides hardware-level isolation powered by Intel CPU. ### What are the limitations of the TEE environment in Phala? Can my app access file and network IO? * Apps in CVM cannot directly access the host file/network IO. * Internet access for the app is allowed but must go through the proxy module. * Local filesystem access within the CVM is supported, similar to how a docker container accesses its host machine. * Direct access to the host's filesystem is not allowed when deployed on Phala Cloud ### How can I serve a REST API in Phala's TEE environment? You need a web server for serving REST APIs. Requests will be forwarded through a proxy module (dstack-gateway) to CVM. Exposed ports in the docker-compose file will generate a public endpoint for accessing your service. ### Can I run an app with a database inside the container? Yes, local disk access is supported within the container environment, allowing you to run an app with a database. ### Can the encrypted environment variable be accessed by any other part, including the host OS? No, it's encrypted on the client side and sent to the CVM using X25519 encryption scheme. The variables can only be decrypted inside the CVM. ### Can Docker logs be accessed by any other part, including the host OS? Docker logs are not end-to-end encrypted. When **Public Logs** is enabled, anyone with a container's log URL can view its output without signing in to Phala Cloud. To get the URL, open the CVM detail page, click **Logs**, select the container under **Docker Containers**, then choose **Open in New Window** and copy the URL from the browser address bar. For an existing CVM, manage this setting under **Settings → Worker Attestation Visibility Settings → Public Logs**. When **Public Logs** is disabled, Phala Cloud does not provide Docker log URLs. Use a [private log viewer](/phala-cloud/monitoring/private-log-viewer) or forward logs to a private external service instead. Changing the setting restarts the CVM. ### Is application data persistent on the disk? Yes, the data you write to the filesystem inside Docker will persist on the disk and be encrypted. Restarting or upgrading will not affect data recovery. To save data on disk, you need to [configure volumes](https://docs.docker.com/reference/compose-file/volumes/) in the Docker Compose file and write data to the correct path. ### Can I deploy / manage / upgrade CVMs programmatically? Yes. Resources for programmatic management: * [Cloud API docs](/phala-cloud/phala-cloud-api/overview) * [API examples (JavaScript)](https://github.com/Phala-Network/phala-cloud) * [CI/CD pipeline setup](/phala-cloud/phala-cloud-cli/ci-cd-automation/setup-a-ci-cd-pipeline) ### Does the “update” feature sync the latest Docker image? No. By default, Docker does not proactively update the image unless the image reference is changed (e.g., by modifying the tag or the hash), even if an update is triggered. This is because the update feature is essentially equivalent to running: `docker compose down && docker compose up`. To ensure the image is actually updated, it's recommended to always update the tag. Additionally, for best security practices, it's advised to include the image hash to trace the TEE proof back to the exact Docker image file. ### Does a CVM support multiple containers? Yes, you can deploy multiple containers per CVM through the docker compose file. ### Does the cloud support a firewall? You can apply firewall rules inside your containers. For example, add Nginx to apply IP address filters or WAF rules. There is no cloud-level firewall currently. ### Does it support Terraform deployment? Yes! The Terraform provider is now available. See the [Terraform Provider documentation](/phala-cloud/references/terraform-provider/overview) for setup and usage. ### Can CVM accept arbitrary TCP / TLS connections? CVMs support both HTTP-over-TLS (Zero Trust HTTPS) and TCP-over-TLS. See the [TCP port forwarding example](https://github.com/Dstack-TEE/dstack-examples/tree/main/tcp-port-forwarding) for exposing SSH or other TCP ports. Under the hood, the TEE wraps the tcp ports you have exposed in docker with TLS. The gateway then routes the TLS traffic based on SNI, the domain name attached to every TLS connection. TLS is needed because it's the only way to multiplex the tcp traffic. When using the tcp-port-forwarding example, it automatically helps you set up the domain and TLS certificate securely in TEE (thus “Zero Trust”), and reverse-proxy the incoming traffic to your tcp port. You can also manually accept TLS traffic in your CVM and handle the certificate on the application level. ### Is there a simulator available for testing? Yes. The Phala Cloud CLI includes a [simulator](/phala-cloud/phala-cloud-cli/simulator) for local testing. Some new workspaces are also offered a welcome credit when they add a card, while the offer lasts. The dashboard shows the amount before you claim it. ### Is Phala Cloud based on serverless functions or traditional VMs? What are the startup and shutdown times? Phala Cloud uses a VM-based model, not serverless functions. While exact boot time can vary, users can create a CVM to measure startup latency. For most scenarios, it's best to keep a small instance running continuously and scale up during traffic spikes. Spinning up a new VM for every request may not be efficient. There is currently no TEE-based serverless function, but the team is open to collaborating on building one. ### How can I access my docker volume data after deploy? The docker volume is persisted in the TEE encrypted volume. By default it's not accessible by humans or the cloud. However, if your business logic requires to expose the volume or part of the volume, you can do it with your backend code manually. For example if you want to allow users to upload images and download it later, you can implement a simple backend web server with file uploading and static file serving. Here are the example tutorials from Flask ([upload](https://flask.palletsprojects.com/en/stable/patterns/fileuploads/), [static file serving](https://flask.palletsprojects.com/en/stable/tutorial/static/)). And it's also easy to find the tutorials for other web servers (nginx, express, etc). ### Can I send encrypted values (like API keys) through the Phala Cloud API for deployment? Yes, Phala Cloud supports sending encrypted values (e.g., Twitter API keys/secrets) through the API. You must encrypt the variables locally before sending them. The encrypted values can then be included in your deployment request. You can also send them through the feature of Encrypted Environment Variable. If you use CLI, you can set it like [here](https://github.com/Phala-Network/phala-cloud-cli?tab=readme-ov-file#environment-variables-management), or if you on the Cloud UI, use the "Encrypted Environment Variables" feature during VM creation. ### How long does it take to deploy a Docker image in Phala Cloud? Deployment time depends on the Docker image size and decompression requirements: * A small Python-based image (e.g., kennethreitz/httpbin) typically takes about 1-2 minutes. * A larger image like ElizaOS/Eliza (1.4GB) takes 20-25 minutes, with most time spent decompressing after a fast pull. ### How fast can a simple program (e.g., multiplying two numbers) execute in a TEE? Execution speed for a simple operation like multiplying two numbers within a TEE depends on the setup. If the TEE environment (e.g., a Docker container) is already running, execution is near-instantaneous (milliseconds), similar to non-TEE environments. However, if deployment or cold start is required, the total time includes the container pull and decompression (1-2 minutes, as above). For a function-as-a-service (FaaS) experience with seconds-scale execution, the TEE server must be pre-deployed and running, not started on-demand. ### Can I update specific environment variables for a deployed Docker image without changing the entire set? Currently, Phala Cloud does not support updating individual environment variables—you must update all variables together. However, this feature is on the development roadmap. As a workaround: Use two separate environment files: one for static variables (e.g., required for the app to run) and another for dynamic, user-editable variables (e.g., trading parameters). Alternatively, integrate a dedicated HTTPS API endpoint within your deployed instance to allow users to update specific variables without redeploying.\ Discuss custom solutions with the Phala team if this is critical for your use case. ### How can I deploy multiple Docker instances on a single VM to optimize costs? You can deploy multiple Docker instances on a single Phala Cloud VM using a "Docker-in-Docker" approach, similar to what large clients have implemented (e.g., running 150+ instances). To do this: Step 1: Create a larger VM (e.g., 10 vCPUs, 20GB RAM).\ Step 2: Deploy your Dockerized images inside this VM, adjusting ports or configurations as needed to avoid conflicts.\ Step 3: Use custom environment variables per instance for differentiation, for example, set the image name or version through environment variable.\ This reduces overhead (e.g., from multiple OS instances) and can lower costs. Phala can assist with implementation—reach out for support. ### What endpoint do I use to view logs for a specific instance? To access logs for a specific instance, if you use Cloud UI, you can check the log on the container page. If you use the Cloud API, you can use the endpoint GET /api/v1/cvms/app\_\/composition. This returns details about all containers within the Compute VM (CVM), including the log endpoint for each. Replace \ with your instance’s unique identifier. Find the full API specification at /phala-cloud/phala-cloud-api/overview. Ensure you authenticate with your API key in the x-api-key header. ### Can I set my own TLS certificate for my CVM network access? Yes. After configuring your certificates, expose port `8080:443` in your Docker Compose file. To access the service over your TLS certificate, use the public endpoint from the Network section and append `s` to the port number — for example, `-8080s.`. ### How does Phala Cloud ensure that the data in a CVM isn’t accessed by other programs running in the same machine? Phala Cloud CVM uses a hardware root key unique to the TEE platform, from which individual encryption keys are derived for each application. This key hierarchy ensures that each TEE app has its own distinct key, preventing other programs in the same TEE from accessing your encrypted data. Additionally, you should attest the programs running on Phala Cloud (e.g., via remote attestation) to verify they’re not malicious, enhancing security. ### How can others verify that my application is running inside a TEE? Once the application is running, you can prove this by providing the RA Report, which is exported through an endpoint by your Docker application. See [How to Generate Attestation Reports](https://phala.com/posts/how-to-generate-attestation-repport-and-prove-your-application-runs-in-tee) for details. ### What’s the best approach to verify Phala Cloud Attestation Report in a smart contract? You can verify the Attestation Report with [Automata's onchain DCAP verifier](https://github.com/automata-network/automata-dcap-attestation) written in Solidity and deployed on multiple blockchains. To verify the report, user can get the report hex data from Phala Cloud dashboard “Attestation” tab, and call the smart contract method verifyAndAttestOnChain, check the example [here](https://github.com/Leechael/ra-quote-explorer/blob/37a86a96f0f5059359b33fdb61b1f507fd1ca291/src/components/onchain_attestation.tsx#L152). ## Pricing and Resources Rates and billing rules change over time. The dashboard pages always show the current values: * [Pricing](https://cloud.phala.com/about/pricing) - current instance, storage, and GPU rates * [Billing](https://cloud.phala.com/about/billing) - how billing works ### What is the current pricing structure for Phala Cloud? See the [pricing page](https://cloud.phala.com/about/pricing) for current rates and the [billing page](https://cloud.phala.com/about/billing) for billing rules. ### How do I pay for CVMs, GPU instances, and Private AI? Your workspace has one Balance. It pays for CVMs, GPU instances, and Private AI. You top it up in the dashboard, or turn on auto-topup to charge your card when Balance drops below an amount you choose. Auto-topup checks every hour. * **Gifted credits** (for example from a promotion code) pay for CVMs and GPU instances first, then your Balance pays. Gifted credits never pay for Private AI. A welcome credit goes into your Balance. * **Private AI** only uses Balance. We move money from your Balance to Private AI every 5 minutes as you use it. There is no separate Private AI top-up and no minimum. * **With a card** (post-paid, the default when you add one), your CVMs keep running when Balance runs out. We charge your card for the rest. * **Without a card**, top up first. Your CVMs stop when Balance reaches \$0. When you add a card, we charge \$1 to check it and refund it right after. ### Can I get a refund, and do top-ups expire? You can get a refund for a top-up within 24 hours of paying it, for the part you have not used. Each top-up expires one year after you paid it. Gifted credits also expire one year after we give them. See the [billing page](https://cloud.phala.com/about/billing) for details. ### What kind of user levels do we have on Phala Cloud? * **Pro**: Paid users with self-service capabilities * **Enterprise**: Customized pricing, available through Business Development only ### What are the account tier limits? | Tier | Max CVMs | Max vCPUs | Max Memory | Max Total Disk | | - | - | - | - | - | | **Tier 1** | 8 | 16 | 32GB | 160GB | | **Tier 2** | 16 | 32 | 64GB | 1TB | | **Enterprise** | Unlimited | Unlimited | Unlimited | Unlimited | New accounts start at Tier 1. Contact [cloud@phala.network](mailto:cloud@phala.network) to upgrade. > [!NOTE] > > Check your tier limits before you deploy several CVMs. If you go over your limits, you get a "No available nodes found" error. ### What is the billing granularity for Phala Cloud? Is it by hour or minute? **Regular CVMs:** Billed by the minute. The pricing page shows hourly rates, but we charge by the minute. **GPU TEE:** Billed by hours with a minimum rental period. See [GPU TEE Billing](#how-does-gpu-tee-billing-work) for details. ### How does GPU TEE billing work? For On-Demand GPU TEE (e.g., H200): * **Minimum charge**: Each instance has a minimum rental period, charged upfront when you order. For example, a single H200 has a 24-hour minimum and a B300 has a 30-day (720-hour) minimum. Check the [pricing page](https://cloud.phala.com/about/pricing) for current hourly rates. * **When billing starts**: Only when the instance is actually launched * Topping up your Balance or configuring Docker settings does not incur charges * GPU instances use Gifted credits first, then your Balance * Usage beyond the minimum period is billed hourly * If you stop and restart later, the minimum charge applies again For commitment plans (30, 180, or 365 days), you get lower hourly rates. ### What happens if my Balance reaches zero? It depends on whether your workspace has a card. * **With a card** (post-paid, the default when you add one): your CVMs keep running, and we charge your card for the usage beyond your Balance. * **Without a card**: your CVMs stop. We keep the data of stopped CVMs for 30 days. After that, we may delete it. Top up within those 30 days to get everything back. * **Private AI** stops when your Balance is too low to fund it. Your API keys stay on, and calls work again within about 5 minutes after you top up. To avoid running out, turn on auto-topup on the Billing page. Enterprise customers can contact [cloud@phala.network](mailto:cloud@phala.network) for custom terms. ### Are there any anti-spam measures? Yes, Phala implements several measures: * Adding a card runs a \$1 card check (refunded right after) to prevent automated registrations * Gifted credits do not pay for Private AI; it is paid from your Balance * Free VMs may be offered when they don't impact paying users * Certain Docker base images may be blocked if they've been used for abuse If your deployment is blocked with "violates terms & conditions", try using official base images (e.g., `python:3.11`, `node:20`) or contact support if you believe it's a false positive. ### Can I deploy CVMs through GitHub Actions / CI/CD? Yes! Phala Cloud supports automated deployments through GitHub Actions. See the [CI/CD Pipeline Guide](/phala-cloud/phala-cloud-cli/ci-cd-automation/setup-a-ci-cd-pipeline) for: * Setting up repository secrets * Configuring the deployment workflow * Using the `phala-deploy-action` You can also use the [Phala Cloud API](/phala-cloud/phala-cloud-api/overview) for custom automation. ### Is Phat Contract / DevPhase / Swanky still supported? > [!WARNING] > > **Phat Contract has been sunset.** DevPhase and Swanky are no longer supported. The tech stack has moved to **dstack**-based infrastructure. For new projects, use: * [Phala Cloud CVMs](/phala-cloud/what-is/what-is-phala-cloud) for TEE deployments * [dstack](/dstack/overview) for the underlying TEE infrastructure # Get and Verify Attestation Source: https://docs.phala.com/phala-cloud/getting-started/attestation Get a TEE attestation report from your CVM and verify it step by step. ## Introduction Remote Attestation (RA) lets a remote verifier confirm that an application runs inside a genuine TEE with the expected configuration and code. This guide shows how to access and verify TEE attestation reports in Phala Cloud. ### How to Get the Attestation Report Navigate to **Attestations** in your CVM's sidebar to view the full Remote Attestation report. ![Phala Cloud attestation page showing TEE proof and remote attestation report](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/getting-started/attestation-01.png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=651a9e7aca78ce3ad077392e9bf4c21c) Attestation Report ## How to Verify Attestation Scroll down to the **Certificate Chain** section and click the **Check Attestation** button next to **App Cert**. ![Certificate chain section with Check Attestation button highlighted for App Cert verification](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/getting-started/attestation-02.png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=161b36d1a887043218f7e71ee6303685) Check Attestation This opens the [TEE Attestation Explorer](https://proof.t16z.com/) where you can verify the attestation quote. You can share this quote with anyone as proof that your application is running inside a genuine TEE. ![TEE Attestation Explorer showing verified attestation status with detailed verification report](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/getting-started/attestation-03.png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=9f3620827a77696d94c0f1edfce3baa1) Attestation Verification Report You can also request customized Remote Attestation reports programmatically via API: [Generate Remote Attestation](/phala-cloud/attestation/get-attestation). For more details, see [how dstack attestation works](https://github.com/Dstack-TEE/dstack/blob/next/docs/attestation-tdx.md). # Core Concepts Refresher Source: https://docs.phala.com/phala-cloud/getting-started/core-concepts-refresher Key building blocks of Phala Cloud — CVMs, key management, and GPU TEE. Before deploying, familiarize yourself with the three core building blocks of Phala Cloud. > [card] > > Confidential VM (CVM) > > [Open](/phala-cloud/cvm/overview) > [card] > > Key Management Service (KMS) > > [Open](/dstack/design-documents/key-management-protocol) > [card] > > GPU TEE > > [Open](/phala-cloud/confidential-ai/overview) # Deploy Your First CVM Source: https://docs.phala.com/phala-cloud/getting-started/deploy-first-cvm Go from zero to a running Confidential VM on Phala Cloud using the Dashboard, CLI, or SDK. You can deploy a CVM on Phala Cloud in under five minutes. This guide walks you through the full flow — sign up, write a compose file, deploy, and verify — using whichever tool you prefer. We'll deploy an nginx web server as the example app. The same steps apply to any Docker image. ## Prerequisites * A [Phala Cloud account](/phala-cloud/getting-started/sign-up-for-cloud-account) * For CLI/SDK: an [API key](/phala-cloud/phala-cloud-api/overview) from **Settings > API Keys** in the dashboard ## Choose an Instance Type Phala Cloud offers several instance sizes. For a simple web server, `tdx.small` is plenty. | Instance Type | vCPU | RAM | Good For | | - | - | - | - | | `tdx.small` | 2 | 4 GB | Lightweight services, testing | | `tdx.medium` | 4 | 8 GB | Production APIs, small databases | | `tdx.large` | 8 | 16 GB | Multi-container apps, ML inference | See all options with [`phala instance-types`](/phala-cloud/phala-cloud-cli/instance-types). ## Write Your Docker Compose File Create a `docker-compose.yml` that defines your services. Here's a minimal nginx example: ```yaml theme={"system"} services: web: image: nginx:stable ports: - "80:80" ``` Every service in the compose file runs inside the same CVM, so containers can communicate over `localhost`. ## Deploy Pick the method that fits your workflow. All three produce the same result: a running CVM with a public HTTPS endpoint. ### Option A — Dashboard UI **Step 1** ### Open the Deploy page Navigate to your workspace and click **Deploy** in the top-right corner of the CVMs page. **Step 2** ### Configure the CVM Enter a name (e.g. `my-nginx`), paste your `docker-compose.yml` into the editor, select **Phala** as the KMS provider, pick a region, and choose **tdx.small** as the instance type. **Step 3** ### Click Deploy You'll be redirected to the CVMs page. The status changes from **starting** to **running** in about one to two minutes. ### Option B — CLI **Step 1** ### Install the CLI ```bash theme={"system"} npm install -g phala ``` **Step 2** ### Deploy Run `phala deploy` from the directory containing your `docker-compose.yml`. The CLI auto-selects a region and instance type if you don't specify them. ```bash theme={"system"} export PHALA_CLOUD_API_KEY="phak_your_key" phala deploy -n my-nginx -t tdx.small ``` The command returns once the CVM is created. The CVM keeps booting after that; run `phala cvms get my-nginx` or open the dashboard to see when it is running. Add `--wait` to make the command wait until the CVM is running. ### Option C — SDK ```typescript JavaScript theme={"system"} import { createClient } from "@phala/cloud"; const client = createClient({ apiKey: process.env.PHALA_CLOUD_API_KEY }); const provision = await client.provisionCvm({ name: "my-nginx", vcpu: 2, memory: 4096, diskSize: 20, composeFile: { dockerComposeFile: ` services: web: image: nginx:stable ports: - "80:80" `, }, }); const cvm = await client.commitCvmProvision({ appId: provision.appId, composeHash: provision.composeHash, transactionHash: provision.transactionHash, }); console.log("CVM deployed:", cvm); ``` ```python Python theme={"system"} from phala_cloud import create_client client = create_client() # reads PHALA_CLOUD_API_KEY from env result = client.provision_cvm({ "name": "my-nginx", "compose_file": { "docker_compose_file": "services:\n web:\n image: nginx:stable\n ports:\n - '80:80'", }, "vcpu": 2, "memory": 4096, "disk_size": 20, }) cvm = client.commit_cvm_provision({ "app_id": result.app_id, "compose_hash": result.compose_hash, "transaction_hash": result.transaction_hash, }) print("CVM deployed:", cvm) ``` ```go Go theme={"system"} package main import ( "context" "fmt" "log" phala "github.com/Phala-Network/phala-cloud/go" ) func main() { client, err := phala.NewClient() if err != nil { log.Fatal(err) } result, err := client.ProvisionCVM(context.Background(), &phala.ProvisionCVMRequest{ Name: "my-nginx", ComposeFile: &phala.ComposeFile{ DockerComposeFile: "services:\n web:\n image: nginx:stable\n ports:\n - \"80:80\"", }, VCPU: phala.Int(2), Memory: phala.Int(4096), DiskSize: phala.Int(20), }) if err != nil { log.Fatal(err) } cvm, err := client.CommitCVMProvision(context.Background(), &phala.CommitCVMProvisionRequest{ AppID: result.AppID, ComposeHash: result.ComposeHash, TransactionHash: result.TransactionHash, }) if err != nil { log.Fatal(err) } fmt.Printf("CVM deployed: %+v\n", cvm) } ``` ## Verify Your Deployment Once the status shows **running**, your CVM has a public endpoint. The URL follows this pattern: ```text theme={"system"} https://-.dstack-pha-.phala.network ``` You can find the exact URL in the dashboard under **CVM > Home > INGRESS**, or query it from the CLI: ```bash theme={"system"} phala cvms get my-nginx ``` Open the endpoint in your browser. You should see the nginx welcome page. > [!NOTE] > > Endpoints may take 30 to 60 seconds to become reachable after the CVM enters the running state. ## Verify TEE Attestation Every CVM generates a remote attestation report proving it runs inside a genuine TEE. Navigate to **Attestations** in the CVM sidebar and click **Check Attestation** to verify it in the [TEE Attestation Explorer](https://proof.t16z.com/). For details, see [Get Attestation and Verify](/phala-cloud/getting-started/attestation). ## Next Steps * [Environment Variables](/phala-cloud/cvm/set-secure-environment-variables) — pass secrets securely to your CVM * [Docker Compose Configuration](/phala-cloud/cvm/create-with-docker-compose) — multi-service setups and private registries * [Set Up CI/CD](/phala-cloud/phala-cloud-cli/ci-cd-automation/setup-a-ci-cd-pipeline) — automate deployments on every push * [Scale with Replicas](/phala-cloud/cvm/multi-replica-scaling) — run multiple copies of your app # Deploy ERC-8004 Agent in 5 Minutes Source: https://docs.phala.com/phala-cloud/getting-started/explore-templates/deploy-erc-8004-agent Deploy a verifiable ERC-8004 Trustless Agent using Phala Cloud's VibeVM with TEE attestation ## TL;DR * **ERC-8004** gives us onchain primitives to register and discover *trustless agents*. * To make those registrations meaningful, you want verifiable runtime evidence, not just a signature. * **Confidential VMs (CVMs)** running **dstack** to deliver **deterministic key derivation** + **remote attestation** so your agent can prove *where* it executed. * **Phala Cloud** wraps this in a bow: VibeVM templates, an onchain KMS/registry workflow, and (optionally) confidential inference (GPU TEE) support. * This post walks the whole flow: deploy a CVM → produce attestation → register identity on Sepolia → verify via **TEERegistry**. [Deploy ERC-8004 Agent Overview](https://www.youtube.com/embed/OP99InL0cU8) *** ## Why Trustless Agents Matter Distributed systems increasingly outsource work to off-chain agents—indexers, oracles, model inference, payment relays. When an agent signs a statement or moves value, a bare signature only proves **key possession**, not execution context. The missing link is provenance: *did this response come from the runtime I expect?* **ERC-8004** gives us a compact onchain model for agent identity and discovery. Pair it with TEE-backed CVMs and you get the runtime receipts you've been wishing for: **attested execution**. Explore more [confidential AI agent use cases](https://phala.com/solutions/ai-agents) and implementations. *** ## What's broken today (and how we fix it) * Agents are usually deployed ad hoc; signed responses alone don't say anything about *where* the code ran. * Keys can be copied; logs can be forged; environments can be jailbroken. * What agents actually need: 1. **Deterministic key material** derived inside the runtime. 2. **Remote attestation** that binds keys + code measurements to a platform identity. 3. **Onchain discovery** so other contracts/clients can programmatically verify them. ERC-8004 covers the onchain identity/registry. **TEEs + CVMs** supply runtime evidence. **Phala Cloud** ties it all together with templates, SDKs, and an onchain governance/KMS model. *** ## Deploy Your ERC-8004 Agent in TEE ### Pre-reqs * [Phala Cloud](https://phala.com) account * GitHub account (token only needed if cloning private repos) * Wallet with **ETH Sepolia** funds for registration/funding ### 1) Deploy VibeVM: the TEE coding environment * Go to [https://cloud.phala.com/templates/VibeVM](https://cloud.phala.com/templates/VibeVM) → **Deploy** [Deploy VibeVM](https://www.youtube.com/embed/G1CjuPQ1SyE) ### 2) Configure the CVM * **OS:** `dstack-dev-0.5.x` or newer * **Instance:** Large TDX, **4 vCPU**, **8 GB RAM**, **>40 GB storage** * **Set Encrypted Secrets (remember to change the password):** ```bash theme={"system"} VIBEVM_AUTH_ENABLED=true VIBEVM_USERNAME=vibe VIBEVM_PASSWORD=vibevm4454 GITHUB_REPO=https://github.com/Phala-Network/erc-8004-tee-agent # optional if the repo is private GH_TOKEN= ``` ![CVM Configuration](https://mintcdn.com/phalanetwork-1606097b/u-RQFDGRKhvg8ZpU/phala-cloud/getting-started/explore-templates/images/erc-8004-agent/config.jpg?fit=max\&auto=format\&n=u-RQFDGRKhvg8ZpU\&q=85\&s=4cf3074ddb04716c5e1eb2cb552e7921) > [!NOTE] > > **Tip:** GH\_TOKEN only needed for private repos. ### 3) Deploy & open VibeVM * Click **Deploy** and let provisioning finish. * Open **View details → Networks** and click the URL with port **8080** to open the frontend. ![Network Details](https://mintcdn.com/phalanetwork-1606097b/qg5qPVMhhp3UKpah/phala-cloud/getting-started/explore-templates/images/erc-8004-agent/network-details.jpg?fit=max\&auto=format\&n=qg5qPVMhhp3UKpah\&q=85\&s=a083876a171dc1757dd4f5f9b8477675) ### 4) Sign into the VibeVM frontend * Use the credentials you set. * You'll land in a VSCode server with the repo already cloned. ![VibeVM Login](https://mintcdn.com/phalanetwork-1606097b/qg5qPVMhhp3UKpah/phala-cloud/getting-started/explore-templates/images/erc-8004-agent/vibevm-login.jpg?fit=max\&auto=format\&n=qg5qPVMhhp3UKpah\&q=85\&s=ae81d716555d002199ba02754075de41) ### 5) Prep the agent In the VSCode server terminal: ```bash theme={"system"} cd erc-8004-tee-agent cp .env.example .env # Edit .env: # AGENT_DOMAIN= # REDPILL_API_KEY= # a Private AI API key: dashboard → Private AI → API Keys ``` ![Environment Configuration](https://mintcdn.com/phalanetwork-1606097b/qg5qPVMhhp3UKpah/phala-cloud/getting-started/explore-templates/images/erc-8004-agent/env-configuration.jpg?fit=max\&auto=format\&n=qg5qPVMhhp3UKpah\&q=85\&s=e7d771d3cfd6c79a515a7065288359c9) ### 6) Build & run ```bash theme={"system"} pip3 install -e . python3 deployment/local_agent_server.py ``` Service should come up at: ``` https://-8000. ``` ![Agent Running](https://mintcdn.com/phalanetwork-1606097b/qg5qPVMhhp3UKpah/phala-cloud/getting-started/explore-templates/images/erc-8004-agent/agent-running.jpg?fit=max\&auto=format\&n=qg5qPVMhhp3UKpah\&q=85\&s=703f6d9441b18cf3efe226127349d863) ### 7) Register & fund the agent * Visit your agent domain and step through the registration + wallet-connect funding flow. * This calls **IdentityRegistry** on **Sepolia** to record the agent and posts the attestation to **TEERegistry**. * Example demo transactions (Sepolia): * IdentityRegistry: [0x88a03a29fe2c9a5881bbbdece91cd75c4e816a4dcda3f4ed2610bc119c517011](https://sepolia.etherscan.io/tx/0x88a03a29fe2c9a5881bbbdece91cd75c4e816a4dcda3f4ed2610bc119c517011) * TEERegistry verify: [0x4b9810c3d1753b79c029938add20c237a4fd7b58eccd9b094bc54b3197c97a9e](https://sepolia.etherscan.io/tx/0x4b9810c3d1753b79c029938add20c237a4fd7b58eccd9b094bc54b3197c97a9e) ![Agent Registration](https://mintcdn.com/phalanetwork-1606097b/qg5qPVMhhp3UKpah/phala-cloud/getting-started/explore-templates/images/erc-8004-agent/agent-registration.jpg?fit=max\&auto=format\&n=qg5qPVMhhp3UKpah\&q=85\&s=b57a84fc40b91fabfcd7f7ec492dd7a2) ![Registration Transaction](https://mintcdn.com/phalanetwork-1606097b/qg5qPVMhhp3UKpah/phala-cloud/getting-started/explore-templates/images/erc-8004-agent/registration-transaction.jpg?fit=max\&auto=format\&n=qg5qPVMhhp3UKpah\&q=85\&s=52f60f7248b21a11fe597e0374a89776) ### 8) Verify attestation via TEERegistry * Use the TEERegistry contract UI or explorer to confirm the attestation entry matches your IdentityRegistry entry. * [View TEERegistry verification transaction](https://sepolia.etherscan.io/tx/0x4b9810c3d1753b79c029938add20c237a4fd7b58eccd9b094bc54b3197c97a9e) ![TEERegistry Verification](https://mintcdn.com/phalanetwork-1606097b/qg5qPVMhhp3UKpah/phala-cloud/getting-started/explore-templates/images/erc-8004-agent/tee-registry-verification.jpg?fit=max\&auto=format\&n=qg5qPVMhhp3UKpah\&q=85\&s=1621afa46de8a0a57727afa306a782cd) ### 9) Talk to the agent * Hit the Agent API. You should get signed responses whose key matches what you registered, and whose runtime is backed by the TEE attestation onchain. [Interact with Agent](https://www.youtube.com/embed/f4Ii_sb7KMg) ## Architecture ```mermaid theme={"system"} flowchart LR Client -->|API| AgentAPI[(ERC-8004 Agent API)] AgentAPI -->|creates signature| Client AgentAPI -->|registers| IdentityRegistry[IdentityRegistry Sepolia] AgentAPI -->|attestation| TEERegistry[TEERegistry Sepolia] subgraph Phala Cloud CVM CVM[dstack CVM - VibeVM] CVM -->|derive key from path| GetKey CVM -->|produce attestation| GetQuote end AttestationService --> TEERegistry IdentityRegistry --> TEERegistry ``` ## Conclusion ERC-8004 + TEE on **Phala Cloud** give you a practical path to trustless agents: deterministic keys, remote attestations, and onchain identity—wrapped in a dev flow that feels like spinning up a regular VM, just with superpowers. ## Resources * [ERC‑8004 EIP](https://eips.ethereum.org/EIPS/eip-8004) * [VibeVM Template](https://cloud.phala.com/templates/VibeVM) * [Agent Template Repository](https://github.com/Phala-Network/erc-8004-tee-agent) * [Phala Cloud](https://phala.com) # Eliza Agent Source: https://docs.phala.com/phala-cloud/getting-started/explore-templates/launch-an-eliza-agent Quick guide for launching Eliza Agent on Phala Cloud Phala Cloud has introduced a new feature that allows users to deploy an [Eliza agent](https://www.elizaos.ai/) without any coding. You can access this feature through [cloud.phala.com/eliza](https://cloud.phala.com/eliza). Learn how [private AI agents](https://phala.com/solutions/ai-agents) protect user privacy and maintain autonomy in decentralized environments. **In this tutorial, we'll guide you through the process of deploying an agent named Trump, capable of tweeting in his distinctive tone**. Before you begin, it would be ideal to understand what an [**Eliza's character file**](https://github.com/elizaOS/eliza/blob/main/docs/docs/core/characterfile.mdx) is. However, if you're unfamiliar with it, that's perfectly fine. You can start with a template and customize it to suit your needs. There are only two things you need to prepare: * **An X account for the agent to connect and tweet** * **An OpenAI account for the agent to send requests and harness its intelligence** ### **Step 1: Customize the Agent Character File** You can either upload your own character file or select one from the built-in options available in the [Eliza official repository](https://github.com/elizaOS/eliza/tree/main/characters). In this example, we'll choose Trump. Don't worry—you can still customize the template later if needed. ![](https://img0.phala.world/files/1960317e-04a1-801e-b487-e7b1ea85325d.jpg) ### **Step 2: Configure Clients for Agent Connection** You can select multiple clients and configure the account information for each. In this example, we'll choose an X account and set the necessary information. You can also override the account information later if needed ![](https://img0.phala.world/files/1960317e-04a1-8023-ae37-d6f257e290f9.jpg) * Set basic information * Set `TWITTER_USERNAME` , `TWITTER_PASSWORD` , `TWITTER_EMAIL` environments that you set for your account. * ```shell theme={"system"} TWITTER_USERNAME="realagenttrump_" TWITTER_PASSWORD="giggity giggity" TWITTER_EMAIL="realagenttrump_@gmail.com" ``` * Set `TWITTER_2FA_SECRET` * You should enable 2FA on your X account settings page and select an authentication app as the method. During setup, make sure to copy the secure code (it's 16 uppercase letters and numbers) by click the button under the QR code. This secure code will be the value you set for **`TWITTER_2FA_SECRET`**. * ``` ``` * Others * To enable the agent to reply to messages more quickly, it is recommended to set **`TWITTER_POLL_INTERVAL=10,`**` `` ``but means more quote usage from LLM provders. ` ### **Step 3: Set the Model Provider** You need to choose a model provider for your agent to connect with and send requests to. In this example, we'll use [**OpenAI**](https://platform.openai.com/api-keys), but you can also use Phala's [**Private AI**](/phala-cloud/confidential-ai/confidential-model/confidential-ai-api) at `https://inference.phala.com/v1`, an OpenAI-compatible API paid from your workspace Balance. If you're unsure about other settings, you only need to configure the **API key** and **API URL** and **model names**. You can generate an API key using your OpenAI account on the [**dashboard**](https://platform.openai.com/api-keys). Type API URL: `https://api.openai.com/v1` ![](https://img0.phala.world/files/1960317e-04a1-8083-944b-d0f99ecbce58.jpg) ### **Step 4: Review Configuration and Deploy the Agent** In this step, you can review your configuration settings. You'll have the opportunity to update account information in the **Environment Variables** section and further customize the character file before deploying the agent. ![](https://img0.phala.world/files/1960317e-04a1-8054-ae05-d8d549dcb9a5.jpg) After clicking the "Complete" button, you will be redirected to the Cloud dashboard, If not yet login, it will ask to login first and all your data will store locally; If you don’t have an account, you can register one with this [invit link](https://cloud.phala.com/register?invite=ELIZADEVS). Please be patient, as it may take several minutes to complete the deployment. Once the status changes from "STARTING" to "RUNNING," it indicates that your agent is now live. ![](https://img0.phala.world/files/1960317e-04a1-803f-9fac-c6830a49dd00.jpg) Now, let’s check the agent X account, it already starting to mutter. And congratulation, you deployed an autonomous agent in TEE without a single line coding🎉. 💡 Join the technical support groups if you got any questions. CN: [https://t.me/+GZwUzcON9OkzOGVl](https://t.me/+GZwUzcON9OkzOGVl) EN: [https://t.me/+MfWRvYRyQDk2MjQ1](https://t.me/+MfWRvYRyQDk2MjQ1) #### Resources * [https://github.com/elizaOS/eliza](https://github.com/elizaOS/eliza) * [https://github.com/elizaOS/eliza-starter](https://github.com/elizaOS/eliza-starter) * [https://github.com/thejoven/awesome-eliza](https://github.com/thejoven/awesome-eliza) * [https://github.com/elizaOS/elizaos.github.io](https://github.com/elizaOS/elizaos.github.io) ## ❓ FAQs ### Do I need to create a custom Docker image for my Eliza agent? * If you want to use the default framework example, you can use the template provided by Phala * If you have customized code, you'll need to: 1. Convert your Eliza code into a Docker image 2. Upload it to a Docker registry 3. Configure it in the Phala TEE setup ### Can I change the Docker image after creating an agent? Yes, applications are upgradable. To update your application: 1. Push your updated Docker image to Docker Hub 2. Execute the upgrade on the cloud dashboard ### What are the recommended resources for running Eliza? It's strongly recommended to run Eliza with 2 vCPUs + 4GB RAM for optimal performance. ### How can I connect the X Account with my Agent? Besides setting user name, password, and email with specific environments, you also need to enable 2FA on your X account and set it through `TWITTER_2FA_SECRET`. Check the [tutorial](https://phala.com/posts/guide-to-exploring-the-phala-cloud-agent-builder) for more information. If you still receive a `Login attempt failed` error, consider logging into your X account via a browser and logging out of the existing session. See the related [issue](https://github.com/elizaOS/eliza/issues/905) on the Eliza repository. # Explore Templates Source: https://docs.phala.com/phala-cloud/getting-started/explore-templates/overview Deploy pre-built confidential applications on Phala Cloud using templates. ![Phala Cloud Templates page with search bar and category filters including VibeVM, TEE, AI, MCP, A2A, x402, and more](https://mintcdn.com/phalanetwork-1606097b/EKy3E_Vajo5ZLWvm/images/getting-started/phala-cloud-template.png?fit=max\&auto=format\&n=EKy3E_Vajo5ZLWvm\&q=85\&s=489ef8cbc911070435500e52aae55273) Phala Cloud Templates [**Phala Cloud Templates**](https://cloud.phala.com/templates) provide pre-built, production-grade setups for deploying confidential applications. Browse templates by category — including MCP, A2A, AI, Next.js, x402, and more — and deploy them to a TEE with one click. To use a template: 1. Visit the [Templates page](https://cloud.phala.com/templates) 2. Search or filter by category to find a template 3. Click on a template card and follow the deploy instructions # NextJS & Python Source: https://docs.phala.com/phala-cloud/getting-started/explore-templates/start-from-template Get started quickly with Next.js and Python templates on Phala Cloud. There are a couple templates that we offer to allow you to get started without any heavy lifting. The steps to get started are simple and easy to test in a few minutes. > [!NOTE] > > #### Before You Start > > Make sure you have [Docker Desktop](https://www.docker.com/products/docker-desktop/) or [OrbStack](https://orbstack.dev/) started before you begin. \ > \ > Also, make sure you have gone through the [Sign-up for Cloud Account](/phala-cloud/getting-started/sign-up-for-cloud-account) section before continuing. > [tab] Next.js Template > > ### Phala Cloud Next.js Starter > > This is a template for developing a [Next.js](https://nextjs.org/)-based app with boilerplate code targeting deployment on [Phala Cloud](https://cloud.phala.com/) and [dstack](https://github.com/dstack-TEE/dstack/). It includes the SDK by default to make integration with TEE features easier. This repo also includes a default Dockerfile and docker-compose.yml for deployment. > > ### Requirements > > * [Node](https://nodejs.org/en) >= v18.18 > * [yarn](https://yarnpkg.com/) > * Docker or Orbstack > > ### Development > > First, you need to clone this repo: > > ```shell theme={"system"} > git clone --depth 1 https://github.com/Phala-Network/phala-cloud-nextjs-starter.git > ``` > > Next, let's initialize the development environment: > > ```shell theme={"system"} > yarn > cp env.local.example .env.local > ``` > > We also need to download the dstack simulator: > > ```shell theme={"system"} > # Mac > wget https://github.com/Leechael/tappd-simulator/releases/download/v0.1.4/tappd-simulator-0.1.4-aarch64-apple-darwin.tgz > tar -xvf tappd-simulator-0.1.4-aarch64-apple-darwin.tgz > cd tappd-simulator-0.1.4-aarch64-apple-darwin > ./tappd-simulator -l unix:/tmp/tappd.sock > > # Linux > wget https://github.com/Leechael/tappd-simulator/releases/download/v0.1.4/tappd-simulator-0.1.4-x86_64-linux-musl.tgz > tar -xvf tappd-simulator-0.1.4-x86_64-linux-musl.tgz > cd tappd-simulator-0.1.4-x86_64-linux-musl > ./tappd-simulator -l unix:/tmp/tappd.sock > ``` > > Once the simulator is running, you need to open another terminal to start your Next.js development server: > > ```shell theme={"system"} > yarn dev > ``` > > By default, the Next.js development server will listen on port 3000. Open [http://127.0.0.1:3000/](http://127.0.0.1:3000/) in your browser and check. > > This repo also includes code snippets for the following common use cases: > > * `/api/tdx_quote`: The `reportdata` is `test` and generates the quote for attestation report via `getQuote` API. > * `/api/tdx_quote_raw`: The `reportdata` is `Hello DStack!` and generates the quote for attestation report. The difference from `/api/dx_quote` is that you can see the raw text `Hello DStack!` in [Attestation Explorer](https://proof.t16z.com/). > * `/api/eth_account/address`: Using the `getKey` API to generate a deterministic wallet for Ethereum, a.k.a. a wallet held by the TEE instance. > * `/api/solana_account/address`: Using the `getKey` API to generate a deterministic wallet for Solana, a.k.a. a wallet held by the TEE instance. * `/api/info`: Returns the TCB Info of the hosted CVM. ### Build and Publish to Docker Registry You need to build the image and push it to DockerHub for deployment. The following instructions are for publishing to a public registry via DockerHub: > [!NOTE] > > For this to be logged into Docker to push to registry. Run docker login to login in the CLI. #### Build and Publish with Docker CLI ```shell theme={"system"} docker build . -t /my-app:latest docker push /my-app:latest ``` Now we have an official docker image for our nextjs app. Let's deploy to Phala Cloud now. ### Deploy to Phala Cloud You can copy and paste the `docker-compose.yml` file from this repo to see the example up and running. #### Deploy in Phala UI Go to your Phala Cloud dashboard and click Deploy. You will have an option for deploying via docker compose file. Click on this option to deploy. ![Phala Cloud Deploy page with docker-compose editor](https://mintcdn.com/phalanetwork-1606097b/EKy3E_Vajo5ZLWvm/images/getting-started/deploy-top.png?fit=max\&auto=format\&n=EKy3E_Vajo5ZLWvm\&q=85\&s=22be3ed432a8ced77111188214cc9769) You will come to a CVM configuration page. Click on **Advanced** and replace the default docker compose contents with the following (Make sure to replace the ``with your own: ```docker theme={"system"} services: app: image: /my-app:latest container_name: app ports: - "3000:3000" volumes: - /var/run/dstack.sock:/var/run/dstack.sock ``` ![Screenshot](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/getting-started/phala-cloud-templates-01.png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=f4c5a30289b3df9f35a466fdf62aa818) Docker Compose Example #### Deploy via Phala Cloud CLI For those using the CLI, you can deploy from the terminal with: > [!NOTE] > > Make sure to change the `image` field to match your published docker image (ex: `0xii/my-app:latest`) ```sh theme={"system"} npx phala deploy -c docker-compose.yml -n my-app ``` #### Interact with Your Next.js App in Phala Cloud Your application should be deployed now to your Phala Cloud dashboard. Go to the **Network** tab to be able to open your application. ![Screenshot](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/getting-started/phala-cloud-templates-02.png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=c8f021d1b95daceb104a0bcd61b35a4f) ![Screenshot](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/getting-started/phala-cloud-templates-03.png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=09fd2337f9f32e57cb16502fd571f673) > [tab] Python Template > > ## Phala Cloud Python Starter > > This is a template for developing a [FastAPI](https://fastapi.tiangolo.com/)-based app with boilerplate code targeting deployment on [Phala Cloud](https://cloud.phala.com/) and [dstack](https://github.com/dstack-TEE/dstack). It includes the SDK by default to make integration with TEE features easier. This repo also includes a default Dockerfile and docker-compose.yml for deployment. > > ### Development > > In this tutorial, we'll start with venv and pip. First, you need to clone this repo: > > ```bash theme={"system"} > git clone --depth 1 https://github.com/Phala-Network/phala-cloud-python-starter.git > ``` > > Next, let's initialize the development environment with venv & pip: > > ```bash theme={"system"} > python -m venv venv > source venv/bin/activate > > python -m pip install -r requirements.txt > cp env.example .env > ``` > > We also need to download the dstack simulator: > > ```bash theme={"system"} > # Mac > wget https://github.com/Leechael/tappd-simulator/releases/download/v0.1.4/tappd-simulator-0.1.4-aarch64-apple-darwin.tgz > tar -xvf tappd-simulator-0.1.4-aarch64-apple-darwin.tgz > cd tappd-simulator-0.1.4-aarch64-apple-darwin > ./tappd-simulator -l unix:/tmp/tappd.sock > > # Linux > wget https://github.com/Leechael/tappd-simulator/releases/download/v0.1.4/tappd-simulator-0.1.4-x86_64-linux-musl.tgz > tar -xvf tappd-simulator-0.1.4-x86_64-linux-musl.tgz > cd tappd-simulator-0.1.4-x86_64-linux-musl > ./tappd-simulator -l unix:/tmp/tappd.sock > ``` > > Once the simulator is running, you need to open another terminal to start your FastAPI development server: > > ```bash theme={"system"} > # Activate the Python venv > source venv/bin/activate > > # Start the FastAPI dev server > python -m fastapi dev > ``` > > By default, the FastAPI development server will listen on port 8000. Open [http://127.0.0.1:8000/tdx\_quote](http://127.0.0.1:8000/tdx_quote) in your browser to get the quote with reportdata `test`. > > #### Build and Publish with Docker CLI > > ```bash theme={"system"} > docker build . -t /my-app:latest > docker push /my-app:latest > ``` > > Now we have an official docker image for our Python app. Let's deploy to Phala Cloud now. > > ### Deploy to Phala Cloud > > You can copy and paste the `docker-compose.yml` file from this repo to see the example up and running. > > #### Deploy in Phala UI > > Go to your Phala Cloud dashboard and click Deploy. You will have an option for deploying via docker compose file. Click on this option to deploy. > > ![Phala Cloud Deploy page with docker-compose editor](https://mintcdn.com/phalanetwork-1606097b/EKy3E_Vajo5ZLWvm/images/getting-started/deploy-top.png?fit=max\&auto=format\&n=EKy3E_Vajo5ZLWvm\&q=85\&s=22be3ed432a8ced77111188214cc9769) > > You will come to a CVM configuration page. Click on **Advanced** and replace the default docker compose contents with the following (Make sure to replace the ``with your own: > > ``` > services: > app: > image: /my-app:latest > container_name: app > ports: > - "8000:8000" > volumes: > - /var/run/dstack.sock:/var/run/dstack.sock > ``` > > ![Screenshot](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/getting-started/phala-cloud-templates-04.png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=ab77a0d28821ac6cfe48c95946f04509) > > Now you can interact with your application by going to the **Network** tab and making calls like the following. > > ![Screenshot](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/getting-started/phala-cloud-templates-05.png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=fedf6dc4fc30b665b265d3fd2e670fb7) > > ![Screenshot](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/getting-started/phala-cloud-templates-06.png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=5e7dc0759bbf8a576722c19e2a57eb18) > > /tdx\_quote > > ![Screenshot](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/getting-started/phala-cloud-templates-07.png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=d8e82cbf8bf541c4aa0e680ed16104d7) > > /derive\_key > > And output of **GET /eth\_account** > > ```json theme={"system"} > { > "address":"0xf75647Ec8372BF710D95ad634EDb1ED198CeAE6C" > } > ``` > > Output of **GET /sol\_account** > > ```json theme={"system"} > { > "address":"5JPbG1BP7pZQWsoqQsyCLSvs56SpC2ZAgSHLouVX5Vdn" > } > ``` ## Conclusion The last 2 tutorials were key to understanding the basics of deploying a Docker app on a TEE Server. Now you are ready to start building on dstack! For more info on the design of dstack, check out the [Design Documents](/dstack/design-documents/whitepaper). # Quick Start Source: https://docs.phala.com/phala-cloud/getting-started/overview Get started with Phala Cloud in minutes. Deploy your first TEE application and verify attestation proofs with this step-by-step quick start guide. Deploy your first Confidential VM (CVM) on Phala Cloud in minutes. Follow these steps to go from sign-up to a running TEE application. ## What You'll Accomplish * Create your Phala Cloud account * Deploy a Jupyter Notebook inside a TEE * Access your application via a public HTTPS endpoint * Verify the TEE attestation proof ## Getting Started **Step 1** ### [Create Your Phala Cloud Account](/phala-cloud/getting-started/sign-up-for-cloud-account) (1 minute) Sign up at [cloud.phala.com/register](https://cloud.phala.com/register) with GitHub, Google, or email. Then add a card or top up your Balance to start deploying. **Step 2** ### [Deploy Your First CVM](/phala-cloud/getting-started/start-from-cloud-ui) (2-3 minutes) Deploy a Jupyter Notebook to a Confidential VM using the web UI. No coding required. > [!NOTE] > > Prefer the command line? Check out [Start from Cloud CLI](/phala-cloud/phala-cloud-cli/start-from-cloud-cli). ## Next Steps Once you've deployed your first CVM: * [Advanced CVM configurations](/phala-cloud/cvm/create-with-docker-compose) — customize your Docker Compose setup * [Explore Templates](/phala-cloud/getting-started/explore-templates/overview) — deploy pre-built applications in one click * [Security Architecture](/phala-cloud/security-and-privacy/security-architecture) — learn how Phala Cloud protects your data * [Performance Report](/phala-cloud/references/performance-report) — understand CVM performance characteristics ## Support If you encounter issues or have questions: * **Troubleshooting**: [Debug your application](/phala-cloud/troubleshooting/debug-your-application) * **Community**: [Telegram (Global)](https://t.me/+nbhjx1ADG9EyYmI9) | [Telegram (Chinese)](https://t.me/+4PcAE9qTZ1kzM2M9) # Create Account Source: https://docs.phala.com/phala-cloud/getting-started/sign-up-for-cloud-account Create your Phala Cloud account to start deploying confidential applications. ## Register a New Account [Register Now](https://cloud.phala.com/register) Sign up with **GitHub**, **Google**, or **email and password**. Registration takes under a minute. After registration, set up your workspace. Add a card, or skip it and top up your Balance instead. When you add a card, we charge \$1 to check it and refund it right after. Some new workspaces are offered a welcome credit when they add a card, while the offer lasts. Your Balance pays for CVMs, GPU instances, and Private AI. See [How do I pay?](/phala-cloud/faqs#how-do-i-pay-for-cvms-gpu-instances-and-private-ai) for details. # CVM Deployment Source: https://docs.phala.com/phala-cloud/getting-started/start-from-cloud-ui Deploy your first TEE application on Phala Cloud using the web UI. > [!NOTE] > > Make sure you have [created your Phala Cloud account](/phala-cloud/getting-started/sign-up-for-cloud-account) before continuing. In this tutorial, you deploy a Jupyter Notebook inside a Confidential VM (CVM) on Phala Cloud and verify its TEE proof. By the end, you'll have a running application with a public HTTPS endpoint secured by hardware-level encryption. ## Prerequisites * A [Phala Cloud account](/phala-cloud/getting-started/sign-up-for-cloud-account) * Basic familiarity with Docker Compose ## Step 1 — Open the Deploy Page Navigate to your workspace and click the **Deploy** button in the top-right corner of the CVMs page. ## Step 2 — Configure Your CVM On the Deploy page, fill in the following: 1. **Name**: Enter a name for your CVM (e.g., `my-first-cvm`). 2. **docker-compose.yml**: Replace the default content with the Jupyter Notebook configuration below: ```yaml theme={"system"} services: jupyter: image: quay.io/jupyter/base-notebook ports: - 8080:8888 volumes: - /var/run/dstack.sock:/var/run/dstack.sock environment: - GRANT_SUDO=yes user: root command: "start-notebook.sh --NotebookApp.token=${TOKEN}" ``` ![Deploy page showing name field set to my-first-cvm and docker-compose.yml editor with Jupyter Notebook configuration](https://mintcdn.com/phalanetwork-1606097b/EKy3E_Vajo5ZLWvm/images/getting-started/deploy-top.png?fit=max\&auto=format\&n=EKy3E_Vajo5ZLWvm\&q=85\&s=22be3ed432a8ced77111188214cc9769) Deploy page with CVM name and docker-compose.yml editor 3. **KMS Provider**: Select **Phala** (no wallet setup needed for testing). 4. **Region**: Choose a region closest to you (e.g., **US West**). 5. **Instance Type**: Keep the default **CPU TEE** with **Small TDX Instance** (1 vCPU, 2GB RAM). ## Step 3 — Set Encrypted Secrets Scroll down and expand the **Encrypted Secrets** section. Add the following key-value pair: | Key | Value | | - | - | | `TOKEN` | `phala` | This sets the Jupyter Notebook login token. The `TOKEN` variable is referenced in the `command` field of the compose file as `${TOKEN}`. Encrypted Secrets are end-to-end encrypted between you and your CVM. ![Encrypted Secrets section expanded showing TOKEN key set to phala value](https://mintcdn.com/phalanetwork-1606097b/EKy3E_Vajo5ZLWvm/images/getting-started/deploy-secrets.png?fit=max\&auto=format\&n=EKy3E_Vajo5ZLWvm\&q=85\&s=da14d7f5eaf2a8e21fe6e3f6289be17a) Encrypted Secrets with TOKEN variable ## Step 4 — Deploy Click the **Deploy** button. You'll be redirected to the CVMs page where your CVM will show a **starting** status. This typically takes 1–2 minutes. Once ready, the status changes to **running**. ![CVMs page showing my-first-cvm with running status, tdx.small instance on prod5](https://mintcdn.com/phalanetwork-1606097b/EKy3E_Vajo5ZLWvm/images/getting-started/cvm-running.png?fit=max\&auto=format\&n=EKy3E_Vajo5ZLWvm\&q=85\&s=3d43f2c623186e08fc7905f9a77c7917) CVM running on the CVMs page ## Step 5 — Access Your Application Click **Overview** on the CVM card, then click **Home** in the sidebar. Expand the **INGRESS** section to find your application's public endpoint URL. ![CVM Home page showing INGRESS section expanded with HTTPS endpoint URL](https://mintcdn.com/phalanetwork-1606097b/EKy3E_Vajo5ZLWvm/images/getting-started/cvm-endpoint.png?fit=max\&auto=format\&n=EKy3E_Vajo5ZLWvm\&q=85\&s=4350bc99456f299d3862c776c46238e0) Endpoint URL in the INGRESS section The endpoint URL follows this pattern: ``` https://-.dstack-pha-.phala.network ``` * **App ID**: Your CVM's unique identifier * **Port**: The external port mapped in your compose file (`8080` in this example) * **Node**: The infrastructure node running your CVM Open the endpoint URL in your browser. You'll see the Jupyter Notebook login page. Enter the token `phala` (the value you set in Encrypted Secrets) to access the notebook. ## Step 6 — Verify TEE Proof Navigate to **Attestations** in the sidebar to view the Remote Attestation report for your CVM. This report proves your application is running inside a genuine TEE. Click **Check Attestation** to open the [TEE Attestation Explorer](https://proof.t16z.com/), where you can verify the attestation quote. You can share this proof with anyone to demonstrate that your application runs in a secure, confidential environment. For more details on attestation, see [Get Attestation and Verify](/phala-cloud/getting-started/attestation). > [!NOTE] > > Attestation reports may take a few minutes to become available after deployment. ## Next Steps Now that you've deployed your first CVM, explore further: * [Create CVMs with Docker Compose](/phala-cloud/cvm/create-with-docker-compose) — advanced configuration options * [Deploy from CLI](/phala-cloud/phala-cloud-cli/start-from-cloud-cli) — deploy and manage CVMs from your terminal * [Explore Templates](/phala-cloud/getting-started/explore-templates/overview) — pre-built setups for common frameworks * [Security Architecture](/phala-cloud/security-and-privacy/security-architecture) — understand how Phala Cloud protects your data # Cloud vs Onchain KMS Source: https://docs.phala.com/phala-cloud/key-management/cloud-vs-onchain-kms Choose between centralized Cloud KMS or blockchain-governed Onchain KMS for your dstack application. ## Quick Decision Both Cloud KMS and Onchain KMS offer highly secured code authentication and key management. The only difference is governance: * **Cloud KMS**: Phala manages authorization policies (faster, simpler) * **Onchain KMS**: Blockchain smart contracts control authorization (distributed trust, provable enforcement) Choose Cloud KMS for quick deployment. Choose Onchain KMS when you need distributed governance that no single entity controls. ## Why This Matters With Onchain KMS, authorization policies are enforced by blockchain consensus, not a single company. In Cloud KMS, Phala controls what code runs. If Phala's systems are compromised or pressured, policies can change. With Onchain KMS, governance rules are enforced by the blockchain network—thousands of nodes must agree to execute the smart contract logic. No single entity can override these rules. This distributed enforcement matters for high-stakes applications. Even if the developer accounts are compromised, attackers can't deploy malicious code without satisfying your onchain governance requirements (like multi-sig approval or timelock delays). The blockchain network enforces your rules, not a centralized service. ## Cloud KMS Cloud KMS uses centralized governance managed by Phala Cloud. You deploy your application, and Phala handles all KMS infrastructure and authorization. This works well when you want fast deployment and trust Phala to manage governance policies. ### How it works Deploy to Phala Cloud and your application automatically gets keys from Cloud KMS after attestation. No blockchain setup needed. ### Trade-offs Simple and fast. Phala controls authorization policies and can update them. This means users trust both you (the developer) and Phala's operational security. ## Onchain KMS Onchain KMS uses blockchain smart contracts to control what code can run under your application identity. Governance is enforced by distributed consensus, not a single party. This works well for privacy-focused or high-value applications where you need provable governance that survives compromise of any single entity. You can implement collective decision-making through multi-sig, DAO, or timelock contracts. ### How it works Deploy your DstackApp contract via the web UI: 1. Go to Phala Cloud dashboard 2. Choose "Onchain KMS" when creating your app 3. Select Ethereum or Base 4. Click deploy **Advanced**: You can also deploy DstackApp contracts via CLI or deploy your own custom contracts that follow the interface. See the [dstack repository](https://github.com/Dstack-TEE/dstack) for details. ### Governance controls The DstackApp contract has an `owner` role that controls what code can run. By default it's your wallet address, but you can set it to any contract. Set the owner to a timelock contract for a 7-day delay on code updates. Or use a multi-sig wallet to require 3-of-5 signatures for changes. Or point it to your DAO contract for token holder voting. This enables collective decision-making instead of single-admin control. Even if one key is compromised, governance rules still require the full multi-sig or timelock delay. ### What governance controls Governance controls your **application identity**: what code is allowed to run and access your application's keys. This includes initial deployment, code updates, and who can approve changes. The difference from Cloud KMS: blockchain nodes enforce these rules through consensus. You can't bypass them by compromising a server or pressuring a company. The blockchain network validates every authorization check. ### Authorization flow When your CVM requests keys, KMS verifies your TEE attestation quote, then queries your DstackApp contract on Ethereum or Base. The contract checks if this code hash is approved. If yes, keys are provisioned. This query is validated by blockchain consensus. The result is cryptographically verifiable and can't be tampered with by any single party. ### Trade-offs You get distributed enforcement and collective decision-making. Setup requires deploying a contract, though Phala's UI makes this simple. ### Ethereum vs Base Phala Cloud supports Onchain KMS on both Ethereum and Base. Ethereum has higher gas costs but maximum decentralization. Base is an L2 with lower gas costs and fast finality. > [accordion] Ethereum > > Parameters of the Ethereum KMS > > | | | > | - | - | > | Contract Address | [0xd343a3f5593b93D8056aB5D60c433622d7D65a80](https://etherscan.io/address/0xd343a3f5593b93D8056aB5D60c433622d7D65a80#code) | > | Gateway Address | [0xd343a3f5593b93D8056aB5D60c433622d7D65a80](https://etherscan.io/address/0xd343a3f5593b93D8056aB5D60c433622d7D65a80#code) | > [accordion] Base > > Parameters of the Base KMS > > | | | > | - | - | > | Contract Address | [0x2f83172A49584C017F2B256F0FB2Dca14126Ba9C](https://basescan.org/address/0x2f83172A49584C017F2B256F0FB2Dca14126Ba9C#code) | > | Gateway Address | [0x2f83172A49584C017F2B256F0FB2Dca14126Ba9C](https://basescan.org/address/0x2f83172A49584C017F2B256F0FB2Dca14126Ba9C#code) | ## Updating CVMs with Onchain KMS Any change that affects the compose hash requires on-chain registration. When you hold the DstackApp owner key as an EOA, [Updating with Onchain KMS](/phala-cloud/key-management/updating-with-onchain-kms) walks through the single-command flow. When the owner is a Safe, timelock, or DAO contract, [Multisig and Governance](/phala-cloud/key-management/multisig-governance) covers the prepare-and-commit flow plus webhook automation for approvers. ## Security Both use identical dstack-kms security for TEE operations: attestation-based key provisioning, key rotation, forward/backward secrecy. The difference is governance enforcement: * **Cloud KMS**: Centralized policy enforcement by Phala * **Onchain KMS**: Distributed policy enforcement by blockchain consensus With Onchain KMS, compromise of any single entity (your keys, Phala's systems, or individual blockchain nodes) doesn't compromise governance. The blockchain network collectively enforces your rules. See [What is KMS](/phala-cloud/key-management/key-management-protocol) for detailed security model. # Create Crypto Wallets Source: https://docs.phala.com/phala-cloud/key-management/create-crypto-wallet Generate blockchain wallets with deterministic keys in Phala Cloud Create blockchain wallets using deterministic keys derived from your application's root key. Each wallet address is unique to your application and consistently reproducible. ## Prerequisites Your application must be running in the Phala Cloud TEE environment with access to the dstack socket. In your `docker-compose.yml`: ```yaml theme={"system"} services: app: # your app configuration volumes: - /var/run/dstack.sock:/var/run/dstack.sock ``` ## Ethereum Wallet ```javascript ethereum.js theme={"system"} import { DstackClient } from '@phala/dstack-sdk'; import { toViemAccountSecure } from '@phala/dstack-sdk/viem'; const client = new DstackClient(); const keyResult = await client.getKey('wallet/ethereum/mainnet'); const account = toViemAccountSecure(keyResult); console.log('Address:', account.address); ``` ```python ethereum.py theme={"system"} from dstack_sdk import DstackClient from eth_account import Account client = DstackClient() result = client.get_key('wallet/ethereum/mainnet') account = Account.from_key(result.decode_key()) print(f'Address: {account.address}') ``` ## Solana Wallet ```javascript solana.js theme={"system"} import { DstackClient } from '@phala/dstack-sdk'; import { toKeypairSecure } from '@phala/dstack-sdk/solana'; const client = new DstackClient(); const keyResult = await client.getKey('wallet/solana/mainnet'); const keypair = toKeypairSecure(keyResult); console.log('Address:', keypair.publicKey.toBase58()); ``` ```python solana.py theme={"system"} from dstack_sdk import DstackClient from solders.keypair import Keypair client = DstackClient() result = client.get_key('wallet/solana/mainnet') keypair = Keypair.from_bytes(result.decode_key()) print(f'Address: {keypair.pubkey()}') ``` ## Important Security Notes * **Use secure functions**: Always use `toViemAccountSecure()` and `toKeypairSecure()` (not the legacy versions) * **Application-specific**: Wallet addresses are unique to your application ID * **Deterministic**: Same path always generates the same wallet * **Keep keys in TEE**: Never expose private keys outside the secure environment ## Multi-Wallet Support Generate multiple wallets by using different paths: ```javascript multiWallet.js theme={"system"} // User wallets const userWallet = await client.getKey('wallet/user/123/v1'); // Treasury wallet const treasury = await client.getKey('wallet/treasury/v1'); // Hot wallet for operations const hotWallet = await client.getKey('wallet/hot/v1'); ``` ```python multi_wallet.py theme={"system"} # User wallets user_wallet = client.get_key('wallet/user/123/v1') # Treasury wallet treasury = client.get_key('wallet/treasury/v1') # Hot wallet for operations hot_wallet = client.get_key('wallet/hot/v1') ``` ## Migration from v0.3.x If you're upgrading from dstack v0.3.x, **wallet addresses will change** when using secure functions. See the [Migration from dstack v0.3](/phala-cloud/references/migration-from-dstack-v03) guide for detailed upgrade instructions and wallet migration strategies. # Deploying with Onchain KMS Source: https://docs.phala.com/phala-cloud/key-management/deploying-with-onchain-kms Deploy a dstack CVM whose authorization is governed by a smart contract on Ethereum or Base, using either the Phala Cloud dashboard or the phala CLI. This page walks through the **first deployment** of an Onchain KMS CVM end to end, in the dashboard and from the CLI, then shows how to verify the result on-chain and in Phala Cloud. Before you start, skim [Understanding Onchain KMS](/phala-cloud/key-management/understanding-onchain-kms) for the mental model — which contracts exist, who signs what, and how the KMS verifies your CVM at boot time. If you are weighing Cloud KMS versus Onchain KMS, see [Cloud vs Onchain KMS](/phala-cloud/key-management/cloud-vs-onchain-kms) first. Once your CVM is running, the follow-up guides are: * [Updating with Onchain KMS](/phala-cloud/key-management/updating-with-onchain-kms) — roll a new compose file when you hold the DstackApp owner key. * [Multisig and Governance](/phala-cloud/key-management/multisig-governance) — the same flow when the DstackApp owner is a Safe, timelock, or DAO contract. * [Device Management](/phala-cloud/key-management/device-management) — allowlist the nodes your app is allowed to run on. ## Prerequisites You need the following before starting: * **The phala CLI** if you plan to deploy from the command line. Install it globally with npm, or run it on demand without installing: ```bash theme={"system"} npm install -g phala ``` After installing, authenticate with `phala login` (device flow) or `phala login --manual` (API key). * **A wallet and its private key.** The first deployment signs one transaction (`deployAndRegisterApp` on KmsAuth). Subsequent compose updates sign one more (`addComposeHash` on your DstackApp), plus possibly `addDevice` if the node changes. For production, you will typically transfer ownership to a Safe after the first deploy — see [Multisig and Governance](/phala-cloud/key-management/multisig-governance). * **A little gas.** The CLI enforces a minimum balance of 0.001 ETH by default before it will attempt to deploy. For first-time users, **Base is the recommended chain** because the same transactions cost a fraction of a cent. Ethereum mainnet is supported if you want maximum decentralization and are willing to pay L1 gas. * **An RPC URL for the chain you pick** (optional). The CLI and SDK use viem internally, which ships with a default public RPC endpoint for each supported chain, so you can often skip this. For production or anything that does more than a handful of calls, buy an RPC from a reliable provider (Alchemy, QuickNode, Infura, or equivalent) and pass it via `--rpc-url` or the `ETH_RPC_URL` environment variable (the foundry/cast convention). The dashboard uses a bundled RPC by default and also lets you override it per deployment. * **A `docker-compose.yml`** for the workload you want to run. This gets embedded into the `app-compose.json` manifest described above. * **Environment variables** (optional). Your workload may not need any beyond what the image already defaults to. If it does, pass them with a `.env` file (`-e .env`) or inline (`-e KEY=VALUE`). Env vars are **end-to-end encrypted** before they leave the CLI — the CLI fetches the CVM's per-application `app_env_encrypt_pubkey` (a public key derived inside the KMS), encrypts each value locally, and submits only the ciphertext to the backend. Neither Phala Cloud nor any node operator can read plaintext env vars; only the CVM can, after the KMS releases the matching private key. The KmsAuth contract addresses for Ethereum and Base are listed in [Cloud vs Onchain KMS](/phala-cloud/key-management/cloud-vs-onchain-kms#ethereum-vs-base). Do not hard-code them anywhere — the CLI and dashboard read them from the Phala Cloud backend. > [!NOTE] > > You do not need to install anything dstack- or solidity-related. The CLI bundles the KmsAuth and DstackApp ABIs and handles the transaction construction for you. ### Checklist Before running the CLI or opening the dashboard, make sure you can answer yes to all of the following: * I have an API key or an active `phala login` session for the workspace I want to deploy into. * I have a `docker-compose.yml` that runs my workload end to end locally. * I have a wallet and I know its private key (or I have a browser wallet extension ready). * My wallet holds at least a little native token on the chain I am targeting — 0.001 ETH on Base is plenty for the first deploy and the first few updates; on Ethereum mainnet you will want more depending on current gas. * I know which chain I want to govern this application: Base for fast and cheap, Ethereum for maximum decentralization. ### A note on private key hygiene The CLI accepts the deploy private key via `--private-key` or the `PRIVATE_KEY` environment variable. Both leave a trail somewhere (shell history, environment export) and are fine for a dev wallet or a CI secret, but they are not a long-term production posture. After your first successful deploy, the recommended path is: 1. Keep the deploy wallet as the initial DstackApp owner only long enough to verify the CVM is running. 2. Transfer `owner` to a Safe or timelock that you actually use for production governance. 3. From that point on, updates go through [Multisig and Governance](/phala-cloud/key-management/multisig-governance), not through `--private-key`. Do not put a mainnet hot wallet private key into a shared CI environment. If you need CI to update your CVM regularly, use a dedicated wallet that only holds enough gas for transactions and scope its permissions via a multisig or a restricted-update contract. ## A Concrete Example Before We Start To make the rest of this page easier to follow, imagine you want to deploy the [Phala Cloud Gin starter](https://github.com/Phala-Network/phala-cloud-gin-starter) as a CVM on Base, with the DstackApp owned by your personal wallet for now. You will upgrade to a Safe after the first deploy is working. > [!TIP] > > The Gin starter is only one of several ready-to-run templates maintained by Phala Network. If Go is not your thing, you can swap it for any of the following — the compose file layout and deployment flow are the same, only the image changes: > > * [phala-cloud-python-starter](https://github.com/Phala-Network/phala-cloud-python-starter) — FastAPI × dstack > * [phala-cloud-nextjs-starter](https://github.com/Phala-Network/phala-cloud-nextjs-starter) — Next.js > * [phala-cloud-bun-starter](https://github.com/Phala-Network/phala-cloud-bun-starter) — Bun Your `docker-compose.yml`: ```yaml theme={"system"} services: app: image: ghcr.io/phala-network/phala-cloud-gin-starter:v0.1.5-full restart: unless-stopped ports: - "80:8080" volumes: - /var/run/dstack.sock:/var/run/dstack.sock environment: - FAILURE_THRESHOLD=10 healthcheck: test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8080/healthz >/dev/null 2>&1 || exit 1"] interval: 10s timeout: 5s retries: 3 start_period: 10s ``` No `.env` file is needed for this example. If you later add env vars they will be end-to-end encrypted before leaving the CLI, as described in the prerequisites. In your shell, export the private key of the wallet you will deploy from: ```bash theme={"system"} export PRIVATE_KEY=0x... ``` You do not need to set `ETH_RPC_URL` for a first deploy — the CLI will fall back to viem's default public RPC for Base. If you hit rate limits, set `ETH_RPC_URL` to a paid RPC from Alchemy, QuickNode, or any other provider. After this page you will have: * A DstackApp contract on Base, owned by your wallet, with the initial compose hash in its allowlist and the scheduled node's device ID in its allowlist. * A running CVM serving the Gin starter on port 80, whose keys the KMS released after verifying the TDX quote and reading the DstackApp. * A clear command you can run any time you want to update the compose file. With that in mind: ## Deploying via the Dashboard The dashboard flow is a single wizard at `https://cloud.phala.com//deploy`. It provisions the CVM first, then pops open a drawer asking your wallet to deploy the DstackApp contract, then commits the CVM to the backend. ### Step 1: Start a new deployment From your workspace home, click **Deploy** (or pick a template from the template gallery, which pre-fills the compose file). The wizard opens with sections for Basic Info, Resources, Environment, SSH Access, Advanced Features, and a Deployment Summary. ![Workspace Home with Deploy button](https://mintcdn.com/phalanetwork-1606097b/-WnKlfXNtR8R6Xel/images/cloud/workspace-home-deploy-button.jpg?fit=max\&auto=format\&n=-WnKlfXNtR8R6Xel\&q=85\&s=656d31073445ad8cb09f0417229f12df) ### Step 2: Pick your compose file and resources Enter a name, paste your `docker-compose.yml` (or keep the template's default), and choose an instance type. The wizard queries the backend for available nodes and surfaces three things that matter for onchain KMS: * **Node selection.** Only nodes that support onchain KMS will expose a `device_id` that the DstackApp can allowlist. The wizard filters the list for you. * **KMS Provider cards.** Below the resource section you will see a row of cards labeled "KMS Provider," one per available KMS. Pick the card for **Base** or **Ethereum** depending on which chain you want to govern this application. The default, if you do not pick one, is Phala Cloud's centralized KMS — which is the other page's topic. * **OS Image.** Only dstack OS images that the KmsAuth contract has allowlisted will show up once you select a chain-backed KMS. (This is the dstack operating system image that boots the CVM, not the Docker image your app runs as.) ![CVM create wizard with KMS Provider, Base selected](https://mintcdn.com/phalanetwork-1606097b/-WnKlfXNtR8R6Xel/images/cloud/deploy-wizard-kms-provider-base.jpg?fit=max\&auto=format\&n=-WnKlfXNtR8R6Xel\&q=85\&s=bb51629c9f360149d5c6203b02413d18) ### Step 3: Fill in environment variables Any required variables from a template will be flagged. The wizard will refuse to submit until they are filled. These values never leave your browser in plaintext — they are encrypted to the CVM's per-app env-encryption key before being sent to the backend. ### Step 4: Click "Deploy" When you submit the form, the dashboard calls the `/cvms/preflight` and provisioning endpoints. The backend computes the `compose_hash` and `device_id`, and returns them along with the selected KMS's `chain_id`, `kms_contract_address`, and RPC URL. At this point the CVM is **provisioned but not committed** — nothing is running yet, and no on-chain state exists. ### Step 5: Configure the DstackApp contract The wizard opens a drawer titled **Configure DstackApp Contract** with two options: * **Deploy New DstackApp Contract (recommended).** This is the common case. The drawer shows you the selected KMS URL, the chain ID, and the KmsAuth contract address (truncated). Expand **Customize RPC Endpoint** if you want to use your own RPC provider; the dashboard ships with defaults you can test with the **Test RPC** button. * **Use Existing DstackApp Contract.** If you already have a DstackApp you want to reuse (for example, replicating an app to a new CVM), paste its address here and the wizard will skip the deployment transaction. ![Configure DstackApp Contract with Deploy New selected](https://mintcdn.com/phalanetwork-1606097b/-WnKlfXNtR8R6Xel/images/cloud/configure-dstackapp-contract-deploy-new.jpg?fit=max\&auto=format\&n=-WnKlfXNtR8R6Xel\&q=85\&s=0936bee6c61ef6769111ed95f345c88e) Click **Deploy and Continue**. Your connected browser wallet will pop up a transaction request. This is the on-chain deployment of a new DstackApp contract through the KmsAuth factory. The call is `KmsAuth.deployAndRegisterApp(deployer, disableUpgrades, allowAnyDevice, deviceId, composeHash)`. In a single transaction it both deploys the DstackApp contract and registers the initial compose hash and device ID — so after it confirms, both allowlists are already populated for the CVM that is about to start. ![Wallet popup showing deployAndRegisterApp transaction](https://mintcdn.com/phalanetwork-1606097b/-WnKlfXNtR8R6Xel/images/cloud/wallet-popup-deploy-and-register-app.jpg?fit=max\&auto=format\&n=-WnKlfXNtR8R6Xel\&q=85\&s=abc8fadef834a710cbe8c3184f9d371f) Approve it in your wallet. The dashboard watches for the `AppDeployedViaFactory` event and extracts the new `appId` (which equals the DstackApp contract address). ### Step 6: Backend commits the CVM With the DstackApp address in hand, the dashboard calls the commit endpoint. The backend verifies the contract state on-chain, encrypts the env vars with the CVM's env-encryption key, and writes the CVM record. When this returns, you are redirected to the app overview page at `//apps/`. The first CVM boot then kicks off the attestation flow described in [Understanding Onchain KMS → Boot-Time Verification Flow](/phala-cloud/key-management/understanding-onchain-kms#boot-time-verification-flow). You can watch progress on the app overview page — under the **On-Chain KMS** sidebar you will see the DStack KMS address, the DStack App address, and the deployer address. All three link out to Basescan or Etherscan. ![App overview with On-Chain KMS sidebar](https://mintcdn.com/phalanetwork-1606097b/-WnKlfXNtR8R6Xel/images/cloud/app-overview-onchain-kms.jpg?fit=max\&auto=format\&n=-WnKlfXNtR8R6Xel\&q=85\&s=2859643a0b4c48b3cad52bdb0a0c6f03) ### What to do if the wallet pop-up never appears A few common misconfigurations stop the pop-up before you see it: * **No wallet extension installed.** The dashboard uses the standard `window.ethereum` injection. Install MetaMask, Rabby, or a similar extension first. * **Wallet is unlocked on a different chain.** Open the extension and switch to Base (chain ID 8453) or Ethereum mainnet (chain ID 1). The drawer's **Test RPC** button will tell you whether the selected RPC is reachable and on the expected chain. * **Missing `device_id` or `compose_hash`.** This means the provisioning step did not return onchain-KMS metadata — usually because the selected node does not support Onchain KMS. Go back and pick a different node, or pick a different KMS provider card. ### Using an existing DstackApp instead of deploying a new one If you already own a DstackApp from a previous deployment and you want to reuse it — for example, to run a second replica of the same application under the same identity — pick **Use Existing DstackApp Contract** in the drawer and paste the DstackApp address. The wizard will skip the `deployAndRegisterApp` transaction. You still need to make sure the new CVM's compose hash and device ID are allowlisted on that contract, either before starting or by running a follow-up `addComposeHash` / `addDevice` transaction. ## Deploying via the CLI The CLI handles everything in a single command. This is the fastest way to deploy for developers who already have a wallet configured in their shell. ```bash theme={"system"} export PRIVATE_KEY=0x... phala deploy \ --kms base \ -c docker-compose.yml \ --private-key "$PRIVATE_KEY" ``` `--kms` accepts `phala` (default), `ethereum`, `eth`, or `base`. The `--private-key` flag falls back to the `PRIVATE_KEY` environment variable if you omit it. `--rpc-url` is optional — when omitted, the CLI uses viem's default public RPC for the selected chain. Pass `--rpc-url` (or set `ETH_RPC_URL`) if you want to use a paid provider for stability. If the deployment succeeds, the CLI prints a summary to stdout: ``` CVM created successfully! CVM ID: 01234567-89ab-cdef-0123-456789abcdef Name: phala-cloud-gin-starter App ID: app_ff22c67f5d3b4c8a9e1f0a2b3c4d5e6f7a8b9c0d1 Dashboard URL: https://cloud.phala.com/dashboard/cvms/01234567-89ab-cdef-0123-456789abcdef ``` Pass `--json` to get a machine-readable version instead: ```json theme={"system"} { "success": true, "vm_uuid": "01234567-89ab-cdef-0123-456789abcdef", "name": "phala-cloud-gin-starter", "app_id": "ff22c67f5d3b4c8a9e1f0a2b3c4d5e6f7a8b9c0d1", "dashboard_url": "https://cloud.phala.com/dashboard/cvms/01234567-89ab-cdef-0123-456789abcdef" } ``` > [!NOTE] > > The `app_id` in these outputs is the DstackApp contract address. The CLI's human-readable view prepends `app_` for historical compatibility, and the JSON view strips the `0x` prefix — both forms refer to the same 20-byte Ethereum address. On Basescan, you will see it as `0xff22c67f5d3b4c8a9e1f0a2b3c4d5e6f7a8b9c0d1`. > [!NOTE] > > The `dashboard_url` field in the CLI output currently points to `/dashboard/cvms/`, which is a redirect target. The canonical workspace-scoped URLs are: > > * **App overview** — `https://cloud.phala.com//apps/` > * **CVM instance detail** — `https://cloud.phala.com//apps//instances/` > > Both use your workspace slug (not `dashboard`) and require the app\_id or CVM uuid in the path. After landing through the redirect you will see one of these in the browser address bar. ### What happens under the hood The CLI command maps to the following steps, in order: 1. **Read the compose file and encrypt env vars locally.** Size is capped at a few hundred kilobytes combined. 2. **Provision the CVM** via the Phala Cloud backend. The backend picks a node, computes the `compose_hash` and `device_id`, and returns them together with the KMS metadata (`chain_id`, `kms_contract_address`, RPC URL, `chain` object for viem). At this point nothing is on-chain yet. 3. **Deploy the DstackApp contract.** The CLI calls `KmsAuth.deployAndRegisterApp(deployer, disableUpgrades=false, allowAnyDevice=false, deviceId, composeHash)` from your `--private-key`. This is the single wallet-facing transaction. The resulting `appId` is read from the `AppDeployedViaFactory` event. 4. **Fetch the CVM's env-encryption public key.** The backend has one per app, derived inside the KMS. The CLI uses it to encrypt your env vars for the commit call. 5. **Commit the CVM provision.** The CLI sends the `app_id`, `compose_hash`, `contract_address`, and encrypted env to the backend, which then starts the CVM. The backend verifies on-chain that the DstackApp exists, the compose hash is registered, and the deployer address matches before flipping the CVM into the running state. If any of those steps fail, the CLI prints a structured error with the step that failed and a suggested recovery. The most common failure is insufficient gas — the CLI enforces a minimum balance of 0.001 ETH before it sends the deploy transaction, and will abort with a clear message if your wallet is too empty. ### Using the CLI with Ethereum instead of Base Same command, `--kms ethereum` instead of `--kms base`: ```bash theme={"system"} phala deploy \ --kms ethereum \ -c docker-compose.yml \ --private-key "$PRIVATE_KEY" \ --rpc-url https://your-alchemy-endpoint ``` For Ethereum mainnet, using a paid RPC is strongly recommended — the default public endpoint may rate-limit during a deploy transaction, and rate limiting in the middle of a multi-step deploy is confusing to debug. Budget a few dollars of ETH for gas; the `deployAndRegisterApp` transaction is a contract deployment, so it is noticeably more expensive than a normal transfer. `--kms eth` is accepted as an alias for `--kms ethereum` if you prefer it. ### Common CLI flag reference The flags you will reach for most often on top of the basic `--kms base -c docker-compose.yml --private-key`: | Flag | Purpose | | - | - | | `-e ` | Encrypt env vars for the CVM. Accepts a `.env` path or inline `KEY=VALUE`, repeatable. | | `--wait` | Wait for the deployment to finish. On a new deployment, the command registers the app on-chain, commits the provision, and then waits until the CVM is running. If the CVM does not start, the command fails with the boot error and the CVM ID. On an update (`--cvm-id`), it waits for the update to finish. | | `--instance-type tdx.medium` | Pick a specific size instead of letting the scheduler decide. Use when you care about exact vCPU / memory / disk. | | `--no-public-logs`, `--no-public-sysinfo` | Opt out of public log and system-info endpoints at deploy time. Private by default for audit-sensitive workloads. | | `--rpc-url ` | Override the default public RPC. Strongly recommended for production — pass an Alchemy, QuickNode, or equivalent endpoint. | | `--kms ethereum` / `--kms eth` | Deploy against Ethereum mainnet instead of Base. Budget real ETH for gas. | | `--json` | Emit machine-readable JSON instead of the human-readable summary. | A production-shaped deploy using several of these: ```bash theme={"system"} phala deploy \ --kms base \ --instance-type tdx.medium \ -c docker-compose.yml \ -e .env \ --no-public-logs --no-public-sysinfo \ --private-key "$PRIVATE_KEY" \ --rpc-url https://base-mainnet.g.alchemy.com/v2/ ``` ## Verifying Your Deployment Once the CLI or dashboard has finished, three independent checks will confirm that the DstackApp contract is set up correctly. ### 1. Read the contract from a block explorer Open the DstackApp contract on the appropriate explorer. The address is the `app_id` returned by the CLI (prepend `0x` to get the Basescan/Etherscan form), or the "DStack App" row in the dashboard's On-Chain KMS sidebar. On Basescan or Etherscan, click **Contract** -> **Read Contract** and check: * `owner()` — should return your wallet address. After transferring ownership to a Safe, this is where you confirm the new owner address. * `allowedComposeHashes(0x)` — should return `true`. Copy the compose hash from the CLI output or the app overview page. * `allowedDeviceIds(0x)` — should return `true` for the device your CVM was scheduled on. Alternatively, `allowAnyDevice()` may return `true` if you explicitly chose that mode (not recommended for production). You can sanity-check which wallet deployed the contract by looking at the transaction log for `AppDeployedViaFactory(appId, deployer)` on the KmsAuth contract. ### 2. Check the CVM status in the dashboard Navigate to the app overview page at `https://cloud.phala.com//apps/`. It has an **On-Chain KMS** sidebar that shows: * The DStack KMS (KmsAuth) contract address with a link to the explorer * The DStack App (DstackApp) contract address with a link to the explorer * The deployer address — and a **Connect** button that, after connecting your wallet, tells you whether your connected address is the contract owner If the sidebar does not appear, the CVM is not using Onchain KMS — double-check that you picked the Base or Ethereum KMS card during deployment. To drill into a specific CVM — for logs, operations, compose content, or observability — use `https://cloud.phala.com//apps//instances/`. ### 3. Check the CVM status from the CLI ```bash theme={"system"} phala cvms get ``` The CLI accepts any of: the CVM name (if unique in your workspace), the CVM UUID, or the app\_id. It prints Name, App ID, Status, vCPU, Memory, Disk Size, Dstack Image, and App URL. If the CVM reached `Status: running`, the KMS has already released the application keys, which means all three contract checks in step 1 passed at boot time. Note that `phala cvms get` does not currently print KMS metadata (chain, DstackApp address, compose hash). For those, use the dashboard sidebar from step 2. If the CVM is stuck in a pre-running state, check the logs: ```bash theme={"system"} phala logs ``` In a healthy boot you should see lines indicating that the dstack guest reached the KMS and received keys. In a failed boot the logs will typically call out the specific check that failed (compose hash, device ID, or attestation). ### What a healthy deployment looks like To summarize: after a successful first deploy, all of the following should be true. * `phala cvms get ` reports `Status: running`. * On the explorer, `DstackApp.owner()` returns your wallet address. * On the explorer, `DstackApp.allowedComposeHashes(0x)` returns `true` for the hash the CLI or dashboard reported. * On the explorer, `DstackApp.allowedDeviceIds(0x)` returns `true` for the device the scheduler picked, or `DstackApp.allowAnyDevice()` returns `true`. * In the dashboard, the **On-Chain KMS** sidebar on the app overview page shows the three addresses and, after you connect your wallet, identifies you as the deployer. If any of those is off, do not move on to production traffic until it is fixed. ## What's Next Your CVM is running. From here: * **To change the compose file.** See [Updating with Onchain KMS](/phala-cloud/key-management/updating-with-onchain-kms) for the single-command EOA path, or [Multisig and Governance](/phala-cloud/key-management/multisig-governance) if you plan to transfer ownership to a Safe or timelock. * **To allowlist more nodes** for HA or migration. See [Device Management](/phala-cloud/key-management/device-management). * **To transfer DstackApp ownership** to a Safe, timelock, or DAO. Read [Multisig and Governance](/phala-cloud/key-management/multisig-governance) **before** you transfer — an irreversible mistake leaves the CVM frozen on its current compose. ## Troubleshooting > [accordion] The CLI aborts with 'Not enough ETH' > > The CLI enforces a minimum wallet balance of 0.001 ETH before it will send `deployAndRegisterApp`. Top up the wallet on the chain you are targeting and retry. On Base, the Base bridge or any mainstream exchange withdrawal works. On Ethereum mainnet, account for the L1 gas cost of a contract deployment — empty wallets will not do. > [accordion] The CLI says 'Chain required for publicClient' or 'Chain required for walletClient' > > This usually means `--rpc-url` was not set and `ETH_RPC_URL` is not in your environment either. Set one of them and retry. You can verify with `echo $ETH_RPC_URL`. > [accordion] The DstackApp deploys but the CVM never reaches 'running' > > Check the CVM logs first, from the dashboard or with `phala logs`. If the KMS rejected the attestation, the logs will say so. The most common root causes are: > > * The compose hash computed on the node does not match what the contract stores. This normally only happens if something mutates the compose file after provisioning — unusual, but worth re-running the deploy if you see it. > * The device ID of the node the scheduler picked is not in `allowedDeviceIds`. On a fresh deploy this should not happen because `deployAndRegisterApp` registers the current device ID in the same transaction. If it does, cross-check the DstackApp on the explorer: `allowedDeviceIds()` should be `true`. > * The DstackApp `owner` is not who you think it is. If the contract was created by someone else's wallet, `owner()` on the explorer will reveal it. > [accordion] I picked the wrong chain and want to move the app to the other chain > > Onchain KMS is not portable across chains — the DstackApp lives on one chain, and the KMS on that chain is the one that holds the keys. You cannot migrate a deployed CVM from Ethereum to Base (or vice versa) while keeping the same keys. The practical workflow is: > > 1. Deploy a fresh CVM on the new chain with `phala deploy --kms base` or `--kms ethereum`. > 2. Point traffic and any persistent storage at the new CVM. > 3. Delete the old CVM. > > Plan the chain choice up front. > [accordion] The dashboard wallet pop-up is asking for the wrong chain > > Your browser wallet is still on a different network. Open the wallet extension and switch to Base (chain ID 8453) or Ethereum Mainnet (chain ID 1), then click **Deploy and Continue** again. The dashboard will reject the transaction if the chain ID from your wallet does not match the KMS you selected. ## Next Steps * [Updating with Onchain KMS](/phala-cloud/key-management/updating-with-onchain-kms) — roll a new compose file when you hold the DstackApp owner key as an EOA. * [Multisig and Governance](/phala-cloud/key-management/multisig-governance) — the prepare-and-commit flow for compose updates when the DstackApp owner is a Safe, timelock, DAO, or any custom contract. Also covers webhook notifications for pending approvals. * [Device Management](/phala-cloud/key-management/device-management) — how `device_id` is derived, how to allow new nodes, and how to recover when a node's device ID drifts after a hardware change. * [Understanding Onchain KMS](/phala-cloud/key-management/understanding-onchain-kms) — the conceptual model if you want to revisit the contracts and boot-time flow. * [Error Codes reference](/phala-cloud/references/error-codes) — the full catalog of `ERR-01-*` codes returned by the CVM API. # Device Management Source: https://docs.phala.com/phala-cloud/key-management/device-management Manage which physical nodes can run your Onchain KMS app by controlling the on-chain device allowlist. When you use Onchain KMS, your `DstackApp` contract keeps a list of the physical nodes that are allowed to run your application. If a node is not on that list, the KMS will refuse to hand it keys — and your CVM cannot boot there. This page is for operators of an already-deployed Onchain KMS app. It covers how device identity works, how to view the allowlist, how to add and remove nodes from the CLI and the dashboard, and how to recover when a node's identity changes after a hardware upgrade. If you have not deployed an Onchain KMS app yet, start with [Deploying with Onchain KMS](/phala-cloud/key-management/deploying-with-onchain-kms). For the conceptual model behind `compose_hash` and `device_id`, see [Understanding Onchain KMS](/phala-cloud/key-management/understanding-onchain-kms). ## Why Device Identity Matters Onchain KMS decides whether to release keys based on three things: the TEE attestation quote, the code that is running (`compose_hash`), and the physical node the code is running on (`device_id`). All three must match values that your `DstackApp` contract considers valid. The device check is the one most operators overlook. When your CVM is created on node A, the deployment flow registers node A's `device_id` in the allowlist for you. But if you later replicate the CVM to node B for high availability, migrate it to node C after a hardware failure, or the same node's underlying identity changes after a BIOS update, the KMS will look up the new `device_id` on-chain, find it missing, and deny the key request. The CVM will fail to boot and you will see a device-not-allowed rejection in the boot log. Managing the allowlist is therefore a routine operational task whenever you change where your app runs. It is also the main knob for auditability: the allowlist, together with the on-chain events emitted when it changes, gives you a cryptographic record of exactly which machines were ever authorized to run your code. ## What a `device_id` Is Every Intel TDX host exposes a **Platform Provisioning ID** (PPID) — a hardware-level identifier derived from the CPU and the platform's provisioning keys. Two different machines have different PPIDs. The same machine, under normal operation, keeps the same PPID across reboots. Phala Cloud surfaces each node's PPID to the workspaces that are allowed to deploy to it. PPID is not a global public directory — you can see the PPID and `device_id` of the nodes listed in your own workspace's deployable node list (for example, in the node picker inside the create-CVM wizard). Nodes you cannot deploy to are not exposed. Phala Cloud and the `DstackApp` contract never store the raw PPID on-chain. Instead they store the SHA-256 hash of the PPID bytes — `device_id = sha256(ppid)`. This derivation is implemented in dstack's attestation library ([`dstack-attest/src/attestation.rs`](https://github.com/Dstack-TEE/dstack/blob/next/dstack/dstack-attest/src/attestation.rs)) and is the same value that Phala Cloud surfaces in the node list, writes to the `DstackApp.allowedDeviceIds` mapping, and checks at boot time. This derivation gives you: * A fixed-length 32-byte value, represented as a 64-character hex string off-chain and as `bytes32` on-chain. * A stable one-to-one mapping: one physical node corresponds to one `device_id` under normal operation. * No reversibility: the on-chain value does not leak the PPID to third parties. ### When `device_id` Changes The PPID is not completely immutable. It can change when the platform's provisioning state changes — most commonly after: * A BIOS firmware update * A CPU microcode update * Some motherboard replacements or TDX re-provisioning events When the PPID changes, `sha256(new_ppid)` changes too, so the node presents a new `device_id` the next time it asks KMS for keys. Phala Cloud keeps an internal history of per-node device identity changes so operators can audit when a node's identity changed, but the on-chain contract does not know about the old-to-new mapping. Any CVMs whose allowlist still points at the stale `device_id` will need the new one added before they can boot again. > [!NOTE] > > A `device_id` change is not a security incident on its own — it is an expected consequence of firmware maintenance. It only becomes a problem because an allowlist entry that used to match the node no longer matches it. ## The On-Chain Allowlist Model The `DstackApp` contract stores two pieces of state that control device access: * `allowedDeviceIds(bytes32) → bool` — a mapping from `device_id` to whether that device is allowed. * `allowAnyDevice() → bool` — a bypass flag. When `true`, the per-device mapping is ignored and any node in the KMS's scope is allowed. All writes are gated by the contract's `owner`. The following functions all revert if called by anyone other than the owner: ```solidity theme={"system"} function addDevice(bytes32 deviceId) external; function removeDevice(bytes32 deviceId) external; function setAllowAnyDevice(bool _allowAnyDevice) external; ``` And the contract emits one event per change: ```solidity theme={"system"} event DeviceAdded(bytes32 deviceId); event DeviceRemoved(bytes32 deviceId); event AllowAnyDeviceSet(bool allowAny); ``` Those events are what auditors and monitoring tools should watch. They give you an immutable, timestamped log of every allowlist mutation on your app. ## Viewing the Current Allowlist You have three independent ways to look at the state of the allowlist. They should always agree; if they do not, trust the on-chain view. ### Dashboard Open your app in the Phala Cloud dashboard at `https://cloud.phala.com//apps/` and scroll the app overview page to the **Device Allowlist** section in the right sidebar. ![Device Allowlist section with Allow any device toggle and device rows](https://mintcdn.com/phalanetwork-1606097b/-WnKlfXNtR8R6Xel/images/cloud/device-allowlist.jpg?fit=max\&auto=format\&n=-WnKlfXNtR8R6Xel\&q=85\&s=04c1d8448196b296819e28513636c51a) Every time you open this page, the dashboard reads the current on-chain allowlist **and** cross-checks it against the `device_id` of every node your CVMs are actually running on. If any deployed node is missing from the allowlist — including the common case where a BIOS or microcode update silently drifted a node's PPID — a warning banner appears at the top of the section, and the offending rows are highlighted so you can act on them without having to hunt for the mismatch. The panel shows: * An **Allow any device** row at the top. When on, the contract's `allowAnyDevice` flag is `true` and the per-device toggles below are effectively ignored. * One row per known device. The list is merged from two sources — devices your CVMs are currently running on (whether or not they are allowed) and devices on nodes your workspace can deploy to. Each row shows the 32-byte `device_id` (click to copy), the node name with a region flag where available, and a status icon: green check for allowed, amber triangle for deployed-but-not-allowed, grey X for known-but-not-deployed. If your connected wallet is the contract owner, each row has a toggle that sends the matching on-chain transaction through your wallet — that is how you remediate a PPID drift without leaving the dashboard. If the owner is not an EOA you control, the toggles are hidden; see the [Non-EOA Owner](#non-eoa-owner) callout below. ### CLI ```bash theme={"system"} phala allow-devices list ``` `` can be a CVM UUID, a CVM name, an `instance_id`, or an `app_id` (raw hex or `app_` prefixed). The command resolves it to the underlying `DstackApp` contract and queries the chain directly. Example output: ``` Contract: 0x1234…abcd Chain: Base Owner: 0xabcd…1234 Allow Any Device: no DEVICE_ID NODE 0xaabbccdd… prod6 0x11223344… use2 ``` > [!TIP] > > To discover the `device_id` of every node your workspace can deploy to, run `phala nodes ls`. The output includes `NAME`, `REGION`, `PPID`, `DEVICE_ID`, and `VERSION` columns, so you can pick the node name or paste its `device_id` directly into the write commands below. When `allowAnyDevice` is on, the per-device table is not printed (the underlying read would just echo every queried ID back without meaning). You can pass `--rpc-url ` (or set `ETH_RPC_URL`) to use a specific RPC endpoint. `list` never signs anything, so `--private-key` is not required. For machine-readable output, pass `--json`. ### On-Chain (Independent Verification) Because the contract is public, anyone can read the allowlist directly without going through Phala Cloud. On Basescan or Etherscan, open your app contract, switch to **Contract → Read Contract**, and call: * `allowAnyDevice()` — returns `true` or `false`. * `allowedDeviceIds(bytes32)` — paste the 32-byte `device_id` (with the `0x` prefix) and read the boolean result. This is the most trustworthy view. If the dashboard or the CLI ever disagrees with the contract, the contract is right. ## Adding and Removing Devices from the CLI All write commands need two things: * A signing key with enough gas on the target chain. Pass `--private-key 0x…` or set `PRIVATE_KEY` in your environment. * An RPC URL for the chain. Pass `--rpc-url ` or set `ETH_RPC_URL`. If omitted, the CLI falls back to the chain's public default RPC, which is frequently rate-limited; use a dedicated RPC for anything beyond a quick experiment. Every write command accepts an optional `--wait` flag. Without `--wait`, the command returns as soon as the transaction is submitted. With `--wait`, it polls the RPC until the on-chain state reflects the change (or times out after roughly one minute). > [!WARNING] > > The signing wallet you pass with `--private-key` must be the `DstackApp` contract owner. If ownership has been transferred to a Safe, a timelock, or any other contract, the transaction will revert and the CLI will report a failure. See the [Non-EOA Owner](#non-eoa-owner) section. ### Add a Device ```bash theme={"system"} phala allow-devices add \ --private-key 0x... ``` `` can be either a node name (as shown by `phala nodes ls`, for example `prod6` or `use2`) or a 32-byte hex string (with or without `0x`). When you pass a node name, the CLI looks it up against your workspace's deployable-node list and resolves it to the node's current `device_id`. Ambiguous names are rejected rather than guessed. ```bash theme={"system"} # By node name (recommended — survives device_id drift if you rerun it) phala allow-devices add my-cvm prod6 --private-key 0x... # By raw device_id phala allow-devices add my-cvm 0xaabbccdd... --private-key 0x... ``` Interactive mode selects from nodes you have access to but which are not yet on the allowlist: ```bash theme={"system"} phala allow-devices add -i --private-key 0x... ``` The CLI prints a checkbox list of candidate nodes (` `), lets you multi-select, then submits one `addDevice(bytes32)` transaction per selection. Successful output looks like: ``` Submitting add-device transaction for 0xaabbccdd... RPC URL: https://base-mainnet.example.com Add-device transaction for 0xaabbccdd... submitted: 0xdeadbeef... Explorer: https://basescan.org/tx/0xdeadbeef... Waiting for 1 confirmation... Added 0xaabbccdd... Transaction: 0xdeadbeef... Explorer: https://basescan.org/tx/0xdeadbeef... Backend allowlist API may lag behind chain. Use --wait to verify via RPC. ``` Underlying contract call: `addDevice(bytes32 deviceId)`. The contract emits `DeviceAdded(deviceId)` on success. ### Remove a Device ```bash theme={"system"} phala allow-devices remove \ --private-key 0x... \ --rpc-url https://base-mainnet.example.com ``` Interactive removal lists the devices currently marked `allowed` by the backend: ```bash theme={"system"} phala allow-devices remove -i --private-key 0x... ``` Underlying contract call: `removeDevice(bytes32 deviceId)`. The contract emits `DeviceRemoved(deviceId)`. > [!NOTE] > > Removing a device while `allowAnyDevice` is `true` has no practical effect — the bypass flag still lets the node boot. The CLI warns about this when you use `--wait`: > > ``` > Warning: allowAnyDevice is enabled — removed devices still appear as allowed. Disable allow-any-device first if you want per-device enforcement. > ``` ### Enable or Disable the "Allow Any Device" Bypass ```bash theme={"system"} phala allow-devices allow-any --enable --private-key 0x... phala allow-devices allow-any --disable --private-key 0x... ``` You must pass exactly one of `--enable` or `--disable`; the command refuses to run otherwise. Underlying call: `setAllowAnyDevice(bool)`. The contract emits `AllowAnyDeviceSet(allowAny)`. `disallow-any` is a shortcut that only turns the flag off: ```bash theme={"system"} phala allow-devices disallow-any --private-key 0x... ``` It is equivalent to `allow-any --disable`. Use whichever reads better in your runbooks. `toggle-allow-any` flips the current state (or forces it with `--enable` / `--disable`): ```bash theme={"system"} phala allow-devices toggle-allow-any --private-key 0x... ``` Without any flag, it reads the current `allowAnyDevice` value from the backend and sends a transaction to set the opposite. Pass `--enable` or `--disable` if you want to assert a specific end state instead of toggling. ## Multi-Replica and HA Patterns When an app runs on more than one node — whether for geographical redundancy, scaling, or active failover — you have two broad strategies: ### Option A: Precise Allowlist Maintain a per-node allowlist using `addDevice` and `removeDevice`. Every node the app is allowed to run on has an explicit on-chain entry. * **Pros.** You get a cryptographic audit trail of exactly which physical machines were ever authorized to execute your app. Removing a node is a provable, on-chain event. This is the strongest model for compliance-sensitive workloads and for auditors that want to reason about the blast radius of a compromise. * **Cons.** Operational overhead. Adding capacity is a signed transaction; so is rotating out a failed node; so is recovering from a BIOS-driven `device_id` change. ### Option B: `allowAnyDevice = true` Flip the bypass flag. The contract stops checking `allowedDeviceIds` and permits **any Phala Cloud node attached to this KMS** to host the app. The "any" is scoped to hosts that the KMS already considers trusted — hosts that have passed dstack-KMS onboarding and are part of the Phala Cloud fleet — not any random TEE machine on the internet. * **Pros.** You can scale freely across any Phala Cloud node without touching the allowlist. No per-migration overhead. * **Cons.** Weaker audit guarantees. Any Phala Cloud host the KMS considers trusted can attempt to run your app, and your on-chain record no longer pins execution to a specific set of machines. > [!WARNING] > > `allowAnyDevice = true` trades cryptographic per-node enforcement for operational convenience. For production workloads where execution locality is part of your threat model or compliance story, prefer Option A and accept the operational cost. For production and audit-sensitive deployments we recommend Option A. Use Option B only when the simplicity is genuinely worth giving up the per-node audit trail. ## Recovering from a Hardware Upgrade When a node's PPID changes after a BIOS, microcode, or platform update, any CVM whose allowlist entry still references the old `device_id` will stop booting there. **Symptoms.** * CVMs on the affected node fail to start or fail to obtain keys on the next reboot. * The boot log or the dashboard warning banner reports that the node's `device_id` is not on the allowlist. * `phala allow-devices list ` does not include the node's current `device_id`. **Recovery.** 1. Look up the node's **new** `device_id` by running `phala nodes ls`. The output shows one row per deployable node, including the current `device_id` after any drift. The quickest path is to either remember the node name (for example `prod6`) or copy the new 32-byte hex value. 2. Add the node back to the app's allowlist. You can pass either the node name or the raw `device_id`: ```bash theme={"system"} phala allow-devices add prod6 \ --private-key 0x... \ --wait ``` The CLI resolves `prod6` against your workspace's node list and submits `addDevice(bytes32)` with the node's current `device_id`. If you prefer to be explicit, pass the 32-byte hex value instead: ```bash theme={"system"} phala allow-devices add 0x \ --private-key 0x... \ --wait ``` 3. The dashboard's **Device Allowlist** section is the fastest way to check the result — open `https://cloud.phala.com//apps/`, and the warning banner for this node should be gone. 4. Restart the CVM on the affected node. It should now complete the KMS handshake and boot successfully. 5. Optionally, remove the old `device_id` with `phala allow-devices remove` once you are sure nothing else needs it. If the CVM was actively running on the node at the moment the platform update took effect, expect a brief window of downtime between the old identity being invalidated and the new one being authorized. You can shorten that window by preparing and signing the `addDevice` transaction in advance of the maintenance. ## Non-EOA Owner > [!WARNING] > > The `phala allow-devices` commands assume the `DstackApp` owner is an externally-owned account whose private key you hold. If your app's owner is a Safe, a timelock, a DAO, or any other contract, the `--private-key` path will not work — the transaction will be sent from an EOA that the contract considers unauthorized, and it will revert. > > The CLI does **not** currently support a `--prepare-only` mode for device operations. For non-EOA owners you must call the contract directly through your governance tooling: > > * **Safe.** Open the Safe Transaction Builder, point it at your `DstackApp` contract address, and call `addDevice(bytes32)`, `removeDevice(bytes32)`, or `setAllowAnyDevice(bool)` with the 32-byte `device_id` you want to change. > * **Timelock.** Queue the same call through the timelock's `schedule` / `execute` flow. > * **Custom governance contract.** Use whatever path your contract exposes for executing arbitrary calls against external contracts. > > See [Multisig and Governance](/phala-cloud/key-management/multisig-governance) for the full walkthrough of managing an Onchain KMS app whose owner is a multisig or timelock. ## Next Steps * [Deploying with Onchain KMS](/phala-cloud/key-management/deploying-with-onchain-kms) — the prerequisite for everything on this page. Covers the first-time deploy of a `DstackApp` contract and its initial `device_id` / `compose_hash` registration. * [Multisig and Governance](/phala-cloud/key-management/multisig-governance) — how to operate an app whose owner is a Safe, a timelock, or a DAO, including the manual path for device operations when the CLI's `--private-key` flow cannot be used. # Get a Deterministic Key Source: https://docs.phala.com/phala-cloud/key-management/get-a-key Generate deterministic keys for cryptographic operations in Phala Cloud Generate deterministic 256-bit keys from your application's root key in the TEE. Keys are unique to your application ID, and the same input parameters always produce the same key. ## Prerequisites Your application must be running in the Phala Cloud TEE environment with access to the dstack socket. In your `docker-compose.yml`: ```yaml theme={"system"} services: app: # your app configuration volumes: - /var/run/dstack.sock:/var/run/dstack.sock ``` ## Quick Start ```javascript index.js theme={"system"} import { DstackClient } from '@phala/dstack-sdk'; const client = new DstackClient(); const result = await client.getKey('my-app/encryption/v1'); const keyBytes = result.key; // Uint8Array(32) ``` ```python main.py theme={"system"} from dstack_sdk import DstackClient client = DstackClient() result = client.get_key('my-app/encryption/v1') key_bytes = result.decode_key() # 32 bytes ``` ```bash curl.sh theme={"system"} curl --unix-socket /var/run/dstack.sock -X POST \ http://dstack/GetKey \ -H 'Content-Type: application/json' \ -d '{"path": "my-app/encryption/v1"}' ``` ## Parameters * **`path`** (required): Unique identifier for the key. Use forward slashes to organize: `app-name/feature/version` The same path always generates the same key. Different paths generate different keys. > [!TIP] > > **Advanced: Purpose Parameter** > > The `getKey()` method accepts an optional second parameter called `purpose`: > > ```javascript theme={"system"} > const result = await client.getKey('wallet/ethereum', 'mainnet'); > ``` > > The `purpose` parameter is purely for organization and signature chain management. It doesn't affect the returned key material (only `path` participates in key derivation). `getKey()` returns an ECDSA-based signature chain where `purpose` is hased into the signed message to isolate the namespace. Please leave it empty it if you are not sure what it does. ## Key Properties * **Application-specific**: Keys are derived from your app's unique master key (tied to app ID) * **Deterministic**: Same `path` always generates the same key * **Isolated**: Different applications cannot derive each other's keys * **32 bytes**: Raw key material suitable for various cryptographic operations ## Common Use Cases The 32-byte key can be used as: * AES-256 encryption key * HMAC secret * Random number generator seed * Input for key derivation functions (KDF) * Signing key for custom protocols ## Best Practices * Use descriptive paths: `app-name/feature/version` * Never log or expose keys outside TEE * Use different paths for different purposes * Version your keys in the path (e.g., `/v1`, `/v2`) ## Migration from v0.3.x If you're upgrading from dstack v0.3.x, see the [Migration from dstack v0.3](/phala-cloud/references/migration-from-dstack-v03) guide for breaking changes and upgrade instructions. # What is KMS Source: https://docs.phala.com/phala-cloud/key-management/key-management-protocol Technical design documents and architecture details for the dstack TEE platform. In [Decentralized Root-of-Trust](/dstack/design-documents/decentralized-root-of-trust), we described our motivation to update the TEE Root-of-Trust from hardware-kept unrecoverable secret keys to a smart-contract-governed software (i.e., DeRoT). In this article, we’ll delve deeper into the details of its key management protocol. ## Threat Model [#p-8432-threat-model-1](#p-8432-threat-model-1) A fundamental assumption in our threat model is that *TEE can be compromised*. Therefore, our primary goal is to ensure that even if the TEE hardware is compromised, the application should still function correctly with minimal data leakage. This is why we introduce Decentralized Root-of-Trust (DeRoT), a verifiable Key Management Service (KMS) for TEE governed by smart contracts, to replace the hardware-kept unrecoverable secret keys in TEE. Based on this assumption, we discuss potential threats and corresponding countermeasures. Specifically, both the confidentiality and integrity guarantees provided by TEE hardware can be compromised. * If confidentiality is compromised, encrypted memory values may be leaked, and this will further affect the sealed data on persistent storage. The countermeasures aim to: * Limit the damage scope when a single worker is compromised to only the minimal amount of data it knows. * Ensure forward and backward secrecy so that historical and future data remains safe. * If the integrity promise is broken, an adversary can instruct the TEE to produce false results. In this case, all outputs from the compromised TEE should not be trusted or used by other TEE hardware and clients. While detecting TEE vulnerabilities and compromises is beyond the scope of DeRoT, it should be able to revoke authentication and prevent dirty data from being persisted. ## Introducing DeRoT [#p-8432-introducing-derot-2](#p-8432-introducing-derot-2) Compared to traditional key management services, DeRoT differs in two aspects: * **Access Control on Clients:** DeRoT verifies its clients to ensure they are genuine TEE hardware running valid applications. * **Verifiable Chain-of-Trust:** The DeRoT program, along with all its generated keys, must be verifiable through blockchain technology. We will explain how to verify the integrity of the DeRoT program and check whether a key is genuinely generated by DeRoT in the following sections. DeRoT is designed to enhance the functionalities of the current hardware-kept secret key in TEE in two major scenarios: 1) identifying the TEE hardware, and 2) [data sealing](https://www.intel.com/content/www/us/en/developer/articles/technical/introduction-to-intel-sgx-sealing.html) (i.e., the encryption of persistent storage). Its advantages include: * **Vendor- and Hardware-Agnostic TEE Verification:** DeRoT is responsible for distributing secret keys only to valid TEE hardware and controlling the key lifecycle. Clients can delegate the Remote Attestation (RA) report verification to DeRoT, needing only to verify whether the key held by the TEE is valid. This simplifies client implementation and abstracts away the details of RA reports. Additionally, this approach can be easily extended to support different TEE hardware and get integrated into existing certificate chains. * **Key Rotation in Data Sealing with Enhanced Security Features:** With key rotation, the time window for attackers is significantly limited. Furthermore, this approach ensures forward and backward secrecy for sealed data, enhancing overall security. * **Support for Upgradable and Migratable Applications:** Since the sealed data is now encrypted with keys generated by the standalone DeRoT, storage can be entirely separated from TEE hardware. This allows upgraded applications to decrypt saved states in a controllable way, and enables dynamic addition or removal of TEE hardware without concerns about data loss. Additionally, this architecture aligns with the existing cloud paradigm, facilitating easier migration. ## Unique Challenge: Stealthy Deployer Attack [#p-8432-unique-challenge-stealthy-deployer-attack-3](#p-8432-unique-challenge-stealthy-deployer-attack-3) Unlike in smart contracts that every operation is observable onchain, the introduce of DeRoT enables a blockchain-TEE hybrid system where the interactions can happen both onchain and invisibly off-chain. Also, the support for upgradable application code will introduce more risks since the benign code may be changed to dump the encrypted data in an unconscious way. Considering the following attack from a malicious application deployer: 1. An open-source benign application is deployed to TEE and trusted by its users to process the privacy data; 2. The deployer asks the DeRoT to upgrade the application code. It seems no reason to reject it since he is the owner; 3. The deployer injects malicious logic to dump all the privacy data in the new code, but doesn't announce this to the public. Since this upgrade is between the TEE and DeRoT, it is not observable from the onchain perspective; 4. The deployer can make another upgrade to remove the malicious logic to erase the evidence. Actually, similar attacks on the upgradable smart contracts happened before, but the difference is that such attack will not be naturally perceived when the application and the DeRoT are running off-chain. It’s worth noting that adding more access control on the application upgrade operation (e.g. enforce a multi-sig smart contract) cannot mitigate this risk. This attack motivates an important principle in our design: *every operation involving key authorization changes must be initiated onchain to ensure observability*. This will ensure the security equivalence to existing smart contracts. ## Design [#p-8432-design-4](#p-8432-design-4) ### Verifiable DeRoT and Key Chain [#p-8432-verifiable-derot-and-key-chain-5](#p-8432-verifiable-derot-and-key-chain-5) ![Decentralized Root-of-Trust (DeRoT) key chain architecture showing smart contract governance and key derivation hierarchy](https://mintcdn.com/phalanetwork-1606097b/HhZAgNWhhdRirRzb/images/derot-key-chain.png?fit=max\&auto=format\&n=HhZAgNWhhdRirRzb\&q=85\&s=8513a31b2d85250aceb4e054904fd521) To enable the verification on the DeRoT program integrity and correctness, its measurement will be specified in the governance smart contract. Several steps need to be followed to ensure the smart contract’s governance over the DeRoT program. 1. The DeRoT code is open-source for anyone to do code and security review to ensure the correctness of key management logic and no backdoors; 2. The executable must be produced with reproducible build so the verifier can know it matches the source code; 3. The digest of valid executable is published through onchain governance; 4. Multiple DeRoT instances run inside TEE. Here we only rely on TEE to provide the measurement over the executable, and ensure it matches the digest onchain. Apart from RA report verification, the core logic of key management in DeRoT is quite compact. It just involves two operations: * the creation of the RootKey; * the derivation of each application key using RootKey and nonce including deployer identity and application measurement. Because of the simple logic, it can use MPC/FHE-based threshold key generation and derivation with no concern about the performance overhead. The public key of RootKey must be published onchain to enable any party to verify the validity of application keys with it. We will show that such root-key-derivation pattern is important to enable an efficient key rotation in the following section. ### Key Derivation [#p-8432-key-derivation-6](#p-8432-key-derivation-6) The key management of DeRoT follows the *Principle of Least Privilege* that the secrecy known by each entity in the system is strictly limited to what it requires to finish the jobs. We first explain the keys used during program execution, and then discuss the privileges of different entities. ![Key derivation hierarchy diagram showing RootKey, AppRootKey, SealingKey, and StorageKey relationships in DeRoT](https://mintcdn.com/phalanetwork-1606097b/HhZAgNWhhdRirRzb/images/key-derivation-hierarchy.png?fit=max\&auto=format\&n=HhZAgNWhhdRirRzb\&q=85\&s=7eda9f1c80b6e8147d0ec73b21f39794) DeRoT turns the previous hardware-centric key management to application-centric key management. That is, each application has its own keys to seal the states and encrypt the databases, and they can be distributed to different TEE workers to enable the applications to be migrated between them. There are three entities involved in the key management protocol, and they have different knowledge of the keys: * DeRoT, which knows the RootKey and is able to generate any key; * Storage service, which can be the external storage server or service containing the data and states of the application. The storage service holds the StorageKey and can rotate it independently to keep re-encrypting the data. It’s worth noting that the DeRoT can rotate it synchronously if they share the same timestamp; * The TEE worker running the applications. Every key it holds must be distributed from DeRoT. An important feature here is that *every key received by TEE worker is kept in rotation*, so the DeRoT can passively “revoke” the worker’s access to certain program states by not to deliver the newly rotated keys. Once DeRoT rejects to deliver the latest keys, the TEE worker will not able to decrypt the local sealed data or read/write to the external storage. During program execution, the DeRoT keeps delivering the latest AppKeys to functional workers so they can correctly decrypt the program states. Although this makes DeRoT the single point of failure, we want to argue that since the DeRoT only focuses on key management, it is easier to do thorough code review to ensure its security. Further, as discussed above, the DeRoT only listens to the application deployment request from blockchain and is not accessible to others, which greatly reduces the attack interface. The RootKey is only known by DeRoT and a Key Derivation Function (KDF) is used to generate all the other keys. The AppRootKey above is merely a logical entity and can be skipped in the actual key generate. For example, $SealingKey_{epoch}=KDF(RootKey,(deployer\_id,app\_hash,nonce,"seal",epoch))$ ### Key Rotation [#p-8432-key-rotation-7](#p-8432-key-rotation-7) There are two rotation variables above: the RootKey itself and by changing `epoch` during key derivation. The rotation of the RootKey will immediately changes all the keys in the system, while the interval of updating `epoch` can be configured independently for different storage services so they can be rotated in different frequencies based on the requirements. The update of the applications, which will change the `app_hash` above, can be regarded as a special key rotation for the application. #### Forward and Backward Secrecy Ensurance in TEE Workers [#p-8432-forward-and-backward-secrecy-ensurance-in-tee-workers-8](#p-8432-forward-and-backward-secrecy-ensurance-in-tee-workers-8) On one hand, the TEE worker runtime will only keep the latest AppKeys and remove all the used keys from its memory to preserve the forward secrecy; on the other hand, once a worker is considered compromised, the DeRoT will stop delivered the rotated new keys, so the worker will not be able to get further access to the following code and state updates of the program, preserving the backward secrecy. # Multisig and Governance Source: https://docs.phala.com/phala-cloud/key-management/multisig-governance Run production Onchain KMS apps with Safe, Timelock, or DAO ownership using the prepare and commit flow. Production apps often need more than a single hot wallet for code updates. This page walks through transferring DstackApp ownership to a Safe or governance contract, then using the CLI prepare and commit flow (and webhooks) to push compose updates without the CVM operator ever holding the owner key. For a primer on which contracts govern what, see [Understanding Onchain KMS](/phala-cloud/key-management/understanding-onchain-kms). For the EOA-owned update path that this page replaces once ownership is transferred, see [Updating with Onchain KMS](/phala-cloud/key-management/updating-with-onchain-kms). For device-level operations, see [Device Management](/phala-cloud/key-management/device-management). ## When to Use Multisig Use multisig ownership when no single person on your team should be able to push a compose update on their own. Typical triggers: * Production apps where an unauthorized code change has material impact on users or funds. * Compliance programs that require separation of duties for production changes. * DAO-governed apps where token holders vote on what code runs. * Insurance or audit requirements that ask for m-of-n approval on sensitive deployments. The trade-off is speed. Every compose change has to be proposed, signed by enough owners, mined, and then committed back to Phala Cloud. Hot-patching a broken build takes minutes to hours instead of seconds. Plan release cycles accordingly, and keep an EOA-owned staging app for fast iteration. Phala Cloud does not host a multisig for you. You bring your own Safe, Timelock, DAO contract, or any other contract that exposes an owner role. Phala Cloud only cares about one thing: the `owner()` of your DstackApp contract must be able to authorize `addComposeHash(bytes32)` calls. Whatever contract shape makes that happen is up to you. ## Ownership Model Recap Your DstackApp contract stores: * `owner` — the address allowed to call `addComposeHash`, `addDevice`, `removeDevice`, `setAllowAnyDevice`, and `transferOwnership`. * `allowedComposeHashes` — the set of compose hashes approved to boot under this app identity. * `allowedDeviceIds` — the set of nodes allowed to host this app (see [Device Management](/phala-cloud/key-management/device-management)). By default, `owner` is the deployer EOA that created the app. The CLI `phala deploy --cvm-id ... --private-key ...` path works as long as that EOA still holds ownership. To move to multisig, you transfer ownership to a contract address, after which direct EOA updates fail and all future updates go through the prepare and commit flow. > [!NOTE] > > `owner` on DstackApp governs your application identity only. It does not control the KmsContract that Phala operates, and it cannot mint or rotate keys by itself. Keys are still derived inside the TEE after KMS verifies attestation against whatever compose hashes `owner` has approved. ## Transferring Ownership to a Safe > [!WARNING] > > Ownership transfer is a one-way on-chain action. If you transfer to an address that cannot sign (a contract that does not implement `addComposeHash` forwarding, a Safe with the wrong threshold, a mistyped address), you lose the ability to update the app forever. Always test the full flow on a throwaway DstackApp first. The transfer itself is a plain `transferOwnership(address)` call on the DstackApp contract. You do it from the current owner EOA using any Ethereum or Base tool you prefer. 1. Deploy your Safe first, or have its address handy. On Base, use [safe.global](https://app.safe.global) with the network set to Base. Record the Safe address (for example `0x1234...abcd`) and the signer threshold (for example 3-of-5). 2. Open your DstackApp contract on [Basescan](https://basescan.org) or [Etherscan](https://etherscan.io). The address is the same as your app ID with a `0x` prefix. You can also find it on the Phala Cloud dashboard under the app overview. 3. DstackApp is deployed as a **proxy contract**, so its write methods live on the proxy page, not the implementation. Go to the **Contract** tab and choose **Write as Proxy** (not **Write Contract**). If the **Write as Proxy** tab is missing or shows no functions, click the **Verify** link on the proxy first — Basescan/Etherscan needs the implementation address resolved before it can expose the proxy's write methods. 4. Click **Connect to Web3** and connect the EOA that currently owns the app. 5. Find `transferOwnership` in the write methods. Enter the Safe address. Submit and wait for confirmation. 6. Verify on-chain. Switch to **Read as Proxy** and call `owner()`. It should return the Safe address. From this moment on, `phala deploy --cvm-id --private-key ` will fail with an owner-mismatch error on the `addComposeHash` step. Do not panic — this is expected. All future compose updates go through the prepare and commit flow described below. If your governance contract is a Timelock, DAO voting contract, or any other shape, the steps are the same. You are simply calling `transferOwnership(address)` from the EOA that currently holds the role. Use whichever UI you prefer — Basescan, Etherscan, Safe Transaction Builder, `cast send`, Foundry scripts — the on-chain effect is identical. ## The Prepare, Approve, Commit Model With EOA ownership, the CLI does everything in one shot: it reads your compose file, computes the hash, sends `addComposeHash` to the chain, and tells Phala Cloud to roll the update forward. With multisig ownership, that one step splits into three phases across two different actors. > [!NOTE] > > **The CVM does not restart until Phase 3 completes.** Prepare and approve are both no-ops from the running CVM's point of view — the live workload keeps serving traffic under the old compose hash throughout. Only when commit succeeds does Phala Cloud save the new compose, re-encrypt env vars, and trigger the restart. If you abandon a flow halfway, there is nothing to roll back. **Phase 1 — Prepare.** The CVM operator runs `phala deploy --cvm-id ... --prepare-only -c new-compose.yml`. Phala Cloud computes the compose hash, checks current on-chain state, and mints a one-time commit token (a UUID) valid for 14 days. The CLI prints the compose hash, the exact on-chain action required, and the commit URLs. Nothing on-chain has changed yet, and the CVM keeps running its existing compose hash. **Phase 2 — Approve.** A human (or a governance contract) takes the compose hash from Phase 1 and submits `addComposeHash(bytes32)` to the DstackApp contract through the Safe, Timelock, or DAO. This is where signatures are collected and the transaction is mined. Phala Cloud is not involved in Phase 2 at all — the approvers only need the compose hash and the DstackApp contract address. The CVM is still running the old compose during this phase. **Phase 3 — Commit.** Once the on-chain transaction is mined, someone (the original operator, a CI job, or an automation bot) tells Phala Cloud the transaction landed. The backend verifies that the compose hash is now registered on-chain and that the provided transaction hash contains the expected state change, then rolls the CVM update forward — this is the point where the CVM actually restarts onto the new compose. A few properties of this design worth internalizing: * **Commit tokens expire after 14 days.** If approval takes longer, re-run prepare. The expiry is enforced by the Phala Cloud backend. For a simple Safe with a few signers this is rarely a problem, but see the Timelock note below. * **Re-preparing invalidates the previous token.** If you run `--prepare-only` twice for the same CVM, only the second token works. This is intentional: it prevents stale updates from racing with newer ones. If two people are preparing in parallel, coordinate offline first. * **Prepare is idempotent with respect to the compose file.** If the compose file has not changed, re-running prepare gives you a fresh token pointing at the same compose hash. * **Prepare does not touch the CVM.** The CVM keeps running the old compose hash until Phase 3 completes. If you cancel mid-flow, nothing rolls back — just discard the token. ### Long-delay Timelocks and the 14-day window If your governance contract is a Timelock with a delay approaching or exceeding 14 days, the straightforward "prepare, propose, wait, execute, commit" sequence can fail at commit time: by the time the Timelock delay elapses, the commit token has already expired. The fix is to decouple the Phase 2 on-chain action from the Phase 1 token's lifetime. Phases 2 and 3 only need to agree on the **compose hash**, not the token, because the backend verifies the chain state by hash. Concretely: 1. Run `phala deploy --cvm-id ... --prepare-only` once to discover the compose hash. Record it and discard the token — you will not use it. 2. Encode `addComposeHash(bytes32)` with that hash and queue it through your Timelock immediately. 3. Wait for the Timelock delay to elapse and execute the transaction on-chain. Record the resulting transaction hash. 4. Run `phala deploy --cvm-id ... --prepare-only` again with the same compose file. This produces a fresh 14-day token pointing at the same compose hash. 5. Immediately commit with the fresh token and the real transaction hash. The second prepare is cheap (no on-chain writes) and exists solely to give you a current token. Keep the compose file identical across both prepare calls — any edit between them changes the hash and invalidates the on-chain approval you already waited days for. ## CLI: Prepare Phase ### Compose updates For a normal compose file update: ```bash theme={"system"} phala deploy --cvm-id \ --prepare-only \ -c new-compose.yml \ -e .env ``` The `-e .env` is optional; include it if you are changing environment variables alongside the compose file. Environment variables are encrypted with the app's public key and bound to the commit token — they land atomically when Phase 3 runs. Human-readable output (exactly what the CLI prints with `--no-json` or when running interactively): ``` CVM update prepared successfully (pending on-chain approval). Compose Hash: 0xff22c67f1c8d5e4a9b3d2c1e0f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9 App ID: 0x09cef33ca9c6e4f2b1d5a7c3e8f0b2a4d6e8f1c3 Device ID: 0x7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4e5f6a7b8 Chain: Base (ID: 8453) Contract: https://basescan.org/address/0x09cef33ca9c6e4f2b1d5a7c3e8f0b2a4d6e8f1c3 Commit Token: a5732e36-8f4b-4c1d-9e7a-2b5c8d9e0f1a Commit URL: https://cloud.phala.com/my-team/cvms/01234567-89ab-cdef-0123-456789abcdef/confirm-update?token=a5732e36-8f4b-4c1d-9e7a-2b5c8d9e0f1a&compose_hash=ff22c67f1c8d5e4a9b3d2c1e0f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9 API Commit URL: https://cloud-api.phala.com/api/v1/cvms/01234567-89ab-cdef-0123-456789abcdef/commit-update?token=a5732e36-8f4b-4c1d-9e7a-2b5c8d9e0f1a (POST) On-chain Status: Compose Hash: NOT registered Device ID: registered To complete the update after on-chain approval: phala deploy --cvm-id 01234567-89ab-cdef-0123-456789abcdef \ --commit \ --token a5732e36-8f4b-4c1d-9e7a-2b5c8d9e0f1a \ --compose-hash 0xff22c67f1c8d5e4a9b3d2c1e0f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9 \ --transaction-hash ``` Every field carries information the approver or an automation needs: * **Compose Hash** — the 32-byte keccak256 hash of your compose document, prefixed with `0x`. This is the exact `bytes32` argument to pass to `addComposeHash` on-chain. It also serves as the idempotency key for the update. * **App ID** — the DstackApp contract address (same as the app ID with `0x` prefix). This is the `to` address for the on-chain transaction. * **Device ID** — the device identifier for the node currently hosting this CVM. It is shown so you can confirm whether the device is already allowed. If you see `Device ID: NOT registered`, you also need to call `addDevice(bytes32)` as part of the multisig flow (see section below). * **Chain** — human-readable chain name and EIP-155 chain ID. Double-check that your Safe and your CLI are pointed at the same chain. * **Contract** — a block explorer link to the DstackApp contract. Use this to verify `owner()` before approving, and to review the on-chain state after. * **Commit Token** — the UUID that unlocks Phase 3. It expires 14 days from prepare time. Treat it like a one-time API key. * **Commit URL** — the dashboard Confirm Update page. Share this with approvers who want a guided UI for Phase 3. * **API Commit URL** — the raw `POST` endpoint for Phase 3. Use this from CI or scripts. * **On-chain Status** — a live snapshot read from the chain at prepare time. It tells you whether `addComposeHash` and `addDevice` are strictly required, or whether the state is already good (for example, if the compose hash is already registered from a previous aborted flow). The same data is available as JSON for automation: ```bash theme={"system"} phala deploy --cvm-id \ --prepare-only \ -c new-compose.yml \ --json ``` ```json theme={"system"} { "success": true, "prepare_only": true, "compose_hash": "0xff22c67f1c8d5e4a9b3d2c1e0f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9", "app_id": "0x09cef33ca9c6e4f2b1d5a7c3e8f0b2a4d6e8f1c3", "device_id": "0x7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4e5f6a7b8", "kms_info": { "chain_id": 8453, "kms_contract_address": "0x2f83172A49584C017F2B256F0FB2Dca14126Ba9C" }, "chain_id": 8453, "contract_explorer_url": "https://basescan.org/address/0x09cef33ca9c6e4f2b1d5a7c3e8f0b2a4d6e8f1c3", "onchain_status": { "compose_hash_allowed": false, "device_id_allowed": true, "is_allowed": false }, "commit_token": "a5732e36-8f4b-4c1d-9e7a-2b5c8d9e0f1a", "commit_url": "https://cloud.phala.com/my-team/cvms/01234567-89ab-cdef-0123-456789abcdef/confirm-update?token=a5732e36-8f4b-4c1d-9e7a-2b5c8d9e0f1a&compose_hash=ff22c67f1c8d5e4a9b3d2c1e0f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9", "api_commit_url": "https://cloud-api.phala.com/api/v1/cvms/01234567-89ab-cdef-0123-456789abcdef/commit-update?token=a5732e36-8f4b-4c1d-9e7a-2b5c8d9e0f1a" } ``` ### Replicating to a new node Replication to an additional node (for HA or migration) uses the same prepare mechanism: ```bash theme={"system"} phala cvms replicate \ --node \ --prepare-only ``` The replicate prepare path prints the same fields as the deploy prepare path. If the target node's `device_id` is not already on the allowlist, the on-chain status will show `Device ID: NOT registered` — in that case you need to run two separate on-chain actions as part of Phase 2: `addDevice(bytes32)` for the new device, then `addComposeHash(bytes32)` if the compose hash is also missing. Both can be batched into a single Safe transaction (see the Transaction Builder section below). See [Device Management](/phala-cloud/key-management/device-management) for how to look up `device_id` for a given node. ### What is on-chain Status telling me? `onchain_status` reflects the actual DstackApp state at prepare time. There are three useful combinations: * `compose_hash_allowed: false` and `device_id_allowed: true` — standard case for a compose file change on an existing node. Approve `addComposeHash` only. * `compose_hash_allowed: false` and `device_id_allowed: false` — new node and new compose hash. Approve `addDevice` and `addComposeHash`, ideally in a single Safe batch. * `compose_hash_allowed: true` — the compose hash was already registered, perhaps by a previous aborted prepare. You can skip Phase 2 entirely and go straight to Phase 3 with `--transaction-hash already-registered`. ## Approve Phase — Three Paths The approve phase is off the Phala Cloud backend. Whoever holds signing power on the owner contract runs an on-chain transaction that calls `addComposeHash(bytes32)` (and possibly `addDevice(bytes32)`) on the DstackApp contract. How they do it depends on your governance setup. ### Path A: Dashboard Confirm Update page The simplest path is for a single human approver who personally holds a signing wallet. Open the `Commit URL` from the prepare output. It takes you to the Confirm Update page, which shows: * Workspace name and slug * CVM name and App ID * The compose hash to register (with a copy button) * Who initiated the prepare and when * An input for the transaction hash * A large **Commit Update** button ![Confirm Update page with compose hash and transaction hash input](https://mintcdn.com/phalanetwork-1606097b/-WnKlfXNtR8R6Xel/images/cloud/app-overview-pending-update.jpg?fit=max\&auto=format\&n=-WnKlfXNtR8R6Xel\&q=85\&s=3c93b9ec6b75ad849ca9a05a89f0df05) The page does not sign the on-chain transaction for you. You still need to run `addComposeHash` from your wallet (via Basescan, Etherscan, Safe, or any other tool), then paste the resulting transaction hash into the form. Once you click **Commit Update**, the dashboard calls the same `POST /cvms/{id}/commit-update` endpoint that the CLI calls in Phase 3, and the backend verifies the transaction receipt before rolling the update forward. If the compose hash is already registered on-chain (see `onchain_status.compose_hash_allowed: true`), leave the transaction hash field empty. The backend will accept `already-registered` as a sentinel and only re-verify state. ### Path B: Gnosis Safe Transaction Builder For a Safe-owned app, most teams use the official Transaction Builder app. 1. Open your Safe at [app.safe.global](https://app.safe.global). Make sure the network matches the chain from the prepare output (Base or Ethereum). 2. Go to **Apps** and open **Transaction Builder**. 3. Paste the DstackApp contract address (the **App ID** field from prepare output) into the address field. The Transaction Builder will fetch the ABI from Basescan/Etherscan if the contract is verified. If auto-fetch fails, paste the ABI for `addComposeHash(bytes32)` manually — you can copy it from any existing DstackApp contract page on the explorer. 4. Select `addComposeHash` from the method dropdown. 5. Enter the compose hash from the prepare output as the `bytes32` parameter. Triple-check the value — it is the single most important field and it is irreversible once executed. A mistyped hash means you authorized the wrong code to run. 6. Click **Add Transaction**. If you also need to allow a new device, click **Add Transaction** again, select `addDevice`, and enter the `device_id` from the prepare output. Both actions end up in the same Safe batch. 7. Click **Create Batch**, then **Send Batch**. This creates a Safe transaction pending signatures. 8. Have the other signers approve through Safe's Transactions tab until the threshold is met. 9. Execute the transaction. Copy the resulting transaction hash — you will need it for Phase 3. > [!TIP] > > The Transaction Builder does not verify that the compose hash matches anything meaningful. You are trusting the prepare output. Before signing, cross-check the compose hash against the git commit or release artifact that the hash was computed from. The backend re-hashes the compose document at commit time, so a mismatch between the file you prepared and the file currently saved on Phala Cloud will surface as `HASH_INVALID_OR_EXPIRED`. ### Path C: Custom governance contract (Timelock, DAO) If your owner is a Timelock or a DAO voting contract, you typically need to encode a generic proposal targeting the DstackApp contract. Two pieces of information are required: * **Target** — the DstackApp contract address (the `app_id` field from prepare output, with `0x` prefix). * **Calldata** — the ABI-encoded call to `addComposeHash(bytes32)` with the compose hash as the argument. > [!WARNING] > > The `onchain_action.calldata` field in the webhook payload (see the next section) contains only the raw compose hash, **not** the fully ABI-encoded calldata that most governance contracts expect. You must encode the function call yourself before submitting to a Timelock or DAO proposer. The field name is kept generic because different governance frameworks expect different input shapes. To encode the calldata, use any Ethereum tooling. With `cast` (Foundry): ```bash theme={"system"} cast calldata "addComposeHash(bytes32)" \ 0xff22c67f1c8d5e4a9b3d2c1e0f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9 ``` Output: ``` 0x... (4-byte selector) || 32-byte compose hash ``` Or in TypeScript with `viem`: ```typescript theme={"system"} import { encodeFunctionData } from "viem"; const calldata = encodeFunctionData({ abi: [ { type: "function", name: "addComposeHash", inputs: [{ name: "composeHash", type: "bytes32" }], stateMutability: "nonpayable", }, ], functionName: "addComposeHash", args: [ "0xff22c67f1c8d5e4a9b3d2c1e0f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9", ], }); ``` Feed the encoded bytes into your governance contract's proposal method alongside the DstackApp address. Once the proposal passes the Timelock delay or DAO vote, execute it. The resulting transaction hash goes into Phase 3. Before submitting, decode the calldata one more time to sanity-check: ```bash theme={"system"} cast calldata-decode "addComposeHash(bytes32)" ``` It should echo back the same compose hash you started with. ## CLI: Commit Phase Once the on-chain transaction is mined, tell Phala Cloud to roll the CVM update forward. ```bash theme={"system"} phala deploy --cvm-id \ --commit \ --token a5732e36-8f4b-4c1d-9e7a-2b5c8d9e0f1a \ --compose-hash 0xff22c67f1c8d5e4a9b3d2c1e0f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9 \ --transaction-hash 0x1234abcd5678ef90... ``` You can also POST directly to `api_commit_url`: ```bash theme={"system"} curl -X POST "https://cloud-api.phala.com/api/v1/cvms//commit-update" \ -H "Content-Type: application/json" \ -d '{ "token": "a5732e36-8f4b-4c1d-9e7a-2b5c8d9e0f1a", "compose_hash": "0xff22c67f1c8d5e4a9b3d2c1e0f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9", "transaction_hash": "0x1234abcd5678ef90..." }' ``` The commit endpoint is token-based and does not require an API key. Only someone holding the commit token can finalize the update. This is intentional — it lets you hand off Phase 3 to a CI job or an automation bot without provisioning a full API token. When the backend receives the commit request it: 1. Looks up the token and checks that it has not expired or been superseded. 2. Verifies that the compose hash in the request matches the compose hash bound to the token at prepare time. If they differ, it rejects with `HASH_INVALID_OR_EXPIRED` — usually because the compose file was edited between prepare and commit. 3. Reads `allowedComposeHashes` from the DstackApp contract. If the compose hash is not present on-chain, it rejects with `HASH_REGISTRATION_REQUIRED`. 4. If a transaction hash other than `already-registered` was provided, it fetches the receipt and checks that the transaction interacted with the DstackApp contract and produced the expected state change. Mismatches surface as `TX_VERIFICATION_FAILED`. 5. On success, proceeds with the regular update workflow: saves the new compose file, re-encrypts environment variables, and triggers the CVM restart. Successful commit output: ```json theme={"system"} { "success": true, "vm_uuid": "01234567-89ab-cdef-0123-456789abcdef", "correlation_id": "corr_01HXYZ...", "status": "pending" } ``` `correlation_id` lets you trace the update in the workspace audit log. `status` reflects the CVM state machine at the moment of response — follow up with `phala cvms get ` or the dashboard to watch the actual update complete. ## Automating Approvals with Webhooks The whole flow above assumes a human notices when a prepare happens. For production teams, that is too fragile. Phala Cloud emits a `cvm.update.pending_approval` webhook every time a prepare-only update is created, which lets you wire prepare into Slack bots, approval dashboards, or automated Safe proposers. ### Subscribing In the dashboard, go to **Workspace → Webhooks** and click **Add Webhook**. Enter: * **Endpoint URL** — an HTTPS URL you control. Plain `http://` is rejected, and private IPs, cloud metadata endpoints, `localhost`, and `.local` hostnames are all blocked at delivery time by the URL validator. * **Events** — check **Update Pending Approval** (event type `cvm.update.pending_approval`). * **Name** (optional) — a label for your own bookkeeping. When you save, the dashboard shows the signing secret exactly once in a dialog. The secret is prefixed with `whsec_` followed by 32 base64url bytes. Copy it into your secrets manager right away. If you lose it, you can reveal it again or rotate it, but both actions require a second-factor challenge — the reveal and rotate endpoints are gated by 2FA step-up verification. ![Webhook list with URL, masked secret, events, and stats columns](https://mintcdn.com/phalanetwork-1606097b/-WnKlfXNtR8R6Xel/images/cloud/webhooks-list.jpg?fit=max\&auto=format\&n=-WnKlfXNtR8R6Xel\&q=85\&s=16923d11e2e0782e600a625c1cb69f36) ![Webhook Created dialog showing the signing secret](https://mintcdn.com/phalanetwork-1606097b/-WnKlfXNtR8R6Xel/images/cloud/webhook-created-signing-secret.jpg?fit=max\&auto=format\&n=-WnKlfXNtR8R6Xel\&q=85\&s=5bc05a9e1ad488172617ecff015fe7f5) The same operations are available via the API: ```bash theme={"system"} curl -X POST "https://cloud-api.phala.com/api/v1/workspace/webhooks" \ -H "Authorization: Bearer $PHALA_API_KEY" \ -H "X-Workspace-Id: my-team" \ -H "Content-Type: application/json" \ -d '{ "url": "https://bot.example.com/phala/webhook", "events": ["cvm.update.pending_approval"], "name": "Approval bot" }' ``` The response body includes the generated `secret` on create. Subsequent `GET /workspace/webhooks` and `GET /workspace/webhooks/{id}` responses return a masked version — you have to hit `POST /workspace/webhooks/{id}/reveal-secret` (2FA required) to see the full value again, or `POST /workspace/webhooks/{id}/rotate-secret` (also 2FA required) to generate a new one. ### Payload When a prepare-only update happens, Phala Cloud sends a JSON POST to your endpoint: ```json theme={"system"} { "id": "evt_0a1b2c3d4e5f6789", "event": "cvm.update.pending_approval", "version": "1", "created_at": "2026-04-10T12:34:56.789Z", "workspace": { "id": "my-team", "name": "My Team" }, "data": { "cvm_id": "01234567-89ab-cdef-0123-456789abcdef", "cvm_name": "payments-api", "compose_hash": "0xff22c67f1c8d5e4a9b3d2c1e0f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9", "app_id": "0x09cef33ca9c6e4f2b1d5a7c3e8f0b2a4d6e8f1c3", "device_id": "0x7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4e5f6a7b8", "kms": { "chain_id": 8453, "contract_address": "0x2f83172A49584C017F2B256F0FB2Dca14126Ba9C" }, "onchain_action": { "to": "0x09cef33ca9c6e4f2b1d5a7c3e8f0b2a4d6e8f1c3", "method": "addComposeHash(bytes32)", "calldata": "0xff22c67f1c8d5e4a9b3d2c1e0f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9" }, "commit_token": "a5732e36-8f4b-4c1d-9e7a-2b5c8d9e0f1a", "commit_url": "https://cloud.phala.com/my-team/cvms/01234567-89ab-cdef-0123-456789abcdef/confirm-update?token=a5732e36-8f4b-4c1d-9e7a-2b5c8d9e0f1a&compose_hash=ff22c67f1c8d5e4a9b3d2c1e0f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9", "api_commit_url": "https://cloud-api.phala.com/api/v1/cvms/01234567-89ab-cdef-0123-456789abcdef/commit-update?token=a5732e36-8f4b-4c1d-9e7a-2b5c8d9e0f1a", "expires_at": "2026-04-24T12:34:56.789Z", "initiated_by": { "user_id": "usr_01HXYZ", "username": "alice" } } } ``` Envelope fields (present on every webhook, not just this event): * `id` — unique event ID in the form `evt_<16 hex chars>`. Use this as an idempotency key on your side. * `event` — the event type. For this flow it is always `cvm.update.pending_approval`. * `version` — schema version, currently `"1"`. * `created_at` — ISO 8601 UTC timestamp of dispatch. * `workspace.id` — the workspace slug (not the numeric team ID). * `workspace.name` — human-readable workspace name. Event-specific `data` fields: * `cvm_id` — the CVM UUID that is being updated. * `cvm_name` — user-provided CVM name. * `compose_hash` — the 32-byte compose hash with `0x` prefix. This is the argument to `addComposeHash`. * `app_id` — the DstackApp contract address. Same value as `onchain_action.to`. * `device_id` — the node device ID currently hosting the CVM. * `kms.chain_id` — EIP-155 chain ID (1 for Ethereum, 8453 for Base). * `kms.contract_address` — the KmsContract address (the Phala-operated KMS root, not your DstackApp). * `onchain_action.to` — target address for the on-chain transaction (your DstackApp address). * `onchain_action.method` — the method signature, currently always `addComposeHash(bytes32)`. * `onchain_action.calldata` — the raw compose hash. Note again: this is **not** ABI-encoded calldata. Encode it yourself if your governance contract needs a full function call payload. * `commit_token` — the commit token. Combined with `api_commit_url`, enough to complete Phase 3. * `commit_url` — the dashboard Confirm Update page. * `api_commit_url` — the raw `POST` endpoint. * `expires_at` — ISO 8601 timestamp, exactly 14 days after dispatch. Your automation should refuse to act on expired tokens. * `initiated_by.user_id` — hashed user ID of the person who ran `--prepare-only`. * `initiated_by.username` — their username. ### Headers Every webhook delivery carries these HTTP headers: * `Content-Type: application/json` * `User-Agent: PhalaCloud-Webhook/1.0` * `X-Webhook-Id` — same as `payload.id`. * `X-Webhook-Event` — same as `payload.event`. * `X-Webhook-Timestamp` — Unix epoch seconds as a decimal string. This is the timestamp used in the HMAC message. * `X-Webhook-Signature` — the HMAC-SHA256 signature, in the form `sha256=<64 hex chars>`. ### HMAC verification The signature is computed from the raw request body (as sent on the wire) and the timestamp header. The exact formula: ``` message = f"{X-Webhook-Timestamp}.{raw_body_utf8}" signature = hex(HMAC_SHA256(key=secret, msg=message)) header = f"sha256={signature}" ``` Two things matter for correctness: 1. The body must be the **raw** POST body, not a re-serialized version. If your framework parses JSON and then re-encodes it, key order or whitespace may differ and the HMAC will not match. Grab the raw bytes before parsing. 2. Use a **constant-time** comparison when matching the signature. A naive `==` on strings leaks timing information. #### Python (FastAPI) ```python theme={"system"} import hashlib import hmac import logging import os from fastapi import FastAPI, Header, HTTPException, Request app = FastAPI() logger = logging.getLogger("phala-webhook") WEBHOOK_SECRET = os.environ["PHALA_WEBHOOK_SECRET"] # whsec_... def verify_signature( secret: str, timestamp: str, raw_body: bytes, signature_header: str ) -> bool: if not signature_header.startswith("sha256="): return False provided = signature_header.removeprefix("sha256=") message = f"{timestamp}.{raw_body.decode('utf-8')}".encode("utf-8") expected = hmac.new( secret.encode("utf-8"), message, hashlib.sha256 ).hexdigest() return hmac.compare_digest(expected, provided) @app.post("/phala/webhook") async def receive_webhook( request: Request, x_webhook_timestamp: str = Header(...), x_webhook_signature: str = Header(...), x_webhook_event: str = Header(...), ): raw_body = await request.body() if not verify_signature( WEBHOOK_SECRET, x_webhook_timestamp, raw_body, x_webhook_signature ): raise HTTPException(status_code=401, detail="Invalid signature") if x_webhook_event != "cvm.update.pending_approval": # Ignore other events for this endpoint return {"ok": True} payload = await request.json() data = payload["data"] logger.info( "Pending approval: cvm=%s hash=%s commit_url=%s expires_at=%s", data["cvm_id"], data["compose_hash"], data["commit_url"], data["expires_at"], ) # Hand off to your approval pipeline here (Slack, Safe API, etc.) return {"ok": True} ``` #### Node.js (Express) ```javascript theme={"system"} import crypto from "node:crypto"; import express from "express"; const app = express(); const WEBHOOK_SECRET = process.env.PHALA_WEBHOOK_SECRET; // whsec_... // IMPORTANT: capture the raw body before JSON parsing app.use("/phala/webhook", express.raw({ type: "application/json" })); function verifySignature(secret, timestamp, rawBody, signatureHeader) { if (!signatureHeader?.startsWith("sha256=")) return false; const provided = signatureHeader.slice("sha256=".length); const message = `${timestamp}.${rawBody.toString("utf8")}`; const expected = crypto .createHmac("sha256", secret) .update(message, "utf8") .digest("hex"); const providedBuf = Buffer.from(provided, "hex"); const expectedBuf = Buffer.from(expected, "hex"); if (providedBuf.length !== expectedBuf.length) return false; return crypto.timingSafeEqual(providedBuf, expectedBuf); } app.post("/phala/webhook", (req, res) => { const timestamp = req.header("x-webhook-timestamp"); const signature = req.header("x-webhook-signature"); const event = req.header("x-webhook-event"); if (!verifySignature(WEBHOOK_SECRET, timestamp, req.body, signature)) { return res.status(401).json({ error: "Invalid signature" }); } const payload = JSON.parse(req.body.toString("utf8")); if (event !== "cvm.update.pending_approval") { return res.json({ ok: true }); } const { cvm_id, compose_hash, commit_url, expires_at } = payload.data; console.log("Pending approval", { cvm_id, compose_hash, commit_url, expires_at, }); // Hand off to your approval pipeline here return res.json({ ok: true }); }); app.listen(3000); ``` ### Delivery semantics * **Success** — any HTTP 2xx response is treated as success. The delivery is recorded and no further attempts are made. * **Failure** — any non-2xx response, connection error, or timeout is treated as a failure and retried. * **Timeout** — 10 seconds per delivery attempt. Design your handler to return quickly (queue the work, return 200 immediately). * **Retries** — up to 3 additional attempts on failure, with delays of 1 minute, 10 minutes, and 1 hour. After the final attempt the delivery is logged as `failed` and no further retries happen. * **Idempotency** — retries reuse the same `event_id`. Use it as a dedup key on your side so retried deliveries do not double-approve. * **URL validation at delivery time** — every attempt re-validates the URL. HTTPS is mandatory; private IPs, link-local addresses, loopback, `169.254.169.254` (cloud metadata), `localhost`, and `.local` hostnames are all rejected. This guards against DNS rebinding attacks — a hostname that passes validation at save time but later resolves to an internal IP will be blocked on delivery. ### Viewing deliveries The dashboard has a per-webhook deliveries page at **Workspace → Webhooks → (view icon)** that shows the last 50 attempts: status, attempt count, response code, latency, and any error message. From the same page you can resend a failed delivery — this generates a new `event_id` linked to the original via `original_event_id`, so your handler can dedupe either way. ![Webhook deliveries table with status badges, latency, and resend button](https://mintcdn.com/phalanetwork-1606097b/-WnKlfXNtR8R6Xel/images/cloud/webhook-deliveries.jpg?fit=max\&auto=format\&n=-WnKlfXNtR8R6Xel\&q=85\&s=5e76cc327a1cc462413c3142581c56fd) The same data is available programmatically: ```bash theme={"system"} curl "https://cloud-api.phala.com/api/v1/workspace/webhooks//deliveries?limit=50" \ -H "Authorization: Bearer $PHALA_API_KEY" \ -H "X-Workspace-Id: my-team" ``` And aggregate stats: ```bash theme={"system"} curl "https://cloud-api.phala.com/api/v1/workspace/webhooks//stats" \ -H "Authorization: Bearer $PHALA_API_KEY" \ -H "X-Workspace-Id: my-team" ``` ### Automation patterns Once you have a verified receiver, the question is what to do with the event. A few common shapes: * **Slack bot approval** — post a message to a private channel with the CVM name, compose hash, and a link to the Confirm Update page. Require a specific reviewer to click an approval button, then call `api_commit_url` from the bot after the on-chain transaction is mined. * **Auto-propose to Safe** — use the [Safe API Kit](https://github.com/safe-global/safe-core-sdk) to create a pending Safe transaction calling `addComposeHash(bytes32)` the moment a webhook fires. Signers approve in the Safe UI. A second script watches the Safe for executed transactions and calls the commit endpoint when the transaction lands. * **CI/CD approval queue** — store the webhook payload in a queue table (Postgres, Redis, S3). Your release pipeline reads the queue, assigns a reviewer, and eventually commits through a service account. `expires_at` gates the queue: drop entries after 14 days. * **Timelock relay** — decode the webhook into a Timelock proposal, submit, wait for the delay to elapse, execute, and commit. This is the fully on-chain DAO shape. ## Error Modes and Troubleshooting ### Compose hash drift between prepare and commit Symptom: Phase 3 fails with `HASH_INVALID_OR_EXPIRED` even though the on-chain transaction was accepted. Cause: someone edited the compose file between prepare and commit, so the hash you registered on-chain no longer matches the compose currently saved for this CVM. The backend re-hashes the compose document at commit time and refuses to roll forward if the hashes disagree. Fix: rerun `phala deploy --cvm-id ... --prepare-only -c new-compose.yml` with the final compose file, repeat Phase 2 with the new hash, and commit again. The old on-chain `addComposeHash` is harmless — it stays in the allowlist but is never used. ### Expired commit token Symptom: Phase 3 fails with `Failed to commit CVM update: ... expired ...` and the CLI suggests running `--prepare-only` again. Cause: either the 14-day TTL elapsed, or a newer prepare for the same CVM invalidated this token. Fix: rerun prepare. If your team is hitting the 14-day window regularly, shorten your review cycle or switch to webhook-driven automation. If a second operator also ran prepare, coordinate and pick which token to use — only the latest one is valid. ### Owner mismatch (direct EOA update after transferring to Safe) Symptom: `phala deploy --cvm-id ... --private-key ... -c new-compose.yml` fails inside the `addComposeHash` or `addDevice` step with an EVM revert about ownership. Cause: you transferred ownership to a Safe (or any other contract) and then tried to update using an EOA. The EOA no longer holds the owner role, so the on-chain write reverts. Fix: check `owner()` on Basescan or Etherscan. If it returns a Safe address, use the prepare and commit flow. If it returns an EOA different from the one you signed with, you transferred to the wrong account — recover by signing with the correct EOA and calling `transferOwnership` back, or by using the current owner to push the update. ### Transaction reverted on-chain Symptom: Your Safe or governance contract executes the proposal but the `addComposeHash` call reverts. Common causes: * The Safe is on a different chain than the DstackApp contract. Double-check the network selector before signing. * The calldata was hand-built with the wrong function selector or the wrong argument type. Use `cast calldata-decode` to sanity-check before proposing. * The `owner()` of the DstackApp contract is still the EOA, not the Safe. Verify ownership was transferred before preparing. * Gas ran out on a Timelock relay. Resubmit with a higher gas limit. ### Error code reference The four error codes you will see most often in this flow all live under Module 01 in the [Error Codes reference](/phala-cloud/references/error-codes): `ERR-01-005` (hash registration required), `ERR-01-006` (hash invalid or expired), `ERR-01-007` (transaction verification failed), and `ERR-01-008` (hash not allowed). The reference page has the full list with HTTP status codes and exception class names; use it as the source of truth. A quick map of which phase you most commonly hit each one in: * **Phase 3 commit fails with `ERR-01-005`** — Phase 2 has not actually landed on-chain yet, or it landed on a different contract. Check `allowedComposeHashes` on the DstackApp you prepared against. * **Phase 3 commit fails with `ERR-01-006`** — the commit token is expired or superseded, or the compose file on the backend no longer matches what the token was bound to. Re-prepare. * **Phase 3 commit fails with `ERR-01-007`** — the transaction hash you passed does not verify against the expected state change. Double-check you pasted the correct hash and that the transaction is mined. * **Phase 3 commit fails with `ERR-01-008`** — the compose hash is simply not on the allowlist. Same remediation as `ERR-01-005`; most often it means the Safe batch executed but targeted the wrong address or wrong method selector. When the CLI hits `ERR-01-006`, it explicitly hints at re-running `--prepare-only` to get a new token. When it hits `ERR-01-007`, it prints the transaction hash so you can look it up on the explorer. ## Device Operations Without CLI Prepare/Commit > [!WARNING] > > At the time of writing, the CLI `phala allow-devices` subcommands (`list`, `add`, `remove`, `allow-any`, `disallow-any`, `toggle-allow-any`) all require `--private-key` and do not support `--prepare-only`. If your DstackApp owner is a Safe, Timelock, or DAO, the CLI cannot drive device operations for you. You must use the wallet UI path. The workaround is straightforward: use the same Safe Transaction Builder or governance proposal path from the approve phase, just targeting a different method on the same DstackApp contract. 1. Look up the `device_id` you want to add or remove. For a new node, this is the `device_id` shown in the node picker when provisioning, and also in the prepare output when you run `phala cvms replicate ... --prepare-only`. See [Device Management](/phala-cloud/key-management/device-management) for the lookup paths. 2. Open your DstackApp contract on Basescan or Etherscan, or open Safe Transaction Builder and paste the contract address. 3. Call the relevant method: * `addDevice(bytes32 deviceId)` — allow a specific device to host the app. * `removeDevice(bytes32 deviceId)` — revoke a previously allowed device. * `setAllowAnyDevice(bool allow)` — toggle the global bypass. When `true`, any node in the workspace can boot the CVM without the per-device check. 4. Collect Safe signatures and execute, or push through the Timelock delay / DAO vote. 5. There is no commit phase for device operations. The next time the CVM is provisioned on a new node, KMS reads the allowlist straight from the contract. See [Device Management](/phala-cloud/key-management/device-management) for the full conceptual model, how `device_id` is derived from TDX PPID, the one-node-to-one-device rule, and HA recommendations for `allowAnyDevice`. ## Next Steps * [Deploying with Onchain KMS](/phala-cloud/key-management/deploying-with-onchain-kms) — the first-time deployment walkthrough. * [Updating with Onchain KMS](/phala-cloud/key-management/updating-with-onchain-kms) — the direct EOA update path when ownership has not been transferred to a multisig yet. * [Understanding Onchain KMS](/phala-cloud/key-management/understanding-onchain-kms) — the conceptual model (contracts, boot-time flow, compose hash). * [Device Management](/phala-cloud/key-management/device-management) — device allowlisting, PPID, HA, and the `allow-devices` CLI reference. * [Cloud vs Onchain KMS](/phala-cloud/key-management/cloud-vs-onchain-kms) — conceptual comparison and governance trade-offs. # Understanding Onchain KMS Source: https://docs.phala.com/phala-cloud/key-management/understanding-onchain-kms The mental model behind Onchain KMS — which contracts exist, who signs what, and how the KMS verifies your CVM at boot time. Onchain KMS puts a smart contract in the critical path between your CVM and the keys it needs to run. The contract decides which code is allowed, which hardware is allowed, and who can change either list. Phala Cloud can read the contract, but it cannot write to it — every authorization change originates from your wallet. This page is the conceptual reference. Read it once before your first deploy so the rest of the Onchain KMS docs click into place. If you already have the mental model and want to ship, go straight to [Deploying with Onchain KMS](/phala-cloud/key-management/deploying-with-onchain-kms). For the higher-level "should I use Cloud KMS or Onchain KMS?" comparison, see [Cloud vs Onchain KMS](/phala-cloud/key-management/cloud-vs-onchain-kms). For the underlying protocol and threat model, see [What is KMS](/phala-cloud/key-management/key-management-protocol). ## Two Contracts Two contracts cooperate to authorize your CVM. **KmsAuth** is a shared contract that Phala operates, one per chain. There is a single KmsAuth deployment on Ethereum and a separate one on Base. It knows the identity of the KMS nodes running inside TEE, keeps a list of approved dstack OS images, and exposes a factory method that mints a new per-application contract. You interact with KmsAuth exactly once per application, when you deploy a new app. **DstackApp** is a per-application contract that you deploy through the KmsAuth factory. Each CVM is bound to one DstackApp. It stores three things that matter for the rest of these docs: * `owner` — the address that can add or remove allowlisted code and devices. Initially this is the wallet that deployed the DstackApp. You can transfer it to a Safe, a timelock, or any contract. * `allowedComposeHashes` — the set of compose hashes that are allowed to run under this application identity. Detailed in [What the compose hash is](#what-the-compose-hash-is) below. * `allowedDeviceIds` — the set of TDX device identities that are allowed to host this application. Detailed in [Device Management](/phala-cloud/key-management/device-management). The critical property is that **Phala Cloud's backend does not send any transaction on your behalf.** Deploying the DstackApp, adding a compose hash, and adding a device are all writes initiated by either the CLI (which signs with `--private-key`) or a browser wallet connected through the dashboard. The backend only reads the chain afterwards to verify that the state it expects is actually there. Contract addresses for each chain are listed under the `Ethereum` and `Base` accordions in [Cloud vs Onchain KMS](/phala-cloud/key-management/cloud-vs-onchain-kms#ethereum-vs-base). ## Who Writes What, and When It helps to keep a mental table of who signs which transaction: | Operation | Contract | Who signs | | - | - | - | | First deploy (creates DstackApp + registers first compose hash + first device) | `KmsAuth.deployAndRegisterApp` | Your wallet (CLI `--private-key` or browser wallet) | | Add a new compose hash (update the running code) | `DstackApp.addComposeHash` | The DstackApp owner | | Add a new device (allow a new node to host the CVM) | `DstackApp.addDevice` | The DstackApp owner | | Transfer ownership to a Safe / timelock / DAO | `DstackApp.transferOwnership` | The current DstackApp owner | Phala Cloud's backend appears nowhere in that table. It offers to compute `compose_hash` and `device_id` for you during provisioning, but neither value is a secret — both are deterministic functions of inputs you control, so you can compute and verify them yourself if you want. The backend never writes to the chain. ## What the Compose Hash Is The `compose_hash` is the SHA-256 of a canonicalized JSON document called **`app-compose.json`**, not a hash of `docker-compose.yml` by itself. `app-compose.json` is the dstack manifest for your application and includes all of the following fields — any one of which, if changed, changes the hash: * `manifest_version` * `name` * `runner` — `docker-compose`, `bash`, etc. * `docker_compose_file` — the full compose file contents embedded as a string (for `runner: docker-compose`) * `bash_script` — the script contents (for `runner: bash`) * `pre_launch_script` — optional * `kms_enabled`, `gateway_enabled`, `local_key_provider_enabled`, `key_provider`, `key_provider_id` * `allowed_envs` — whitelist of environment variable names your workload may read * `public_logs`, `public_sysinfo`, `public_tcbinfo` * `no_instance_id`, `secure_time`, `storage_fs`, `swap_size` See the [`AppCompose` definition in dstack-types](https://github.com/Dstack-TEE/dstack/blob/next/dstack/dstack-types/src/lib.rs) for the authoritative list of fields. Canonicalization sorts the object keys alphabetically and serializes with a specific JSON variant so that the hash is deterministic regardless of which tool produced it. The CLI exports [`getComposeHash()`](https://github.com/Phala-Network/phala-cloud/blob/main/js/src/utils/get_compose_hash.ts) from `@phala/cloud` if you want to compute the hash in your own code and compare it against what the backend or the contract reports. Two consequences worth keeping in mind: * **Any change to `app-compose.json` — not just the compose file inside it, but any field — produces a new compose hash.** Toggling `public_logs`, adding an entry to `allowed_envs`, or bumping the `runner` all change the hash. Each change requires a new on-chain `addComposeHash` call before the CVM can start. * **Bumping a Docker image tag inside `docker_compose_file` changes the embedded string, which changes the compose hash.** You cannot sneak a new image under an old allowlisted hash. ## What the Device ID Is The `device_id` is a derivation of the TDX platform identifier (PPID) for the node where the CVM is scheduled. If the scheduler places your CVM on a new node, the device ID will be different, and the DstackApp has to allowlist it before the KMS will release keys on that node. [Device Management](/phala-cloud/key-management/device-management) covers the derivation, drift, and recovery scenarios in detail. For the rest of these onchain KMS guides, you only need to know that the CLI and dashboard add the current node's device ID to the allowlist for you during the first deploy. ## Boot-Time Verification Flow When a CVM starts and asks the KMS for keys, the sequence is: ``` CVM boots inside TDX | v Worker generates a TDX quote bound to the running compose hash + device ID | v KMS verifies the TDX quote against Intel's attestation roots | v KMS reads the DstackApp contract: - DstackApp.allowedComposeHashes(composeHash) == true ? - DstackApp.allowedDeviceIds(deviceId) == true (or DstackApp.allowAnyDevice() == true) | v Both checks pass | v KMS releases derived application keys over an attested channel ``` Every gate in this flow is either a hardware attestation check or a contract read. There is no Phala-operated allowlist in the middle. If the DstackApp rejects the CVM, the CVM never sees its keys, regardless of what the Phala Cloud backend believes. That is the chain of trust Onchain KMS buys you: the policy enforcement lives in code that thousands of blockchain nodes agree on, not on a server you have to trust. The implication for threat modeling is concrete. If Phala Cloud's backend were compromised and an attacker tried to push a new compose hash to your CVM without your consent, they could not do it — the KMS would check the DstackApp, see that the new hash is not in `allowedComposeHashes`, and refuse to release keys. The only way to get a new compose hash past the KMS is to convince your wallet (or your Safe, or your DAO) to sign `addComposeHash`. See [What is KMS](/phala-cloud/key-management/key-management-protocol) for the full threat model, including why "every operation involving key authorization changes must be initiated onchain" is a design principle. ## Next Steps * [Deploying with Onchain KMS](/phala-cloud/key-management/deploying-with-onchain-kms) — the first-deploy walkthrough via the dashboard or the CLI, with a worked example and verification steps. * [Updating with Onchain KMS](/phala-cloud/key-management/updating-with-onchain-kms) — how to roll a new compose file when the DstackApp owner is a plain wallet you control. * [Device Management](/phala-cloud/key-management/device-management) — PPID, device\_id derivation, HA allowlist patterns, and recovering from hardware drift. * [Multisig and Governance](/phala-cloud/key-management/multisig-governance) — the prepare-and-commit flow when the DstackApp owner is a Safe, timelock, or DAO contract. # Updating with Onchain KMS Source: https://docs.phala.com/phala-cloud/key-management/updating-with-onchain-kms Roll a new compose file to a running Onchain KMS CVM when the DstackApp owner is a plain wallet you control. This page covers the happy path for changing the compose file of a running Onchain KMS CVM when you still hold the DstackApp `owner` key as a plain EOA. The update is a single CLI command that handles the on-chain transactions for you. If the owner is a Safe, timelock, or DAO contract, the single-command path will not work — jump to [Multisig and Governance](/phala-cloud/key-management/multisig-governance). For the first-deploy flow and conceptual background, see [Deploying with Onchain KMS](/phala-cloud/key-management/deploying-with-onchain-kms) and [Understanding Onchain KMS](/phala-cloud/key-management/understanding-onchain-kms). ## What Triggers a New Compose Hash Any change that modifies `app-compose.json` produces a new `compose_hash` and requires a new on-chain `addComposeHash` call before the CVM can start running the new version. Common triggers: * Editing `docker-compose.yml` (bumping an image tag, adding a service, changing a port, whitespace changes — all count) * Changing `allowed_envs`, `public_logs`, `public_sysinfo`, or `public_tcbinfo` * Changing the `runner` or `pre_launch_script` Env var value changes alone (without touching `allowed_envs`) do not change the compose hash — they are encrypted and stored separately. But they still go through this same update command. See [What the compose hash is](/phala-cloud/key-management/understanding-onchain-kms#what-the-compose-hash-is) for the full list of fields that participate in hashing. ## The Single-Command Update When the DstackApp owner is still a plain wallet, updating is one command: ```bash theme={"system"} phala deploy \ --cvm-id \ -c new-compose.yml \ --private-key "$PRIVATE_KEY" ``` The `--cvm-id` flag accepts the CVM name (if unique in your workspace), the CVM UUID, or the app\_id — whichever is most convenient. The CLI detects that you passed `--cvm-id`, so it goes down the update path instead of the new-deployment path. Add `-e .env` or inline `-e KEY=VALUE` if you are changing environment variables alongside the compose file. Env var values are encrypted with the CVM's per-application env-encryption public key before leaving the CLI, same as on first deploy. Expect two wallet signatures in the worst case (one for `addDevice`, one for `addComposeHash`). In the common case where the scheduler kept your CVM on the same node, just one. ## What Happens Under the Hood The single command maps to the following sequence, in order: 1. **Reads the CVM metadata** from the backend, including the existing DstackApp contract address and the chain info. 2. **Patches the CVM** with the new compose file (and optional new env vars). The backend computes the new `compose_hash` and responds with `requiresOnChainHash: true`, along with the device ID of the current node. 3. **Checks on-chain prerequisites** by calling a read-only helper that asks the DstackApp contract whether the compose hash and device ID are already allowed. 4. **If the device is not yet allowed**, sends `addDevice(deviceId)` from `--private-key`. This happens automatically when the scheduler puts your CVM on a node it has not used before. 5. **Sends `addComposeHash(newHash)`** from `--private-key`. This is the main update transaction. It is idempotent at the contract level — the CLI sends it even if a state read says the hash is already allowed, so the backend can confirm against a real transaction hash. 6. **Confirms the patch** with the backend. The backend reads the receipt, checks the `ComposeHashAdded` event, re-reads the contract state, and rolls the CVM over to the new compose file. For reference when reading CI/CD logs, the flow maps to these backend and on-chain calls in order: 1. `GET /api/v1/cvms/` — read existing CVM metadata. 2. `PATCH /api/v1/cvms/` — send new compose file and encrypted env. When the new hash is not on the contract yet, the backend answers HTTP 465 with the new `compose_hash` and `device_id`. The CLI reports this as `requiresOnChainHash: true`. 3. Read-only chain call — `DstackApp.allowedDeviceIds(deviceId)` and `DstackApp.allowedComposeHashes(composeHash)` batched through a single RPC. 4. If needed, on-chain `DstackApp.addDevice(deviceId)` signed by `--private-key`. 5. On-chain `DstackApp.addComposeHash(composeHash)` signed by `--private-key`. The CLI waits for one confirmation. 6. `PATCH /api/v1/cvms/` again, with the `X-Compose-Hash` and `X-Transaction-Hash` headers — the backend verifies the receipt, re-reads the contract state, and rolls the CVM onto the new compose. ## What Changes and What Does Not When you run an update like this, the following stay the same: * **The DstackApp contract address.** It is still your `app_id`. Clients already talking to your service do not need to change anything. * **The CVM's `vm_uuid`.** The dashboard URL for the CVM does not change. * **The KMS-derived application keys.** Key derivation is tied to the `app_id`, not to the compose hash, so your persistent encrypted storage continues to decrypt correctly across updates. The following change: * **`compose_hash`** — a new hash is now in `allowedComposeHashes`. * **The container image and env var ciphertext.** The CLI re-encrypts new env values for the CVM's env-encryption key. * **The running processes inside the CVM.** The old compose is replaced by the new one. The old compose hash is not automatically removed from the allowlist. If you want to strictly block rollbacks, call `removeComposeHash(oldHash)` on the DstackApp from your wallet after the update is live. ## When This Simple Flow Does Not Work The single-command EOA path assumes `--private-key` can sign transactions that the DstackApp will accept. Two situations break that assumption: * **The owner is no longer an EOA.** If you transferred ownership to a Safe, a timelock, or any other contract, `addComposeHash` called from a bare wallet will revert on-chain. You need the prepare-and-commit flow so the transaction can be routed through your governance contract. See [Multisig and Governance](/phala-cloud/key-management/multisig-governance). * **You want to add or remove a node without changing the compose file.** Device allowlisting is a separate flow from compose-hash updates. See [Device Management](/phala-cloud/key-management/device-management). > [!WARNING] > > Do not transfer DstackApp ownership on a production CVM before reading [Multisig and Governance](/phala-cloud/key-management/multisig-governance). An irreversible mistake (pointing `owner` at an address you do not control) will leave you unable to update the compose hash, and the CVM will be frozen on its current version. ## Troubleshooting > [accordion] 'Transaction verification failed on backend' during the update > > The backend reads the receipt for the `addComposeHash` transaction and looks for the `ComposeHashAdded(bytes32)` event. This can fail briefly right after sending due to RPC propagation delay. The backend retries a few times with short gaps before giving up. If you consistently see this error: > > * Double-check that `--rpc-url` points to a healthy endpoint and is consistent between your signing RPC and the backend's read RPC. > * Verify the transaction actually succeeded on the block explorer — a reverted transaction will also produce this error. > * If everything looks fine on-chain but the backend still rejects, retry the update from the start. The CLI will re-send `addComposeHash`, which is idempotent at the contract level. > [accordion] 'Owner mismatch' or EVM revert on addComposeHash > > The wallet behind `--private-key` is not the current DstackApp owner. Open the DstackApp contract on Basescan or Etherscan and read `owner()`: > > * If `owner()` returns a different EOA, you are signing with the wrong key. Switch keys and retry. > * If `owner()` returns a contract address (Safe, Timelock, or other), the EOA path will never work. Switch to [Multisig and Governance](/phala-cloud/key-management/multisig-governance). > [accordion] Compose hash did not change when I expected it to > > You edited something that does not affect `app-compose.json`. Env var values, the `--private-key`, and the `--rpc-url` do not participate in the hash. Only the fields listed in [What the compose hash is](/phala-cloud/key-management/understanding-onchain-kms#what-the-compose-hash-is) do. > > Run the update anyway — if the CLI sees no hash change, it skips `addComposeHash` entirely and only pushes the new env var ciphertext through the patch endpoint. > [accordion] CVM stuck in 'updating' or 'pending' after confirm-patch succeeded > > Commit succeeded but the CVM restart is still rolling. Check the CVM logs with `phala logs ` or in the dashboard. The common slow paths are image pull time (large images on a fresh node) and the workload's own startup time. If the CVM keeps reverting to the old compose, open a support ticket with the correlation\_id from the CLI output. > [accordion] The CLI says 'Chain required for publicClient' or 'Chain required for walletClient' > > The CLI could not resolve the chain from the CVM metadata and no `--rpc-url` / `ETH_RPC_URL` fallback was provided. Set `--rpc-url` explicitly and retry, or set `ETH_RPC_URL` in your environment. You can verify with `echo $ETH_RPC_URL`. ### Error codes Errors from the confirm step map to structured error codes from Module 01 of the [Error Codes reference](/phala-cloud/references/error-codes). The four that matter for this flow are `ERR-01-005` through `ERR-01-008`. Each one tells you something specific: * **`ERR-01-005` (HTTP 465)** — the compose hash is not yet on `allowedComposeHashes`. Usually a transient state during the confirm step if you bailed out before `addComposeHash` landed; retry. * **`ERR-01-006` (HTTP 466)** — the provision cache for this compose hash has expired (14-day TTL) or the compose file changed since you started the update. Re-run the update command. * **`ERR-01-007` (HTTP 467)** — the transaction hash you (or the CLI) passed does not verify against the expected `addComposeHash` state change. Usually RPC propagation delay or a reverted tx; see the accordion above. * **`ERR-01-008` (HTTP 468)** — the compose hash is genuinely not in `allowedComposeHashes` from the contract's point of view. If this appears after `addComposeHash` supposedly succeeded, you probably called it on the wrong contract — check the DstackApp address on Basescan. [Multisig and Governance](/phala-cloud/key-management/multisig-governance#error-code-reference) discusses which phase of a multisig update each error typically appears in. ## Next Steps * [Multisig and Governance](/phala-cloud/key-management/multisig-governance) — the prepare-and-commit flow for compose updates when the DstackApp owner is a Safe, a timelock, a DAO, or any custom contract. Also covers webhook notifications for pending approvals. * [Device Management](/phala-cloud/key-management/device-management) — how to add and remove nodes from the allowlist without touching the compose file, and how to recover from hardware-driven `device_id` drift. * [Understanding Onchain KMS](/phala-cloud/key-management/understanding-onchain-kms) — the conceptual model behind compose hashes and the boot-time verification flow. * [Error Codes reference](/phala-cloud/references/error-codes) — the full catalog of `ERR-01-*` codes returned by the CVM API. # Datadog Integration Source: https://docs.phala.com/phala-cloud/monitoring/datadog-integration Integrate Datadog with your CVM for metrics, logs, and alerting using a zero-code-change sidecar approach. ## Overview Phala Cloud CVMs expose Prometheus-compatible `/metrics` endpoints from two sources: the built-in `dstack-guest-agent` (system-level metrics on port `8090`) and individual services like `dstack-kms` (business metrics on their own ports). You can integrate Datadog by adding a Datadog Agent container as a sidecar in your Docker Compose file. No application code changes are needed. This guide covers the guest-agent integration (CPU, memory, disk) first, then shows how to extend the pattern to any service that exposes Prometheus metrics, using `dstack-kms` as a concrete example. ## Prerequisites * A [Datadog](https://www.datadoghq.com/) account with an **API Key** * The Datadog **site** for your account (e.g., `us5.datadoghq.com`, `datadoghq.com`, `eu.datadoghq.com`) * Your CVM deployed with `--public-sysinfo` enabled (default: `true`) for guest-agent metrics * Each service must enable its own `/metrics` endpoint (e.g., `core.metrics.enabled = true` in KMS) > [!WARNING] > > Do not commit your Datadog API Key to version control. Use encrypted environment variables for production deployments. ## Step 1: Add Datadog Agent to Your Docker Compose Add a `datadog-agent` service to your `docker-compose.yml`: ```yaml theme={"system"} services: # Your application service my-app: image: my-app:latest ports: - "80:80" # Datadog Agent sidecar datadog-agent: image: registry.datadoghq.com/agent:7 network_mode: host environment: - DD_API_KEY= - DD_SITE= - DD_ENV=production - DD_TAGS=env:production,service:my-cvm - DD_LOGS_ENABLED=true - DD_LOGS_CONFIG_CONTAINER_COLLECT_ALL=true - DD_CONTAINER_EXCLUDE=name:datadog-agent - DD_AC_EXCLUDE=name:datadog-agent volumes: - /var/run/docker.sock:/var/run/docker.sock:ro - /var/lib/docker/containers:/var/lib/docker/containers:ro - /proc/:/host/proc/:ro - /sys/fs/cgroup/:/host/sys/fs/cgroup:ro - /var/volatile/dstack/persistent/dd-conf/openmetrics.d:/etc/datadog-agent/conf.d/openmetrics.d:ro pid: host healthcheck: test: ["CMD", "agent", "status"] interval: 30s timeout: 10s retries: 3 start_period: 30s ``` ### Understanding `network_mode: host` The `network_mode: host` setting puts the Datadog Agent directly on the CVM's network stack. This is required for scraping `dstack-guest-agent` because it runs as a systemd service on port `8090` — not inside Docker. Without host networking, the agent can't reach port `8090` at all. But this rule applies **only to systemd-level services.** If your scrape target is another Docker container (like KMS or any application you deployed in the compose file), you have two options: * **Option A: Bridge network.** Remove `network_mode: host` from the agent. Both containers share the default compose network, so the agent can reach your service via Docker DNS (`https://kms:8000/metrics`). This avoids the host's iptables NAT and keeps configuration simpler. * **Option B: Host network.** Keep `network_mode: host` and use the host-mapped port (`https://127.0.0.1:12001/metrics`). This works for standard CVMs but can fail on TDX CVMs due to kernel-level iptables differences. For most multi-container setups, we recommend Option A. Keep the agent on the bridge network and use Docker DNS names for inter-container scraping. ## Step 2: Configure OpenMetrics Check for Guest-Agent Metrics The Datadog Agent collects container logs and host metrics automatically. But to get custom Prometheus metrics, you tell the agent where to scrape them via a `conf.yaml` file. The `dstack-guest-agent` endpoint is at `http://127.0.0.1:8090/metrics`. Create `conf.d/openmetrics.d/conf.yaml` in your project: ```yaml theme={"system"} instances: - openmetrics_endpoint: http://127.0.0.1:8090/metrics namespace: "dstack" metrics: - ".*" tags: - service:dstack-guest-agent ``` The `namespace: "dstack"` prefix goes in front of every collected metric. `system_uptime` becomes `dstack.system_uptime` in Datadog. > [!NOTE] > > **The most common YAML trap.** `instances` must be a top-level key. If you nest it under `init_config`, the check loads but silently finds zero valid instances. > > Any of these formats work: > > ```yaml theme={"system"} > # ✅ Correct: instances as top-level key > instances: > - openmetrics_endpoint: ... > > # ✅ Also correct: init_config is just empty, instances is at root level > init_config: > instances: > - openmetrics_endpoint: ... > > # ❌ Wrong: instances nested under init_config > init_config: > instances: > - openmetrics_endpoint: ... > ``` > > The key rule: `instances` must sit at the file's root indentation level. An empty `init_config:` on its own line is harmless, but `instances` must never be indented under it. ## Step 3: Deploy to CVM CVMs have a read-only filesystem. The only writable path is `/var/volatile/dstack/persistent/`. Your `conf.yaml` must go there, then get mounted into the agent container. ```bash theme={"system"} # 1. Upload the OpenMetrics config to CVM persistent storage phala cp -r ./conf.d/openmetrics.d :/var/volatile/dstack/persistent/dd-conf/openmetrics.d # 2. Deploy (or redeploy) the CVM with your docker-compose.yml phala deploy --cvm-id ``` When the CVM starts, Docker Compose brings up the Datadog Agent with the mounted config and begins scraping immediately. No SSH is required for this flow. ### Alternative: Embed Config in the Agent's Command When you can't or don't want to use volume mounts — for instance, when your config is generated by another container on a shared volume — you can have the Datadog Agent write its own `conf.yaml` at startup. Add this to the agent's `command` in your compose file: ```yaml theme={"system"} datadog-agent: command: - bash - -c - | mkdir -p /etc/datadog-agent/conf.d/openmetrics.d printf "instances:\n - openmetrics_endpoint: https://kms:8000/metrics\n tls_verify: false\n namespace: dstack_kms\n metrics:\n - .*\n" > /etc/datadog-agent/conf.d/openmetrics.d/conf.yaml exec agent run ``` This approach sidesteps cross-container file sharing entirely. The config lives inside the agent container, generated fresh on every start. > [!WARNING] > > Never use multi-line heredocs in Docker Compose `command` blocks for YAML configs. Heredocs inside YAML `|` block scalars can introduce indentation changes that break both the compose file and the generated config. Use `printf` instead. ## Step 4: Verify ### Check Agent Status If SSH is available: ```bash theme={"system"} phala ssh -- "docker exec dstack-datadog-agent-1 agent status" ``` Look for the `openmetrics` check showing `[OK]` with a non-zero metric sample count. ### Verify in Datadog Dashboard 1. Open Datadog at `.datadoghq.com` 2. Go to **Metrics > Explorer** 3. Search for `dstack.system_uptime` to confirm guest-agent metrics are flowing 4. Go to **Logs** and filter by `source:nginx` (or your service name) to confirm logs ## Integrating Custom Service Metrics The same pattern works for any service that exposes a Prometheus `/metrics` endpoint. Here's the concrete setup for `dstack-kms` — the patterns apply to `dstack-gateway`, `dstack-vmm`, or your own services. ### Prerequisite: Enable the Metrics Endpoint Each service controls its `/metrics` endpoint via its own configuration. For KMS, you need this in `kms.toml`: ```toml theme={"system"} [core.metrics] enabled = true ``` Without this flag, the service won't expose any metrics. Check each service's config reference for its equivalent switch. ### Docker Compose Setup Since KMS runs as a Docker container, not a systemd service, we put the Datadog Agent on the **bridge network** and use Docker DNS to reach it. No host networking needed. ```yaml theme={"system"} services: kms: image: your-kms-image:latest ports: - "12001:8000" # ... your KMS config ... datadog-agent: image: registry.datadoghq.com/agent:7 depends_on: - kms environment: - DD_API_KEY= - DD_SITE= - DD_ENV=production - DD_TAGS=env:production,service:phala-cvm - DD_LOGS_ENABLED=true - DD_LOGS_CONFIG_CONTAINER_COLLECT_ALL=true - DD_CONTAINER_EXCLUDE=name:datadog-agent volumes: - /var/run/docker.sock:/var/run/docker.sock:ro - /proc/:/host/proc/:ro - /sys/fs/cgroup/:/host/sys/fs/cgroup:ro - /var/lib/docker/containers:/var/lib/docker/containers:ro command: - bash - -c - | mkdir -p /etc/datadog-agent/conf.d/openmetrics.d printf "instances:\n - openmetrics_endpoint: https://kms:8000/metrics\n tls_verify: false\n namespace: dstack_kms\n metrics:\n - .*\n" > /etc/datadog-agent/conf.d/openmetrics.d/conf.yaml exec agent run ``` What makes this different from the guest-agent setup: * **No `network_mode: host`.** The agent talks to KMS via Docker DNS (`kms:8000`), using the container's internal port, not the host-mapped one. * **`tls_verify: false`** because KMS uses a self-signed certificate. For production, switch to a trusted CA and set this to `true`. * **`namespace: dstack_kms`** to prevent metric name collisions with the guest-agent's `dstack.*` namespace. * Conf.yaml is generated inline with `printf` instead of mounted from a file. This avoids cross-container volume issues. ### KMS Metrics Reference | Metric | Type | Description | | - | - | - | | `dstack_kms_attestation_requests_total` | counter | Total attestation requests handled | | `dstack_kms_attestation_failures_total` | counter | Failed attestation requests | ## Available Guest-Agent Metrics The `dstack-guest-agent` exposes 19 system-level metrics. All appear under the `dstack.` namespace in Datadog. **System metrics:** `system_os_name`, `system_os_version`, `system_kernel_version`, `system_cpu_model`, `system_num_cpus`, `system_uptime`, `system_load_average_1m`, `system_load_average_5m`, `system_load_average_15m` **Memory metrics:** `system_memory_total`, `system_memory_available`, `system_memory_used`, `system_memory_free`, `system_swap_total`, `system_swap_used` **Disk metrics:** `disk_total_size`, `disk_free_size`, `disk_used_size`, `disk_usage_percentage` > [!WARNING] > > The load average metrics are scaled by 100. A value of `92` means `0.92` load average. ## Troubleshooting ### Metrics: Only seeing default Datadog metrics, not your service's Your OpenMetrics check isn't loading. The most common cause is YAML formatting. Double-check that `instances` is a top-level key in `conf.yaml` (see the format examples in Step 2). Other things to verify: * Can you curl the metrics endpoint from outside the CVM? If `curl https://:12001/metrics` returns nothing, the service's metrics endpoint isn't running. * Using `network_mode: host`? The agent might not reach a Docker container's host-mapped port on TDX CVMs. Try removing host networking and switching to Docker DNS. * On TDX CVMs, `network_mode: host` combined with container port mapping can fail silently due to kernel-level iptables rules. Switch to bridge networking when scraping other Docker containers. ### `conf.yaml` in Docker Compose crashing the agent If you embedded your config directly in a Docker Compose `command:` block using a heredoc (`cat < --public-sysinfo ``` ### Cannot mount config file (read-only file system) CVMs have a read-only filesystem. Use `/var/volatile/dstack/persistent/` for all config files and mount from there. ## Next Steps * [Set up alerting with Incident.io or PagerDuty](https://docs.datadoghq.com/monitors/) * [Create custom dashboards](https://docs.datadoghq.com/dashboards/) * [Configure log pipelines for parsing](https://docs.datadoghq.com/logs/log_configuration/pipelines/) * [Enable APM tracing for your application](https://docs.datadoghq.com/tracing/) # Fetch Logs over HTTP Source: https://docs.phala.com/phala-cloud/monitoring/log-api Fetch CVM serial, node, and container logs over HTTP from scripts and monitoring tools. Use this page to read CVM logs from your own scripts, monitoring tools, or clients written in any language. You request a signed log URL from the Phala Cloud API, then read the log stream from that URL with a plain HTTP GET. For the dashboard log viewer, see [Serial Logs](/phala-cloud/monitoring/serials-logs) and [Docker container logs](/phala-cloud/monitoring/public-logs). The `phala logs` command is described in the [CLI reference](/phala-cloud/phala-cloud-cli/logs). ## Get a log URL Call `GET /api/v1/cvms/{id}` on `https://cloud-api.phala.com` with your API key in the `X-API-Key` header and `X-Phala-Version: 2026-01-21`. The response contains a `logs` object: | Field | Description | | - | - | | `logs.serial` | Complete URL for the CVM serial console (boot, kernel). | | `logs.stdout` | Complete URL for the CVM stdout channel. | | `logs.stderr` | Complete URL for the CVM stderr channel. | | `logs.container_log_base` | Base URL for container logs. | | `logs.auth_query` | Query string that authorizes container log requests. | A node log URL has this form (`serial`, `stdout`, or `stderr` in the last path segment): ```text theme={"system"} https://cloud-logs.phala.com/logs/{vm_uuid}/node/{serial|stdout|stderr}?uid=&exp=&kid=&sig= ``` A container log URL is built from the base and the container name: ```text theme={"system"} {logs.container_log_base}/{container_name}?{logs.auth_query} ``` You can also read a ready-made container URL from `log_endpoint` on each container in the response of `GET /api/v1/cvms/{id}/composition`. In API version `2025-10-28`, the serial URL is returned as `syslog_endpoint`. Later versions return it as `logs.serial`. If the requesting user cannot access the CVM, the request returns `404`. The `logs` fields are `null` when signed log URLs are not available for that CVM, for example when it has no VM yet. The container fields (`logs.container_log_base`, `logs.auth_query`, and the container `log_endpoint`) are also `null` unless the CVM has [Public Logs](/phala-cloud/monitoring/public-logs) enabled. Container requests are rejected with `ERR-17-006` when it is disabled. Node logs (`serial`, `stdout`, `stderr`) are not affected by this setting. ### How URLs are signed Phala Cloud signs each URL for the user who requested it. The signature covers the whole CVM, so one signature works for the serial, stdout, stderr, and container URLs. Your client never signs anything. * Do not change the `uid`, `exp`, `kid`, or `sig` parameters. Add your own query parameters after them. * Anonymous access is not supported. You must be a member of the CVM's workspace to get a URL. * Treat a URL like a credential until it expires. Anyone who has it can read the logs. ## Expiry and rotation | Limit | Value | | - | - | | Signature lifetime | 5 minutes. It is checked only when the connection opens. | | Open stream | Not cut when the signature expires. A single stream lasts at most 1 hour. | | Idle client | A client that stops reading for 60 seconds is disconnected. | Because of these limits: * Fetch a fresh URL from the CVM API right before each connection. * Never cache or store URLs. * If a request returns `401` (`ERR-17-002` or `ERR-17-003`), the signature is missing, invalid, or expired. Fetch a new URL and retry (see [Retry rules](#retry-rules)). ## Query parameters The same parameters apply to every log kind unless noted. Unknown or repeated parameters are rejected with `400`. Boolean parameters accept only `true` or `false`. | Parameter | Applies to | Description | | - | - | - | | `tail` | All | Number of most recent lines: `0` to `10000`, or `all`. Default `1000` on every request. | | `follow` | All | `true` keeps the connection open and streams new lines. | | `since` | Container logs | Start time. Unix seconds, relative (`s`, `m`, `h`, `d`), or an RFC 3339 UTC timestamp ending in `Z`. See [Query encoding](#query-encoding). | | `until` | Container logs | End time. Same formats as `since`. | | `timestamps` | Container logs | Prefix each line with its timestamp. | | `ansi` | All | `true` keeps ANSI color codes. Only valid with `format=text`. | | `format` | All | `text` (default), or `ndjson` (container logs only). | Append parameters with `&` after the signature parameters. For a container URL, `auth_query` is already in the query string, so join with `&` as well. ### Query encoding The gateway rejects any request target that contains a `%`, so do not percent-encode query values. Append each parameter to the signed URL as raw text with `&`, for example `&since=1731226542&tail=all`. Do not pass the URL or its parameters through a generic query encoder. Write `since` and `until` as Unix seconds or as relative values (`s`, `m`, `h`, `d`). An RFC 3339 UTC timestamp ending in `Z` is also accepted if you write it literally, such as `2026-11-10T08:15:42Z`. Do not use `+` or other characters that would need encoding. ## Response format ### Text The default. The body is plain text, one log line per line. With `timestamps=true`, each container line starts with an RFC 3339 timestamp with nanoseconds, then one space, then the text: ```text theme={"system"} 2026-11-10T08:15:42.123456789Z server started on port 8080 ``` ### NDJSON With `format=ndjson` (container logs only), each line of the body is a JSON object: ```json theme={"system"} {"channel": "stdout", "message": "server started on port 8080\n"} ``` * `channel` is `stdout`, `stderr`, `console` (containers started with a TTY), or `stdin`. Clients must accept all four. * `message` ends with a newline in most cases. A record can have an empty `message`. Pass it on as an empty string and do not add a newline. * With `timestamps=true`, the timestamp is part of `message`, in the same `` form as the text format. ### Heartbeat lines Node log streams (`serial`, `stdout`, `stderr`) can contain lines whose entire content is `[vmm heartbeat]` or `[teepod heartbeat]`. Drop those lines from node logs only. Keep container lines with the same text, and keep empty lines, which can be real log entries. No other keepalive records are added to the stream. ### Errors inside a stream A stream that opened with `200` can still report a failure in its body. Check every line for these records. | Where | Record | What it means | | - | - | - | | Gateway, text | `[error] ERR-17-0xx `, for example `[error] ERR-17-008 Node VMM unreachable or returned a bad response` or `[error] ERR-17-009 Guest agent or gateway unreachable` | The connection to the CVM broke after the stream opened. Reconnect. | | Gateway, NDJSON | `{"error_code":"ERR-17-0xx","message":""}`, for example `{"error_code":"ERR-17-008","message":"Node VMM unreachable or returned a bad response"}` or `{"error_code":"ERR-17-009","message":"Guest agent or gateway unreachable"}` | Same as above. Reconnect. | | CVM, text or NDJSON | `{"error": ""}` | The agent inside the CVM could not read the container's logs, for example because the container uses a Docker logging driver that does not support reading. This is a final answer for that container. Do not reconnect; report the message. | The `{"error": ...}` record has no `channel` or `message` field and is not always followed by a newline, so it can be glued to the next record on the same line. The record can also be the whole body of a non-follow request. * In NDJSON, a record with a string `error` and no `channel` or `message` is a guest error anywhere in the stream. Read the stream with a streaming JSON decoder, not by splitting on newlines. * In text format, treat `{"error": ...}` as a guest error only at the very start of the response body, before you have delivered any output. It may be glued to the text that follows. Later in the stream, a line of that shape can be ordinary application output, so it cannot be told apart. Use `format=ndjson` for container logs if you need reliable error detection. * Node log streams (`serial`, `stdout`, `stderr`) carry arbitrary process output. Only the gateway `[error] ERR-17-0xx` lines are errors there. Match on the error code, never on the message text, which may change. Treat an error code from the gateway the same way as the same code in an HTTP error response (see [Errors](#errors)). What to do for each case is in [Retry rules](#retry-rules). ## Read logs ### Fetch recent lines ```bash theme={"system"} URL=$(curl -s "https://cloud-api.phala.com/api/v1/cvms/" \ -H "X-API-Key: $PHALA_CLOUD_API_KEY" \ -H "X-Phala-Version: 2026-01-21" | jq -r '.logs.serial') curl -s "$URL&tail=100" ``` For a container (`api` in this example): ```bash theme={"system"} RESP=$(curl -s "https://cloud-api.phala.com/api/v1/cvms/" \ -H "X-API-Key: $PHALA_CLOUD_API_KEY" \ -H "X-Phala-Version: 2026-01-21") BASE=$(echo "$RESP" | jq -r '.logs.container_log_base') AUTH=$(echo "$RESP" | jq -r '.logs.auth_query') curl -s "$BASE/api?$AUTH&tail=100×tamps=true" ``` ### Polling Poll on a timer. On each tick, fetch a fresh URL and request the last `N` lines without `follow`. Use `since` (Unix seconds) for container logs, or compare against the last line you saw, to avoid processing the same lines twice. ### Following Request the URL with `follow=true` and read the response as it arrives. A stream can end for any reason: a normal close, the 1-hour limit, a network error, or an error record in the body. Every time it ends, fetch a fresh URL from the CVM API (one lookup per connection) and reconnect as follows. **Node logs (`serial`, `stdout`, `stderr`).** Send `tail` on the first request only. Reconnect with `tail=0`. Node log lines have no timestamps, so lines written while you were disconnected are not replayed. **Container logs.** Always request `timestamps=true`, even if your users do not want timestamps. You need them to resume. 1. Send `tail` (and `since`, if the user gave one) until the first `200` is accepted. Every later request sends `tail=all` plus `since`, as described below. 2. Keep the Unix second of the latest timestamp you received, and count how many records you received in that second, grouped by channel and full message. Also record the time the first HTTP `200` was accepted, floored to the second. 3. Reconnect with `tail=all` and `since` set to that second. If no timestamped record has arrived yet, there is no cursor: use the caller's own `since` if they set one, otherwise the time the first `200` was accepted, floored to the second. Without `since`, `tail=all` would replay the whole history, for example for a caller who asked for `tail=0` on a quiet container. You must send `tail`: without it the gateway returns only the last 1000 lines, and lines written during a long disconnect would be lost. 4. The server sends every record from that second again. For each record in the boundary second, skip it if you still have a matching count; otherwise deliver it. Deliver records from later seconds as they come. 5. Strip the timestamp prefix before showing a line, unless the user asked for timestamps. Records without a timestamp pass through unchanged. For container logs, check whether Public Logs is on before the first log request and again on every reconnect (each connection looks up the CVM info anyway): the CVM response (API version `2026-01-21` or later) has `public_logs` set to `false` when it is off. Then you fail at once with `ERR-17-006` instead of waiting for the gateway to reject the request. #### Retry rules | Situation | What to do | | - | - | | `401` with `ERR-17-003` (signature expired) | Fetch a fresh URL and retry at once. This has its own limit of 3 refetches in a row. The count resets after a connection that delivered records or ended cleanly. It is separate from the failure count. | | `401` with `ERR-17-002` (signature missing or invalid) | Fetch a fresh URL and retry. This counts as a failure. | | `429` with `ERR-17-011` | Back off and retry. | | Any other `4xx` (including `ERR-17-001`, `ERR-17-004`, `ERR-17-005`, `ERR-17-006`, `ERR-17-007`, `ERR-17-013`) | Stop. Retrying does not help. | | `5xx`, a network or read error, or a gateway in-stream line (`[error] ERR-17-008 ` or `[error] ERR-17-009 ` in text, `{"error_code":"ERR-17-008","message":""}` or `ERR-17-009` in NDJSON) | Back off and retry. | | Guest `{"error": ...}` record | Stop and report the message. | | Node log stream ended cleanly | Reconnect with `tail=0`. Never stop. If it delivered no records and ended within 10 s of the `200` response, back off first (250 ms, doubling up to 5 s, counting consecutive such ends). Otherwise reconnect at once. The 1-hour stream limit ends streams too, and the node sends heartbeats while it is idle. | | Container log stream ended cleanly | Reconnect. If it delivered no new records and ended within 10 s of the `200` response, back off (same delay steps) and count it; after 5 such ends in a row, stop and report that the container has likely stopped. A connection that sat idle longer than 10 s before ending cleanly resets the count: reconnect immediately. If you set `until` and its time was reached, finish normally without an error. | Recommended client behavior: * Back off exponentially: start at 250 ms, double each time, up to 5 s. Reset the delay after a connection that delivered records. * Decide by where the error came from. A gateway error read from the body of a `200` response (`[error] ERR-17-...` in text, `{"error_code":...}` in NDJSON) is a failure to retry. A guest `{"error": ...}` record stops the follow. An HTTP error is decided by its status alone: `5xx` and `429` are failures, `401` with `ERR-17-003` or `ERR-17-002` fetches a new URL, and any other `4xx` stops. * Count `ERR-17-003` refetches separately from failures: allow 3 in a row, and reset that count after a connection that delivered records or ended cleanly. A `401` with `ERR-17-002` also fetches a new URL, but it counts as one of the 5 failures. * Count a connection as recovered only when it delivered at least one record. A `200` whose body immediately fails counts as a failure, not a recovery. * Give up after 5 consecutive failures. * Keep at least 1 s between the starts of consecutive connections, whatever the outcome, so a stream that ends at once cannot cause a tight reconnect loop. * Treat a clean end with no new output as neither a failure nor a recovery. Count it only if the connection ended within 10 s of the `200` response, and back off 250 ms, doubling up to 5 s, before reconnecting. For container logs, stop after 5 such ends in a row: a container that exited ends its stream this way. Node logs never stop on a clean end; they keep backing off and reconnecting. * A long idle connection that ends cleanly is normal: the agent closes an idle stream after 600 s. Reset the clean-end count and reconnect immediately (the 1 s minimum between connection starts still applies). * Reset the clean-end count on any failure or any delivered record, so it means consecutive clean ends. * When a connection delivered records and then failed, reset the failure count when the first record arrived, then count this failure as 1 and wait 250 ms. Failures always back off. * Container reconnects always send `tail=all` with `since`. If no timestamped record has arrived yet, `since` is the caller's own `since` if set, otherwise the time the first `200` was accepted, floored to the second. * Send the caller's initial `tail` until a log response with HTTP `200` has been accepted. A failed URL lookup or a failed log request does not count as the first connection. ### Example: follow a serial log in Python This example follows the retry rules above for node logs. It classifies each response by status and by `error_code` in the JSON body. ```python theme={"system"} import os import re import time from collections.abc import Iterator import httpx API = "https://cloud-api.phala.com/api/v1" HEADERS = { "X-API-Key": os.environ["PHALA_CLOUD_API_KEY"], "X-Phala-Version": "2026-01-21", } CVM_ID = "" MAX_FAILURES = 5 MAX_EXPIRED = 3 # ERR-17-003 refetches in a row. QUIET_SECONDS = 10.0 # A clean end with no records before this is a quick empty end. MIN_CONNECT_INTERVAL = 1.0 # Seconds between connection starts. HEARTBEATS = {"[vmm heartbeat]", "[teepod heartbeat]"} STREAM_ERROR = re.compile(r"^\[error\] ERR-17-0\d\d ") class Retry(Exception): def __init__(self, reason: object, expired: bool = False) -> None: super().__init__(reason) self.expired = expired # True for ERR-17-003: refetch, not a failure. class Stop(Exception): pass def check(resp: httpx.Response) -> None: if resp.status_code == 200: return try: code = resp.json().get("error_code") except ValueError: code = None if resp.status_code == 401 and code == "ERR-17-003": raise Retry(code, expired=True) # Next attempt fetches a fresh URL. if resp.status_code == 401 and code == "ERR-17-002": raise Retry(code) # Fresh URL, but this counts as a failure. if resp.status_code == 429 or resp.status_code >= 500: raise Retry(code or resp.status_code) raise Stop(f"HTTP {resp.status_code} {code}") # 400, 404, 409, ... def read_lines(client: httpx.Client, tail: str, conn: dict[str, float]) -> Iterator[str]: try: resp = client.get(f"{API}/cvms/{CVM_ID}", headers=HEADERS) check(resp) url = resp.json()["logs"]["serial"] if url is None: raise Stop("Signed log URLs are not available for this CVM yet") with client.stream("GET", f"{url}&follow=true&tail={tail}") as resp: if resp.status_code != 200: resp.read() check(resp) conn["opened_at"] = time.monotonic() # A 200 was accepted. for line in resp.iter_lines(): if line in HEARTBEATS: continue if STREAM_ERROR.match(line): raise Retry(line) # Gateway error inside a 200 stream. yield line except httpx.TransportError as exc: # Network and read errors. raise Retry(str(exc)) from exc def backoff(count: int) -> None: time.sleep(min(0.25 * 2 ** (min(count, 6) - 1), 5.0)) def follow_serial() -> None: failures = 0 # Consecutive failed connections. expired = 0 # Consecutive ERR-17-003 refetches. empty_ends = 0 # Consecutive quick clean ends with no records. tail = "100" # Caller's tail, used until a 200 is accepted; then 0. last_start = 0.0 with httpx.Client(timeout=httpx.Timeout(10.0, read=None)) as client: while True: time.sleep(max(0.0, last_start + MIN_CONNECT_INTERVAL - time.monotonic())) last_start = time.monotonic() conn: dict[str, float] = {} delivered = 0 try: for line in read_lines(client, tail, conn): if delivered == 0: failures = 0 # Recovered. expired = 0 empty_ends = 0 delivered += 1 print(line, flush=True) except Retry as exc: print(f"retrying: {exc}") if "opened_at" in conn: tail = "0" empty_ends = 0 if exc.expired: expired += 1 if expired > MAX_EXPIRED: raise RuntimeError("Signature kept expiring") from exc continue # Refetch the URL at once. failures += 1 if failures >= MAX_FAILURES: raise RuntimeError(f"Giving up after {failures} failures") from exc backoff(failures) # Failures always back off. continue # Clean end: the stream closed without an error. tail = "0" expired = 0 if delivered == 0 and time.monotonic() - conn["opened_at"] < QUIET_SECONDS: empty_ends += 1 # Node logs never stop on this; they only back off. backoff(empty_ends) else: empty_ends = 0 try: follow_serial() except Stop as exc: raise SystemExit(str(exc)) ``` This example is simpler than the SDKs. It covers node logs only. It has no container logic, no `until`, and no cancellation. For container logs, change the request and the bookkeeping, not the retry rules: * Request `timestamps=true`. On reconnect, send `tail=all` and `since` set to the last timestamp second (before any record has arrived: the caller's own `since`, or else the time the first `200` was accepted, floored to the second), and drop the records you already delivered in that second (see [Following](#following)). * Do not drop heartbeat lines. * Add the container-only stop rule: count clean ends with no output that came within 10 s of the `200` response, and stop after 5 in a row (see [Retry rules](#retry-rules)). Reset that count on any failure or delivered record. * Stop on a `{"error": ...}` record. Use `format=ndjson` so it is reliably a line of its own; in text format it can be glued to earlier output. * If you set `until` and its time is reached, finish normally when the stream ends cleanly. ## Errors Error responses have a JSON body: ```json theme={"system"} { "error_code": "ERR-17-001", "message": "", "details": [], "suggestions": [], "links": [], "request_id": null } ``` Match on `error_code`. The `message` text is for people and may change. | Status | Code | Meaning | | - | - | - | | `400` | `ERR-17-001` | Invalid log request | | `401` | `ERR-17-002` | Missing or invalid log access signature | | `401` | `ERR-17-003` | Log access signature expired | | `404` | `ERR-17-004` | CVM not found or access denied | | `409` | `ERR-17-005` | CVM is not running (container logs only; `details` has the current CVM `status`) | | `409` | `ERR-17-006` | Container logs are disabled (public logs are off) | | `404` | `ERR-17-007` | Container not found | | `502` | `ERR-17-008` | Node VMM unreachable or returned a bad response | | `502` | `ERR-17-009` | Guest agent or gateway unreachable, or the guest agent could not read the container's logs | | `504` | `ERR-17-010` | Log upstream timed out | | `429` | `ERR-17-011` | Too many concurrent log streams | | `503` | `ERR-17-012` | Node or gateway routing data is unavailable | | `404` | `ERR-17-013` | VM no longer exists on the node | How to react: follow the [Retry rules](#retry-rules). With `ERR-17-005`, node logs (`serial`, `stdout`, `stderr`) remain readable. When you contact support, include the `error_code`, the time of the request, and the CVM ID. ## Known limitations When the node's log file cannot be opened or read, the node log endpoint currently answers HTTP `200` and writes a plain text error line, for example a line starting with ` Network > Endpoint** section. Log in with the secrets (or whatever you set in step 1): * **Username:** `admin` * **Password:** `secret` Only authorized users with valid credentials can view your container logs. > [!TIP] > > For production environments with advanced requirements, consider using the Loki and Grafana stack for centralized log aggregation, querying, and visualization. # Public Logs Source: https://docs.phala.com/phala-cloud/monitoring/public-logs View Docker container logs and control access to their public URLs. Use the CVM log drawer to inspect a container's runtime output. When **Public Logs** is enabled, you can also open the selected container's log stream in a separate browser tab and share its URL. > [!WARNING] > > Docker logs can contain application data, request details, or secrets written by your application. Only enable **Public Logs** when the output is safe to share with anyone who has the URL. ## View Docker container logs The log viewer opens from the **Logs** button in the upper-right corner of the CVM detail-page header. ![CVM detail-page header with the Logs button highlighted in the upper-right corner](https://mintcdn.com/phalanetwork-1606097b/BV6eYrfe2po64O93/images/cloud-log-entry.png?fit=max\&auto=format\&n=BV6eYrfe2po64O93\&q=85\&s=b4c90f7ac380c1bb5af8bee6ef7dbb64) Logs in the CVM detail-page header 1. Open your app in the [Phala Cloud dashboard](https://cloud.phala.com), then open the CVM instance. 2. Click **Logs** in the CVM detail-page header. 3. Under **Docker Containers**, select the container whose logs you want to view. The log drawer switches to the selected container's output. If a container does not have an available log endpoint, the container is disabled in the list. ![CVM log drawer with demo-api selected under Docker Containers and its application output streaming](https://mintcdn.com/phalanetwork-1606097b/BV6eYrfe2po64O93/images/cloud-container-log.png?fit=max\&auto=format\&n=BV6eYrfe2po64O93\&q=85\&s=6a46f223ae65dd9cd2a10a2a53f9104f) Docker Containers in the log source list ## Open and copy a log URL 1. Select a container under **Docker Containers**. 2. Open the log toolbar menu, then click **Open in New Window**. 3. Copy the URL from the new window's browser address bar. **Open in New Window** is available only when the selected container has a log endpoint. The URL is signed for your account and expires 300 seconds after it is issued. Treat the URL like a password until it expires. The expiry is checked only when a stream opens; an open stream runs for up to one hour. To read logs from a script, see [Fetch Logs over HTTP](/phala-cloud/monitoring/log-api). ## Control public access The **Public Logs** setting controls Phala Cloud's managed Docker log endpoints. | Setting | Behavior | | - | - | | Enabled | The dashboard provides a short-lived signed log URL for each available container to members of the workspace. You must be a workspace member to get a URL. The URL itself is a short-lived credential: anyone who holds it can open a stream until it expires (it must be used to open within 5 minutes). | | Disabled | The dashboard does not provide Docker log URLs. Container log requests from the API, the SDKs, and the `phala` CLI fail with error `ERR-17-006`, both when fetching and when following. VM logs (serial, qemu output, qemu stderr) are not affected. Use an in-CVM log viewer or forward logs to a private external service instead. | To change the setting for an existing CVM: 1. Open the CVM detail page and click **Settings**. 2. Find **Worker Attestation Visibility Settings**. 3. Enable or disable **Public Logs**. 4. Click **Save Changes**, then confirm the change. ![Worker Attestation Visibility Settings with the Public Logs switch enabled](https://mintcdn.com/phalanetwork-1606097b/BV6eYrfe2po64O93/images/cloud-public-log-setting.png?fit=max\&auto=format\&n=BV6eYrfe2po64O93\&q=85\&s=7cce5337f16feb1cf883d79d521cae11) Public Logs under Worker Attestation Visibility Settings > [!WARNING] > > Changing a visibility setting restarts the CVM. Its applications are temporarily unavailable during the restart. For authenticated access to private Docker logs, follow [Set up a private log viewer](/phala-cloud/monitoring/private-log-viewer). # Serial Logs Source: https://docs.phala.com/phala-cloud/monitoring/serials-logs View CVM boot and QEMU logs from the Phala Cloud dashboard. VM logs show the CVM boot process and host-side QEMU output. Use them to diagnose startup failures, image download problems, and system initialization errors. ## View VM logs The log viewer opens from the **Logs** button in the upper-right corner of the CVM detail-page header. ![CVM detail-page header with the Logs button highlighted in the upper-right corner](https://mintcdn.com/phalanetwork-1606097b/BV6eYrfe2po64O93/images/cloud-log-entry.png?fit=max\&auto=format\&n=BV6eYrfe2po64O93\&q=85\&s=b4c90f7ac380c1bb5af8bee6ef7dbb64) Logs in the CVM detail-page header 1. Open your app in the [Phala Cloud dashboard](https://cloud.phala.com), then open the CVM instance. 2. Click **Logs** in the CVM detail-page header. 3. Under **VM Logs**, select a log source: * **Kernel serial output** shows the CVM boot and system console output. * **qemu output** shows standard output from the QEMU process. * **qemu stderr** shows errors written by the QEMU process. The log drawer switches to the selected source. Use **Auto-scroll** to follow new output or open the toolbar menu and click **Retry Connection** if the stream disconnects. ![CVM log drawer with VM Logs expanded, Kernel serial selected, and boot output streaming](https://mintcdn.com/phalanetwork-1606097b/BV6eYrfe2po64O93/images/cloud-cvm-log.png?fit=max\&auto=format\&n=BV6eYrfe2po64O93\&q=85\&s=ef0ec3f60b89a1c79908b9becce36c99) Kernel serial output in the CVM log drawer ## View application logs VM logs describe the CVM and its boot process. To inspect output written by your application, select a container under **Docker Containers** instead. See [View and share Docker container logs](/phala-cloud/monitoring/public-logs) for the complete procedure and visibility controls. VM logs do not depend on the **Public Logs** setting. To read them from a script, see [Fetch Logs over HTTP](/phala-cloud/monitoring/log-api); the `phala logs --serial` command and the SDK log helpers read them too. # Architecture Source: https://docs.phala.com/phala-cloud/networking/architecture Understanding how Phala Cloud routes and secures your network traffic Phala Cloud's networking architecture is built around a zero-trust model. The gateway runs in its own TEE and mutually attests with your CVM before routing any traffic. This creates multiple layers of encryption that keep your data private even from the infrastructure operator. Understanding this architecture explains how routing works, why isolation is hardware-enforced, and where performance characteristics come from. For the security details behind this design, see [Network Security](/phala-cloud/networking/security). ## Request Journey Here's how requests flow through the gateway and why each step matters for your application. ### The Complete Path ``` Client → [TLS 1.3] → Gateway → [WireGuard] → CVM → [Plain HTTP] → Your Container ``` Each step serves a purpose: **TLS Handshake (10-30ms first connection, 1-2ms subsequent)**: Client establishes secure connection using standard TLS 1.3. The gateway presents a valid certificate for `*.phala.network`. **SNI Routing (\<1ms)**: Gateway extracts the hostname from the TLS handshake to determine which CVM and port to route to. No decryption of request data happens yet. **WireGuard Tunnel (\<1ms)**: Traffic gets re-encrypted with WireGuard before forwarding to your CVM. Even after TLS termination at the gateway, your data stays encrypted until it reaches your container. **Container Processing**: Inside the CVM's trusted environment, traffic is decrypted and forwarded to your container on the specified port. Total network overhead: approximately 2-3ms on top of your application's response time for established connections. ## How Routing Works The gateway makes intelligent routing decisions based on URL patterns and health status. ### URL Pattern Routing The URL structure tells the gateway how to handle your traffic: ``` deadbeef111111111111111111111111-8080.dstack-prod5.phala.network → TLS termination → HTTP to container deadbeef111111111111111111111111-5432s.dstack-prod5.phala.network → TLS passthrough → Raw TLS to container deadbeef111111111111111111111111-50051g.dstack-prod5.phala.network → HTTP/2 enabled → gRPC to container ``` The suffix changes behavior. No suffix means standard HTTP/HTTPS with TLS termination. Add `s` for TLS passthrough when you need end-to-end encryption. Add `g` to enable HTTP/2 with ALPN negotiation for gRPC. For TLS passthrough use cases and security considerations, see [TLS Passthrough](/phala-cloud/networking/tls-passthrough). ### Load Balancing When you scale to multiple CVMs, the gateway automatically distributes traffic based on health and availability. **Health Detection:** The gateway tracks each instance using WireGuard handshakes. An instance is considered healthy if it completed a handshake within the last 5 minutes. Unhealthy instances are automatically removed from the rotation without any configuration needed from you. **Instance Selection:** The gateway uses a "connect top N" strategy, attempting to connect to multiple healthy instances and selecting the first one that responds successfully. This provides both load distribution and automatic failover. **Session Handling:** Currently there's no session affinity. Each request may hit a different instance, so design your applications to be stateless or use external session storage like Redis. For WebSocket connections, the TCP connection stays with one instance for its lifetime, but reconnections might hit a different instance. ## Network Isolation Each CVM gets complete network isolation from others and the host. ### CVM Boundaries Your CVM operates in its own network segment with: * A unique WireGuard keypair generated on deployment * An isolated IP address in the 10.0.0.0/8 range * No routes to other CVMs on the same host * No access to the host's network services You cannot ping another CVM, connect to the host's localhost, or even discover what other CVMs exist. This isolation happens at the kernel level using network namespaces. For security implications and hardware-level isolation details, see [Network Security](/phala-cloud/networking/security#hardware-isolation). ### Container Networking Inside CVM Within your CVM, containers communicate normally through Docker's bridge network: ```yaml theme={"system"} services: frontend: # Reaches backend at http://backend:3000 backend: # Connects to database at postgres://db:5432 db: # All internal traffic stays in CVM memory ``` This internal traffic never touches the network - it stays within the CVM's encrypted memory space. ## Performance Characteristics Understanding performance helps you make architectural decisions. ### Latency Budget Where latency comes from in your network stack: | Component | Latency | Can Optimize? | | - | - | - | | TLS handshake | 10-30ms (first connection) | Use connection pooling | | Gateway routing | 1-2ms | No (fixed overhead) | | WireGuard tunnel | \<1ms | No (fixed overhead) | | Your application | Variable | Yes - your code | For established connections with keep-alive, expect 2-3ms total network overhead. ### Throughput Capabilities Practical limits you'll encounter: **Single connection**: Limited by instance bandwidth, typically 1-10 Gbps depending on your CVM size. **Concurrent connections**: Each connection uses \~10-50KB of memory. A 4GB instance can handle thousands of concurrent connections. **New connections/second**: CPU-bound by TLS handshakes. Expect hundreds to low thousands per second depending on instance size. ### Scaling Strategies Scale horizontally when you need: * More concurrent connections * Higher new connection rate * Automatic failover Scale vertically when you need: * Maximum single-connection throughput * Lowest possible latency * Stateful services that can't be distributed For security implications of these scaling strategies, including encryption overhead and trust boundaries, see [Network Security](/phala-cloud/networking/security). ## Common Architectural Patterns These patterns take advantage of Phala's sub-millisecond internal networking and hardware isolation. ### Microservices in Single CVM Deploy related microservices together: ```yaml theme={"system"} services: api: ports: ["8080:8080"] worker: # Talks to API via internal network cache: # Shared by all services ``` Benefits: No network latency between services, shared cache layer, simpler deployment. ### Database with Application Co-locate databases with their applications: ```yaml theme={"system"} services: app: ports: ["3000:3000"] postgres: # Only accessible from app ``` Benefits: Zero network latency to database, data never leaves CVM, simpler backup strategy. ### API Gateway Pattern Use one CVM as an API gateway: ```yaml theme={"system"} services: gateway: ports: ["443:443"] environment: BACKEND_1: https://deadbeef111111111111111111111111-8080.dstack-prod5.phala.network BACKEND_2: https://def456-8080.dstack-prod5.phala.network ``` Benefits: Single entry point, centralized auth, routing logic in your control. ## Next Steps Now that you understand the architecture: * [Set up your first service](/phala-cloud/networking/quickstart) * [Configure custom domains](/phala-cloud/networking/setup-custom-domain) * [Learn about security features](/phala-cloud/networking/security) # Domain Attestation Source: https://docs.phala.com/phala-cloud/networking/domain-attestation How to verify your data privacy when connecting to TEE applications This guide shows how to verify that TLS certificates are controlled by a TEE using cryptographic attestation. For application code verification, see your app's attestation documentation. For security concepts, see [Security Architecture](/phala-cloud/networking/security). ## Which Verification Guide to Follow? The verification method depends on what the application deployer chose: | Domain Type | When to Use | Operator | | - | - | - | | **Gateway Domains** (`*.phala.network`) | Your app uses Phala's gateway domain | Phala Cloud | | **Custom Domain** | Your app uses a custom domain with dstack-ingress | Developer | Both provide cryptographic proof of TEE control over TLS certificates. The difference is who operates the certificate infrastructure. ## Gateway Domains Gateway domains expose attestation endpoints that prove TEE control over TLS certificate private keys. ### What You'll Verify The gateway TEE publishes cryptographic evidence at `https://GATEWAY-DOMAIN/.dstack/` endpoints that proves: 1. The TLS certificate private keys are generated and controlled by the gateway TEE 2. TEE hardware backs all certificate operations 3. Only the TEE-controlled Let's Encrypt account can issue certificates for gateway domains 4. All historical certificates are accounted for via TEE remote attestation ### 3-Step Verification **Example**: We'll use `gateway.dstack-pha-prod7.phala.network` - replace with your gateway domain. #### Step 1: Get Gateway Evidence The gateway publishes evidence through three endpoints: ```bash theme={"system"} # Get ACME certificate information curl -s "https://gateway.dstack-pha-prod7.phala.network/.dstack/acme-info" | jq > acme-info.json # Get gateway application information curl -s "https://gateway.dstack-pha-prod7.phala.network/.dstack/app-info" | jq > app-info.json ``` **Expected output from acme-info.json**: ```json theme={"system"} { "account_uri": "https://acme-v02.api.letsencrypt.org/acme/acct/2584877296", "account_quote": { tdx-quote-with-eventlogs }, "hist_keys": [""], "quoted_hist_keys": [ {"public_key": "", "quote": { tdx-quote-with-eventlogs } }, {"public_key": "", "quote": { tdx-quote-with-eventlogs } } ], "active_cert": "-----BEGIN CERTIFICATE-----\n...", "base_domain": "dstack-pha-prod7.phala.network" } ``` **What this means**: The gateway provides its Let's Encrypt account, all certificate public keys (current and historical), and TDX quotes proving the TEE generated these keys. #### Step 2: Verify Certificate Matches TDX Quotes Check that the served certificate matches the TEE-quoted keys: ```bash theme={"system"} # Get the public key from the served certificate openssl s_client -connect gateway.dstack-pha-prod7.phala.network:443 /dev/null | \ openssl x509 -pubkey -noout > served-pubkey.pem # Get the public key from the evidence certificate cat acme-info.json | jq -r '.active_cert' | \ openssl x509 -pubkey -noout > evidence-pubkey.pem # Compare the public keys diff served-pubkey.pem evidence-pubkey.pem ``` **Expected**: No output (files are identical). Now verify the TEE hardware signed the certificate public key: ```bash theme={"system"} # Step 1: Prepare the public key for hashing cat acme-info.json | jq -r '.quoted_hist_keys[0].public_key' | xxd -r -p > pubkey.bin (echo -n "zt-cert:" && cat pubkey.bin) | sha512sum # Output: 68f04e2b77f9ca8324d49ce916a5a7ebc6a715027d68fba4e7d3fb60f0f841a8 - # Step 2: Search for this hash in the TDX quote's report_data jq -r '.quoted_hist_keys[0].quote | fromjson | .report_data' acme-info.json | \ grep -o "68f04e2b77f9ca8324d49ce916a5a7ebc6a715027d68fba4e7d3fb60f0f841a8" # Output: 68f04e2b77f9ca8324d49ce916a5a7ebc6a715027d68fba4e7d3fb60f0f841a8 ``` **What this means**: If you see the same hash in both outputs, Intel TDX hardware has cryptographically signed this public key. Copy the hash from step 1 and search for it in step 2 - they must match exactly. Please follow the [Attestation Verification tutorial](/phala-cloud/attestation/verifying-attestation) to further verify the remote attestation of the gateway. It ensures the implementation and the execution environment of the gateway is secure. #### Step 3: Check Domain Protection and Certificate History Verify only this TEE can issue certificates: ```bash theme={"system"} # Check ALL certificates ever issued for the gateway domain curl -s "https://crt.sh/?q=%.dstack-pha-prod7.phala.network&output=json" | \ jq -r '.[] | "\(.not_before) to \(.not_after): \(.issuer_name)"' | head -10 # Get the TEE's ACME account cat acme-info.json | jq -r '.account_uri' # Output: https://acme-v02.api.letsencrypt.org/acme/acct/2584877296 # Check DNS CAA records for the base domain dig +short CAA dstack-pha-prod7.phala.network ``` **Example output**: ``` # Certificate history 2025-01-15T08:23:45 to 2025-04-15T08:23:44: C=US, O=Let's Encrypt, CN=E5 2024-12-01T10:15:22 to 2025-03-01T10:15:21: C=US, O=Let's Encrypt, CN=R3 # ACME account https://acme-v02.api.letsencrypt.org/acme/acct/2584877296 # CAA record 0 issue "letsencrypt.org;validationmethods=dns-01;accounturi=https://acme-v02.api.letsencrypt.org/acme/acct/2584877296" ``` Verify the following: * All certificates are from Let's Encrypt (no other CAs) * All the CAA record matches the account\_uri from the TEE * Historical keys in `hist_keys` correspond to certificates in CT logs ### Gateway Evidence Endpoints Reference | Endpoint | Contains | Proves | | - | - | - | | `/.dstack/index` | List of available endpoints | Gateway discovery | | `/.dstack/app-info` | App ID, instance ID, device ID, TCB info | TEE application identity | | `/.dstack/acme-info` | ACME account, certificate keys, TDX quotes | Certificate control and history | The `acme-info` response structure: | Field | Type | Purpose | | - | - | - | | `account_uri` | String | Let's Encrypt account URI | | `account_quote` | String | TDX quote proving TEE controls the ACME account | | `hist_keys` | Array | All certificate public keys (current + historical) | | `quoted_hist_keys` | Array | Public keys with TDX quotes proving TEE generated them | | `active_cert` | String | Currently active certificate (PEM format) | | `base_domain` | String | Base domain for gateway (e.g., dstack-pha-prod7.phala.network) | ### Troubleshooting **"Connection refused to /.dstack/ endpoints"**: These endpoints are only accessible via the gateway subdomain: `gateway.dstack-pha-prod7.phala.network` **"Certificate doesn't match quoted keys"**: The gateway may have recently renewed certificates. Re-fetch the evidence with a fresh `acme-info` request. **"Multiple ACME accounts in history"**: Gateway upgrades or migrations may result in new ACME accounts. Check that the CAA record matches the current account\_uri, and verify old certificates have expired. ### What You've Verified When all checks pass, you've cryptographically proven: * **Zero-trust TLS**: The gateway TEE controls certificate private keys, verifiable via TDX attestation * **Phala-operated infrastructure**: Phala Network operates the gateway TEE and maintains CAA records * **Certificate transparency**: All certificates are publicly auditable via CT logs **Key difference from custom domains**: With gateway domains, Phala operates the certificate infrastructure. With custom domains, the application deployer operates it. Both provide cryptographic proof of TEE control. ## Custom Domains Custom domains use dstack-ingress running in your application's TEE to manage certificates. The application deployer operates the certificate infrastructure. ### What You'll Verify Your TEE publishes cryptographic evidence at `https://your-domain.com/evidences/` that proves: 1. The TLS certificate is controlled exclusively by this TEE 2. Intel TDX hardware backs the attestation 3. No one else can issue certificates for this domain Live example: [custom-domain-demo.phala.systems/evidences/](https://custom-domain-demo.phala.systems/evidences/) ### Prerequisites Before starting, you'll need: * Your domain name (e.g., `your-domain.com`) * `curl`, `jq`, `openssl`, and `dig` commands installed * 3 minutes to complete all verifications ### Simple 3-Step Verification **Example**: We'll use `custom-domain-demo.phala.systems` - just replace with your domain. #### Step 1: Get the Evidence Files Your TEE publishes 4 files that prove it controls the certificate: ```bash theme={"system"} # Download the evidence files (4 files total) curl -sO https://your-domain.com/evidences/quote.json curl -sO https://your-domain.com/evidences/sha256sum.txt curl -sO https://your-domain.com/evidences/cert.pem curl -sO https://your-domain.com/evidences/acme-account.json # Verify the files haven't been tampered with sha256sum -c sha256sum.txt ``` **Expected output**: ``` acme-account.json: OK cert.pem: OK ``` This means the files are authentic. #### Step 2: Verify the Certificate Matches Check that the evidence matches what's actually being served: ```bash theme={"system"} # Compare the served certificate with the evidence certificate echo | openssl s_client -connect your-domain.com:443 2>/dev/null | \ openssl x509 -fingerprint -sha256 -noout openssl x509 -in cert.pem -fingerprint -sha256 -noout ``` **What to look for**: Both fingerprints should be identical. For example: ``` SHA256 Fingerprint=62:89:C4:19:E6:F6:B6:50:11:F9:7D:E1:CF:FD:EE:5A:CE:2C:A3:38:24:F0:DE:5F:9E:2C:01:A3:72:D3:8B:DE SHA256 Fingerprint=62:89:C4:19:E6:F6:B6:50:11:F9:7D:E1:CF:FD:EE:5A:CE:2C:A3:38:24:F0:DE:5F:9E:2C:01:A3:72:D3:8B:DE ``` Now verify the TEE hardware signed these files: ```bash theme={"system"} # Step 1: Get the hash of sha256sum.txt sha256sum sha256sum.txt # Output: 7cd338a801531e88a5af8478aa185cfc51baf7501319446ce2f94dade56a0988 sha256sum.txt # Step 2: Search for this complete hash in the TDX quote cat quote.json | jq -r '.quote' | grep -o "7cd338a801531e88a5af8478aa185cfc51baf7501319446ce2f94dade56a0988" # Output: 7cd338a801531e88a5af8478aa185cfc51baf7501319446ce2f94dade56a0988 ``` **What this means**: If you see the same 64-character hash in both outputs, Intel TDX hardware has cryptographically signed your evidence files. Copy the hash from step 1 and search for it in step 2 - they must match exactly. #### Step 3: Check Domain Protection and Timeline Make sure only this TEE can get certificates for your domain: ```bash theme={"system"} # Check ALL certificates ever issued for your domain curl -s "https://crt.sh/?q=your-domain.com&output=json" | \ jq -r '.[] | "\(.not_before) to \(.not_after): \(.issuer_name)"' | head -5 # Get the TEE's ACME account number cat acme-account.json | jq -r '.uri' # Check if your domain is locked to this account dig +short CAA your-domain.com ``` **Example output**: ``` # Certificate history (note the dates!) 2025-08-04T06:10:56 to 2025-11-02T06:10:55: C=US, O=Let's Encrypt, CN=E5 ← Current 2025-08-04T06:00:18 to 2025-11-02T06:00:17: C=US, O=Let's Encrypt, CN=E5 ← TEE deployment # ACME account https://acme-v02.api.letsencrypt.org/acme/acct/2572685661 # CAA record (contains the same account number) 0 issue "letsencrypt.org;validationmethods=dns-01;accounturi=https://acme-v02.api.letsencrypt.org/acme/acct/2572685661" ``` **Critical timeline check**: If you see certificates issued BEFORE your TEE was deployed (before CAA was set), verify they're either: * Already expired (check the "to" date) * Issued by the same ACME account (meaning they were from a previous TEE deployment) If unexpired certificates exist from before CAA setup, they could potentially intercept traffic! ### Understanding the Results When all verifications pass, you've proven: ✅ **Exclusive TEE Control**: Only this specific TEE instance has the private key for your TLS certificate ✅ **Hardware-Backed Security**: Intel TDX hardware cryptographically signed the evidence, proving it's a genuine TEE ✅ **Domain Protection**: CAA DNS records prevent anyone else (even with domain access) from issuing certificates ✅ **Complete Chain of Trust**: Every link from TDX hardware → evidence files → certificate → your connection is verified ### Evidence Files Reference ![Browser showing /evidences/ directory listing with four files: acme-account.json, cert.pem, quote.json, and sha256sum.txt with timestamps and file sizes](https://mintcdn.com/phalanetwork-1606097b/HhZAgNWhhdRirRzb/images/evidence-files-directory.png?fit=max\&auto=format\&n=HhZAgNWhhdRirRzb\&q=85\&s=b0bcf11bc4281a8c0f61b4b883bede34) The four evidence files at `/evidences/` work together: | File | Contains | Proves | | - | - | - | | `quote.json` | TDX attestation with embedded hash | Hardware generated the evidence | | `sha256sum.txt` | SHA256 of cert.pem + acme-account.json | Links certificate to ACME account | | `cert.pem` | Current TLS certificate | What's being served to clients | | `acme-account.json` | ACME account URI | Which account controls certificates | ### Troubleshooting **"Files not found at /evidences/"**: Ensure your domain uses custom domain setup with `SET_CAA=true` **"Certificate doesn't match"**: The TEE may have renewed the certificate. Re-download evidence files. **"Hash not in quote"**: Verify you're checking a production TEE deployment, not a test instance. **"CAA record missing"**: The domain owner needs to set CAA records pointing to the TEE's ACME account. ### Going Deeper: Application Trust While you've verified the network connection is secure, the TLS private key is only as trustworthy as the code handling it. The key management software (dstack-ingress) runs inside the TEE and is open-source auditable code. To verify the exact code handling your keys matches what's deployed, check the compose-hash in the TEE's event log against the published source code. This ensures no malicious code can access or leak your private keys. Learn more: [Application Attestation Documentation](/phala-cloud/attestation/overview) ### Complete Security Checklist > [!NOTE] > > **Network Security** (covered above): > > * ✅ Evidence files verify TEE control > * ✅ TDX attestation proves hardware backing > * ✅ CAA records prevent unauthorized certificates > * ✅ Certificate timeline shows no pre-deployment threats > > **Advanced Verification** (for maximum security): > > * ⚠️ Application code trust - Verify compose-hash matches source code > * ⚠️ Certificate timeline - Ensure no valid pre-CAA certificates exist > * ⚠️ Continuous monitoring - Watch CT logs for unexpected certificates > > For detailed application verification: [Attestation Guide](/phala-cloud/attestation/overview) ## Next Steps ### Monitoring Set up alerts on [crt.sh](https://crt.sh) to detect unexpected certificate issuance: * Gateway domains: `%.dstack-pha-prod7.phala.network` * Custom domains: `your-domain.com` ### Development * **Gateway verification**: Integrate attestation checks into your security monitoring workflow * **Custom domains**: Enable CAA records with `SET_CAA=true` in your deployment configuration ### Security Auditing Review the source code to understand certificate management: * [Gateway implementation](https://github.com/Dstack-TEE/dstack/tree/next/dstack/gateway) * [Custom domain ingress](https://github.com/Dstack-TEE/dstack-examples/tree/main/custom-domain/dstack-ingress) # Enable SSH Access Source: https://docs.phala.com/phala-cloud/networking/enable-ssh-access Connect to your CVM via SSH for debugging and management > [!WARNING] > > SSH works only on dev OS images. Select "dstack-dev" when you create your CVM. Production images have SSH turned off for security. You sign in with an SSH key. Passwords do not work. The Phala CLI connects you through the secure gateway tunnel in one command. ## Prerequisites * [Phala CLI](/phala-cloud/phala-cloud-cli/overview) (latest version) * CVM deployed with Development OS ## Step 1: Configure SSH Keys Start by adding your SSH keys in **Account Settings > SSH Keys** on the [Phala Cloud dashboard](https://cloud.phala.com/account/settings). You can add keys manually or sync them from GitHub. All saved keys are automatically added to every new CVM you deploy. When creating a CVM, the SSH Authorization section lets you add one more public key just for that CVM. It is added alongside your account keys. Your keys are copied into the CVM when it starts for the first time. Adding a key to your account later does not reach a CVM that is already running. To add a key to a running CVM, use **Code Update** and set the `DSTACK_ROOT_PUBLIC_KEY` environment variable. ### Why can't I sign in with a password? Since dstack 0.5.6, the SSH server rejects password logins. Only keys work. `DSTACK_ROOT_PASSWORD` still sets the Linux root password inside the CVM, but SSH will turn it down no matter what you set it to. Add a public key instead. ## Step 2: Connect ```bash theme={"system"} # Connect using phala.toml configuration phala ssh # Or specify the CVM name directly phala ssh my-cvm ``` That's it. The CLI handles the gateway tunnel and SSH configuration automatically. ## Useful Options The `phala ssh` command supports several options: ```bash theme={"system"} # Preview the SSH command without connecting phala ssh my-cvm --dry-run # Enable verbose output for debugging phala ssh my-cvm -v # Forward a local port to the CVM phala ssh my-cvm -- -L 8080:localhost:80 ``` See the [CLI reference](/phala-cloud/phala-cloud-cli/ssh) for all options. > [accordion] Manual SSH Configuration > > If you prefer manual configuration or need to customize your setup, use `phala ssh --dry-run` to generate the SSH config: > > ```bash theme={"system"} > phala ssh my-cvm --dry-run > ``` > > This outputs a working SSH command you can adapt. The underlying mechanism uses OpenSSL to tunnel SSH through TLS: > > ```bash theme={"system"} > Host my-cvm > HostName -22..phala.network > User root > Port 443 > ProxyCommand openssl s_client -quiet -connect %h:%p -servername %h -verify_hostname %h -verify_return_error > ``` > > Replace `` with your application ID and `` with your cluster (e.g., `dstack-pha-prod7`). > > **macOS users:** If you encounter connection timeouts, you may have LibreSSL instead of OpenSSL. Install OpenSSL via Homebrew and use the full path: `/opt/homebrew/bin/openssl`. > > **Windows users:** Install OpenSSL via [Chocolatey](https://chocolatey.org/) (`choco install openssl`) and use the full path in ProxyCommand. Alternatively, use WSL where the Linux instructions work directly. ## What You Can Do Once connected, you have full access to debug and manage your CVM: ```bash theme={"system"} # Check containers docker ps -a docker logs # Monitor resources htop docker stats # Debug networking curl http://localhost:8080 netstat -tulpn ``` > [!TIP] > > Remember to switch to a Production OS image when you're done debugging. ## Troubleshooting | Issue | Solution | | - | - | | Permission denied | Check that Account Settings has the key you are using. Passwords are rejected. For a running CVM, use Code Update to add a key. | | Connection refused | Confirm you deployed with Development OS, not Production | | Connection timeout | Run `phala ssh -v` to see detailed connection info | For more detailed troubleshooting, see [Networking Troubleshooting](/phala-cloud/networking/troubleshooting#ssh-access-denied). # Expose an HTTP Service Source: https://docs.phala.com/phala-cloud/networking/expose-http-service Step-by-step guide to expose HTTP services with automatic HTTPS This guide shows you how to expose HTTP services from your Docker containers to the public internet with automatic HTTPS. ## Prerequisites * A Phala Cloud account * A Docker image that runs an HTTP service ## Step 1: Define Your Service Create a `docker-compose.yml` file with port mapping: ```yaml theme={"system"} services: api: image: your-image:latest ports: - "8080:3000" # Maps container port 3000 to public port 8080 ``` The format is `"HOST_PORT:CONTAINER_PORT"`, following standard Docker behavior: * `HOST_PORT`: The port number that appears in your public URL * `CONTAINER_PORT`: The port your application listens on inside the container ## Step 2: Deploy Your Service 1. Open the [Phala Cloud Dashboard](https://cloud.phala.com) 2. Click "Create CVM" 3. Select "docker-compose.yml" deployment method 4. Paste your configuration 5. Add any secure environment variables if needed 6. Click "Deploy" ## Step 3: Access Your Endpoint After deployment completes, find your endpoint in the Network tab: ```text theme={"system"} https://-8080.dstack-prod5.phala.network ``` Click the link to test your service. The connection is automatically secured with TLS. ## Multiple Ports Per Service A single service can expose any number of ports, just like in Docker: ```yaml theme={"system"} services: app: image: my-app:latest ports: - "3000:3000" # Web interface - "8080:8080" # API endpoint - "9090:9090" # Metrics endpoint - "4000:4000" # WebSocket server ``` This creates four public endpoints for the same service: * `https://-3000.dstack-prod5.phala.network` * `https://-8080.dstack-prod5.phala.network` * `https://-9090.dstack-prod5.phala.network` * `https://-4000.dstack-prod5.phala.network` ## Multiple Services Example You can also deploy multiple services, each with their own ports: ```yaml theme={"system"} services: frontend: image: my-frontend:latest ports: - "3000:3000" # Frontend on port 3000 api: image: my-api:latest ports: - "8080:8080" # API on port 8080 - "8081:8081" # API admin on port 8081 environment: DATABASE_URL: ${DATABASE_URL} admin: image: my-admin:latest ports: - "9000:9000" # Admin panel on port 9000 ``` ## Health Checks Add health checks to ensure your service is ready before receiving traffic: ```yaml theme={"system"} services: api: image: your-image:latest ports: - "8080:3000" healthcheck: test: ["CMD", "curl", "-f", "http://localhost:3000/health"] interval: 30s timeout: 10s retries: 3 start_period: 40s ``` ## Internal Communication Services within the same deployment can communicate using service names: ```yaml theme={"system"} services: frontend: image: my-frontend:latest ports: - "3000:3000" environment: API_URL: http://api:8080 # Internal communication api: image: my-api:latest ports: - "8080:8080" ``` The frontend can reach the API at `http://api:8080` internally, while external users access it at `https://-8080.dstack-prod5.phala.network`. ## Zero-Trust Security All traffic follows zero-trust principles: * External traffic arrives encrypted via TLS at the gateway * The gateway forwards it through WireGuard tunnels to your CVM * **Only your code inside the TEE can decrypt and see the traffic** * Not even Phala Cloud operators or you as the developer can inspect the traffic * The hardware-based isolation ensures complete privacy This means your application handles sensitive data with true confidentiality. Credit cards, API keys, personal information - all remain private to your code alone. ## Security Notes * All external traffic is encrypted with TLS * Internal service-to-service communication uses the Docker network * Don't expose ports you don't need public access to * Use secure environment variables for sensitive data ## Next Steps * [Set up a custom domain](/phala-cloud/networking/setup-custom-domain) * [Add gRPC support](/phala-cloud/networking/setup-grpc-service) * [Learn about security features](/phala-cloud/networking/security) # Expose TCP Services Source: https://docs.phala.com/phala-cloud/networking/expose-tcp-service Expose TCP services like databases with automatic TLS encryption ## Prerequisites * A deployed CVM on Phala Cloud * TCP service configured in your Docker Compose file * socat or Python installed locally (for TCP-over-TLS port forwarding) This guide shows you how to expose TCP services (databases, message queues, custom protocols) with automatic TLS encryption through the gateway. ## How It Works When you expose a TCP port, the gateway automatically wraps your traffic in TLS: 1. Client connects via TLS to `-..phala.network` 2. Gateway terminates TLS and decrypts the traffic 3. Gateway forwards plain TCP to your service inside the CVM 4. Your service doesn't need to handle TLS - the gateway does it for you This gives you encrypted connections without configuring certificates in your service. ## Example: PostgreSQL Database ```yaml theme={"system"} services: postgres: image: postgres:15 ports: - "5432:5432" # Expose PostgreSQL port environment: POSTGRES_PASSWORD: ${DB_PASSWORD} POSTGRES_DB: myapp POSTGRES_USER: dbuser volumes: - postgres-data:/var/lib/postgresql/data volumes: postgres-data: ``` After deployment, connect to your database: ```bash theme={"system"} # Direct TLS connection (if client supports it) psql "postgresql://dbuser:password@-5432.dstack-prod5.phala.network:443/myapp?sslmode=require" ``` ## Example: Custom TCP Service ```yaml theme={"system"} services: tcp-server: image: your-tcp-service:latest ports: - "9000:9000" # Your custom port environment: # No TLS configuration needed - gateway handles it PORT: 9000 ``` ## Connecting with TLS-to-TCP Conversion Many existing clients don't support connecting to TLS-wrapped TCP services. Use these methods to convert TLS back to plain TCP on your local machine: ### Port Forwarding Methods ```bash socat (Linux/macOS) theme={"system"} # Forward local port 5432 to PostgreSQL socat TCP-LISTEN:5432,bind=127.0.0.1,fork,reuseaddr \ OPENSSL:-5432.dstack-prod5.phala.network:443 # Now connect normally psql -h 127.0.0.1 -p 5432 -U dbuser myapp # Forward local port 9000 to custom service socat TCP-LISTEN:9000,bind=127.0.0.1,fork,reuseaddr \ OPENSSL:-9000.dstack-prod5.phala.network:443 # Connect with any TCP client telnet 127.0.0.1 9000 ``` ```bash Python (Cross-platform) theme={"system"} # Download the script from dstack-examples # https://github.com/Dstack-TEE/dstack-examples/blob/main/tcp-port-forwarding/port_forwarder.py # Forward local port 5432 to PostgreSQL python3 port_forwarder.py 5432 -5432.dstack-prod5.phala.network # Connect normally psql -h 127.0.0.1 -p 5432 -U dbuser myapp ``` ## Benefits * **Automatic encryption**: No need to configure TLS in your service * **Zero-trust security**: All external connections are encrypted * **Client compatibility**: Use TLS-to-TCP conversion for legacy clients * **Simple deployment**: Just expose the port, TLS is automatic ## Internal vs External Access Services can communicate internally without TLS: ```yaml theme={"system"} services: app: image: my-app:latest environment: # Internal: plain connection DB_HOST: postgres DB_PORT: 5432 postgres: image: postgres:15 ports: - "5432:5432" # External: TLS-wrapped by gateway ``` External clients use TLS, internal services use plain connections for better performance. ## Troubleshooting **Connection refused?** * Verify the port is exposed in docker-compose.yml * Check the service is running: SSH in and run `docker ps` **TLS handshake failed?** * Ensure you're connecting to port 443 (not the service port) * Use the correct hostname for TLS verification **socat not found?** * Install it: `apt install socat` (Ubuntu) or `brew install socat` (macOS) * Or use the Python script alternative ## Next Steps * [Set up gRPC services](/phala-cloud/networking/setup-grpc-service) * [Enable TLS passthrough](/phala-cloud/networking/tls-passthrough) for end-to-end encryption * [Configure custom domains](/phala-cloud/networking/setup-custom-domain) # Overview Source: https://docs.phala.com/phala-cloud/networking/overview Automatic HTTPS endpoints for your containers with zero configuration Phala Cloud gives you automatic HTTPS endpoints for your containers. Deploy your service and get a secure public URL — no TLS or proxy configuration needed. ## What You Get Every container you deploy gets: * Public HTTPS endpoints that just work * Automatic TLS certificates (no Let's Encrypt setup) * Full internet access with any protocol * Built-in load balancing Your application URL looks like this: ``` https://-.dstack-prod5.phala.network ``` Deploy on port 8080? Your URL is `https://appid-8080.dstack-prod5.phala.network`. Deploy on port 3000? It's `https://appid-3000.dstack-prod5.phala.network`. Simple. ## Zero Configuration Required Just define your service in docker-compose.yml: ```yaml theme={"system"} services: web: image: nginx:alpine ports: - "8000:80" ``` Deploy it and you're done. No reverse proxy setup needed. No certificate management required. No firewall rules to configure. ## Use Your Own Domain Want `api.mycompany.com` instead of the default URL? Add the dstack-ingress container to your deployment. It handles DNS setup and SSL certificates automatically through your DNS provider (Cloudflare, Linode, or Namecheap). ## Beyond HTTP Phala Cloud handles more than just web services: **Databases**: Expose PostgreSQL or MySQL with automatic TLS encryption. Your database connections are secure by default. **gRPC Services**: Full HTTP/2 support. Access gRPC endpoints by appending `g` to your URL (e.g., `appid-8080g.dstack-prod5.phala.network`). **TCP Services**: Any TCP protocol works - Redis, custom game servers, message queues. All get automatic TLS wrapping. **SSH Access**: Debug your containers with SSH access (development mode only). ## What's Next? Ready to deploy something? The [quickstart](/phala-cloud/networking/quickstart) gets you running in 5 minutes. Need to do something specific? Check our guides: * [Expose an HTTP service](/phala-cloud/networking/expose-http-service) * [Set up a custom domain](/phala-cloud/networking/setup-custom-domain) * [Enable SSH access](/phala-cloud/networking/enable-ssh-access) * [Configure gRPC services](/phala-cloud/networking/setup-grpc-service) Want the technical details? See our [architecture deep dive](/phala-cloud/networking/architecture). Questions about security? Check our [security model](/phala-cloud/networking/security). # Quickstart Source: https://docs.phala.com/phala-cloud/networking/quickstart Deploy a service with public HTTPS access in under 5 minutes This quickstart shows you how to deploy a web service with public HTTPS access. ## Deploy Your First Service Create a file named `docker-compose.yml`: ```yaml theme={"system"} services: web: image: nginx:alpine ports: - "8000:80" ``` Deploy through the [Phala Cloud Dashboard](https://cloud.phala.com): 1. Click "Create CVM" 2. Select "docker-compose.yml" 3. Paste the file above 4. Click "Deploy" ## Access Your Service After deployment completes (about 2 minutes), find your endpoint in the dashboard: ```text theme={"system"} https://-8000.dstack-prod5.phala.network ``` The format is always `-..phala.network`. Your app ID is generated automatically. Click the link to see the nginx welcome page. Your service is now publicly accessible via HTTPS. ## What You've Deployed Your nginx container is now: * Running in a Confidential Virtual Machine (Intel TDX) * Accessible via HTTPS with automatic TLS certificates * Connected through secure WireGuard tunneling ## Next Steps * [Expose multiple ports](/phala-cloud/networking/expose-http-service) * [Set up a custom domain](/phala-cloud/networking/setup-custom-domain) * [Connect a database](/phala-cloud/networking/expose-tcp-service) * [Understand the security model](/phala-cloud/networking/security) # Network Security Source: https://docs.phala.com/phala-cloud/networking/security How Phala Cloud keeps your network traffic private even from the cloud provider ## Network Privacy Through Hardware Run your application on Phala Cloud without trusting us to keep your data private—the hardware guarantees it. Intel TDX encrypts your application's memory with keys that never leave the CPU. The host OS cannot decrypt your data because the hardware prevents it. When clients connect to your application, traffic passes through multiple layers of encryption. Each layer protects against different attacks. You can verify all of this through cryptographic attestation. ## How It Works: The Big Picture Your application runs inside a Confidential VM (CVM). When clients connect, their requests flow through a gateway that's also hardware-protected: ```mermaid theme={"system"} graph LR Client["Client
(Browser)"] Gateway["Gateway TEE
- TLS termination
- Certificate mgmt
- Verifiable code"] CVM["Your CVM (TEE)
- Your application
- Your data
- Verifiable code"] Client -->|TLS| Gateway Gateway -->|WireGuard| CVM Gateway <-.->|Mutual Attestation| CVM ``` Both the gateway and your CVM run inside Intel TDX Trusted Execution Environments. The infrastructure operator cannot access their memory or keys because the hardware prevents it. Before any connection is established, the gateway and your CVM verify each other through cryptographic attestation. This ensures you're always connecting to genuine TEE instances, not imposters. TLS certificate private keys are generated inside the TEE and never leave. The keys get sealed to specific hardware measurements, so only verified TEE instances can use them. DNS security records lock your domain to the TEE's certificate account, preventing unauthorized certificate issuance. For network topology and routing details, see [Architecture](/phala-cloud/networking/architecture). ## Security Model ### What We Protect Against **Compromised host OS**: Hardware encrypts your CVM's memory with keys the host cannot access. Even with root access, attackers cannot read your application's memory or network traffic. **Malicious infrastructure operator**: The gateway runs in its own TEE. Even with full infrastructure access, the operator cannot access the gateway's memory, keys, or decrypt your traffic. Both gateway and CVM verify each other before establishing connections. **Certificate compromise**: Certificate private keys are generated inside TEEs and cryptographically bound to hardware measurements. DNS security records prevent unauthorized certificate issuance. Even a compromised certificate authority cannot issue valid certificates without TEE control. **Certificate misissuance**: Public certificate transparency logs track all certificate issuance. Combined with DNS security records, this provides detection and prevention of unauthorized certificates. ### What You Need to Trust The security model shifts trust from people and organizations to hardware and verifiable code. **You don't need to trust the infrastructure.** The gateway operator can't access gateway memory, keys, or traffic because the gateway runs in its own TEE. Other CVMs on the same host can't reach your data due to hardware-enforced isolation. Even the host operating system can't inspect your memory because TEE protection prevents it. Infrastructure providers have no access that can compromise TEEs. **You still need to trust three things.** First, your own application code—application vulnerabilities are your responsibility. Second, the TDX hardware security itself, as Intel's hardware implementation forms the root of trust. Third, the certificate authorities like Let's Encrypt must be trustworthy, though this risk is mitigated by CAA records and CT monitoring. ### Out of Scope **Application security**: Network security doesn't protect against application vulnerabilities. Your code must handle input validation, authentication, and authorization correctly. **Availability attacks**: DDoS protection and high availability are not guaranteed. Design your applications with redundancy and rate limiting as needed. **Side-channel attacks**: Advanced timing attacks or speculative execution vulnerabilities may leak information. Follow secure coding practices and keep software updated. ## Gateway Security Architecture The gateway routes traffic between clients and your CVM while maintaining zero-trust security. Understanding how the gateway works helps explain why even infrastructure operators can't compromise your connections. ### Gateway TEE Protection The gateway itself runs inside an Intel TDX Confidential VM: * Operator cannot access TLS keys or decrypt traffic * Gateway code is verifiable through attestation * All certificate operations happen inside the TEE This means the infrastructure operator has no access to certificate private keys, TLS session keys, or plaintext traffic, even though they control the physical servers. For network routing and load balancing details, see [Architecture: How Routing Works](/phala-cloud/networking/architecture#how-routing-works). ### Mutual Attestation Protocol Before any traffic flows, the gateway and your CVM verify each other. This prevents man-in-the-middle attacks and ensures both sides are genuine TEE instances running verified code: 1. **Attestation First**: Both the gateway TEE and your CVM generate TDX attestation quotes 2. **Mutual Verification**: Each side verifies the other's attestation before proceeding 3. **Key Exchange**: Only after successful attestation do they exchange tunnel keys 4. **Tunnel Creation**: An encrypted tunnel is established using ChaCha20-Poly1305 5. **Continuous Encryption**: All traffic flows through this attested tunnel, invisible to the host This attestation requirement ensures you're always connecting to genuine TEE instances, not imposters. Even after TLS termination at the gateway, your data remains encrypted until it reaches your container. ## Zero-Trust HTTPS (zt-https) TLS certificate private keys are generated inside TEEs and never leave. The keys stay sealed to hardware measurements. Only verified TEE instances can use them. This means certificate private keys remain under TEE control at all times. ### How TEEs Control Certificates Both Phala Cloud gateway domains (via gateway) and custom domains (via dstack-ingress) implement Zero-Trust HTTPS: 1. **TEE generates ECDSA keypair**: The private key is created inside TDX-encrypted memory and never leaves the TEE 2. **Registers with Let's Encrypt**: The TEE establishes its own certificate account using the key 3. **Seals credentials to hardware**: Keys are bound to specific TEE measurements, so only this exact TEE configuration can use them 4. **Requests certificates**: Certificate operations happen entirely inside the TEE The private keys never exist outside the TEE. They're stored on encrypted disk that only the TEE can decrypt, sealed to hardware measurements. Even with full host access, attackers can't extract or use these keys because the hardware cryptographically binds them to the TEE instance. ### Certificate Architecture Zero-Trust HTTPS uses three mechanisms to prevent unauthorized certificate issuance: **CAA DNS Records**: Lock your domain to a specific ACME account ``` your-domain.com CAA 0 issue "letsencrypt.org;accounturi=https://acme-v02.api.letsencrypt.org/acme/acct/YOUR_TEE" ``` This prevents anyone else from getting valid certificates, even with domain control. The certificate authority checks this DNS record before issuing certificates. **Certificate Transparency Monitoring**: Every certificate issuance gets logged publicly. Monitor these logs to detect any unauthorized certificates immediately. Certificate Transparency logs are append-only and publicly auditable. **Cryptographic Evidence**: Custom domains publish proof at `/evidences/` containing: * TDX attestation quote proving hardware backing * SHA256 hash linking the certificate to the ACME account * The actual certificate and account details This creates an auditable chain: the hardware signs the evidence, the evidence contains the certificate, and the certificate serves your traffic. Any tampering breaks the cryptographic chain. ### Preventing Timeline Attacks CAA records only protect future certificate issuance. Existing certificates remain valid until expiration. To ensure complete security: 1. **Check historical certificates**: Review all certificates ever issued for your domain 2. **Verify expiration**: Ensure pre-deployment certificates have expired 3. **Revoke if necessary**: Contact the CA to revoke any unexpired legacy certificates This prevents attackers from using certificates obtained before your TEE deployment. Check Certificate Transparency logs for your domain to see all historical issuance. ### Verification Procedures For step-by-step instructions on verifying certificate control and attestation: * **Gateway domains** (`*.phala.network`): See [Domain Attestation: Gateway Domains](/phala-cloud/networking/domain-attestation#gateway-domains) * **Custom domains**: See [Domain Attestation: Custom Domains](/phala-cloud/networking/domain-attestation#custom-domains) These guides provide complete verification procedures including TDX quote validation, Certificate Transparency monitoring, and CAA record auditing. ## Advanced Privacy with Tor Tor adds an additional layer of network-level anonymity on top of TEE protection. Need network-layer anonymity? Deploy Tor inside your CVM: ```yaml theme={"system"} services: tor: image: torproject/tor volumes: - ./torrc:/etc/tor/torrc app: network_mode: "service:tor" ``` Users connect via .onion addresses. Traffic correlation becomes nearly impossible. TEE attestation still works, so you can cryptographically verify your Tor node runs in a genuine TEE. This combines TEE hardware protection with Tor's network-layer anonymity for maximum privacy. ## Compliance and Standards Hardware-enforced security helps meet regulatory requirements. TEE isolation, encryption at rest and in transit, and cryptographic attestation provide technical controls for GDPR Article 32, HIPAA technical safeguards, and PCI DSS network segmentation. The infrastructure provides several compliance-relevant protections: * Memory encryption (TLS 1.3, WireGuard, TDX) * Hardware isolation between tenants * Cryptographic audit trails via attestation * FIPS-approved cryptography However, infrastructure security alone doesn't guarantee compliance. You still need to handle application-level requirements: * Secure coding practices * Authentication and authorization logic * Data retention and deletion policies Your application design and implementation ultimately determine whether you meet regulatory requirements. ## Technical References * [Intel TDX Architecture Specification](https://intel.com/content/www/us/en/developer/articles/technical/intel-trust-domain-extensions.html) * [WireGuard Protocol Paper](https://wireguard.com/papers/wireguard.pdf) * [RFC 8555: ACME Protocol](https://datatracker.ietf.org/doc/html/rfc8555) * [RFC 9162: Certificate Transparency](https://datatracker.ietf.org/doc/html/rfc9162) # Set Up a Custom Domain Source: https://docs.phala.com/phala-cloud/networking/setup-custom-domain Use your own domain with automatic SSL certificates This guide shows you how to use your own domain (like `api.mycompany.com`) instead of the default Phala Cloud domain. ## Prerequisites * A domain with DNS hosted on Cloudflare (Linode and Namecheap also supported) * Access to your DNS provider's API token * A deployed CVM application ## Step 1: Create DNS API Token > [tab] Cloudflare > > 1. Go to your [Cloudflare Dashboard](https://dash.cloudflare.com/) > 2. Select your domain > 3. Go to **Get Your API Token** > 4. Click **Create Token** > 5. Use the **Edit zone DNS** template > 6. Select your domain in **Zone Resources** > 7. Click **Continue to summary** and create the token > 8. Copy the token for later use > [tab] Linode > > 1. Go to [Linode Cloud Manager](https://cloud.linode.com/) > 2. Click on your profile → **API Tokens** > 3. Create a **Personal Access Token** with Read/Write access to Domains > 4. Copy the token for later use > [tab] Namecheap > > 1. Enable API access in your [Namecheap account](https://www.namecheap.com/myaccount/login/) > 2. Go to **Profile → Tools → API Access** > 3. Note your username and API key ## Step 2: Add dstack-ingress to Your Deployment Update your `docker-compose.yml` to include the dstack-ingress container: ```yaml theme={"system"} services: dstack-ingress: image: dstacktee/dstack-ingress:2.2@sha256:d05a7b343c37c1cca1bba8dbf7e8f3c6d2118158af2d41c455103796db4f67f0 ports: - "443:443" environment: - DOMAIN=api.mycompany.com # Your custom domain - TARGET_ENDPOINT=app:80 # Your app's internal endpoint - CLOUDFLARE_API_TOKEN=${CLOUDFLARE_API_TOKEN} - GATEWAY_DOMAIN=gateway.${DSTACK_GATEWAY_DOMAIN} - CERTBOT_EMAIL=${CERTBOT_EMAIL} - SET_CAA=true volumes: - /var/run/dstack.sock:/var/run/dstack.sock - /var/run/tappd.sock:/var/run/tappd.sock - cert-data:/etc/letsencrypt - evidences:/evidences restart: unless-stopped app: image: your-app:latest # Your application volumes: - evidences:/evidences:ro # No ports exposed here - dstack-ingress handles external access volumes: cert-data: # Persistent storage for SSL certificates evidences: # Generated attestation evidence files ``` Set `DOMAIN` to your custom domain and `TARGET_ENDPOINT` to your app's internal endpoint. `TARGET_ENDPOINT` tells dstack-ingress where to forward incoming traffic: * `app:80` - Forward to service named "app" on port 80 * `api:3000` - Forward to service named "api" on port 3000 * `http://app:80` and `grpc://app:50051` are also accepted, but the protocol prefix is stripped before proxying * Use the service name from docker-compose, not localhost > [!NOTE] > > `dstack-ingress` is a HAProxy-based L4/TCP proxy. It terminates TLS and forwards the TCP stream to `TARGET_ENDPOINT`; it does not apply Nginx-style HTTP redirects, header rules, body limits, or buffering settings. Put HTTP-specific behavior in your application or in a separate HTTP proxy behind `TARGET_ENDPOINT` if needed. > [!WARNING] > > `GATEWAY_DOMAIN` becomes your domain's CNAME target, and its first label must > start with a letter or digit. Android rejects a leading underscore, so the > older `_.${DSTACK_GATEWAY_DOMAIN}` form resolves everywhere except Android — > change it to `gateway.${DSTACK_GATEWAY_DOMAIN}` if your deployment still has it. ## Step 3: Configure Environment Variables In the Phala Cloud dashboard, add these encrypted secrets: > [tab] Cloudflare > > * `CLOUDFLARE_API_TOKEN`: Your API token from Step 1 > * `CERTBOT_EMAIL`: Your email for Let's Encrypt notifications > [tab] Linode > > * `LINODE_API_TOKEN`: Your API token from Step 1 > * `CERTBOT_EMAIL`: Your email for Let's Encrypt notifications > [tab] Namecheap > > * `NAMECHEAP_USERNAME`: Your Namecheap username > * `NAMECHEAP_API_KEY`: Your API key from Step 1 > * `NAMECHEAP_CLIENT_IP`: Your whitelisted IP address > * `CERTBOT_EMAIL`: Your email for Let's Encrypt notifications ## Step 4: Deploy Deploy your updated docker-compose.yml through the dashboard. The first deployment typically takes 3–5 minutes as it: 1. Configures DNS records 2. Requests SSL certificate from Let's Encrypt 3. Starts the HAProxy TCP proxy ## Step 5: Verify After deployment, you can: 1. **Access your domain**: Visit `https://api.mycompany.com` 2. **Check certificate**: Your browser should show a valid Let's Encrypt certificate 3. **Verify evidence**: Visit `https://api.mycompany.com/evidences/` to see attestation data ## Multiple Custom Domains You can route multiple custom domains from one ingress container by using `DOMAINS` and `ROUTING_MAP`: ```yaml theme={"system"} services: ingress: image: dstacktee/dstack-ingress:2.2@sha256:d05a7b343c37c1cca1bba8dbf7e8f3c6d2118158af2d41c455103796db4f67f0 ports: - "443:443" environment: DNS_PROVIDER: cloudflare CLOUDFLARE_API_TOKEN: ${CLOUDFLARE_API_TOKEN} CERTBOT_EMAIL: ${CERTBOT_EMAIL} GATEWAY_DOMAIN: gateway.${DSTACK_GATEWAY_DOMAIN} SET_CAA: true DOMAINS: | app.mycompany.com api.mycompany.com ROUTING_MAP: | app.mycompany.com=frontend:3000 api.mycompany.com=api:8080 volumes: - /var/run/dstack.sock:/var/run/dstack.sock - /var/run/tappd.sock:/var/run/tappd.sock - cert-data:/etc/letsencrypt - evidences:/evidences restart: unless-stopped api: image: my-api:latest volumes: - evidences:/evidences:ro frontend: image: my-frontend:latest volumes: - evidences:/evidences:ro volumes: cert-data: evidences: ``` ## Why We Pin Infrastructure Images The dstack-ingress image uses a SHA256 hash instead of a tag to ensure: * **Auditability**: Anyone can verify the exact infrastructure code handling domains * **Immutability**: The ingress behavior never changes unexpectedly * **Security**: Prevents infrastructure image substitution * **Reproducibility**: Domain handling is consistent across all deployments ## Security Features When `SET_CAA=true` is enabled: * CAA records restrict certificate issuance to the TEE managed Let's Encrypt account * Only certificates requested from within your TEE can be issued * Certificate transparency logs can be monitored for unauthorized certificates > [!WARNING] > > **Cloudflare Users**: Cloudflare automatically overrides CAA records at the apex domain (e.g., `example.com`). This prevents domain attestation from working correctly. > > **Solution options:** > > 1. **Use a subdomain** (recommended): Deploy to `app.example.com` instead of `example.com` > 2. **Disable Cloudflare's CAA management**: See [Cloudflare CAA documentation](https://developers.cloudflare.com/ssl/edge-certificates/caa-records/#caa-records-added-by-cloudflare) > > **To verify your CAA record is working:** > > ```bash theme={"system"} > dig @1.1.1.1 +short CAA your-domain.com > ``` > > Should return the Let's Encrypt account URI with `validationmethods=dns-01;accounturi=...` ## Troubleshooting ### Check Logs Look for dstack-ingress container logs in the dashboard: ```text theme={"system"} Successfully received certificate. Generated evidences successfully Next renewal check in 12 hours ``` ### Certbot Error: "too many certificates (5) already issued for this exact set of identifiers" You may have forgotten to attach the data volume. ### Other Common Issues **DNS not propagating**: Wait 2-5 minutes for DNS changes to propagate globally. **Certificate request failed**: Verify your API token has permission to edit DNS records. **Connection refused**: Ensure `TARGET_ENDPOINT` points to the correct service:port. **CAA record conflicts**: Some providers (like Linode) don't allow CAA and CNAME on the same subdomain. The system will automatically use A records instead. ## Next Steps * [Expose TCP services](/phala-cloud/networking/expose-tcp-service) * [Learn about domain attestation](/phala-cloud/networking/domain-attestation) * [Set up gRPC with custom domain](/phala-cloud/networking/setup-grpc-service) # Set Up gRPC Services Source: https://docs.phala.com/phala-cloud/networking/setup-grpc-service Deploy gRPC services with HTTP/2 and automatic TLS ## Prerequisites * A deployed CVM on Phala Cloud * Docker image with gRPC service * gRPC client tools for testing This guide shows you how to deploy gRPC services with native HTTP/2 support and automatic TLS encryption. ## How gRPC Works Through the Gateway gRPC services get special HTTP/2 treatment: 1. Add a `g` suffix to your port: `-g..phala.network` 2. Gateway detects the `g` suffix and enables HTTP/2 via ALPN negotiation 3. gRPC traffic flows over HTTP/2 with automatic TLS termination 4. Your service handles standard gRPC calls without TLS configuration **Note**: The `g` suffix enables HTTP/2 for any service, not just gRPC. You can use it for any HTTP/2-compatible application that benefits from multiplexing, server push, or header compression. ## Deploy Your gRPC Service ```yaml theme={"system"} services: grpc-server: image: your-grpc-service:latest ports: - "50051:50051" # Standard gRPC port environment: GRPC_PORT: 50051 # No TLS config needed - gateway handles it ``` Access your gRPC service at: `-50051g.dstack-prod5.phala.network:443` Note the `g` suffix - this tells the gateway to enable HTTP/2. ## Connect from Clients ```go Go theme={"system"} // Go client conn, err := grpc.Dial( "-50051g.dstack-prod5.phala.network:443", grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{ ServerName: "-50051g.dstack-prod5.phala.network", })), ) ``` ```python Python theme={"system"} # Python client channel = grpc.secure_channel( '-50051g.dstack-prod5.phala.network:443', grpc.ssl_channel_credentials() ) ``` ```javascript Node.js theme={"system"} // Node.js client const credentials = grpc.credentials.createSsl(); const client = new YourService( '-50051g.dstack-prod5.phala.network:443', credentials ); ``` ## gRPC with Custom Domains Use dstack-ingress for custom domains: ```yaml theme={"system"} services: dstack-ingress: image: dstacktee/dstack-ingress:2.2@sha256:d05a7b343c37c1cca1bba8dbf7e8f3c6d2118158af2d41c455103796db4f67f0 ports: - "443:443" environment: - DOMAIN=api.mycompany.com - TARGET_ENDPOINT=grpc-server:50051 - ALPN=h2 # Allow gRPC clients to negotiate HTTP/2 - CLOUDFLARE_API_TOKEN=${CLOUDFLARE_API_TOKEN} - GATEWAY_DOMAIN=gateway.${DSTACK_GATEWAY_DOMAIN} - CERTBOT_EMAIL=${CERTBOT_EMAIL} volumes: - /var/run/dstack.sock:/var/run/dstack.sock - /var/run/tappd.sock:/var/run/tappd.sock - cert-data:/etc/letsencrypt - evidences:/evidences grpc-server: image: your-grpc-service:latest volumes: cert-data: evidences: ``` Then connect to: `api.mycompany.com`. Learn more details at [Set up custom domains](/phala-cloud/networking/setup-custom-domain). `dstack-ingress` terminates TLS and forwards raw TCP to the backend. For gRPC custom domains, set `ALPN=h2` so clients can negotiate HTTP/2 over TLS; your backend should accept cleartext HTTP/2 on `TARGET_ENDPOINT`. ## Testing with grpcurl ```bash theme={"system"} # List services grpcurl -50051g.dstack-prod5.phala.network:443 list # Call a method grpcurl -d '{"name": "world"}' \ -50051g.dstack-prod5.phala.network:443 \ your.service.v1.YourService/SayHello ``` ## Key Differences **gRPC (with `g` suffix):** * Native HTTP/2 with ALPN negotiation * Optimal performance for gRPC protocols * Proper streaming support **Regular HTTP:** * Standard HTTP/1.1 or HTTP/2 * Best for REST APIs and web applications * No gRPC-specific optimizations ## Internal vs External ```yaml theme={"system"} services: grpc-client: environment: GRPC_SERVER: grpc-server:50051 # Internal: direct connection grpc-server: ports: - "50051:50051" # External: HTTP/2 via gateway ``` ## Troubleshooting **No HTTP/2 negotiation?** Use the `g` suffix and verify ALPN support. **Connection refused?** Check port mapping and service status. **TLS errors?** Connect to port 443 with correct hostname. ## Next Steps * [Expose TCP services](/phala-cloud/networking/expose-tcp-service) * [Set up custom domains](/phala-cloud/networking/setup-custom-domain) * [Learn about security](/phala-cloud/networking/security) # Reference Source: https://docs.phala.com/phala-cloud/networking/specifications Quick lookup for URL patterns, environment variables, and configuration parameters ## URL Patterns | Pattern | Protocol | Example | | - | - | - | | `{app-id}.{cluster}.phala.network` | HTTP/HTTPS to port 80 (default) | `abc123.dstack-prod5.phala.network` | | `{app-id}-{port}.{cluster}.phala.network` | HTTP/HTTPS (TLS termination) | `deadbeef111111111111111111111111-8080.dstack-prod5.phala.network` | | `{app-id}-{port}g.{cluster}.phala.network` | gRPC/HTTP2 | `deadbeef111111111111111111111111-50051g.dstack-prod5.phala.network` | | `{app-id}s.{cluster}.phala.network` | TLS passthrough to port 443 (default) | `abc123s.dstack-prod5.phala.network` | | `{app-id}-{port}s.{cluster}.phala.network` | TLS passthrough | `deadbeef111111111111111111111111-5432s.dstack-prod5.phala.network` | | `{app-id}-22.{cluster}.phala.network` | SSH tunnel | `deadbeef111111111111111111111111-22.dstack-prod5.phala.network` | **Default Port Behaviors:** * No port specified = routes to port 80 for HTTP or port 443 for TLS passthrough * All external connections use port 443 regardless of internal port * `{app-id}` is auto-generated on deployment * `{port}` matches your container's exposed port * `{cluster}` is regional (us, eu, asia) ## Auto-populated Environment Variables You can use these variables in your docker-compose file: | Variable | Value | Example | | - | - | - | | `DSTACK_APP_ID` | Application identifier | `abc123def456` | | `DSTACK_GATEWAY_DOMAIN` | Regional domain | `us.phala.network` | ## Environment Variables The variables you can change to config networking features. ### SSH Access | Variable | Type | Purpose | | - | - | - | | `DSTACK_ROOT_PASSWORD` | string | Root password inside the CVM (dev images only). SSH rejects it since dstack 0.5.6 | | `DSTACK_ROOT_PUBLIC_KEY` | string | SSH public key (dev images only) | ### Custom Domains | Variable | Required | Type | Purpose | | | | - | - | - | - | - | - | | `DOMAIN` | Conditional | string | Single custom domain name; use `DOMAINS` for multi-domain mode | | | | `DOMAINS` | Conditional | string | Multiple custom domain names, one per line | | | | `TARGET_ENDPOINT` | Conditional | string | Backend address for single-domain mode, such as `app:80`; protocol prefixes like `http://` and `grpc://` are accepted and stripped | | | | `ROUTING_MAP` | Conditional | string | Multi-domain routing entries, one `domain=service:port` entry per line | | | | `GATEWAY_DOMAIN` | Yes | string | `gateway.${DSTACK_GATEWAY_DOMAIN}` | | | | `CERTBOT_EMAIL` | Yes | string | Let's Encrypt email | | | | `SET_CAA` | No | boolean | Enable CAA records (default: false) | | | | `DNS_PROVIDER` | No | string | \`cloudflare | linode | namecheap\` (auto-detected) | | `ALPN` | No | string | TLS ALPN protocols, such as `h2` for gRPC custom domains | | | ### DNS Provider Credentials | Provider | Variables | Required Permissions | | - | - | - | | Cloudflare | `CLOUDFLARE_API_TOKEN` | Zone:Read, DNS:Edit | | Linode | `LINODE_API_TOKEN` | Domains:Read/Write | | Namecheap | `NAMECHEAP_USERNAME`, `NAMECHEAP_API_KEY`, `NAMECHEAP_CLIENT_IP` | API enabled | ## Protocol Support | Protocol | Default Mode | TLS Passthrough Mode | Egress Traffic | | - | - | - | - | | HTTP/1.1 | ✅ | ✅ | ✅ | | HTTP/2 | ✅ (with `g` suffix) | ✅ | ✅ | | WebSocket | ✅ | ✅ | ✅ | | TCP | ❌ | ✅ (with `s` suffix) | ✅ | | UDP | ⚠️ (NAT traversal) | N/A | ✅ | ## Docker Images | Component | Image | Hash | | - | - | - | | Custom domains | `dstacktee/dstack-ingress:2.2` | `sha256:d05a7b343c37c1cca1bba8dbf7e8f3c6d2118158af2d41c455103796db4f67f0` | ## Rate Limits ### DNS Providers | Provider | API Limits | Certificate Speed | | - | - | - | | Cloudflare | 1200 req/5min | 1-2 minutes | | Linode | 800 req/hour | 2-5 minutes | | Namecheap | 50 req/hour | 5-15 minutes | ### Let's Encrypt | Limit | Rate | | - | - | | Certificates per domain | 50/week | | Duplicate certificates | 5/week | | Failed validations | 5/hour per hostname | # TLS Passthrough Source: https://docs.phala.com/phala-cloud/networking/tls-passthrough Set up end-to-end encryption with TLS passthrough for databases and custom protocols ## Prerequisites * A deployed CVM on Phala Cloud * TLS certificates for your service * Custom domain configured (for production use) TLS passthrough forwards encrypted traffic directly to your service, enabling end-to-end encryption and advanced TLS features like client certificates. ## When to Use TLS Passthrough Phala Cloud networking infra always ensure end-to-end encryption. You can still choose TLS-termination in TEE protected gateway or passthrough model. **Use passthrough when you need:** * Client certificate authentication (mTLS) * Custom TLS configurations * Database connections with specific TLS requirements **Use TLS termination when you need:** * Simple HTTP/HTTPS services * Automatic certificate management * Load balancing with health checks * Maximum compatibility with clients ## How TLS Passthrough Works 1. Client connects with TLS to `-s.dstack-prod5.phala.network:443` 2. Gateway detects the `s` suffix in the SNI and enables passthrough mode 3. Gateway forwards the encrypted TLS stream directly to your service without decryption 4. Your service handles the TLS handshake and decryption 5. All traffic remains encrypted between client and your application The `s` suffix immediately after the port number tells the gateway to use passthrough mode instead of TLS termination. ## When TLS Passthrough is Actually Useful TLS passthrough is practical for services that need to handle TLS themselves, typically when using custom domains with dstack-ingress or for specific protocols that require end-to-end TLS control. ### Custom Domain with Self-Managed TLS When using your own domain with dstack-ingress, you might want to handle TLS directly: ```yaml theme={"system"} services: api: image: your-api:latest ports: - "8443:8443" # Custom HTTPS port environment: # TLS cert data from environment variables (encrypted deployment) TLS_CERT_PEM: ${TLS_CERT_PEM} TLS_KEY_PEM: ${TLS_KEY_PEM} PORT: 8443 TLS_ENABLED: "true" ``` Then clients connect via TLS passthrough: ```bash theme={"system"} curl https://deadbeef111111111111111111111111-8443s.dstack-prod5.phala.network/api/status ``` Your application handles the TLS termination and can implement custom certificate validation, cipher selection, or client certificate requirements. ### Proxying External TLS Services Building a proxy that preserves TLS context: ```yaml theme={"system"} services: tls-proxy: image: nginx:alpine ports: - "9443:9443" environment: UPSTREAM_HOST: external-api.example.com UPSTREAM_PORT: 443 # Nginx configured to proxy raw TLS streams ``` ### gRPC with Custom TLS Configuration When you need specific TLS settings for gRPC: ```yaml theme={"system"} services: grpc-server: image: your-grpc:latest ports: - "50051:50051" environment: GRPC_TLS_CERT: ${GRPC_TLS_CERT} GRPC_TLS_KEY: ${GRPC_TLS_KEY} # Custom cipher suites, client cert requirements, etc. ``` **Practical note**: TLS passthrough is most useful when you have custom domains (via dstack-ingress) or need to implement specific TLS behaviors that the gateway's automatic TLS termination doesn't support. ## Security Considerations ### Benefits of TLS Passthrough * **Client certificate support**: Enable mTLS authentication * **Custom TLS settings**: Full control over TLS configuration * **Zero gateway trust**: Gateway cannot inspect or modify traffic ### Limitations * **Certificate management**: You handle all certificate operations * **No load balancer health checks**: Gateway cannot inspect traffic for health * **Client compatibility**: Clients must support your TLS configuration * **Debugging difficulty**: Encrypted traffic harder to troubleshoot ### Best Practices * Pass certificate data via encrypted environment variables * Use well-known certificate authorities when possible * Test TLS configuration with standard clients * Monitor application logs for TLS-related errors ## Troubleshooting **Connection refused?** * Confirm you're using the `s` suffix in the URL: `-s.domain:443` * Verify service is configured for TLS and listening on the correct port * Check port mapping in docker-compose.yml **TLS handshake failures?** * Ensure your application is properly handling TLS * Check that certificates are loaded correctly from environment variables * Verify cipher suite compatibility between client and server **Gateway routing issues?** * Confirm the URL format includes the `s` suffix immediately after the port * Test with tools like `socat` or the Python port forwarder from dstack-examples ## Next Steps * [Learn about network security](/phala-cloud/networking/security) * [Set up custom domains](/phala-cloud/networking/setup-custom-domain) * [Understand network architecture](/phala-cloud/networking/architecture) # Troubleshooting Source: https://docs.phala.com/phala-cloud/networking/troubleshooting Diagnosing and fixing common networking issues This guide helps you diagnose and resolve networking problems in Phala Cloud. ## Connection Refused Your service isn't responding on the expected port. ### Quick Checks ```bash theme={"system"} # 1. SSH into CVM (development OS only) ssh my-cvm # 2. Check if container is running docker ps # 3. Check container logs for errors docker logs --tail 50 # 4. Test local connectivity curl http://localhost:8080 ``` ### Common Causes **Port not exposed in docker-compose.yml:** ```yaml theme={"system"} services: app: ports: - "8080:8080" # Add this ``` **Service binding to localhost instead of all interfaces:** ```javascript theme={"system"} // Wrong - only localhost can connect app.listen(3000, '127.0.0.1'); // Right - accepts external connections app.listen(3000, '0.0.0.0'); ``` **Container crashed on startup:** ```bash theme={"system"} # Check exit code and reason docker ps -a docker logs ``` ## Connection Timeout The connection hangs without immediate response. ### Diagnosis Steps ```bash theme={"system"} # 1. Test if gateway is reachable curl -I https://-8080.dstack-prod5.phala.network # 2. Check TLS handshake openssl s_client -connect -8080.dstack-prod5.phala.network:443 # 3. Inside CVM, check if service is listening netstat -tulpn | grep 8080 ``` ### Common Causes **Service still starting:** Some applications take time to initialize. Check logs for startup progress. **Wrong URL format:** ```bash theme={"system"} # Correct - always use port 443 externally https://-8080.dstack-prod5.phala.network # Wrong - don't add port to URL https://-8080.dstack-prod5.phala.network:8080 ``` ## TLS/Certificate Errors ### TLS Handshake Failed For default mode (TLS termination): ```bash theme={"system"} # Test the connection curl -v https://-8080.dstack-prod5.phala.network # Check certificate details openssl s_client -connect -8080.dstack-prod5.phala.network:443 \ -servername -8080.dstack-prod5.phala.network ``` For passthrough mode (`s` suffix): ```bash theme={"system"} # Your service must handle TLS # Inside CVM, verify TLS is configured curl https://localhost:8080 ``` ### Certificate Hostname Mismatch In passthrough mode, you have two options: **Option 1: Use a custom domain with dstack-ingress** ```bash theme={"system"} # Your certificate CN should match your custom domain openssl x509 -in server.crt -text -noout | grep CN # Should show: CN=your-domain.com ``` **Option 2: Configure your service to ignore hostname validation** ```javascript theme={"system"} // For development only - accepts any certificate const server = https.createServer({ key: fs.readFileSync('server.key'), cert: fs.readFileSync('server.crt'), // Don't verify hostname requestCert: false }); ``` Note: You cannot get a valid certificate for `*.phala.network` domains. Use passthrough mode primarily with custom domains or for protocols that handle certificates differently (like some databases). ## Custom Domain Issues ### DNS Not Resolving ```bash theme={"system"} # Check if DNS records exist dig CNAME your-domain.com # Check TXT record for app identification dig TXT your-domain.com # View ingress container logs docker logs ``` ### Resolves Everywhere Except Android ```bash theme={"system"} # Check the CNAME target dig CNAME your-domain.com +short ``` Android rejects a target whose first label starts with an underscore — the old `_.` form. Set `GATEWAY_DOMAIN=gateway.${DSTACK_GATEWAY_DOMAIN}` and redeploy. ### Certificate Not Issued For custom domains using dstack-ingress: ```bash theme={"system"} # Check certificate evidence curl https://your-domain.com/evidences/ # Files available: # - acme-account.json # - cert.pem # - sha256sum.txt # - quote.json ``` DNS propagation takes: * Cloudflare: \~2 minutes * Linode: \~5 minutes * Namecheap: \~2 minutes ### CAA Record Blocking Certificate If you previously used `SET_CAA=true` and then wiped certificates/account, old CAA records may block new certificate issuance: ```bash theme={"system"} # Check existing CAA records dig CAA your-domain.com # If you see old accounturi values, they need to be removed # Example output that would block: # your-domain.com. 300 IN CAA 128 issue "letsencrypt.org;accounturi=https://acme-v02.api.letsencrypt.org/acme/acct/123456789" ``` **Solution options:** 1. **Wait for dstack-ingress to update CAA**: If `SET_CAA=true`, it will attempt to replace old CAA records, but DNS propagation may cause initial failures. 2. **Manually remove old CAA records**: Use your DNS provider's control panel to delete CAA records before redeploying. 3. **Disable CAA temporarily**: Set `SET_CAA=false` to avoid CAA checks during certificate issuance. Note: Namecheap doesn't support CAA records via API, so this issue won't occur with Namecheap as DNS provider. ## gRPC Connection Failed ### HTTP/2 Not Available ```bash theme={"system"} # Must use 'g' suffix for gRPC grpcurl -50051g.dstack-prod5.phala.network:443 list # Without 'g' suffix, HTTP/2 isn't enabled grpcurl -50051.dstack-prod5.phala.network:443 list # Will fail ``` ### Testing gRPC Service ```bash theme={"system"} # From outside grpcurl -50051g.dstack-prod5.phala.network:443 list # Inside CVM (without TLS) grpcurl -plaintext localhost:50051 list ``` ## SSH Access Denied ### Development OS Required SSH only works with development OS images. Production images have SSH disabled. ### Debug with Verbose Mode Use the Phala CLI with verbose output to diagnose connection issues: ```bash theme={"system"} phala ssh my-cvm -v ``` This shows detailed connection information including gateway resolution and SSH handshake. ### Check SSH Keys SSH keys from Account Settings are only injected at CVM creation time. If you added keys after deployment, use Code Update to set `DSTACK_ROOT_PUBLIC_KEY`. ### macOS OpenSSL Issue If using manual SSH configuration, macOS LibreSSL may cause timeouts: ```bash theme={"system"} # Install OpenSSL via Homebrew brew install openssl # Use full path in ProxyCommand /opt/homebrew/bin/openssl s_client -quiet -connect %h:%p -servername %h -verify_hostname %h -verify_return_error ``` For detailed SSH setup, see [Enable SSH Access](/phala-cloud/networking/enable-ssh-access). ## Debugging Commands ### From Outside CVM ```bash theme={"system"} # Test HTTPS endpoint curl -v https://-8080.dstack-prod5.phala.network # Check TLS certificate openssl s_client -connect -8080.dstack-prod5.phala.network:443 # DNS lookup dig -8080.dstack-prod5.phala.network ``` ### Inside CVM (SSH Required) ```bash theme={"system"} # Container status docker ps -a # Container logs docker logs --tail 100 # Network interfaces ip addr show # Port listeners netstat -tulpn # Test outbound connectivity curl -I https://example.com ``` ## Common Patterns ### Service Works Locally but Not Externally 1. Check port is exposed in docker-compose.yml 2. Verify service binds to 0.0.0.0, not 127.0.0.1 3. Confirm URL format is correct (no port number in URL) ### Intermittent Connection Failures Could indicate unhealthy instances if you have multiple replicas. The gateway removes unhealthy instances from rotation after 5 minutes without WireGuard handshake. ### Works with curl but Not Application Check if your application: * Supports SNI (Server Name Indication) * Uses correct TLS version (1.2 or 1.3) * Handles redirects properly ## Getting Support When reporting issues, provide: 1. **Application ID** from your deployment 2. **Exact URL** you're trying to access 3. **Error message** (complete output) 4. **Container logs**: `docker logs --tail 100` 5. **Test results** from debugging commands above For API error codes like `ERR-01-xxx`, see the [Error Codes Reference](/phala-cloud/references/error-codes). The more specific information you provide, the faster issues can be resolved. # Attestation API Reference Source: https://docs.phala.com/phala-cloud/phala-cloud-api/attestations Complete API reference for Phala Cloud's remote attestation service. Covers all endpoints, parameters, schemas, and integration patterns for Intel SGX and TDX quote verification. Looking to get started quickly? Check out our [5-minute quickstart guide](/phala-cloud/attestation/api-quickstart) first. ## API Endpoints ### POST /attestations/verify Upload and verify an SGX or TDX attestation quote. **Supported Input Formats:** 1. **File Upload** (multipart/form-data) - Recommended for most use cases 2. **Hex String JSON** (application/json) - For programmatic integration 3. **Hex String Form Data** (application/x-www-form-urlencoded) - For simple form submissions **Quote Requirements:** * Valid Intel SGX DCAP or TDX quote (2-8KB typical size) * Complete certificate chains included * ECDSA-P256 signature format * Generated from genuine Intel SGX/TDX platform **Request Parameters:** | Parameter | Type | Format | Description | | - | - | - | - | | `file` | binary | multipart/form-data | Quote file upload (recommended) | | `hex` | string | JSON or form data | Hex-encoded quote data | **Hex String Notes:** * Optional `0x` prefix supported * Case insensitive * Whitespace automatically trimmed ```bash File Upload theme={"system"} curl -X POST "https://cloud-api.phala.com/api/v1/attestations/verify" \ -H "Content-Type: multipart/form-data" \ -F "file=@quote.bin" ``` ```bash JSON Hex theme={"system"} curl -X POST "https://cloud-api.phala.com/api/v1/attestations/verify" \ -H "Content-Type: application/json" \ -d '{"hex": "0x48656c6c6f..."}' ``` ```bash Form Hex theme={"system"} curl -X POST "https://cloud-api.phala.com/api/v1/attestations/verify" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "hex=48656c6c6f..." ``` ```javascript JavaScript theme={"system"} // File upload const formData = new FormData(); formData.append('file', fileInput.files[0]); const response = await fetch('https://cloud-api.phala.com/api/v1/attestations/verify', { method: 'POST', body: formData }); const result = await response.json(); console.log('Verified:', result.quote.verified); console.log('Checksum:', result.checksum); ``` ```python Python theme={"system"} import requests # File upload with open('quote.bin', 'rb') as f: response = requests.post( 'https://cloud-api.phala.com/api/v1/attestations/verify', files={'file': f} ) result = response.json() print(f"Verified: {result['quote']['verified']}") print(f"Checksum: {result['checksum']}") ``` **Response Schema: VerificationResponse** ```json theme={"system"} { "success": true, "quote": { "header": { "version": 4, "ak_type": "ECDSA_P256", "tee_type": "TEE_TDX", "qe_vendor": "0x939a7233f79c4ca9940a0db3957f0607", "user_data": "0x65004f4410967df7fc6a1faf0d9b6fc000000000" }, "body": { "tee_tcb_svn": "06010300000000000000000000000000", "mrseam": "0x5b38e33a6487958b72c3c12a938eaa5e3fd4510c51aeeab58c7d5ecee41d7c436489d6c8e4f92f160b7cad34207b00c1", "mrtd": "0xc68518a0ebb42136c12b2275164f8c72f25fa9a34392228687ed6e9caeb9c0f1dbd895e9cf475121c029dc47e70e91fd", "rtmr0": "0x0bb3d6375f94482cdd24b767e4a0d720348527c4f2ab433d77f842b9394fa1638bb6df83fb0a1301f29c71bf60da48bb", "rtmr1": "0x154e08f5c1f7b1fce4cbfe1c14f3ba67b70044ede2751487279cd1f2e4239dee99a6d45e24ebde6b6a6f5ae49878e0e6", "rtmr2": "0x9edcd363660e85b71c318324996dda756c372d9f6960edbfa863b1e684822eb48dd95e218ae2b78e51ef97f3b8f5c9dc", "rtmr3": "0x56491496510e698faad85d0dc444636174789195f272899ab5b1fc8f83531375fb9077cb32e7dac16667470f854ba5d0", "reportdata": "0x00000000000000000000000000000000000000000000000000000000000000006ab141daaabe33787711861c8aa66ad3c95c49cebfd9525c85911b90233408ed" }, "cert_data": "-----BEGIN CERTIFICATE-----\nMIIE8TCCBJegAwIBAgIVANOAucofjgQfe1LTb4vrnuUCYTTrMAoGCCqGSM49BAMC...", "verified": true }, "checksum": "9aa049fb9049d4f582ca316206f7cf34ee185c2b5b63370a518921432385b81a", "can_download": true, "uploaded_at": "2025-08-15T16:01:28+00:00", "quote_collateral": { "pck_crl_issuer_chain": "-----BEGIN CERTIFICATE-----...", "tcb_info": "{\"id\":\"TDX\",\"version\":3,...}", "qe_identity": "{\"id\":\"TD_QE\",\"version\":2,...}" } } ``` **Response Fields:** | Field | Type | Description | | - | - | - | | `success` | boolean | Whether verification process completed successfully | | `quote` | Quote | Parsed quote object with header, body, and verification status | | `checksum` | string | SHA256 hash serving as unique identifier for this quote | | `can_download` | boolean | Whether the raw binary quote data can be downloaded | | `uploaded_at` | string | ISO 8601 timestamp when quote was first uploaded to Phala Cloud | | `quote_collateral` | QuoteCollateralV3 | Cryptographic verification data from Intel PCS | **Error Responses:** **Error Responses:** | Status | Cause | Common Issues | | - | - | - | | 400 | Input validation | Missing data, both file and hex provided, invalid hex format | | 422 | Invalid quote | Wrong file type, corrupted data, missing certificates | | 400 | Verification failed | Non-genuine platform, revoked certificates, outdated TCB | | 500 | Server error | Service unavailable, Intel PCS issues | *** ### GET /attestations/view/ Retrieve complete quote details including header, body, and verification status. **Path Parameters:** * `checksum` (string): Quote's unique SHA256 identifier ```bash cURL theme={"system"} curl "https://cloud-api.phala.com/api/v1/attestations/view/{checksum}" ``` ```javascript JavaScript theme={"system"} const response = await fetch(`https://cloud-api.phala.com/api/v1/attestations/view/${checksum}`); const quote = await response.json(); console.log('TEE Type:', quote.header.tee_type); console.log('MRTD:', quote.body.mrtd); console.log('Verified:', quote.verified); ``` ```python Python theme={"system"} response = requests.get(f'https://cloud-api.phala.com/api/v1/attestations/view/{checksum}') quote = response.json() print(f"TEE Type: {quote['header']['tee_type']}") print(f"MRTD: {quote['body']['mrtd']}") print(f"Verified: {quote['verified']}") print(f"Uploaded: {quote['uploaded_at']}") ``` **Response:** Full Quote object with additional metadata ```json theme={"system"} { "header": { "version": 4, "ak_type": "ECDSA_P256", "tee_type": "TEE_TDX", "qe_vendor": "0x939a7233f79c4ca9940a0db3957f0607", "user_data": "0x65004f4410967df7fc6a1faf0d9b6fc000000000" }, "body": { "tee_tcb_svn": "06010300000000000000000000000000", "mrtd": "0xc68518a0ebb42136c12b2275164f8c72f25fa9a34392228687ed6e9caeb9c0f1dbd895e9cf475121c029dc47e70e91fd", "rtmr0": "0x0bb3d6375f94482cdd24b767e4a0d720348527c4f2ab433d77f842b9394fa1638bb6df83fb0a1301f29c71bf60da48bb", "rtmr1": "0x154e08f5c1f7b1fce4cbfe1c14f3ba67b70044ede2751487279cd1f2e4239dee99a6d45e24ebde6b6a6f5ae49878e0e6", "reportdata": "0x00000000000000000000000000000000000000000000000000000000000000001d7ce0146d345b6e3e28b5605db5bbd7502507092f8f1e8f48c5e8f2d0e750f3" }, "cert_data": "-----BEGIN CERTIFICATE-----\\nMIIE8TCCBJegAwIBAgIVANOAucofjgQfe1LTb4vrnuUCYTTrMAoGCCqGSM49BAMC\\nMHAxIjAgBgNVBAMMGUludGVsIFNHWCBQQ0sgUGxhdGZvcm0gQ0ExGjAYBgNVBAoM\\nEUludGVsIENvcnBvcmF0aW9uMRQwEgYDVQQHDAtTYW50YSBDbGFyYTELMAkGA1UE\\nCAwCQ0ExCzAJBgNVBAYTAlVTMB4XDTI1MDEwNDAxMDQwNloXDTMyMDEwNDAxMDQw\\nNlowcDEiMCAGA1UEAwwZSW50ZWwgU0dYIFBDSyBDZXJ0aWZpY2F0ZTEaMBgGA1UE\\n...", "verified": true, "uploaded_at": "2025-08-15T16:01:28+00:00", "checksum": "9540fda5e6416c9d02bae726b146be58bee3caccfe7f874dbc68c808a13b1139", "can_download": true } ``` **Error Responses:** * **404 Not Found**: Quote with specified checksum doesn't exist *** ### GET /attestations/collateral/ Get cryptographic collateral (certificates, CRLs, TCB info) used for verification. **Response Headers:** * `Cache-Control: public, max-age=86400` (24 hour cache) * `ETag: "{checksum}"` (for conditional requests) ```bash cURL theme={"system"} curl "https://cloud-api.phala.com/api/v1/attestations/collateral/{checksum}" ``` ```javascript JavaScript theme={"system"} const response = await fetch(`https://cloud-api.phala.com/api/v1/attestations/collateral/${checksum}`); const collateral = await response.json(); // Parse nested JSON fields const tcbInfo = JSON.parse(collateral.tcb_info); const qeIdentity = JSON.parse(collateral.qe_identity); console.log('Platform FMSPC:', tcbInfo.fmspc); console.log('TCB Issue Date:', tcbInfo.issueDate); console.log('QE Identity Version:', qeIdentity.version); ``` ```python Python theme={"system"} import json response = requests.get(f'https://cloud-api.phala.com/api/v1/attestations/collateral/{checksum}') collateral = response.json() tcb_info = json.loads(collateral['tcb_info']) qe_identity = json.loads(collateral['qe_identity']) print(f"Platform FMSPC: {tcb_info['fmspc']}") print(f"TCB Issue Date: {tcb_info['issueDate']}") print(f"QE Identity Version: {qe_identity['version']}") ``` **Response:** QuoteCollateralV3 object **Headers:** * `Cache-Control: public, max-age=86400` * `CDN-Cache-Control: public, max-age=86400` * `Vary: Accept-Encoding` * `ETag: "9540fda5e6416c9d02bae726b146be58bee3caccfe7f874dbc68c808a13b1139"` **Error Responses:** * **404 Not Found**: Quote with specified checksum doesn't exist * **400 Bad Request**: Unable to retrieve collateral data *** ### GET /attestations/raw/ Download original binary quote data. **Response:** * `Content-Type: application/octet-stream` * `Content-Disposition: attachment; filename={checksum}.bin` * `Content-Length: {size}` (typically 2-8KB) ```bash cURL theme={"system"} curl "https://cloud-api.phala.com/api/v1/attestations/raw/{checksum}" \ --output quote.bin ``` ```javascript JavaScript theme={"system"} const response = await fetch(`https://cloud-api.phala.com/api/v1/attestations/raw/${checksum}`); const blob = await response.blob(); ``` ```python Python theme={"system"} response = requests.get(f'https://cloud-api.phala.com/api/v1/attestations/raw/{checksum}') with open(f'{checksum}.bin', 'wb') as f: f.write(response.content) print(f'Downloaded {len(response.content)} bytes') ``` *** ### HEAD /attestations/raw/ Check quote existence and size without downloading. ```bash cURL theme={"system"} curl -I "https://cloud-api.phala.com/api/v1/attestations/raw/{checksum}" ``` ```javascript JavaScript theme={"system"} const response = await fetch( `https://cloud-api.phala.com/api/v1/attestations/raw/${checksum}`, { method: 'HEAD' } ); const size = response.headers.get('Content-Length'); console.log(`Quote size: ${size} bytes`); ``` ```python Python theme={"system"} response = requests.head(f'https://cloud-api.phala.com/api/v1/attestations/raw/{checksum}') size = response.headers.get('Content-Length') print(f'Quote size: {size} bytes') ``` *** ### GET /attestations/recent List recently uploaded quotes with pagination. **Query Parameters:** * `skip` (integer): Records to skip (default: 0) * `limit` (integer): Maximum records to return (default: 20) ```bash cURL theme={"system"} curl "https://cloud-api.phala.com/api/v1/attestations/recent?limit=10" ``` ```javascript JavaScript theme={"system"} const response = await fetch('https://cloud-api.phala.com/api/v1/attestations/recent?limit=10'); const quotes = await response.json(); quotes.forEach(q => console.log(`${q.checksum}: ${q.verified ? 'verified' : 'failed'}`)); ``` ```python Python theme={"system"} response = requests.get('https://cloud-api.phala.com/api/v1/attestations/recent', params={'limit': 10}) for quote in response.json(): status = 'verified' if quote['verified'] else 'failed' print(f"{quote['checksum']}: {status}") ``` Returns array of quote summaries: ```json theme={"system"} [ { "checksum": "9540fda5e6416c9d02bae726b146be58bee3caccfe7f874dbc68c808a13b1139", "verified": 1, "created_at": "2025-08-15T16:01:28+00:00" } ] ``` | Field | Type | Description | | - | - | - | | `checksum` | string | SHA256 hash (unique identifier) | | `verified` | integer | 1 = verified, 0 = failed | | `created_at` | string | Upload timestamp (ISO 8601) | *** ## Data Models ### Quote ```json theme={"system"} { "header": QuoteHeader, "body": QuoteBody, "cert_data": string | null, "verified": boolean } ``` ### QuoteHeader ```json theme={"system"} { "version": 4, "ak_type": "ECDSA_P256", "tee_type": "TEE_TDX", "qe_vendor": "0x939a7233f79c4ca9940a0db3957f0607", "user_data": "0x65004f4410967df7fc6a1faf0d9b6fc000000000" } ``` | Field | Type | Description | | - | - | - | | `version` | integer | Quote format version (typically 4) | | `ak_type` | string | Attestation key type ("ECDSA\_P256") | | `tee_type` | string | "TEE\_SGX" or "TEE\_TDX" | | `qe_vendor` | string | Quoting Enclave vendor ID (hex) | | `user_data` | string | User-defined data (hex, 20 bytes) | ### QuoteBody Core attestation measurements and platform data. > [accordion] Complete Sample Data > > ```json theme={"system"} > { > "tee_tcb_svn": "06010300000000000000000000000000", > "mrseam": "0x5b38e33a6487958b72c3c12a938eaa5e3fd4510c51aeeab58c7d5ecee41d7c436489d6c8e4f92f160b7cad34207b00c1", > "mrsignerseam": "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", > "seamattributes": "0x0000000000000000", > "tdattributes": "0x0000001000000000", > "xfam": "0xe702060000000000", > "mrtd": "0xc68518a0ebb42136c12b2275164f8c72f25fa9a34392228687ed6e9caeb9c0f1dbd895e9cf475121c029dc47e70e91fd", > "mrconfig": "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", > "mrowner": "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", > "mrownerconfig": "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", > "rtmr0": "0x0bb3d6375f94482cdd24b767e4a0d720348527c4f2ab433d77f842b9394fa1638bb6df83fb0a1301f29c71bf60da48bb", > "rtmr1": "0x154e08f5c1f7b1fce4cbfe1c14f3ba67b70044ede2751487279cd1f2e4239dee99a6d45e24ebde6b6a6f5ae49878e0e6", > "rtmr2": "0x9edcd363660e85b71c318324996dda756c372d9f6960edbfa863b1e684822eb48dd95e218ae2b78e51ef97f3b8f5c9dc", > "rtmr3": "0x6485726f70094502412a81dc0097b3bd67181f6eb8c647fe6ddb47c8efa38e6f35b88bd99a4ece93c9f3d44be45c58a0", > "reportdata": "0x00000000000000000000000000000000000000000000000000000000000000001d7ce0146d345b6e3e28b5605db5bbd7502507092f8f1e8f48c5e8f2d0e750f3" > } > ``` **Complete Field Reference:** | Field | Type | Description | Size | | - | - | - | - | | `tee_tcb_svn` | string | TCB Security Version Number (platform firmware version) | 16 bytes | | `mrseam` | string | Measurement of SEAM module (Intel TDX hypervisor component) | SHA384 | | `mrsignerseam` | string | SEAM signer measurement (hash of entity that signed SEAM) | SHA384 | | `seamattributes` | string | SEAM module attributes and capabilities | 8 bytes | | `tdattributes` | string | Trust Domain attributes and configuration flags | 8 bytes | | `xfam` | string | Extended Features Available Mask (CPU features accessible to TD) | 8 bytes | | `mrtd` | string | **Measurement Root of Trust Domain** (TD fingerprint/initial state) | SHA384 | | `mrconfig` | string | Configuration measurement | SHA384 | | `mrowner` | string | TD owner measurement | SHA384 | | `mrownerconfig` | string | Owner configuration measurement | SHA384 | | `rtmr0` | string | **Runtime Measurement Register 0** (virtual hardware environment) | SHA384 | | `rtmr1` | string | **Runtime Measurement Register 1** (Linux kernel) | SHA384 | | `rtmr2` | string | **Runtime Measurement Register 2** (kernel cmdline and initrd) | SHA384 | | `rtmr3` | string | **Runtime Measurement Register 3** (application-specific measurements) | SHA384 | | `reportdata` | string | **User-defined data** (nonces, challenges, application state) | 64 bytes | **Critical Fields for Verification:** * **`mrtd`**: Trust domain fingerprint - must match expected value * **`rtmr0-3`**: Software measurements - verify boot chain and application integrity * **`reportdata`**: Challenge-response data - must contain expected nonce/response * **`tee_tcb_svn`**: Platform security level - check against known vulnerabilities ### QuoteCollateralV3 Cryptographic verification data from Intel PCS. > [accordion] Sample Data > > ```json theme={"system"} > { > "pck_crl_issuer_chain": "-----BEGIN CERTIFICATE-----...", > "root_ca_crl": "deadbeef1234...", > "pck_crl": "cafebabe5678...", > "tcb_info_issuer_chain": "-----BEGIN CERTIFICATE-----...", > "tcb_info": "{\"version\":3,\"issueDate\":\"2025-01-01T00:00:00Z\",...}", > "tcb_info_signature": "3045022100abc123...", > "qe_identity_issuer_chain": "-----BEGIN CERTIFICATE-----...", > "qe_identity": "{\"version\":2,\"issueDate\":\"2025-01-01T00:00:00Z\",...}", > "qe_identity_signature": "3046022100def456..." > } > ``` **Complete Field Reference:** | Field | Type | Description | | - | - | - | | `pck_crl_issuer_chain` | string | PEM certificate chain for PCK Certificate Revocation List verification | | `root_ca_crl` | string | Root CA Certificate Revocation List (hex-encoded, optional) | | `pck_crl` | string | Platform Certification Key Certificate Revocation List (hex-encoded) | | `tcb_info_issuer_chain` | string | PEM certificate chain for TCB info signature verification | | `tcb_info` | string | JSON string containing Trusted Computing Base information and security levels | | `tcb_info_signature` | string | ECDSA signature over the TCB info data (hex-encoded) | | `qe_identity_issuer_chain` | string | PEM certificate chain for Quoting Enclave identity verification | | `qe_identity` | string | JSON string containing QE identity, version, and TCB levels | | `qe_identity_signature` | string | ECDSA signature over the QE identity data (hex-encoded) | **Usage Notes:** * **Certificate Chains**: Used to validate signatures back to Intel root certificates * **CRL Data**: Check for revoked certificates and compromised platforms * **TCB Info**: Contains platform security version info and vulnerability advisories * **QE Identity**: Validates the Quoting Enclave that signed the quote * **Signatures**: All signatures use ECDSA-P256 and must be validated against certificate chains ## Verification Process 1. **Parse** - Extract header, body, and certificates from binary quote 2. **Platform Check** - Verify quote from genuine Intel SGX/TDX platform 3. **TCB Validation** - Check platform firmware is current and not revoked 4. **Signature Verification** - Validate using Intel-provided certificates 5. **Storage** - Cache results and collateral for future access ## Integration Patterns ### Basic Verification Workflow **Binary File Upload:** ```bash theme={"system"} # 1. Upload quote file checksum=$(curl -s -X POST "$API_BASE/verify" -F "file=@quote.bin" | jq -r .checksum) # 2. Check verification status curl "$API_BASE/view/$checksum" | jq .verified # 3. Share results echo "Verification report: https://proof.t16z.com/reports/$checksum" ``` **Hex Data from dstack SDK:** ```javascript theme={"system"} import crypto from 'crypto'; // 1. Generate and upload quote const client = new DstackClient(endpoint); // Manually hash data if > 64 bytes const data = 'challenge'; const hash = crypto.createHash('sha256').update(data).digest(); const quoteResult = await client.getQuote(hash.slice(0, 32)); const response = await fetch('$API_BASE/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ hex: quoteResult.quote }) }); const { checksum, quote: result } = await response.json(); // 2. Verification status console.log('Verified:', result.verified); console.log('Report:', `https://proof.t16z.com/reports/${checksum}`); ``` **Hex String Conversion:** ```bash theme={"system"} # Convert hex file to binary xxd -r -p quote.hex > quote.bin # Or send hex directly curl -X POST "$API_BASE/verify" \ -H "Content-Type: application/json" \ -d "{\"hex\": \"$(cat quote.hex | tr -d '\n')\"}" ``` ### Error Handling Best Practices **Input Format Issues:** * **422 Unprocessable Entity**: Wrong file format, corrupted data, or invalid hex * **400 Bad Request**: Missing input, invalid hex characters, or format conflicts **Verification Issues:** * **400 Verification Failed**: Platform may be development/non-genuine * **404 Not Found**: Invalid checksum or quote not uploaded * **500 Server Error**: Retry after delay, Intel PCS may be unavailable ### Cache Policy * Quote collateral is cached for 24 hours to improve performance * Raw quote data and verification results are stored permanently * ETags are provided for efficient client-side caching ### Security Notes * All quotes are **publicly accessible** by checksum * Always validate `reportdata` contains expected nonces/challenges * Check `verified: true` before trusting quote contents * Verification depends on Intel's Provisioning Certification Service *** **Need help getting started?** Check out our [quick start guide](/phala-cloud/attestation/api-quickstart) for a 5-minute walkthrough. # API Overview Source: https://docs.phala.com/phala-cloud/phala-cloud-api/overview Deploy confidential applications with Phala Cloud's managed TEE infrastructure. > [!NOTE] > > The Cloud API is in beta. The interface may change between versions. Report issues on [GitHub](https://github.com/Phala-Network/phala-cloud/issues) or in our [Telegram group](https://t.me/+nbhjx1ADG9EyYmI9). The Cloud API exposes the same backend used by the Phala Cloud dashboard. You can use it to create, manage, and monitor CVMs programmatically. The full interactive API reference is available in the sidebar — browse endpoints by category (Apps, CVMs, Attestations, etc.) to see request parameters, response schemas, and try requests directly. For working examples (creating and managing CVMs), see the [Cloud API examples](https://github.com/Phala-Network/phala-cloud). ## Error Handling API errors return structured error codes in the format `ERR-{MODULE}-{CODE}`. See the [Error Codes Reference](/phala-cloud/references/error-codes) for a complete list of error codes and their meanings. # allow-devices Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/allow-devices Manage on-chain device allowlist for an app contract > [!NOTE] > > This command is marked as unstable and may change in future releases. ### Command: `phala allow-devices` #### Syntax ``` phala allow-devices [options] ``` #### Description Manage on-chain device allowlist for an app contract #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * Display help: ```bash theme={"system"} phala allow-devices --help ``` ### Subcommands | Command | Description | | - | - | | `list` | List allowed devices from the on-chain contract | | `add` | Add devices to the on-chain allowlist | | `remove` | Remove devices from the on-chain allowlist | | `allow-any` | Set the allow-any-device flag on the contract. Requires --enable or --disable. | | `disallow-any` | Disable allow-any-device on the contract. Equivalent to `allow-any --disable`. | | `toggle-allow-any` | Toggle allow-any-device on the contract (or force via --enable/--disable) | # allow-devices add Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/allow-devices/add Add devices to the on-chain allowlist > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala allow-devices add` ### Syntax ``` phala allow-devices add [options] [] ``` ### Description Add devices to the on-chain allowlist ### Arguments | Argument | Description | | - | - | | `` | CVM or app identifier (UUID, app\_id, instance\_id, or name) | | `?` | Device ID (bytes32 hex) or node name. Node names are resolved to device IDs from available nodes. | ### Options | Option | Description | | - | - | | `--wait` | Wait for on-chain state to reflect the change via RPC polling | ### Advanced Options | Option | Description | | - | - | | `--private-key ` | Private key for signing on-chain transactions (or set PRIVATE\_KEY env var) | | `--rpc-url ` | RPC URL for on-chain KMS transactions (or set ETH\_RPC\_URL env var) | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `-i, --interactive` | Enable interactive mode | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Add device to allowlist ```bash theme={"system"} phala allow-devices add app_abc123 0xaabb... --private-key 0x... ``` * Interactive multi-select from available nodes ```bash theme={"system"} phala allow-devices add app_abc123 -i --private-key 0x... ``` # allow-devices allow-any Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/allow-devices/allow-any Set the allow-any-device flag on the contract. Requires --enable or --disable. > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala allow-devices allow-any` ### Syntax ``` phala allow-devices allow-any [options] ``` ### Description Set the allow-any-device flag on the contract. Requires --enable or --disable. ### Arguments | Argument | Description | | - | - | | `` | CVM or app identifier (UUID, app\_id, instance\_id, or name) | ### Options | Option | Description | | - | - | | `--enable` | Enable allow-any-device | | `--disable` | Disable allow-any-device | | `--wait` | Wait for on-chain state to reflect the change via RPC polling | ### Advanced Options | Option | Description | | - | - | | `--private-key ` | Private key for signing on-chain transactions (or set PRIVATE\_KEY env var) | | `--rpc-url ` | RPC URL for on-chain KMS transactions (or set ETH\_RPC\_URL env var) | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Enable allow-any-device ```bash theme={"system"} phala allow-devices allow-any app_abc123 --enable --private-key 0x... ``` * Disable allow-any-device ```bash theme={"system"} phala allow-devices allow-any app_abc123 --disable --private-key 0x... ``` # allow-devices disallow-any Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/allow-devices/disallow-any Disable allow-any-device on the contract. Equivalent to `allow-any --disable`. > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala allow-devices disallow-any` ### Syntax ``` phala allow-devices disallow-any [options] ``` ### Description Disable allow-any-device on the contract. Equivalent to `allow-any --disable`. ### Arguments | Argument | Description | | - | - | | `` | CVM or app identifier (UUID, app\_id, instance\_id, or name) | ### Options | Option | Description | | - | - | | `--wait` | Wait for on-chain state to reflect the change via RPC polling | ### Advanced Options | Option | Description | | - | - | | `--private-key ` | Private key for signing on-chain transactions (or set PRIVATE\_KEY env var) | | `--rpc-url ` | RPC URL for on-chain KMS transactions (or set ETH\_RPC\_URL env var) | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Disable allow-any-device ```bash theme={"system"} phala allow-devices disallow-any app_abc123 --private-key 0x... ``` # allow-devices list Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/allow-devices/list List allowed devices from the on-chain contract > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala allow-devices list` ### Syntax ``` phala allow-devices list [options] ``` ### Description List allowed devices from the on-chain contract ### Arguments | Argument | Description | | - | - | | `` | CVM or app identifier (UUID, app\_id, instance\_id, or name) | ### Advanced Options | Option | Description | | - | - | | `--rpc-url ` | RPC URL for on-chain KMS transactions (or set ETH\_RPC\_URL env var) | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * List devices on-chain ```bash theme={"system"} phala allow-devices list app_abc123 ``` # allow-devices remove Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/allow-devices/remove Remove devices from the on-chain allowlist > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala allow-devices remove` ### Syntax ``` phala allow-devices remove [options] [] ``` ### Description Remove devices from the on-chain allowlist ### Arguments | Argument | Description | | - | - | | `` | CVM or app identifier (UUID, app\_id, instance\_id, or name) | | `?` | Device ID (bytes32 hex) or node name. Node names are resolved to device IDs from available nodes. | ### Options | Option | Description | | - | - | | `--wait` | Wait for on-chain state to reflect the change via RPC polling | ### Advanced Options | Option | Description | | - | - | | `--private-key ` | Private key for signing on-chain transactions (or set PRIVATE\_KEY env var) | | `--rpc-url ` | RPC URL for on-chain KMS transactions (or set ETH\_RPC\_URL env var) | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `-i, --interactive` | Enable interactive mode | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Remove device from allowlist ```bash theme={"system"} phala allow-devices remove app_abc123 0xaabb... --private-key 0x... ``` * Interactive multi-select from allowed devices ```bash theme={"system"} phala allow-devices remove app_abc123 -i --private-key 0x... ``` # allow-devices toggle-allow-any Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/allow-devices/toggle-allow-any Toggle allow-any-device on the contract (or force via --enable/--disable) > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala allow-devices toggle-allow-any` ### Syntax ``` phala allow-devices toggle-allow-any [options] ``` ### Description Toggle allow-any-device on the contract (or force via --enable/--disable) ### Arguments | Argument | Description | | - | - | | `` | CVM or app identifier (UUID, app\_id, instance\_id, or name) | ### Options | Option | Description | | - | - | | `--enable` | Force enable allow-any-device | | `--disable` | Force disable allow-any-device | | `--wait` | Wait for on-chain state to reflect the change via RPC polling | ### Advanced Options | Option | Description | | - | - | | `--private-key ` | Private key for signing on-chain transactions (or set PRIVATE\_KEY env var) | | `--rpc-url ` | RPC URL for on-chain KMS transactions (or set ETH\_RPC\_URL env var) | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Toggle based on current state ```bash theme={"system"} phala allow-devices toggle-allow-any app_abc123 --private-key 0x... ``` * Force enable ```bash theme={"system"} phala allow-devices toggle-allow-any app_abc123 --enable --private-key 0x... ``` # annotations Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/annotations Show or set CVM annotations: unmeasured key/value metadata for host-side tools ### Command: `phala annotations` #### Syntax ``` phala annotations [options] ... ``` #### Description Show or set CVM annotations: unmeasured key/value metadata for host-side tools #### Arguments | Argument | Description | | - | - | | `` | \[cvm-id] \[KEY=VALUE ...]. The CVM id is optional and falls back to phala.toml; an argument containing '=' is a pair. | #### Options | Option | Description | | - | - | | `--unset ` | Remove an annotation key (repeatable) | | `--clear` | Remove every annotation | | `--replace` | Make the given pairs the whole set instead of merging them | #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * Show annotations ```bash theme={"system"} phala annotations app_abc123 ``` * Set annotations (CVM from phala.toml) ```bash theme={"system"} phala annotations memory_tier=fast pin_numa=0 ``` * Remove a key ```bash theme={"system"} phala annotations app_abc123 --unset memory_tier ``` * Replace the whole set ```bash theme={"system"} phala annotations app_abc123 memory_tier=fast --replace ``` * Remove every annotation ```bash theme={"system"} phala annotations app_abc123 --clear ``` # api Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/api Make an authenticated HTTP request to Phala Cloud API. ### Command: `phala api` #### Syntax ``` phala api [options] ``` #### Description Make an authenticated HTTP request to Phala Cloud API. #### Arguments | Argument | Description | | - | - | | `` | API endpoint path | #### Options | Option | Description | | - | - | | `-X, --method ` | HTTP method (default: GET) | | `-f, --query ` | Query parameter: key=value (use key=@file to read from file) | | `-F, --field ` | Body field: key=value (string) or key:=value (typed JSON). Supports @file | | `-H, --header ` | HTTP header: key:value | | `-d, --data ` | Request body data (cURL-style) | | `--input ` | Read body from file (use "-" for stdin) | | `-i, --include` | Print response headers | | `-q, --jq ` | Filter output with jq expression | | `--silent` | Don't print response body | #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * List CVMs ```bash theme={"system"} phala api /cvms ``` * Get CVM by app ID ```bash theme={"system"} phala api /cvms/app_xxx ``` * Filter with jq ```bash theme={"system"} phala api /cvms -q '.items[].name' ``` * GET with query params ```bash theme={"system"} phala api /endpoint -f status=active -f page=2 ``` * POST with body fields ```bash theme={"system"} phala api /endpoint -X POST -F name=foo -F count:=10 ``` * POST with cURL-style -d ```bash theme={"system"} phala api /endpoint -X POST -d '{"foo":"bar"}' ``` * POST from file ```bash theme={"system"} phala api /endpoint -X POST --input data.json ``` * Query params + body combined ```bash theme={"system"} phala api /endpoint -X POST -f page=1 -F name=foo ``` * Body field from file ```bash theme={"system"} phala api /endpoint -X POST -F config:=@settings.json ``` * Show response headers ```bash theme={"system"} phala api /cvms -i ``` # apps Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/apps List dstack apps > [!NOTE] > > This command is marked as unstable and may change in future releases. ### Command: `phala apps` #### Syntax ``` phala apps [options] ``` #### Description List dstack apps #### Options | Option | Description | | - | - | | `--page ` | Page number (1-based) | | `--page-size ` | Number of items per page | | `--search ` | Search by name, app\_id, vm\_uuid, or instance\_id | | `--status ` | Filter by CVM status (can be specified multiple times) | | `--listed, --no-listed` | Filter by listed status | | `--base-image ` | Filter by base image name | | `--instance-type ` | Filter by instance type | | `--kms-type ` | Filter by KMS type | | `--node ` | Filter by node name | | `--region ` | Filter by region identifier | #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * List apps ```bash theme={"system"} phala apps ``` * Second page ```bash theme={"system"} phala apps --page 2 ``` * Search by name ```bash theme={"system"} phala apps --search my-app ``` * Filter by status ```bash theme={"system"} phala apps --status running ``` * Output as JSON ```bash theme={"system"} phala apps --json ``` ### Subcommands | Command | Description | | - | - | | `launch-token` | Set, rotate or clear an app's launch token | # apps launch-token Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/apps/launch-token Set, rotate or clear an app's launch token ## Command: `phala apps launch-token` ### Syntax ``` phala apps launch-token [options] ``` ### Description Set, rotate or clear an app's launch token. See [Launch Token](/phala-cloud/cvm/launch-token) for what the token protects against and how to roll it out to each CVM. ### Subcommands | Command | Description | | - | - | | `set` | Set or rotate the app's launch token and print it and its hash once | | `clear` | Remove the app's launch token. Remove launch\_token\_hash from every CVM of the app first. | ## Command: `phala apps launch-token set` ### Syntax ``` phala apps launch-token set [options] ``` ### Arguments | Argument | Description | | - | - | | `` | App ID (hex) | ### Options | Option | Description | | - | - | | `--token ` | Token to set (at least 32 bytes). Omit to have Phala Cloud generate one. | ### Examples * Generate a new token ```bash theme={"system"} phala apps launch-token set 0123456789abcdef0123456789abcdef01234567 ``` * Then point a CVM at the new hash ```bash theme={"system"} phala deploy --cvm-id app_123 --launch-token-hash ``` ## Command: `phala apps launch-token clear` ### Syntax ``` phala apps launch-token clear ``` ### Arguments | Argument | Description | | - | - | | `` | App ID (hex) | ### Examples * Remove the hash from a CVM, then clear the token ```bash theme={"system"} phala deploy --cvm-id app_123 --launch-token-hash "" && phala apps launch-token clear 0123456789abcdef0123456789abcdef01234567 ``` ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | # auth (Deprecated) Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/auth Authenticate with Phala Cloud > [!WARNING] > > This command is deprecated. Use `phala login`, `phala logout`, and `phala status` instead. ### Command: `phala auth` #### Syntax ``` phala auth [options] ``` #### Description Authenticate with Phala Cloud #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * Display help: ```bash theme={"system"} phala auth --help ``` ### Deprecated Subcommands | Command | Description | | - | - | | `login` | Authenticate with Phala Cloud (use 'phala login' instead) | | `logout` | Remove stored API key (use 'phala logout' instead) | | `status` | Check auth status (use 'phala status' instead) | # auth login (Deprecated) Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/auth/login Authenticate with Phala Cloud (use 'phala login' instead) > [!WARNING] > > This command is deprecated. See the newer alternatives. ## Command: `phala auth login` ### Syntax ``` phala auth login [options] [] ``` ### Description Authenticate with Phala Cloud (use 'phala login' instead) ### Arguments | Argument | Description | | - | - | | `?` | API key (triggers device flow if omitted) | ### Options | Option | Description | | - | - | | `--manual` | Enter API key manually | | `--no-open` | Skip browser launch | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Display help: ```bash theme={"system"} phala auth login --help ``` # auth logout (Deprecated) Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/auth/logout Remove stored API key (use 'phala logout' instead) > [!WARNING] > > This command is deprecated. See the newer alternatives. ## Command: `phala auth logout` ### Syntax ``` phala auth logout ``` ### Description Remove stored API key (use 'phala logout' instead) ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Display help: ```bash theme={"system"} phala auth logout --help ``` # auth status (Deprecated) Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/auth/status Check auth status (use 'phala status' instead) > [!WARNING] > > This command is deprecated. See the newer alternatives. ## Command: `phala auth status` ### Syntax ``` phala auth status [options] ``` ### Description Check auth status (use 'phala status' instead) ### Options | Option | Description | | - | - | | `-d, --debug` | Enable debug output | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Display help: ```bash theme={"system"} phala auth status --help ``` # Changelog Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/changelog Release history for the Phala Cloud CLI ## [1.1.20](https://github.com/Phala-Network/phala-cloud/compare/cli-v1.1.19...cli-v1.1.20) (2026-07-26) ### Features * Added `phala kms list`, `phala kms nodes`, and `phala kms phala` for contract-centric KMS discovery. * Added `phala keccak256sum` with stdin, check, quiet, and status modes. * Added `--force-stop` to `phala deploy` for updates that must bypass graceful shutdown. * Added `--timeout` and `--api-version 2026-06-23` as global options. * Added compose types and `mr_config_id` computation to the deployment flow. * Added KMS contract verification anchors to on-chain detail output. ### Changes and fixes * Removed the legacy `phala docker` command group and `phala cvms create`. Use `phala deploy` to create CVMs. * Added `0x` prefixes to hex output and clearer KMS allowlist labels. * Improved API and provisioning errors with request details and structured error codes. * Verified KMS environment encryption public keys before use. ## [1.1.19](https://github.com/Phala-Network/phala-cloud/compare/cli-v1.1.18...cli-v1.1.19) (2026-05-19) * Added app instance names. * Added the CVM creation resource graph. ## [1.1.18](https://github.com/Phala-Network/phala-cloud/compare/cli-v1.1.17...cli-v1.1.18) (2026-04-17) ### feat * **cli:** add instances rm command with multi-UUID support ([0f78fc6](https://github.com/Phala-Network/phala-cloud/commit/0f78fc63116b65368830a13df387df50d819b87d)) * **cli:** move apps instances to top-level instances command, add instances ls ([67046a1](https://github.com/Phala-Network/phala-cloud/commit/67046a18644c3e84a022c0bf66d67fbb5964081a)) * **sdk,cli:** add POST /apps//instances support ([80498ab](https://github.com/Phala-Network/phala-cloud/commit/80498ab02f56610a21cbbc807b92d878304a1eb2)) ### fix * **cli:** include live status in instances ls --json output ([06b0360](https://github.com/Phala-Network/phala-cloud/commit/06b0360ed7d28779d61335facf51666f27fc2892)) * **cli:** polish instances/link UX and add commit-token routing ([4ab23c5](https://github.com/Phala-Network/phala-cloud/commit/4ab23c52f51abd73f13de2a28213f8f1ba36b20c)) * **cli:** poll both deviceAllowed and composeHashAllowed before commit ([755a256](https://github.com/Phala-Network/phala-cloud/commit/755a256e47e38c82d3566fedf30b53d7a278500f)) * **cli:** poll on-chain state before commit after registering compose hash ([2fb4094](https://github.com/Phala-Network/phala-cloud/commit/2fb409430f06a3bc530d0e5841fb4be567f0a936)) * **cli:** preserve all existing fields when backfilling app\_id in link ([1108cc7](https://github.com/Phala-Network/phala-cloud/commit/1108cc7415fb300595381d516c4535b4900ae21b)) * **cli:** reject unknown subcommand paths for leaf commands ([397b92b](https://github.com/Phala-Network/phala-cloud/commit/397b92b9e0ccf3c2073a13f9a753901fe8bb4ec6)) * **cli:** resolve profile by workspace slug fallback and use actual profile key in link ([a06748b](https://github.com/Phala-Network/phala-cloud/commit/a06748ba58f2874b90dcb3bdd363b1b6e8408028)) * **cli:** skip CVM fetch in instances add when no env-file provided ([98bb666](https://github.com/Phala-Network/phala-cloud/commit/98bb6668700b4ca9f4b6e812a85424a36eadd719)) * **cli:** write workspace slug as profile key, not workspace name ([e707e84](https://github.com/Phala-Network/phala-cloud/commit/e707e846b62023f3b5436785f346748d6c56dddd)) ## [1.1.16](https://github.com/Phala-Network/phala-cloud/compare/cli-v1.1.15...cli-v1.1.16) (2026-04-10) ### fix * **cli:** correct deploy --commit requirements in --help ([157f103](https://github.com/Phala-Network/phala-cloud/commit/157f103bb4033cc49abdacc6541d28db15b8a82b)) ### refactor * clarify --help strings and unify --transaction-hash option ([0749dc0](https://github.com/Phala-Network/phala-cloud/commit/0749dc0bc193697ef44d1ac86069d689838b9f58)) ## [1.1.15](https://github.com/Phala-Network/phala-cloud/compare/cli-v1.1.14...cli-v1.1.15) (2026-04-10) ### feat * **cli:** add profiles command aliases (list, rm, mv) ([b46dbc7](https://github.com/Phala-Network/phala-cloud/commit/b46dbc7c46ef30e5829edaee1e72ddaec9041b2b)) * **cli:** add profiles use, rename, delete subcommands ([3a7ab22](https://github.com/Phala-Network/phala-cloud/commit/3a7ab22e5635aa4906cf0e22d41d07141ffdea86)) * **cli:** add renameProfile utility to credentials ([1e07a24](https://github.com/Phala-Network/phala-cloud/commit/1e07a24f847d86b7c5c08050f4d91a7bc447e5fe)) * **cli:** unify global option handling ([8dc77c1](https://github.com/Phala-Network/phala-cloud/commit/8dc77c19c5ddd241e4baeb568981563f670b857f)) ### fix * **cli:** add two-phase replicate flow with on-chain approval ([a77a011](https://github.com/Phala-Network/phala-cloud/commit/a77a011e47e34129c3a5b17c9adcd7f60ee3bec8)) * **cli:** improve replicate output formatting and error display ([87cd7c8](https://github.com/Phala-Network/phala-cloud/commit/87cd7c8bff9c963219da4f03201f26ca2b57e966)) * **cli:** resolve app\_id ambiguity with --compose-hash in replicate ([15ff65d](https://github.com/Phala-Network/phala-cloud/commit/15ff65d20a86702c519df63df4b86989832152f1)) * **cli:** show full values in on-chain registration error ([600cb66](https://github.com/Phala-Network/phala-cloud/commit/600cb66b9c8732a9e89fe296fc01d117a6d3f012)) * **cli:** show on-chain status before requiring private key in replicate ([986f1ac](https://github.com/Phala-Network/phala-cloud/commit/986f1acd6b925e452a0608c8fc91717822363d0f)) * **cli:** strip app\_ prefix when matching cvm list by app\_id ([fcfed6e](https://github.com/Phala-Network/phala-cloud/commit/fcfed6e7dab1a609ff09e52c2a1448ea1c3f4fc4)) * **cli:** support universal cvm ids for replicate ([5fa84ba](https://github.com/Phala-Network/phala-cloud/commit/5fa84ba486cb3329e6b222bbc8a4edf03e1a41a3)) * **cli:** use app CVMs endpoint for compose-hash disambiguation ([2f2266a](https://github.com/Phala-Network/phala-cloud/commit/2f2266a7ab0ffb93c94d458298ec5082111e402c)) * **cli:** use correct pubkey source for CVM replicate env encryption ([2b3b98b](https://github.com/Phala-Network/phala-cloud/commit/2b3b98b9fdcd369f94887a05cea1827978cddeb1)) * **cli:** use instance-level cvm replication ([fd0cb03](https://github.com/Phala-Network/phala-cloud/commit/fd0cb0352c35987606d1efe901fb6a6b305b6319)) * **cli:** use plaintext output for cvm replicate ([1a9ba68](https://github.com/Phala-Network/phala-cloud/commit/1a9ba688895a3334cae4a69defc3f4d429062841)) * **cli:** use sdk private key flow in allow-devices ([d697761](https://github.com/Phala-Network/phala-cloud/commit/d697761a30a7b19cbbefff61ed0b74d82ae94ae4)) * **sdk:** chain resolution, owner pre-check, and ABI error definitions ([0c6a50c](https://github.com/Phala-Network/phala-cloud/commit/0c6a50c7fc57370ecb61359f34f04210c645ca18)) ### refactor * add `phala help ` subcommand with bundled topics ([8880334](https://github.com/Phala-Network/phala-cloud/commit/88803342ad4a5506642d3d517be55361659b1b0e)) * add RPC timeout + retry hint for allow-devices ([7a20577](https://github.com/Phala-Network/phala-cloud/commit/7a20577545e3da42bd37017574db962f5fc953f6)) * add transaction progress logging and RPC transport timeouts ([29849a2](https://github.com/Phala-Network/phala-cloud/commit/29849a283025fe74543254e75afae888ab29f848)) * allow direct app identifier in allow-devices to avoid CVM ambiguity ([a440bed](https://github.com/Phala-Network/phala-cloud/commit/a440bedb6334c87ed3b2bf82a6813421ee5204a4)) * log RPC URL before blockchain operations ([c9956b2](https://github.com/Phala-Network/phala-cloud/commit/c9956b22b0fe1c7a66b13f9b7bc04051600fb1f4)) * skip device list in allow-devices ls when allowAnyDevice is on ([597bbb4](https://github.com/Phala-Network/phala-cloud/commit/597bbb4be1e69d1832093ee167bf69eda801e3e2)) * unify --private-key / --rpc-url and add ETH\_RPC\_URL fallback ([162ff8a](https://github.com/Phala-Network/phala-cloud/commit/162ff8a0451ca799061534d3eb9711a85aebd1af)) ## [1.1.14](https://github.com/Phala-Network/phala-cloud/compare/cli-v1.1.13...cli-v1.1.14) (2026-03-27) ### feat * **cli:** add --prepare-only and --commit flags for multisig CVM updates ([99edfc0](https://github.com/Phala-Network/phala-cloud/commit/99edfc0f0a472bc8c92dc81dc1bebe26ac174ae0)) * **cli:** show chain ID and block explorer URL in --prepare-only output ([6de7e4a](https://github.com/Phala-Network/phala-cloud/commit/6de7e4aec4a8e0be258ff1db4638f2bd4e961441)) * display on-chain status in --prepare-only output ([f98f614](https://github.com/Phala-Network/phala-cloud/commit/f98f6149f13b9452099e23409964dcedbfb82ff7)) * **js,cli:** add on-chain prerequisite checks and improve update flow ([d3209e1](https://github.com/Phala-Network/phala-cloud/commit/d3209e1fd2b0be61455f5ec69de64a7919b1b7e2)) * **js:** add patchCvm and confirmCvmPatch for unified PATCH /cvms/ ([30cabaf](https://github.com/Phala-Network/phala-cloud/commit/30cabaf7084e72dbda656504d9f4359db95e2a16)) ### fix * **cli:** --commit mode no longer requires API key ([39bdd7a](https://github.com/Phala-Network/phala-cloud/commit/39bdd7ae98cfb39579a471e0abda3ba86cd56fb4)) * **cli:** 0x prefix on explorer URL, expired token hint ([4cb7398](https://github.com/Phala-Network/phala-cloud/commit/4cb73980850cab2a9f95f08ba0d1433c39a1faab)) * **cli:** add 0x prefix to compose hash in --prepare-only output ([62e4122](https://github.com/Phala-Network/phala-cloud/commit/62e4122486c281b82de0b538839ae3cff2ca6671)) * **cli:** add missing return after --prepare-only warning on non-on-chain CVM ([6a4abb8](https://github.com/Phala-Network/phala-cloud/commit/6a4abb8fc27fadcd90f3dc27f3cc5dc9b0a5755b)) * **cli:** fix --prepare-only output formatting for shell continuation ([732cbb8](https://github.com/Phala-Network/phala-cloud/commit/732cbb82787b04479db04d0d29f760bae78ca895)) * **cli:** fix --prepare-only output indentation, make --transaction-hash optional ([79e695f](https://github.com/Phala-Network/phala-cloud/commit/79e695f3402e38ba0c7233c30a517c63472157b2)) * **cli:** warn when --prepare-only used on non-on-chain KMS CVM ([f874b65](https://github.com/Phala-Network/phala-cloud/commit/f874b6526bcfe130e2078e5ecf4a7a64a429869c)) * **js,cli:** add missing files and fix compose hash tx verification ([7656a45](https://github.com/Phala-Network/phala-cloud/commit/7656a459ced2843a03146d6757fd019ede2f1f53)) ## [1.1.13](https://github.com/Phala-Network/phala-cloud/compare/cli-v1.1.12...cli-v1.1.13) (2026-03-14) ### feat * add device management blockchain actions to SDK and CLI ([290ca2a](https://github.com/Phala-Network/phala-cloud/commit/290ca2a8d4b246b8d9d4b87281132bf573128989)) * add os-images listing, kms on-chain detail to SDK and CLI ([9fe5c9a](https://github.com/Phala-Network/phala-cloud/commit/9fe5c9a845ca6c46d3c8777eeb8eec50476a396b)) * add phala cvms device-allowlist CLI command ([6d7b48f](https://github.com/Phala-Network/phala-cloud/commit/6d7b48f58198e85e17bc48aef56948a61f4e84dd)) * **cli,sdk:** add --fs option to deploy command for filesystem selection ([716723d](https://github.com/Phala-Network/phala-cloud/commit/716723d5e6a4ca3f443ee073dc8f74c44af162d6)) * **cli:** add --wait RPC verification for device allowlist ops ([97447f0](https://github.com/Phala-Network/phala-cloud/commit/97447f01a25a8642d50f8658ca3b005ec9cda6de)) * **cli:** add `phala envs encrypt` and `phala envs update` commands ([ddd4cfc](https://github.com/Phala-Network/phala-cloud/commit/ddd4cfc4a8c56970685d0c0478b8a5e807e99fe0)) * **cli:** add disallow-any and toggle-allow-any commands ([dbff4e5](https://github.com/Phala-Network/phala-cloud/commit/dbff4e5007d4241dad40270bfe62875011af0581)) * **cli:** add interactive multi-select for devices add/remove ([4f0f2d4](https://github.com/Phala-Network/phala-cloud/commit/4f0f2d4560cdbfd944a784fae09d4de12ab1c002)) * **cli:** add pagination flags to os-images command ([1ef6cd9](https://github.com/Phala-Network/phala-cloud/commit/1ef6cd941d88a9818e4ce196e145a9159427348b)) * **cli:** move device allowlist to top-level `phala allow-devices` ([430cd9c](https://github.com/Phala-Network/phala-cloud/commit/430cd9cd7a6e44a9f89ed0f6301e82128bae06a0)) * **kms:** simplify CLI output and include device node names ([e48019c](https://github.com/Phala-Network/phala-cloud/commit/e48019cb972c96c049aadc2e285f4b3a06de0c14)) * query and display contract owner in allow-devices list ([37fe2e1](https://github.com/Phala-Network/phala-cloud/commit/37fe2e124880f59b3e9bb0087cafb71b350781f5)) ### fix * **cli:** add viem as direct dependency for CI type-check ([bcc4df3](https://github.com/Phala-Network/phala-cloud/commit/bcc4df3bebea07e564743e17ccf0456e35734a3e)) * **cli:** address Sentry review issues in allow-devices commands ([a205282](https://github.com/Phala-Network/phala-cloud/commit/a2052828f9f5ce8324b1dbefed4df3109720c7b1)) * **cli:** ensure timeout floor of 5000ms for small command groups ([370eb98](https://github.com/Phala-Network/phala-cloud/commit/370eb985abc7a1e7b18a1de8339688ff2f7dc7eb)) * **cli:** exclude already-allowed devices from add interactive list ([f0a6b53](https://github.com/Phala-Network/phala-cloud/commit/f0a6b53ce52af6ad6d34624a707096e699a3d71d)) * **cli:** fix node name matching and separate chain line in ls ([b7a4ce3](https://github.com/Phala-Network/phala-cloud/commit/b7a4ce3ba68b5cb3713c95421bfbb5ef1ee9595e)) * **cli:** increase timeout for command existence compat tests ([a9889be](https://github.com/Phala-Network/phala-cloud/commit/a9889befdc562c4d02f38a40ad7090ab101cf7dd)) * **cli:** query chain directly for allow-devices list ([b40d8e3](https://github.com/Phala-Network/phala-cloud/commit/b40d8e39220c9a7f6491456ea2133faa3087a626)) * **cli:** remove redundant status column from devices list ([b49744d](https://github.com/Phala-Network/phala-cloud/commit/b49744df0407cd66b98dcfd0769b6fea644ad461)) * **cli:** use shared walletClient with nonceManager for batch tx ([ef93049](https://github.com/Phala-Network/phala-cloud/commit/ef93049ccf2293bfa3ecf8440fc70cccc6fa9be7)) * guard against null app\_id in device-allowlist command ([0b8bdd8](https://github.com/Phala-Network/phala-cloud/commit/0b8bdd802c4d93bf8d41f1f6a77e603bdf0b506c)) * replace event scanning with readContract for device allowlist ([fb2a4b2](https://github.com/Phala-Network/phala-cloud/commit/fb2a4b275912d4bd2931c1b12d3b5b1368a26458)) ### perf * **cli:** skip prerequisite checks in batch add/remove ([e814237](https://github.com/Phala-Network/phala-cloud/commit/e814237bbf9259a9d7a397a9bfb7adec2f0d29c8)) ## [1.1.12](https://github.com/Phala-Network/phala-cloud/compare/cli-v1.1.12-beta.1...cli-v1.1.12) (2026-03-04) ### feat * **cli:** add --api-version global option ([f96397f](https://github.com/Phala-Network/phala-cloud/commit/f96397f81056af09fb854b3fc99cda09721c5e2f)) ### fix * **cli:** validate --api-version flag against supported versions ([a6b4f68](https://github.com/Phala-Network/phala-cloud/commit/a6b4f684039cf5e676160fcce2bc6f4084e26dee)) ## [1.1.12-beta.1](https://github.com/Phala-Network/phala-cloud/compare/cli-v1.1.11...cli-v1.1.12-beta.1) (2026-03-03) ### feat * **cli:** show changelog URL in self update command ([8f569e8](https://github.com/Phala-Network/phala-cloud/commit/8f569e8c4361848708e2b0e06a423686d9461942)) * **cli:** show changelog URL in update notifications ([22a6648](https://github.com/Phala-Network/phala-cloud/commit/22a6648b5f21384c4675f652bc25bcd6d0bb97e6)) ### fix * **cli:** use --no-cache and exact version for bun global installs ([a63a11d](https://github.com/Phala-Network/phala-cloud/commit/a63a11d19e0b6248e99acf93851c2dabec462fcc)) * **cli:** use generic id field in waitForCvmReady poller ([4b2132d](https://github.com/Phala-Network/phala-cloud/commit/4b2132dd25ef752ada519570efcfb0c744b1cfcb)) ## [1.1.11](https://github.com/Phala-Network/phala-cloud/compare/cli-v1.1.10...cli-v1.1.11) (2026-03-02) ### fix * **cli:** error when body provided with GET/HEAD/OPTIONS ([abf6ab9](https://github.com/Phala-Network/phala-cloud/commit/abf6ab9fd8eeddc0e2465cf10ac536dcfd479a61)) * **cli:** restore -i/--interactive flag for switch command ([b4786fa](https://github.com/Phala-Network/phala-cloud/commit/b4786fae5a2449b19e123905407c09e7c2b06239)) ## [1.1.10](https://github.com/Phala-Network/phala-cloud/compare/cli-v1.1.9...cli-v1.1.10) (2026-02-25) ### feat * **sdk+cli:** add SSH key and CVM runtime-config commands ([692321a](https://github.com/Phala-Network/phala-cloud/commit/692321a05bacdbc4da9bcfbc9b82ab8fcfc9d25a)) * **cli:** improve SSH key commands ([565f36a](https://github.com/Phala-Network/phala-cloud/commit/565f36a90a1145bd68bd493d9b3857a15e24866f)) ### fix * **cli:** add --json output support to all ssh-keys commands ([6c93846](https://github.com/Phala-Network/phala-cloud/commit/6c938469d6bee77b36d34c70d5b5a5e8ff89c6ac)) * **cli:** fix selectCvm() to use correct API response shape ([47f2c34](https://github.com/Phala-Network/phala-cloud/commit/47f2c346463fdc0ee3d2dcb07660817adad29a96)) ## [1.1.9](https://github.com/Phala-Network/phala-cloud/compare/cli-v1.1.8...cli-v1.1.9) (2026-02-12) ### feat * **cli:** add `phala whoami` command ([4fa9e30](https://github.com/Phala-Network/phala-cloud/commit/4fa9e3039f28e7e0bef55b55e476c5f84946a313)) * **cli:** redesign `phala logs` as unified log command ([f3b8a5b](https://github.com/Phala-Network/phala-cloud/commit/f3b8a5b2e1e44c516971bc85fc67c93a7c6bde26)) * **cli:** show workspace in whoami, add upgrade check to status ([5bac9cc](https://github.com/Phala-Network/phala-cloud/commit/5bac9cc2b46944c0541efd713214479233b8ea1f)) ### fix * **cli:** percent-encode query parameter values in `phala api` ([f407411](https://github.com/Phala-Network/phala-cloud/commit/f407411ebab2d5588118cab8939af84616e3ec2c)) * **cli:** unify CVM ID handling across commands ([abff9bb](https://github.com/Phala-Network/phala-cloud/commit/abff9bb2e906a80a61607f7b324860763f348727)) ## [1.1.8](https://github.com/Phala-Network/phala-cloud/compare/cli-v1.1.7...cli-v1.1.8) (2026-02-07) ### feat * add 200KB size limit for compose file + pre-launch script ([fe45765](https://github.com/Phala-Network/phala-cloud/commit/fe4576593cc08c2576e4c91d1c2b6b68cb3b9601)) * add filter flags to apps and cvms list commands ([3f5ac90](https://github.com/Phala-Network/phala-cloud/commit/3f5ac907a08155171d93ad487ba8b226f2682e97)) ### fix * wire --pre-launch-script flag to payload and fix combined size check ([cecca57](https://github.com/Phala-Network/phala-cloud/commit/cecca57279eafecaffe4bce207f77bb561067ed6)) ## [1.1.7](https://github.com/Phala-Network/phala-cloud/compare/cli-v1.1.6...cli-v1.1.7) (2026-01-31) ### feat * use workspace slug as profile name, add profiles command, update default API domain ([5c150a0](https://github.com/Phala-Network/phala-cloud/commit/5c150a024d575414e60d6ead26f19a1fc9eaad4a)) ## [1.1.6](https://github.com/Phala-Network/phala-cloud/compare/cli-v1.1.5...cli-v1.1.6) (2026-01-31) ### feat * **cli:** add `phala ps` command to list CVM containers ([4e218b1](https://github.com/Phala-Network/phala-cloud/commit/4e218b1f91b6b315422600ba037343fdf7d25ddc)) * **cli:** add `phala switch` command for profile switching ([907f1fe](https://github.com/Phala-Network/phala-cloud/commit/907f1fe693d8ca90843726b118f371cefd6deb84)) * **cli:** add phala apps command and align cvms ls output ([eb194b7](https://github.com/Phala-Network/phala-cloud/commit/eb194b74adb7433a15ee806715a2053c7ddeba3f)) * **cli:** add phala instance-types command ([7cba272](https://github.com/Phala-Network/phala-cloud/commit/7cba272c4156d79f1ed8ecf7fce0ca0d38de9e8a)) * **cli:** add phala logs command ([fa281ba](https://github.com/Phala-Network/phala-cloud/commit/fa281ba3705208f0d66ef1f6c776ba156204e8ab)) * **cli:** migrate nodes list to workspace nodes API ([08e39e7](https://github.com/Phala-Network/phala-cloud/commit/08e39e7825bf72cd627c27ff4c91ab3056213be9)) ### fix * **cli:** fix boolean flag handling and visibility update race condition ([a9f94e1](https://github.com/Phala-Network/phala-cloud/commit/a9f94e1c177e675009ea503afe92a12514d903b1)) * upgrade CLI to API version 2026-01-21 ([9a92b54](https://github.com/Phala-Network/phala-cloud/commit/9a92b54038daba79f9e54e6e6c42c37744031d5c)) ## [1.1.5](https://github.com/Phala-Network/phala-cloud/compare/cli-v1.1.4...cli-v1.1.5) (2026-01-23) ### feat * **cli:** add -d/--data and @file syntax for api command ([93d6bb3](https://github.com/Phala-Network/phala-cloud/commit/93d6bb3670283e92fd15f8ba676d615b96b20e98)) * **cli:** add privacy settings to deploy command ([edf9b40](https://github.com/Phala-Network/phala-cloud/commit/edf9b407d154f696ca2521af2bbc1d01971f3cd3)) * **cli:** simplify KMS option to --kms \[phala|ethereum|eth|base] ([35d1fcd](https://github.com/Phala-Network/phala-cloud/commit/35d1fcd090c4dceaa8b502297a26d552b3ca4195)) ## [1.1.4](https://github.com/Phala-Network/phala-cloud/compare/cli-v1.1.4-beta.1...cli-v1.1.4) (2026-01-19) ### feat * **cli:** add link command to connect local directory to existing CVM ([9c33607](https://github.com/Phala-Network/phala-cloud/commit/9c33607e546ded7e373b3b80173fdeac07ad419e)) * **cli:** add update check and self update ([714ea99](https://github.com/Phala-Network/phala-cloud/commit/714ea995c17992a43fe69dfd2069641238ef5861)) * **cli:** add api command for raw HTTP requests ([eaaecec](https://github.com/Phala-Network/phala-cloud/commit/eaaecec8a38421b29f62b6e9eb908215b837f987)) ## [1.1.2](https://github.com/Phala-Network/phala-cloud/compare/cli-v1.1.1...cli-v1.1.2) (2026-01-09) ### fix * **cli:** Update environment variables when using onchain KMS ([3acbb61](https://github.com/Phala-Network/phala-cloud/commit/3acbb618ccc2b6e95fd134ceb7a8286fd27e7569)) ## [1.1.1](https://github.com/Phala-Network/phala-cloud/compare/cli-v1.1.0...cli-v1.1.1) (2026-01-06) ### feat * **cli:** add --interactive flag to logs commands ([4d7e7f4](https://github.com/Phala-Network/phala-cloud/commit/4d7e7f4889125fe8e6007447ff006ac3a830f53e)) * **cli:** add logs and serial-logs commands for CVMs ([793de6b](https://github.com/Phala-Network/phala-cloud/commit/793de6b6c5e1545e270109228fbfc127c0692cf3)) ## [1.1.0](https://github.com/Phala-Network/phala-cloud/tree/cli-v1.1.0) (2025-12-22) Major release with CLI completion, phala.toml support, SSH commands, cp command, and link command. ### feat * add CLI completion support ([37dc21b](https://github.com/Phala-Network/phala-cloud/commit/37dc21b14bb7377bbdefd35c9663bf0a74bda4ab)) * added phala.toml support ([e02c130](https://github.com/Phala-Network/phala-cloud/commit/e02c1307790066f0de4e2d9913acb8ebb5ab6650)) * **cli:** added command ssh ([89161d9](https://github.com/Phala-Network/phala-cloud/commit/89161d930321833abbb2f85fe2d93ae7619182f1)) * **cli:** added cp command ([4d320c5](https://github.com/Phala-Network/phala-cloud/commit/4d320c5ed07541200aa2a21f16b340afb7f3df2d)) * **cli:** add --json flag support to multiple commands ([1ea0c34](https://github.com/Phala-Network/phala-cloud/commit/1ea0c348bb5b7fb3d5db055a67dfb29b758fa4f3)) * **cli:** add --wait flag to deploy command for CVM updates ([b11f739](https://github.com/Phala-Network/phala-cloud/commit/b11f73982391fa1c46beef4f968cd8ad02dacbc2)) * **cli:** add stability classification to commands ([46635fe](https://github.com/Phala-Network/phala-cloud/commit/46635febba351ef8f34c75a8c74009d0677c031d)) * **cli:** open browser & login workflow ([2b56074](https://github.com/Phala-Network/phala-cloud/commit/2b560742b9e6f9e1d3f1da173d3d05e6feac880e)) * **cli:** support -e KEY=VALUE format for deploy command ([d152c12](https://github.com/Phala-Network/phala-cloud/commit/d152c12d63e5f168c6c70d7d56f1b5f8f3aa3e87)) # Deploy with the GitHub Action Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/ci-cd-automation/github-deploy-action Update a CVM from GitHub Actions with the Phala deploy action, using phala.toml and an API key stored as a repository secret. The [Phala deploy action](https://github.com/Phala-Network/phala-deploy-action) updates a CVM from your GitHub workflow. It installs the Phala CLI, runs `phala deploy --json --wait`, and reports the result as workflow outputs. You do not write any CLI commands yourself. Use it when you want the shortest path from a push to a deployed CVM. If you need to build images, run extra steps, or use another CI system, see [Set Up a CI/CD Pipeline](/phala-cloud/phala-cloud-cli/ci-cd-automation/setup-a-ci-cd-pipeline). ## What do I need before I start? * A `phala.toml` file at the root of your repository. The action stops with an error if the file is missing. It tells the CLI which CVM to update, so it must name an existing CVM (see [below](#which-cvm-does-the-action-update)). See [phala.toml Configuration](/phala-cloud/phala-cloud-cli/phala-toml). * A Docker Compose file in the repository. The CLI reads it the same way it does for `phala deploy`. * A Phala Cloud [API key](/phala-cloud/phala-cloud-api/overview). * An `actions/checkout` step before the action, so the files are on the runner. On self-hosted runners, use Actions Runner 2.327.1 or newer. GitHub-hosted `ubuntu-latest` runners already work. ## How do I add the API key? Store the key as a repository secret. Do not put it in the workflow file. 1. In your GitHub repository, open **Settings > Secrets and variables > Actions**. 2. Select **New repository secret**. 3. Name it `PHALA_API_KEY` and paste your Phala Cloud API key. If the key is ever exposed in logs or committed to a repository, create a new one in the Phala Cloud dashboard and replace the secret. ## What does a minimal workflow look like? ```yaml theme={"system"} name: Deploy to Phala Cloud on: push: branches: [main] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: Phala-Network/phala-deploy-action@v3 with: api-key: ${{ secrets.PHALA_API_KEY }} ``` To deploy only when your configuration changes, add a `paths` filter under `push`: ```yaml theme={"system"} on: push: branches: [main] paths: - "phala.toml" - "docker-compose.yml" ``` ## What are the inputs? | Input | Required | Default | Description | | - | - | - | - | | `api-key` | Yes, unless you use keyless login | | Your Phala Cloud API key. Pass it from a repository secret. | | `envs` | No | | Environment variables for the CVM, one `KEY=VALUE` per line. | | `workspace` | No | | Slug of the workspace to deploy into. | | `cli-version` | No | `1.2.3` | The Phala CLI version the action installs. | | `oidc-audience` (Beta) | No | `https://cloud.phala.com` | Audience of the GitHub OIDC token. Change it only if support tells you to. See [Keyless login](#keyless-login-with-github-oidc-beta). | ## What are the outputs? Read outputs from a step that has an `id`, for example `steps.deploy.outputs.status`. | Output | Description | | - | - | | `status` | `success`, `failed`, or `pending_approval`. | | `result` | Full CVM information as JSON. | | `app-id` | App ID of the CVM. | | `vm-uuid` | VM UUID of the CVM. | | `cvm-name` | Name of the CVM. | | `dashboard-url` | Link to the CVM in the dashboard. | | `compose-hash` | SHA256 hash of the normalized app compose. | | `docker-compose-hash` | SHA256 hash of the raw `docker-compose.yml`. | | `pre-launch-script-hash` | SHA256 hash of the pre-launch script. | | `os-image` | OS image name. | | `os-image-version` | OS image version. | | `os-image-hash` | OS image hash. | | `kms-type` | Key management type: `phala`, `ethereum`, or `base`. | | `device-id` | Device ID of the node. | | `commit-token` | Token for approving an update that needs on-chain approval. Empty otherwise. | | `oidc-repository` (Beta) | Source repository, when the API returns it. May be empty. | | `oidc-commit-sha` (Beta) | Source commit SHA, when the API returns it. May be empty. | `status`, `app-id`, `vm-uuid`, `cvm-name`, and `dashboard-url` come straight from the deploy result. The hash, OS image, `kms-type`, and `device-id` outputs come from a second request for the CVM's details, which the action makes with your API key. If that request fails, the deploy still counts as successful, the action prints a warning, and those outputs are empty. ## When does the job succeed or fail? The job waits for the real result. It does not stop after the request is accepted. * **New CVM (no CVM named in `phala.toml`):** the job creates a new CVM and waits until it is running, then succeeds with `status=success`. If the CVM does not start, the job fails with the reason. The CVM still exists, so check it in the dashboard. * **Update finishes:** the job succeeds with `status=success`. * **Update fails or is cancelled:** the job fails with `status=failed`, and the deploy output is printed in the job log. * **Wait takes too long:** the CLI waits up to 5 minutes. After that the job fails, but the CVM may still be starting or updating. Check the CVM in the dashboard before you re-run the workflow. * **CVM that is not running before an update:** the job waits for the CVM to be stopped, not running. A stopped CVM stays stopped, and so does a CVM in `error` status. ## Which CVM does the action update? The action is built to update a CVM that already exists. It finds the CVM from `phala.toml`. If `phala.toml` does not name a CVM, the CLI creates a new CVM, and it does so on every workflow run. Create the CVM first, for example with `phala deploy -n -c docker-compose.yml`. Then put its name in `phala.toml`: ```toml theme={"system"} name = "my-tee-app" ``` You can also use `app_id`, `uuid`, or `instance_id` in place of `name`. See [phala.toml Configuration](/phala-cloud/phala-cloud-cli/phala-toml). The action then updates that CVM on each push. ## What happens when nothing changed? If the configuration, compose file, and environment variables match what is already deployed, the job succeeds right away. The CVM is not restarted. ## What if the CVM uses on-chain KMS? An update to a CVM that uses on-chain KMS must be approved on-chain before it takes effect. The job does not fail in this case. It ends with `status=pending_approval`, prints the compose hash as a warning, and sets `compose-hash` and `commit-token`. Approve the update in the dashboard. Do not treat this status as a finished deployment. ```yaml theme={"system"} - uses: Phala-Network/phala-deploy-action@v3 id: deploy with: api-key: ${{ secrets.PHALA_API_KEY }} - name: Remind the team to approve if: steps.deploy.outputs.status == 'pending_approval' run: echo "Approve compose hash ${{ steps.deploy.outputs.compose-hash }} in the dashboard." ``` ## How do I pass environment variables and secrets? Use the `envs` input. Put one `KEY=VALUE` on each line, and take every value from a GitHub secret. ```yaml theme={"system"} - uses: Phala-Network/phala-deploy-action@v3 with: api-key: ${{ secrets.PHALA_API_KEY }} envs: | DATABASE_URL=${{ secrets.DATABASE_URL }} REDIS_URL=${{ secrets.REDIS_URL }} ``` The action writes these lines to a `.env` file on the runner and passes it to the deploy. The CLI encrypts the values before it sends them, so they reach your CVM as [encrypted secrets](/phala-cloud/cvm/set-secure-environment-variables). Use a repository secret for each value. Never type a secret directly into the workflow file. ## Which CLI version should I use? Leave `cli-version` unset. The action installs the version it was tested with, which is `1.2.3`. Because the action pins the version, a new CLI release does not change your deployments until you change the input. To use a different release, set the input to an exact version: ```yaml theme={"system"} - uses: Phala-Network/phala-deploy-action@v3 with: api-key: ${{ secrets.PHALA_API_KEY }} cli-version: "1.2.3" ``` Use `1.2.1` or newer. Older versions do not wait correctly on stopped CVMs and do not check the update result with keyless login. ## Keyless login with GitHub OIDC (Beta) Keyless login lets a workflow deploy without an API key. GitHub gives the job a short-lived token, and Phala Cloud accepts it from a GitHub repository that you registered for the app. This feature is in Beta. It is enabled per workspace, so contact support to turn it on for yours. To use it: 1. Ask support to enable it for your workspace. 2. Open your app in the dashboard and go to **GitHub**. This item appears only after support has enabled the feature. 3. Under **GitHub repository**, enter the repository that may deploy this app, in `owner/repo` format, and select **Save**. Phala Cloud asks you to confirm with a fresh two-factor verification when you save. You cannot save it with an API key. 4. Give the workflow the `id-token: write` permission, and `contents: read` for checkout. 5. Leave out `api-key`. The page also has two optional fields. **Only this git ref** limits deploys to one ref, such as `refs/heads/main`. **Only this workflow** limits deploys to one workflow. Each app trusts one repository, and saving a new one replaces the old one. Select **Remove** to stop that repository from deploying the app. ```yaml theme={"system"} name: Deploy to Phala Cloud on: push: branches: [main] permissions: contents: read id-token: write jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: Phala-Network/phala-deploy-action@v3 ``` If the repository is registered for apps in more than one workspace, set the `workspace` input to the one you want. If you pass both an `api-key` and the permission, the CLI uses the API key. With keyless login the action reads the result from the deploy response only. The compose hash, OS image, `kms-type`, and `device-id` outputs are empty. `oidc-repository` and `oidc-commit-sha` are filled in only when the API returns them, so they can be empty too. ## Troubleshooting **The job says `phala.toml not found`.** Add `phala.toml` to the repository root, and make sure `actions/checkout` runs before the action. **The job says no authentication method is available.** Pass `api-key` and check that the secret name matches the one you created. For keyless login, check that the workflow has the `id-token: write` permission. **The job fails after about 5 minutes.** The update may still be running. Open the CVM in the dashboard and check its status before you run the workflow again. **An output is empty.** Hash, OS image, `kms-type`, and `device-id` outputs are filled in only when the action could fetch the CVM's details. Look for a warning in the job log. # Set Up a CI/CD Pipeline Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/ci-cd-automation/setup-a-ci-cd-pipeline Automate CVM deployments with GitHub Actions, GitLab CI, and Phala Cloud SDKs. Automating deployments means every push to your main branch updates your CVM without manual intervention. This guide covers four approaches: the Phala CLI in GitHub Actions, the JS SDK in GitHub Actions, a GitLab CI pipeline, and Terraform in CI. ## Prerequisites * A Git repository with your application code and a `docker-compose.yml` * A [Phala Cloud account](https://cloud.phala.com/register) with an [API key](/phala-cloud/phala-cloud-api/overview) * A container registry account (Docker Hub, GHCR, or similar) ## Secrets Management Regardless of which CI platform you use, store your Phala Cloud API key as a secret. Never hardcode it in workflow files. **GitHub:** Go to **Settings > Secrets and variables > Actions** and add: | Secret | Description | | - | - | | `PHALA_CLOUD_API_KEY` | Your Phala Cloud API key | | `DOCKER_REGISTRY_USERNAME` | Container registry username | | `DOCKER_REGISTRY_PASSWORD` | Registry password or access token | **GitLab:** Go to **Settings > CI/CD > Variables** and add the same values as masked variables. > [!WARNING] > > Rotate your API key immediately if it's ever exposed in logs or committed to a repository. Generate a new one from **Settings > API Keys** in the Phala Cloud dashboard. ## GitHub Actions with the deploy action If you only need to update a CVM from `phala.toml`, use the Phala deploy action. It installs the CLI, waits for the update, and returns the result as outputs. See [Deploy with the GitHub Action](/phala-cloud/phala-cloud-cli/ci-cd-automation/github-deploy-action). ## GitHub Actions with CLI This is the simplest approach. The workflow builds your Docker image, pushes it to a registry, and deploys with `phala deploy`. ```yaml theme={"system"} name: Deploy to Phala Cloud on: push: branches: [main] workflow_dispatch: jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Log in to Docker Registry uses: docker/login-action@v3 with: username: ${{ secrets.DOCKER_REGISTRY_USERNAME }} password: ${{ secrets.DOCKER_REGISTRY_PASSWORD }} - name: Build and Push Docker image uses: docker/build-push-action@v5 with: context: . push: true tags: ${{ secrets.DOCKER_REGISTRY_USERNAME }}/my-app:${{ github.sha }} - name: Update compose with image tag run: | sed -i "s|\${DOCKER_IMAGE}|${{ secrets.DOCKER_REGISTRY_USERNAME }}/my-app:${{ github.sha }}|g" docker-compose.yml - name: Install Phala CLI run: npm install -g phala - name: Deploy to Phala Cloud env: PHALA_CLOUD_API_KEY: ${{ secrets.PHALA_CLOUD_API_KEY }} run: phala deploy --cvm-id my-tee-app -c docker-compose.yml --wait ``` Your `docker-compose.yml` should reference the image variable: ```yaml theme={"system"} services: app: image: ${DOCKER_IMAGE} ports: - "80:80" ``` `--cvm-id` names the CVM to update, so each push updates `my-tee-app` in place and `--wait` waits for the update to finish. The CLI does not look up an existing CVM by `--name`: `phala deploy -n my-tee-app` always creates a new CVM, on every run. With `--wait`, a new CVM waits until it is running, but it is still a new CVM, not an update. Create the CVM once before the first pipeline run, for example with `phala deploy -n my-tee-app -c docker-compose.yml`. ## GitHub Actions with JS SDK If you need more control over the deployment (conditional logic, custom error handling, multi-step provisioning), use the SDK directly in a Node.js script. **Step 1** ### Create a deploy script Add `scripts/deploy.mjs` to your repository: ```javascript theme={"system"} import { createClient } from "@phala/cloud"; const client = createClient({ apiKey: process.env.PHALA_CLOUD_API_KEY, }); const imageTag = process.env.IMAGE_TAG; const appName = process.env.APP_NAME || "my-tee-app"; const compose = ` services: app: image: ${imageTag} ports: - "80:80" `; // Check if CVM already exists const cvms = await client.getCvmList(); const existing = cvms.items.find((c) => c.name === appName); if (existing) { // Update existing CVM await client.updateDockerCompose({ id: existing.id, dockerCompose: compose, }); await client.restartCvm({ id: existing.id }); console.log(`Updated CVM: ${existing.id}`); } else { // Provision new CVM const provision = await client.provisionCvm({ name: appName, composeFile: { dockerComposeFile: compose }, vcpu: 2, memory: 4096, diskSize: 20, }); const cvm = await client.commitCvmProvision({ appId: provision.appId, composeHash: provision.composeHash, transactionHash: provision.transactionHash, }); console.log(`Created CVM: ${cvm}`); } ``` **Step 2** ### Create the workflow ```yaml theme={"system"} name: Deploy with SDK on: push: branches: [main] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Setup Node.js uses: actions/setup-node@v4 with: node-version: "20" - name: Log in to Docker Registry uses: docker/login-action@v3 with: username: ${{ secrets.DOCKER_REGISTRY_USERNAME }} password: ${{ secrets.DOCKER_REGISTRY_PASSWORD }} - name: Build and Push Docker image uses: docker/build-push-action@v5 with: context: . push: true tags: ${{ secrets.DOCKER_REGISTRY_USERNAME }}/my-app:${{ github.sha }} - name: Install dependencies run: npm install @phala/cloud - name: Deploy env: PHALA_CLOUD_API_KEY: ${{ secrets.PHALA_CLOUD_API_KEY }} IMAGE_TAG: ${{ secrets.DOCKER_REGISTRY_USERNAME }}/my-app:${{ github.sha }} APP_NAME: my-tee-app run: node scripts/deploy.mjs ``` ## GitLab CI GitLab CI uses a similar pattern. Define a `.gitlab-ci.yml` in your repository root: ```yaml theme={"system"} stages: - build - deploy variables: IMAGE_TAG: "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA" build: stage: build image: docker:24 services: - docker:24-dind script: - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" "$CI_REGISTRY" - docker build -t "$IMAGE_TAG" . - docker push "$IMAGE_TAG" deploy: stage: deploy image: node:20 script: - npm install -g phala - sed -i "s|\${DOCKER_IMAGE}|$IMAGE_TAG|g" docker-compose.yml - phala deploy --cvm-id my-tee-app -c docker-compose.yml --wait variables: PHALA_CLOUD_API_KEY: "$PHALA_CLOUD_API_KEY" only: - main ``` > [!NOTE] > > GitLab's built-in container registry works well here. The `$CI_REGISTRY_*` variables are available automatically in every pipeline. ## Terraform in CI For infrastructure-as-code workflows, run Terraform in your pipeline. This is especially useful when you manage replicas, instance types, or environment variables declaratively. ```yaml theme={"system"} name: Deploy with Terraform on: push: branches: [main] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Setup Terraform uses: hashicorp/setup-terraform@v3 with: terraform_version: "1.5" - name: Terraform Init run: terraform init working-directory: ./infra - name: Terraform Apply env: PHALA_CLOUD_API_KEY: ${{ secrets.PHALA_CLOUD_API_KEY }} run: terraform apply -auto-approve -var="image_tag=${{ github.sha }}" working-directory: ./infra ``` Your `infra/main.tf` would look something like this: ```hcl theme={"system"} variable "image_tag" { type = string } resource "phala_app" "web" { name = "my-tee-app" size = "tdx.medium" region = "US-WEST-1" image = "dstack-dev-0.5.7-9b6a5239" disk_size = 40 replicas = 1 docker_compose = <<-YAML services: app: image: myregistry/my-app:${var.image_tag} ports: - "80:80" YAML wait_for_ready = true wait_timeout_seconds = 900 } ``` > [!NOTE] > > Store your Terraform state in a remote backend (S3, GCS, or Terraform Cloud) so that CI runs can access the same state file. Without remote state, each pipeline run would try to create a new CVM instead of updating the existing one. ## Verify Deployment After your pipeline completes, confirm the CVM is running: ```bash theme={"system"} # CLI phala cvms get my-tee-app # Or check the dashboard # https://cloud.phala.com/dashboard ``` ## Troubleshooting **Authentication errors:** Make sure `PHALA_CLOUD_API_KEY` is set correctly in your CI secrets. Test locally with `phala status` to verify the key works. **Build failures:** Ensure your Dockerfile builds locally with `docker build .` before pushing to CI. **Deploy timeouts:** `--wait` waits up to 5 minutes. If it times out, the update or the new CVM may still be starting. Check the dashboard or run `phala cvms get my-tee-app` to see the current status. **Image pull errors:** Verify the image tag in your compose file matches what was pushed to the registry. For private registries, set `DSTACK_DOCKER_USERNAME` and `DSTACK_DOCKER_PASSWORD` as [encrypted secrets](/phala-cloud/cvm/set-secure-environment-variables) on the CVM. # phala completion Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/completion Generate shell completion scripts for bash, zsh, or fish. ## Usage ``` phala completion [options] ``` ## Options | Flag | Short | Default | Description | | - | - | - | - | | `--shell` | | auto-detect | Shell type (bash, zsh, fish) | | `--fig` | | | Generate Fig/Amazon Q completion spec | If `--shell` is omitted, the CLI auto-detects the shell from the `$SHELL` environment variable. ## Examples ### Bash ```bash theme={"system"} $ phala completion --shell bash >> ~/.bashrc && source ~/.bashrc ``` ### Zsh ```bash theme={"system"} $ phala completion --shell zsh >> ~/.zshrc && source ~/.zshrc ``` ### Fish ```bash theme={"system"} $ phala completion --shell fish > ~/.config/fish/completions/phala.fish ``` ### Fig/Amazon Q ```bash theme={"system"} $ phala completion --fig ``` # config (Deprecated) Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/config Manage local CLI state > [!WARNING] > > This command is deprecated. See the newer alternatives. ### Command: `phala config` #### Syntax ``` phala config [options] ``` #### Description Manage local CLI state #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * Display help: ```bash theme={"system"} phala config --help ``` ### Subcommands | Command | Description | | - | - | | `get` | Get a configuration value | | `list` | List config values | | `set` | Set a configuration value | # config get Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/config/get Get a configuration value ## Command: `phala config get` ### Syntax ``` phala config get ``` ### Description Get a configuration value ### Arguments | Argument | Description | | - | - | | `` | Configuration key | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Display help: ```bash theme={"system"} phala config get --help ``` # config list Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/config/list List config values ## Command: `phala config list` ### Syntax ``` phala config list [options] ``` ### Description List config values ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Display help: ```bash theme={"system"} phala config list --help ``` # config set Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/config/set Set a configuration value ## Command: `phala config set` ### Syntax ``` phala config set ``` ### Description Set a configuration value ### Arguments | Argument | Description | | - | - | | `` | Configuration key | | `` | Configuration value | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Display help: ```bash theme={"system"} phala config set --help ``` # cp Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/cp Copy files to/from a CVM via SCP > [!NOTE] > > This command is marked as unstable and may change in future releases. ### Command: `phala cp` #### Syntax ``` phala cp [options] ``` #### Description Copy files to/from a CVM via SCP #### Arguments | Argument | Description | | - | - | | `` | Source path (local or cvm-name:path, use :path for phala.toml cvm\_id) | | `` | Destination path (local or cvm-name:path, use :path for phala.toml cvm\_id) | #### Options | Option | Description | | - | - | | `-i, --identity ` | SSH identity file (private key) | | `-p, --port ` | SSH port (priority: CLI > phala.toml > 443) | | `-g, --gateway ` | Gateway domain (priority: CLI > phala.toml > API) | | `-r, --recursive` | Recursively copy directories | | `-v, --verbose` | Show verbose SCP details | | `--dry-run` | Print SCP command without executing | #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `--version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * Upload from phala.toml ```bash theme={"system"} phala cp ./local.txt :/root/remote.txt ``` * Upload to CVM ```bash theme={"system"} phala cp ./local.txt app_123:/root/remote.txt ``` * Download from CVM ```bash theme={"system"} phala cp app_123:/root/remote.txt ./local.txt ``` * Offline mode ```bash theme={"system"} phala cp -g dstack-pha-prod7.phala.network -p 16185 ./file.txt app_123:/root/ ``` * Upload directory recursively ```bash theme={"system"} phala cp -r ./local_dir app_123:/root/remote_dir ``` * Copy with custom SSH key ```bash theme={"system"} phala cp -i ~/.ssh/custom_key app_123:/root/file.txt ./file.txt ``` * Print the SCP command without executing ```bash theme={"system"} phala cp ./local.txt app_123:/root/remote.txt --dry-run ``` # cvms Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/cvms Manage CVMs > [!NOTE] > > This command is marked as unstable and may change in future releases. ### Command: `phala cvms` #### Syntax ``` phala cvms [options] ``` #### Description Manage CVMs #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * Display help: ```bash theme={"system"} phala cvms --help ``` ### Subcommands | Command | Description | | - | - | | `attestation` | Get CVM attestation | | `delete` | Delete a CVM | | `device-allowlist` | Show device allowlist status for a CVM's app | | `get` | Get details of a CVM | | `init-scripts` | Show or change the platform init scripts a CVM runs | | `list` | List CVMs | | `list-nodes` | List worker nodes | | `replicate` | Create a replica of an existing CVM | | `resize` | Resize resources for a CVM | | `restart` | Restart a CVM | | `start` | Start a stopped CVM | | `stop` | Stop a running CVM | ### Deprecated Subcommands | Command | Description | | - | - | | `logs` | Fetch container logs from a CVM | | `serial-logs` | Fetch VM serial console logs from a CVM | | `upgrade` | Upgrade a CVM to a new version (use "phala deploy" instead) | # cvms attestation Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/cvms/attestation Get CVM attestation > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala cvms attestation` ### Syntax ``` phala cvms attestation [options] [] ``` ### Description Get CVM attestation ### Arguments | Argument | Description | | - | - | | `?` | CVM identifier (UUID, app\_id, instance\_id, or name) | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `-i, --interactive` | Enable interactive mode | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Show attestation summary ```bash theme={"system"} phala cvms attestation ``` * Output full attestation JSON ```bash theme={"system"} phala cvms attestation --json ``` # cvms delete Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/cvms/delete Delete a CVM > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala cvms delete` ### Syntax ``` phala cvms delete [options] [] ``` ### Description Delete a CVM ### Arguments | Argument | Description | | - | - | | `?` | CVM identifier (UUID, app\_id, instance\_id, or name) | ### Options | Option | Description | | - | - | | `-f, --force` | Skip confirmation prompt | | `-y, --yes` | Alias for --force (skip confirmation prompt) | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `-i, --interactive` | Enable interactive mode | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Delete a CVM interactively ```bash theme={"system"} phala cvms delete ``` * Delete CVM by app\_id ```bash theme={"system"} phala cvms delete app_123 --force ``` * Delete CVM by UUID ```bash theme={"system"} phala cvms delete 550e8400-e29b-41d4-a716-446655440000 -f ``` * Delete CVM by name ```bash theme={"system"} phala cvms delete my-app --yes ``` # cvms device-allowlist Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/cvms/device-allowlist Show device allowlist status for a CVM's app > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala cvms device-allowlist` ### Syntax ``` phala cvms device-allowlist [options] [] ``` ### Description Show device allowlist status for a CVM's app ### Arguments | Argument | Description | | - | - | | `?` | CVM identifier (UUID, app\_id, instance\_id, or name) | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `-i, --interactive` | Enable interactive mode | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Check device allowlist ```bash theme={"system"} phala cvms device-allowlist app_abc123 ``` # cvms get Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/cvms/get Get details of a CVM > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala cvms get` ### Syntax ``` phala cvms get [options] [] ``` ### Description Get details of a CVM ### Arguments | Argument | Description | | - | - | | `?` | CVM identifier (UUID, app\_id, instance\_id, or name) | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `-i, --interactive` | Enable interactive mode | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Get CVM interactively ```bash theme={"system"} phala cvms get ``` * By app\_id ```bash theme={"system"} phala cvms get app_abc123 ``` * By UUID ```bash theme={"system"} phala cvms get 550e8400-e29b-41d4-a716-446655440000 ``` * By name ```bash theme={"system"} phala cvms get my-app ``` # cvms init-scripts Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/cvms/init-scripts Show or change the platform init scripts a CVM runs > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala cvms init-scripts` ### Syntax ``` phala cvms init-scripts [options] [] [] [] ``` ### Description Show or change the platform init scripts a CVM runs. With only a CVM, it lists the scripts. With a script name and `on` or `off`, it turns that script on or off and keeps the others as they are. Turning a script on or off changes the CVM's compose, so the CVM restarts. See [Init scripts](/phala-cloud/cvm/advanced-settings#init-scripts). ### Arguments | Argument | Description | | - | - | | `?` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `?` | Platform init script (`docker_cleanup`) | | `?` | `on` or `off` | Pass both `` and ``, or neither. ### Options | Option | Description | | - | - | | `--confirm-data-wipe` | Confirm turning on `docker_cleanup`, which erases container stores on every boot | ### Advanced Options | Option | Description | | - | - | | `--prepare-only` | Prepare the update and print the compose hash. Skips on-chain operations. | | `--compose-hash ` | Compose hash from a prepare-only update | | `--transaction-hash ` | Transaction hash proving on-chain compose hash registration. Pass `already-registered` to skip the proof and rely on state-only verification. | | `--private-key ` | Private key for signing on-chain transactions (or set PRIVATE\_KEY env var) | | `--rpc-url ` | RPC URL for on-chain KMS transactions (or set ETH\_RPC\_URL env var) | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `-i, --interactive` | Enable interactive mode | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Output Without a script name, the command prints one row per script with the columns `SLUG`, `SELECTED`, `SELECTABLE`, and `REASON`. `SELECTED` says whether the CVM runs the script. `SELECTABLE` says whether you can turn it on for this CVM, and `REASON` says why not. If the script is already in the state you asked for, the command says so and changes nothing. ### Examples * List init scripts ```bash theme={"system"} phala cvms init-scripts app_123 ``` * Turn docker\_cleanup on ```bash theme={"system"} phala cvms init-scripts app_123 docker_cleanup on --confirm-data-wipe ``` * Turn docker\_cleanup off ```bash theme={"system"} phala cvms init-scripts app_123 docker_cleanup off ``` # cvms list Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/cvms/list List CVMs > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala cvms list` ### Syntax ``` phala cvms list [options] ``` ### Description List CVMs ### Options | Option | Description | | - | - | | `--page ` | Page number (1-based) | | `--page-size ` | Number of items per page | | `--search ` | Search by name, app\_id, vm\_uuid, or instance\_id | | `--status ` | Filter by CVM status (can be specified multiple times) | | `--listed, --no-listed` | Filter by listed status | | `--base-image ` | Filter by base image name | | `--instance-type ` | Filter by instance type | | `--kms-type ` | Filter by KMS type | | `--node ` | Filter by node name | | `--region ` | Filter by region identifier | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * List CVMs ```bash theme={"system"} phala cvms ls ``` * Second page ```bash theme={"system"} phala cvms ls --page 2 ``` * Search by name ```bash theme={"system"} phala cvms ls --search my-cvm ``` * Filter by status ```bash theme={"system"} phala cvms ls --status running ``` * Output as JSON ```bash theme={"system"} phala cvms ls --json ``` # cvms list-nodes Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/cvms/list-nodes List worker nodes > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala cvms list-nodes` ### Syntax ``` phala cvms list-nodes ``` ### Description List worker nodes ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Display help: ```bash theme={"system"} phala cvms list-nodes --help ``` # cvms logs (Deprecated) Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/cvms/logs Fetch container logs from a CVM > [!WARNING] > > This command is deprecated. See the newer alternatives. ## Command: `phala cvms logs` ### Syntax ``` phala cvms logs [options] [] ``` ### Description Fetch container logs from a CVM ### Arguments | Argument | Description | | - | - | | `?` | CVM identifier (UUID, app\_id, instance\_id, or name) | ### Options | Option | Description | | - | - | | `-n, --tail ` | Lines from end | | `-f, --follow` | Stream logs in real-time | | `-t, --timestamps` | Show timestamps | | `-c, --container ` | Container name or ID (defaults to first) | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `-i, --interactive` | Enable interactive mode | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Show container logs from a CVM ```bash theme={"system"} phala cvms logs app_abc123 ``` * Show last 100 lines of logs ```bash theme={"system"} phala cvms logs app_abc123 --tail 100 ``` * Follow logs in real-time ```bash theme={"system"} phala cvms logs app_abc123 --follow ``` * Show logs from a specific container ```bash theme={"system"} phala cvms logs app_abc123 --container my-service ``` * Show logs with timestamps ```bash theme={"system"} phala cvms logs app_abc123 --timestamps ``` # cvms replicate Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/cvms/replicate Create a replica of an existing CVM > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala cvms replicate` ### Syntax ``` phala cvms replicate [options] [] ``` ### Description Create a replica of an existing CVM ### Arguments | Argument | Description | | - | - | | `?` | CVM identifier (UUID, app\_id, instance\_id, or name) | ### Options | Option | Description | | - | - | | `--node ` | Physical node name for the replica, such as `usw5`. Run `phala nodes` to list the nodes you can use. | | `--compose-hash ` | Compose hash to replicate. Required when the source app has multiple live instances. | | `-e, --env-file ` | Path to environment file. | ### Advanced Options | Option | Description | | - | - | | `--private-key ` | Private key for signing on-chain transactions (or set PRIVATE\_KEY env var) | | `--rpc-url ` | RPC URL for on-chain KMS transactions (or set ETH\_RPC\_URL env var) | | `--prepare-only` | Prepare the replica and generate a commit token. Skips all on-chain operations. | | `--commit` | Commit a previously prepared replica using a commit token. Requires --token, --compose-hash, and --transaction-hash. | | `--token ` | Commit token from a prepare-only replica request. | | `--transaction-hash ` | Transaction hash proving on-chain compose hash registration. Pass `already-registered` to skip the proof and rely on state-only verification. | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `-i, --interactive` | Enable interactive mode | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Replicate a CVM ```bash theme={"system"} phala cvms replicate 1234 --node usw5 ``` * Prepare a replica for multisig approval ```bash theme={"system"} phala cvms replicate 1234 --node usw5 --compose-hash --prepare-only ``` * Commit a prepared replica ```bash theme={"system"} phala cvms replicate 1234 --commit --token --compose-hash --transaction-hash ``` # cvms resize Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/cvms/resize Resize resources for a CVM > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala cvms resize` ### Syntax ``` phala cvms resize [options] [] ``` ### Description Resize resources for a CVM ### Arguments | Argument | Description | | - | - | | `?` | CVM identifier (UUID, app\_id, instance\_id, or name) | ### Options | Option | Description | | - | - | | `-v, --vcpu ` | Virtual CPUs | | `-m, --memory ` | Memory in MB | | `-d, --disk-size ` | Disk size in GB | | `-y, --yes` | Skip confirmation | ### Deprecated Options | Option | Description | | - | - | | `-r, --allow-restart ` | Deprecated and ignored: the CVM restarts when the resize needs it | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `--version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `--json` | Output in JSON format | | `-i, --interactive` | Enable interactive mode | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Resize CVM interactively ```bash theme={"system"} phala cvms resize ``` * Resize without confirmation ```bash theme={"system"} phala cvms resize app_123 --vcpu 4 --memory 4096 --disk-size 120 --yes ``` # cvms restart Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/cvms/restart Restart a CVM ## Command: `phala cvms restart` ### Syntax ``` phala cvms restart [options] [] ``` ### Description Restart a CVM ### Arguments | Argument | Description | | - | - | | `?` | CVM identifier (UUID, app\_id, instance\_id, or name) | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `-i, --interactive` | Enable interactive mode | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * By app\_id ```bash theme={"system"} phala cvms restart app_123 ``` * By UUID ```bash theme={"system"} phala cvms restart 550e8400-e29b-41d4-a716-446655440000 ``` * By name ```bash theme={"system"} phala cvms restart my-app ``` # cvms serial-logs (Deprecated) Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/cvms/serial-logs Fetch VM serial console logs from a CVM > [!WARNING] > > This command is deprecated. See the newer alternatives. ## Command: `phala cvms serial-logs` ### Syntax ``` phala cvms serial-logs [options] [] ``` ### Description Fetch VM serial console logs from a CVM ### Arguments | Argument | Description | | - | - | | `?` | CVM identifier (UUID, app\_id, instance\_id, or name) | ### Options | Option | Description | | - | - | | `-n, --tail ` | Lines from end | | `-f, --follow` | Stream logs in real-time | | `-t, --timestamps` | Show timestamps | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `-i, --interactive` | Enable interactive mode | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Show VM serial logs ```bash theme={"system"} phala cvms serial-logs app_abc123 ``` * Show last 100 lines of serial logs ```bash theme={"system"} phala cvms serial-logs app_abc123 --tail 100 ``` * Follow serial logs in real-time ```bash theme={"system"} phala cvms serial-logs app_abc123 --follow ``` * Show serial logs with timestamps ```bash theme={"system"} phala cvms serial-logs app_abc123 --timestamps ``` # cvms start Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/cvms/start Start a stopped CVM ## Command: `phala cvms start` ### Syntax ``` phala cvms start [options] [] ``` ### Description Start a stopped CVM ### Arguments | Argument | Description | | - | - | | `?` | CVM identifier (UUID, app\_id, instance\_id, or name) | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `-i, --interactive` | Enable interactive mode | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Start CVM by app\_id ```bash theme={"system"} phala cvms start app_123 ``` * Start CVM by UUID ```bash theme={"system"} phala cvms start 550e8400-e29b-41d4-a716-446655440000 ``` * Start CVM by name ```bash theme={"system"} phala cvms start my-app ``` # cvms stop Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/cvms/stop Stop a running CVM ## Command: `phala cvms stop` ### Syntax ``` phala cvms stop [options] [] ``` ### Description Stop a running CVM ### Arguments | Argument | Description | | - | - | | `?` | CVM identifier (UUID, app\_id, instance\_id, or name) | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `-i, --interactive` | Enable interactive mode | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Stop CVM by app\_id ```bash theme={"system"} phala cvms stop app_123 ``` * Stop CVM by UUID ```bash theme={"system"} phala cvms stop 550e8400-e29b-41d4-a716-446655440000 ``` * Stop CVM by name ```bash theme={"system"} phala cvms stop my-app ``` # cvms upgrade (Deprecated) Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/cvms/upgrade Upgrade a CVM to a new version (use "phala deploy" instead) > [!WARNING] > > This command is deprecated. See the newer alternatives. ## Command: `phala cvms upgrade` ### Syntax ``` phala cvms upgrade [options] [] ``` ### Description Upgrade a CVM to a new version (use "phala deploy" instead) ### Arguments | Argument | Description | | - | - | | `?` | CVM identifier (UUID, app\_id, instance\_id, or name) | ### Options | Option | Description | | - | - | | `-c, --compose ` | Path to Docker Compose file | | `-e, --env-file ` | Path to environment file | | `--debug` | Enable debug output | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `-i, --interactive` | Enable interactive mode | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Upgrade a CVM interactively ```bash theme={"system"} phala cvms upgrade ``` * Upgrade using a compose file ```bash theme={"system"} phala cvms upgrade app_123 --compose ./docker-compose.yml ``` # deploy Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/deploy Deploy new CVM or update existing one ### Command: `phala deploy` #### Syntax ``` phala deploy [options] ``` #### Description Deploy new CVM or update existing one #### Options | Option | Description | | - | - | | `-n, --name ` | CVM name (defaults to directory name) | | `-c, --compose ` | Path to Docker Compose file (default: docker-compose.yml) | | `-t, --instance-type ` | Instance type (e.g., tdx.small, auto-selected if omitted) | | `-r, --region ` | Preferred region (e.g., us-west, auto-selected if omitted) | | `-e, --env ` | Environment variable (KEY=VALUE) or env file path (repeatable) | | `--kms ` | KMS type: phala (default), ethereum/eth, or base | | `--wait` | Wait for the deployment to finish and fail if it failed. New CVM: wait until it is running. Update (--cvm-id): wait until the CVM is running again, or stays stopped if it was not running before the update | | `--ssh-pubkey ` | SSH public key path (default: \~/.ssh/id\_rsa.pub) | | `--dev-os, --no-dev-os` | Use dev OS image (requires SSH key) | | `--public-logs, --no-public-logs` | Make CVM logs publicly accessible (default: true) | | `--public-sysinfo, --no-public-sysinfo` | Make CVM system info publicly accessible (default: true) | | `--public-tcbinfo, --no-public-tcbinfo` | Make attestation data publicly accessible (default: true) | | `--secure-time, --no-secure-time` | Enable secure time (default: false) | | `--listed, --no-listed` | List CVM on the public Trust Center (default: false) | #### Advanced Options | Option | Description | | - | - | | `--debug` | Enable debug logging | | `--disk-size ` | Disk size with unit (e.g., 50G, default: 40GB) | | `--fs ` | Filesystem for the data disk: zfs (default) or ext4. ext4 has lower I/O overhead; only zfs detects a modified block on the encrypted disk. | | `--image ` | OS image version (auto-selected if omitted) | | `--node ` | Physical node name, such as `usw5` (auto-selected if omitted). Run `phala nodes` to list the nodes you can use. | | `--kms-contract ` | KMS contract address | | `--kms-contract-id ` | KMS contract ID | | `--key-provider-mode ` | Key provider mode: kms or local | | `--experimental-key-provider-type ` | Set key\_provider in compose (kms, local, tpm). Backend resolves key\_provider\_id for kms; local/tpm require manual key\_provider\_id. Computes and displays mr\_config\_id after provision. | | `--skip-gateway` | Skip gateway matching | | `--custom-app-id ` | Custom App ID (requires --nonce for PHALA KMS) | | `--nonce ` | Nonce for deterministic app\_id (requires --custom-app-id, PHALA KMS only) | | `--pre-launch-script ` | Path to pre-launch script | | `--no-pre-launch-script` | Deploy without any pre-launch script. This also skips the automatic local SSH key, unless you pass `--dev-os` or `--ssh-pubkey`. | | `--runner ` | App runner: docker-compose (default), nerdctl-compose, or bash. With bash, --compose is the script to run. nerdctl-compose and bash need the compose\_advanced feature. Create only. | | `--app-compose ` | Path to a whole app-compose JSON file, sent instead of --compose and the compose flags. Needs the compose\_advanced feature. Create only. | | `--init-script ` | Platform init script to run on every boot: docker\_cleanup (repeatable). On update, replaces the current set. | | `--clear-init-scripts` | Remove every platform init script from an existing CVM. Cannot be combined with --init-script. Update only. | | `--launch-token ` | Launch token (at least 32 bytes) the CVM must boot with. Create only. | | `--generate-launch-token` | Gate the CVM with a launch token Phala Cloud generates for a new app (shown once), or with the app's existing token. Create only. | | `--launch-token-hash ` | Set requirements.launch\_token\_hash of an existing CVM to the hash printed by `phala apps launch-token set`; "" removes it. Update only. | | `--event-log-version ` | Event log digest format: 1 or 2 (dstack OS 0.6.0+) | | `--ephemeral-data-disk, --no-ephemeral-data-disk` | Format the data disk on every boot (dstack OS 0.6.3+). Turning it on for an existing CVM needs --confirm-data-wipe. | | `--gateway, --no-gateway` | Route the CVM through the gateway (default: true) | | `--confirm-data-wipe` | Confirm an update that turns on docker\_cleanup or --ephemeral-data-disk, which erase data on every boot. Update only. | | `--private-key ` | Private key for signing on-chain transactions (or set PRIVATE\_KEY env var) | | `--rpc-url ` | RPC URL for on-chain KMS transactions (or set ETH\_RPC\_URL env var) | | `--prepare-only` | Prepare the update and generate a commit token. Skips all on-chain operations. Intended for multisig workflows. | | `--commit` | Commit a previously prepared update using a commit token. Requires --token; --compose-hash and --transaction-hash are read from the token when omitted. | | `--token ` | Commit token from a prepare-only update. | | `--compose-hash ` | Compose hash from a prepare-only update. Optional in --commit mode when the token can provide it. | | `--transaction-hash ` | Transaction hash proving on-chain compose hash registration. Pass `already-registered` to skip the proof and rely on state-only verification. | #### Deprecated Options | Option | Description | | - | - | | `--uuid ` | \[DEPRECATED] Use --cvm-id instead. CVM UUID. | | `--vcpu ` | Use --instance-type instead | | `--memory ` | Use --instance-type instead | | `--env-file ` | Use -e instead | | `--kms-id ` | Use --kms instead | #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `-i, --interactive` | Enable interactive mode | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * Deploy new CVM ```bash theme={"system"} phala deploy ``` * Deploy with environment variables ```bash theme={"system"} phala deploy -e NODE_ENV=production -e DEBUG=true ``` * Deploy with env file ```bash theme={"system"} phala deploy -e .env ``` * Deploy with specific instance type ```bash theme={"system"} phala deploy --instance-type tdx.medium ``` * Deploy to specific region ```bash theme={"system"} phala deploy --region us-west ``` * Deploy from a whole app-compose file ```bash theme={"system"} phala deploy --app-compose app-compose.json ``` * Deploy with a generated launch token ```bash theme={"system"} phala deploy --generate-launch-token ``` * Deploy with Ethereum KMS ```bash theme={"system"} phala deploy --kms ethereum --private-key --rpc-url ``` * Update existing CVM by ID ```bash theme={"system"} phala deploy --cvm-id app_abc123 ``` * Update CVM with new compose file and env ```bash theme={"system"} phala deploy --cvm-id my-app --compose ./new-docker-compose.yml -e .env ``` * Deploy a new CVM and wait until it is running ```bash theme={"system"} phala deploy --wait ``` On a new CVM, `--wait` waits up to 5 minutes for the CVM to run. If it does not start, the command fails with the boot error and the CVM ID. The CVM exists even then, so check it with `phala cvms get `. * Update CVM and wait for completion ```bash theme={"system"} phala deploy --cvm-id app_abc123 --wait ``` On an update, `--wait` first waits for the update operation. If the update fails, the command stops at once with the operation's status and error message. Otherwise it then waits for the CVM to settle. If the CVM was running before the update, it waits until the CVM is running again. In any other state before the update (stopped, error, and so on), it waits until the CVM is stopped. For a CVM that uses the `bash` runner, `--compose` (`-c`) sends the file as the CVM's `bash_script`. * Update CVM from phala.toml ```bash theme={"system"} phala deploy ``` * Deploy with logs and sysinfo disabled ```bash theme={"system"} phala deploy --no-public-logs --no-public-sysinfo ``` * Deploy and list on Trust Center ```bash theme={"system"} phala deploy --listed ``` * Turn on container cleanup for an existing CVM ```bash theme={"system"} phala deploy --cvm-id app_123 --init-script docker_cleanup --confirm-data-wipe ``` * Update existing CVM to disable logs ```bash theme={"system"} phala deploy --cvm-id app_123 --no-public-logs ``` * Prepare update for multisig approval ```bash theme={"system"} phala deploy --cvm-id app_123 --prepare-only -c docker-compose.yml ``` * Commit a prepared update ```bash theme={"system"} phala deploy --cvm-id app_123 --commit --token --compose-hash 0x... --transaction-hash 0x... ``` # envs Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/envs Encrypt and update CVM sealed environment variables ### Command: `phala envs` #### Syntax ``` phala envs [options] ``` #### Description Encrypt and update CVM sealed environment variables #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * Display help: ```bash theme={"system"} phala envs --help ``` ### Subcommands | Command | Description | | - | - | | `encrypt` | Encrypt environment variables for a CVM (sealed, only readable inside TEE) | | `update` | Encrypt and push sealed environment variables to a CVM (only readable inside TEE) | # envs encrypt Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/envs/encrypt Encrypt environment variables for a CVM (sealed, only readable inside TEE) ## Command: `phala envs encrypt` ### Syntax ``` phala envs encrypt [options] [] ``` ### Description Encrypt environment variables for a CVM (sealed, only readable inside TEE) ### Arguments | Argument | Description | | - | - | | `?` | CVM identifier (UUID, app\_id, instance\_id, or name) | ### Options | Option | Description | | - | - | | `-e, --env ` | Environment variable (KEY=VALUE) or env file path (repeatable) | | `-n, --no-newline` | Do not print trailing newline (useful for piping) | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `-i, --interactive` | Enable interactive mode | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Encrypt inline variables ```bash theme={"system"} phala envs encrypt app_abc123 -e SECRET=value -e API_KEY=xxx ``` * Encrypt from env file ```bash theme={"system"} phala envs encrypt app_abc123 -e .env ``` * Encrypt with CVM from phala.toml ```bash theme={"system"} phala envs encrypt -e .env.production ``` * Pipe to file for later use ```bash theme={"system"} phala envs encrypt app_abc123 -e .env > encrypted.hex ``` * Pipe without trailing newline ```bash theme={"system"} phala envs encrypt app_abc123 -n -e .env | some-tool ``` # envs update Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/envs/update Encrypt and push sealed environment variables to a CVM (only readable inside TEE) ## Command: `phala envs update` ### Syntax ``` phala envs update [options] [] ``` ### Description Encrypt and push sealed environment variables to a CVM (only readable inside TEE) ### Arguments | Argument | Description | | - | - | | `?` | CVM identifier (UUID, app\_id, instance\_id, or name) | ### Options | Option | Description | | - | - | | `-e, --env ` | Environment variable (KEY=VALUE) or env file path (repeatable) | | `--encrypted-env ` | Pre-encrypted environment variables as hex string (from 'phala envs encrypt') | ### Advanced Options | Option | Description | | - | - | | `--private-key ` | Private key for signing on-chain transactions (or set PRIVATE\_KEY env var) | | `--rpc-url ` | RPC URL for on-chain KMS transactions (or set ETH\_RPC\_URL env var) | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `-i, --interactive` | Enable interactive mode | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Update with inline variables ```bash theme={"system"} phala envs update app_abc123 -e SECRET=newvalue -e API_KEY=xxx ``` * Update from env file ```bash theme={"system"} phala envs update app_abc123 -e .env.production ``` * Update with CVM from phala.toml ```bash theme={"system"} phala envs update -e .env ``` * Update with pre-encrypted hex (from 'phala envs encrypt') ```bash theme={"system"} phala envs update app_abc123 --encrypted-env $(phala envs encrypt app_abc123 -e .env) ``` * Update with on-chain KMS ```bash theme={"system"} phala envs update app_abc123 -e .env --private-key ``` # instance-types Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/instance-types List available instance types > [!NOTE] > > This command is marked as unstable and may change in future releases. ### Command: `phala instance-types` #### Syntax ``` phala instance-types [options] [] ``` #### Description List available instance types #### Arguments | Argument | Description | | - | - | | `?` | Instance type family (cpu, gpu) | #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * List all instance type families ```bash theme={"system"} phala instance-types ``` * List CPU instance types ```bash theme={"system"} phala instance-types cpu ``` * List GPU instance types ```bash theme={"system"} phala instance-types gpu ``` * Output as JSON ```bash theme={"system"} phala instance-types --json ``` # instances Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/instances Manage app instances > [!NOTE] > > This command is marked as unstable and may change in future releases. ### Command: `phala instances` #### Syntax ``` phala instances [options] ``` #### Description Manage app instances #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * Display help: ```bash theme={"system"} phala instances --help ``` ### Subcommands | Command | Description | | - | - | | `ls` | List instances of an app | | `add` | Create a new instance under an existing app | | `rm` | Delete one or more app instances by VM UUID | # instances add Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/instances/add Create a new instance under an existing app > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala instances add` ### Syntax ``` phala instances add [options] ``` ### Description Create a new instance under an existing app ### Options | Option | Description | | - | - | | `--app-id ` | App ID (hex identifier). Defaults to app\_id in phala.toml. | | `--name ` | Custom CVM name for the new instance. | | `--node ` | Physical node name for the new instance, such as `usw5`. Run `phala nodes` to list the nodes you can use. | | `-c, --compose-file ` | Path to Docker Compose file. | | `--pre-launch-script ` | Path to pre-launch script file. | | `-e, --env-file ` | Path to environment file. | | `--compose-hash ` | Compose hash to use (existing revision). | ### Advanced Options | Option | Description | | - | - | | `--private-key ` | Private key for signing on-chain transactions (or set PRIVATE\_KEY env var) | | `--rpc-url ` | RPC URL for on-chain KMS transactions (or set ETH\_RPC\_URL env var) | | `--prepare-only` | Prepare the instance and generate a commit token. Skips all on-chain operations. | | `--commit` | Commit a previously prepared instance using a commit token. Requires --token, --compose-hash, and --transaction-hash. | | `--token ` | Commit token from a prepare-only request. | | `--transaction-hash ` | Transaction hash proving on-chain compose hash registration. Pass `already-registered` to skip the proof and rely on state-only verification. | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `-i, --interactive` | Enable interactive mode | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Add instance with existing compose ```bash theme={"system"} phala instances add --app-id --node usw5 ``` * Add instance with custom name ```bash theme={"system"} phala instances add --app-id --name redis-0 --node usw5 ``` * Add instance with new Docker Compose ```bash theme={"system"} phala instances add --app-id --node usw5 --compose-file docker-compose.yml ``` * Prepare for multisig approval ```bash theme={"system"} phala instances add --app-id --node usw5 --compose-file docker-compose.yml --prepare-only ``` * Commit a prepared instance ```bash theme={"system"} phala instances add --app-id --commit --token --compose-hash --transaction-hash ``` # instances ls Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/instances/ls List instances of an app > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala instances ls` ### Syntax ``` phala instances ls [options] ``` ### Description List instances of an app ### Options | Option | Description | | - | - | | `--app-id ` | App ID (hex identifier). Defaults to app\_id in phala.toml. | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * List instances for app in phala.toml ```bash theme={"system"} phala instances ls ``` * List instances for a specific app ```bash theme={"system"} phala instances ls --app-id ``` * Output as JSON ```bash theme={"system"} phala instances ls --app-id --json ``` # instances rm Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/instances/rm Delete one or more app instances by VM UUID > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala instances rm` ### Syntax ``` phala instances rm [options] ... ``` ### Description Delete one or more app instances by VM UUID ### Arguments | Argument | Description | | - | - | | `` | VM UUID(s) of the instances to delete | ### Options | Option | Description | | - | - | | `-f, --force` | Skip confirmation prompt | | `-y, --yes` | Alias for --force (skip confirmation prompt) | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Delete a single instance ```bash theme={"system"} phala instances rm 550e8400-e29b-41d4-a716-446655440000 ``` * Delete multiple instances ```bash theme={"system"} phala instances rm 550e8400-e29b-41d4-a716-446655440000 661f9511-f30c-52e5-b827-557766551111 ``` * Delete without confirmation ```bash theme={"system"} phala instances rm 550e8400-e29b-41d4-a716-446655440000 --force ``` # keccak256sum Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/keccak256sum Compute or verify keccak256 checksums of hex inputs ### Command: `phala keccak256sum` #### Syntax ``` phala keccak256sum [options] ... ``` #### Description Compute or verify keccak256 checksums of hex inputs #### Arguments | Argument | Description | | - | - | | `` | Hex strings to hash, or checksum file path when using -c | #### Options | Option | Description | | - | - | | `-c, --check` | Read checksums from file and verify them | | `--quiet` | In check mode, suppress OK messages | | `--status` | In check mode, suppress all output; exit code indicates result | #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * Hash concatenated hex values ```bash theme={"system"} phala keccak256sum deadbeef 0123456789abcdef 0x02 cafe ``` * Hash hex from stdin ```bash theme={"system"} echo 'deadbeef' | phala keccak256sum ``` * Verify checksums from file ```bash theme={"system"} phala keccak256sum -c checksums.txt ``` # kms Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/kms Manage on-chain KMS contracts > [!NOTE] > > This command is marked as unstable and may change in future releases. ### Command: `phala kms` #### Syntax ``` phala kms [options] ``` #### Description Manage on-chain KMS contracts #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * Display help: ```bash theme={"system"} phala kms --help ``` ### Subcommands | Command | Description | | - | - | | `list` | List KMS contracts | | `nodes` | List the KMS nodes (with RPC url) under a contract | | `ethereum` | Show on-chain KMS details for ethereum | | `base` | Show on-chain KMS details for base | | `phala` | Show the off-chain Phala KMS root keys | # kms base Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/kms/base Show on-chain KMS details for base > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala kms base` ### Syntax ``` phala kms base [options] ``` ### Description Show on-chain KMS details for base ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Show base KMS details ```bash theme={"system"} phala kms base ``` * Output as JSON ```bash theme={"system"} phala kms base --json ``` # kms ethereum Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/kms/ethereum Show on-chain KMS details for ethereum > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala kms ethereum` ### Syntax ``` phala kms ethereum [options] ``` ### Description Show on-chain KMS details for ethereum ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Show ethereum KMS details ```bash theme={"system"} phala kms ethereum ``` * Output as JSON ```bash theme={"system"} phala kms ethereum --json ``` # kms list Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/kms/list List KMS contracts > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala kms list` ### Syntax ``` phala kms list [options] ``` ### Description List KMS contracts ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * List KMS contracts ```bash theme={"system"} phala kms list ``` * Output as JSON ```bash theme={"system"} phala kms list --json ``` # kms nodes Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/kms/nodes List the KMS nodes (with RPC url) under a contract > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala kms nodes` ### Syntax ``` phala kms nodes [options] ``` ### Description List the KMS nodes (with RPC url) under a contract ### Arguments | Argument | Description | | - | - | | `` | KMS contract slug (e.g. phala, base, ethereum) | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * List nodes of the phala KMS contract ```bash theme={"system"} phala kms nodes phala ``` * Output as JSON ```bash theme={"system"} phala kms nodes phala --json ``` # kms phala Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/kms/phala Show the off-chain Phala KMS root keys > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala kms phala` ### Syntax ``` phala kms phala [options] ``` ### Description Show the off-chain Phala KMS root keys ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Show Phala KMS keys ```bash theme={"system"} phala kms phala ``` * Output as JSON ```bash theme={"system"} phala kms phala --json ``` # link Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/link Link a local directory to a CVM > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala link` ### Syntax ``` phala link [options] [] ``` ### Description Link a local directory to a CVM. > [!NOTE] > > As of v1.1.18, `phala link` supports linking by a 40-character hex `app_id` (resolved via the `/apps/` endpoint). After authentication, the CLI prints the workspace `name` and `slug` so you can confirm the target context before the link is written. ### Arguments | Argument | Description | | - | - | | `?` | CVM ID or name (interactive if omitted) | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2025-10-28, 2026-01-21) | ### Examples * Link by name or ID ```bash theme={"system"} phala link my-cvm-name ``` * Link interactively ```bash theme={"system"} phala link ``` # login Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/login Authenticate with Phala Cloud ### Command: `phala login` #### Syntax ``` phala login [options] [] ``` #### Description Authenticate with Phala Cloud #### Arguments | Argument | Description | | - | - | | `?` | API key (triggers device flow if omitted) | #### Options | Option | Description | | - | - | | `--manual` | Enter API key manually | | `--no-open` | Skip browser launch | | `--profile ` | Profile name (defaults to workspace slug) | | `--print-token` | Print token to stdout without saving | | `--url ` | Custom API endpoint URL | #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * Display help: ```bash theme={"system"} phala login --help ``` # logout Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/logout Remove stored API key ### Command: `phala logout` #### Syntax ``` phala logout ``` #### Description Remove stored API key #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * Display help: ```bash theme={"system"} phala logout --help ``` # logs Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/logs Fetch logs from a CVM > [!NOTE] > > This command is marked as unstable and may change in future releases. ### Command: `phala logs` #### Syntax ``` phala logs [options] [] ``` #### Description Fetch logs from a CVM #### Arguments | Argument | Description | | - | - | | `?` | Container name to fetch logs from | #### Options | Option | Description | | - | - | | `--serial` | CVM serial console (boot, kernel, docker-compose) | | `--cvm-stdout` | CVM stdout channel | | `--cvm-stderr` | CVM stderr channel | | `--stderr` | Show only stderr (container mode only) | | `--stdout` | Show only stdout, console, and stdin (container mode only) | | `-n, --tail ` | Number of lines from the end (0 to 10000), or all | | `-f, --follow` | Stream in real-time | | `-t, --timestamps` | Show timestamps | | `--since SINCE` | Start time (RFC3339, Unix seconds, or relative, e.g. 42m) | | `--until UNTIL` | End time (RFC3339, Unix seconds, or relative) | #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `-i, --interactive` | Enable interactive mode | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * All container channels ```bash theme={"system"} phala logs my-service ``` * Container stderr only ```bash theme={"system"} phala logs my-service --stderr ``` * Container stdout, console, and stdin only ```bash theme={"system"} phala logs my-service --stdout ``` * Follow container logs ```bash theme={"system"} phala logs my-service -f ``` * CVM serial console ```bash theme={"system"} phala logs --serial ``` * CVM stdout channel ```bash theme={"system"} phala logs --cvm-stdout ``` * CVM stderr channel ```bash theme={"system"} phala logs --cvm-stderr ``` * Last 100 lines ```bash theme={"system"} phala logs my-service -n 100 ``` * All available lines ```bash theme={"system"} phala logs my-service -n all ``` * Specify CVM ```bash theme={"system"} phala logs my-service --cvm-id app_abc123 ``` #### Notes * By default a container shows all channels: stdout, console, and stdin go to standard output, and stderr goes to standard error. `--stdout` and `--stderr` limit the output to one side. They cannot be used together, and they cannot be used with `--serial`, `--cvm-stdout`, or `--cvm-stderr`. * The container name can be the exact name or a unique prefix of the container ID. * `-n, --tail` takes an integer from 0 to 10000, or `all`. * `--since`, `--until`, and `--timestamps` work for container logs only. They are rejected with `--serial`, `--cvm-stdout`, and `--cvm-stderr`. * Errors from the log service print their code once, for example `Error [ERR-17-009]: Docker responded ...`. See [Fetch Logs over HTTP](/phala-cloud/monitoring/log-api#errors) for the code list. * With `-f`, a container that has exited makes the stream end with no new output. The command counts such an end toward the stop only if the connection lasted less than 10 s. After 5 such ends in a row, it stops with `log stream keeps ending without new output; the container may have stopped`. A longer idle connection that ends reconnects without counting. * `phala logs` needs CLI 1.2.6 or later for the behavior above. # nodes Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/nodes Manage TEE nodes > [!NOTE] > > This command is marked as unstable and may change in future releases. ### Command: `phala nodes` #### Syntax ``` phala nodes [options] ``` #### Description Manage TEE nodes #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * Display help: ```bash theme={"system"} phala nodes --help ``` ### Subcommands | Command | Description | | - | - | | `list` | List workspace nodes | # nodes list Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/nodes/list List workspace nodes > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala nodes list` ### Syntax ``` phala nodes list [options] ``` ### Description List workspace nodes The table shows `NAME`, `REGION`, `PPID`, `DEVICE_ID`, and `VERSION`. Pass a `NAME`, such as `usw5`, to `--node` on `phala deploy`, `phala cvms replicate`, or `phala instances add` to place a CVM on that node. Running `phala nodes` with no subcommand does the same as `phala nodes list`. ### Options | Option | Description | | - | - | | `--page ` | Page number (1-based) | | `--page-size ` | Number of items per page | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * List nodes (page 1) ```bash theme={"system"} phala nodes list ``` * List nodes (page 2) ```bash theme={"system"} phala nodes list --page 2 ``` * Output as JSON ```bash theme={"system"} phala nodes list --json ``` # os-images Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/os-images List available OS images > [!NOTE] > > This command is marked as unstable and may change in future releases. ### Command: `phala os-images` #### Syntax ``` phala os-images [options] ``` #### Description List available OS images #### Options | Option | Description | | - | - | | `--dev` | Show only dev images | | `--prod` | Show only prod images | | `--page ` | Page number (1-indexed) | | `--page-size ` | Items per page (max 100) | | `--all` | Fetch all pages | #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * List all OS images ```bash theme={"system"} phala os-images ``` * List prod images only ```bash theme={"system"} phala os-images --prod ``` * List page 2 with page size 20 ```bash theme={"system"} phala os-images --page 2 --page-size 20 ``` * Fetch all pages ```bash theme={"system"} phala os-images --all ``` * Output as JSON ```bash theme={"system"} phala os-images --json ``` # CLI Overview Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/overview Deploy and manage CVMs from your terminal The Phala Cloud CLI (`phala`) is a command-line tool for deploying and managing Confidential Virtual Machines (CVMs) on Phala Cloud. It is also available as the `pha` alias. ## Install ```bash theme={"system"} npm install -g phala ``` Or run without installing: `npx phala` / `bunx phala` ## Get Started Follow the [Deploy Your First CVM](/phala-cloud/phala-cloud-cli/start-from-cloud-cli) tutorial to deploy a Jupyter notebook and test TEE functions in under 10 minutes. ## API Versioning The CLI communicates with the Phala Cloud API using header-based versioning. The current default API version is `2026-06-23`. The CLI sends an `X-Phala-Version` header with every request. This determines the response format returned by the server. See the [JS SDK API Versioning](/phala-cloud/references/cloud-js-sdk/api-versioning) page for details on version differences. | Version | Status | | - | - | | `2026-06-23` | Default | | `2026-05-22` | Supported | | `2026-01-21` | Supported | | `2025-10-28` | Legacy | You can override the API version with the `--api-version` global flag *(added in v1.1.12)*: ```bash theme={"system"} phala apps --api-version 2025-10-28 ``` ## Authentication | Command | Description | | - | - | | [`login`](/phala-cloud/phala-cloud-cli/login) | Authenticate with Phala Cloud | | [`logout`](/phala-cloud/phala-cloud-cli/logout) | Remove stored API key | | [`status`](/phala-cloud/phala-cloud-cli/status) | Check authentication status | | [`whoami`](/phala-cloud/phala-cloud-cli/whoami) | Print the current user | | [`profiles`](/phala-cloud/phala-cloud-cli/profiles) | List auth profiles | | [`switch`](/phala-cloud/phala-cloud-cli/switch) | Switch auth profiles | ## Deployment | Command | Description | | - | - | | [`deploy`](/phala-cloud/phala-cloud-cli/deploy) | Deploy new CVM or update existing one | | [`instance-types`](/phala-cloud/phala-cloud-cli/instance-types) | List available instance types | ## App Management | Command | Description | | - | - | | [`apps`](/phala-cloud/phala-cloud-cli/apps) | List deployed CVMs | | [`cvms`](/phala-cloud/phala-cloud-cli/cvms) | Manage CVMs (start, stop, restart, delete, resize, ...) | | [`link`](/phala-cloud/phala-cloud-cli/link) | Link a local directory to a CVM | | [`nodes`](/phala-cloud/phala-cloud-cli/nodes) | List TEE worker nodes | | [`ssh-keys`](/phala-cloud/phala-cloud-cli/ssh-keys) | Manage SSH keys (list, add, remove, import from GitHub) | ## CVM Operations | Command | Description | | - | - | | [`logs`](/phala-cloud/phala-cloud-cli/logs) | Fetch logs from a CVM (container, serial, stdout/stderr) | | [`ps`](/phala-cloud/phala-cloud-cli/ps) | List containers of a CVM | | [`ssh`](/phala-cloud/phala-cloud-cli/ssh) | Connect to a CVM via SSH | | [`cp`](/phala-cloud/phala-cloud-cli/cp) | Copy files to/from a CVM via SCP | | [`runtime-config`](/phala-cloud/phala-cloud-cli/runtime-config) | Show CVM runtime configuration | ## Advanced | Command | Description | | - | - | | [`allow-devices`](/phala-cloud/phala-cloud-cli/allow-devices) | Manage an app contract's device allowlist | | [`api`](/phala-cloud/phala-cloud-cli/api) | Make authenticated API requests | | [`keccak256sum`](/phala-cloud/phala-cloud-cli/keccak256sum) | Compute or verify Keccak-256 checksums | | [`kms`](/phala-cloud/phala-cloud-cli/kms) | List KMS contracts and inspect their nodes | | [`self`](/phala-cloud/phala-cloud-cli/self) | CLI self-management (update) | | [`simulator`](/phala-cloud/phala-cloud-cli/simulator) | Local TEE simulator for development | | [`completion`](/phala-cloud/phala-cloud-cli/completion) | Generate shell completion scripts | ## Deprecated These commands remain available for compatibility but have newer replacements. | Command | Use instead | | - | - | | `auth` | [`login`](/phala-cloud/phala-cloud-cli/login), [`logout`](/phala-cloud/phala-cloud-cli/logout), [`status`](/phala-cloud/phala-cloud-cli/status) | | [`config`](/phala-cloud/phala-cloud-cli/config) | Profile-based credentials (`~/.phala-cloud/credentials.json`) | | `cvms upgrade` | [`deploy --cvm-id `](/phala-cloud/phala-cloud-cli/deploy) | | `cvms logs` | [`logs`](/phala-cloud/phala-cloud-cli/logs) | | `cvms serial-logs` | [`logs --serial`](/phala-cloud/phala-cloud-cli/logs) | Deprecated `deploy` options: | Option | Use instead | | - | - | | `--vcpu`, `--memory` | `--instance-type` | | `--env-file` | `-e` | | `--kms-id`, `--uuid` | `--custom-app-id` | ## Profiles & Credentials The CLI supports multiple authentication profiles stored in `~/.phala-cloud/credentials.json`. Each profile stores: | Field | Description | | - | - | | `token` | API key | | `api_prefix` | API base URL | | `workspace` | Linked workspace (name + slug) | | `user` | Linked user (username + email) | | `updated_at` | Last update timestamp | Use [`profiles`](/phala-cloud/phala-cloud-cli/profiles) to list profiles and [`switch`](/phala-cloud/phala-cloud-cli/switch) to change the active profile. ## Environment Variables | Variable | Description | | - | - | | `PHALA_CLOUD_API_KEY` | Override the stored API key | | `PHALA_CLOUD_API_PREFIX` | Override the API base URL | | `PHALA_CLOUD_DIR` | Override the credentials directory (default: `~/.phala-cloud`) | | `PHALA_UPDATE_CHANNEL` | Release channel for `self update` (e.g., `latest`, `beta`) | ## Configuration Credentials are stored in `~/.phala-cloud/credentials.json` (schema version 1, supports multiple profiles). Project-level configuration is in `phala.toml` in the working directory. Supported fields: | Field | Type | Description | | - | - | - | | `id` / `uuid` / `app_id` / `instance_id` / `name` | `string` | CVM identifier (any format) | | `profile` | `string` | Auth profile to use for this project | | `gateway_domain` | `string` | Custom gateway domain | | `gateway_port` | `number` | Custom gateway port | | `compose_file` | `string` | Path to Docker Compose file | | `env_file` | `string` | Path to `.env` file | | `public_logs` | `boolean` | Make container logs public | | `public_sysinfo` | `boolean` | Make system info public | | `listed` | `boolean` | List CVM in the public directory | Example `phala.toml`: ```toml theme={"system"} id = "cvm-abc123" profile = "production" compose_file = "docker-compose.yml" env_file = ".env" public_logs = true ``` ## Global Flags | Flag | Description | | - | - | | `--json` | Output in JSON format for programmatic use | | `--api-token ` | Override the stored API key for this command | | `--api-version ` | Override the API version, including `2026-06-23`, `2026-05-22`, `2026-01-21`, and `2025-10-28` | | `--timeout ` | Set the API request timeout in seconds; the default is 60 | ## Related * [Cloud JS SDK](/phala-cloud/references/cloud-js-sdk/overview) — programmatic access via JavaScript/TypeScript * [Cloud API Reference](/phala-cloud/phala-cloud-api/overview) — full REST API docs * [Local Development](/dstack/local-development) — local TEE simulator * [CI/CD Pipeline](/phala-cloud/phala-cloud-cli/ci-cd-automation/setup-a-ci-cd-pipeline) — GitHub Actions automation # phala.toml Configuration Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/phala-toml Project configuration file for the Phala Cloud CLI, defining default settings for CVM deployments and operations. `phala.toml` is the project configuration file for Phala Cloud CLI. Place it in your project root to set default CVM identity, gateway settings, and API version for all CLI commands. ## Quick Start Create a minimal config with just a CVM name: ```toml theme={"system"} name = "my-awesome-app" ``` Create `phala.toml` manually in your project root. The current CLI reads this file but does not generate it for you. ## CVM Identifier Use the `name` field to identify your CVM. It's human-readable and follows RFC 1123 hostname format. ```toml theme={"system"} name = "payment-service" ``` Name requirements: 5–63 characters, starts with a letter, lowercase letters/numbers/hyphens only. > [!NOTE] > > If you have existing deployments using UUIDs or app IDs, those legacy fields still work. See [Legacy Identifiers](#legacy-identifier-fields) below. ## Gateway Configuration Configure custom gateway settings for CVM access: ```toml theme={"system"} name = "payment-api" gateway_domain = "gateway.example.com" gateway_port = 8080 ``` Both fields are optional. The CLI uses Phala's default gateway when omitted. ## API Version Rarely needed — the CLI defaults to the latest supported version: ```toml theme={"system"} api_version = "v1" ``` ## How the CLI Resolves CVM Identity When you run commands like `phala deploy` or `phala ssh`, the CVM ID is resolved in this order: 1. **Interactive selection** — `-i` or `--interactive` flag 2. **Command-line flag** — `--cvm-id` or `--uuid` 3. **phala.toml** — configuration in the current directory ```bash theme={"system"} # Without phala.toml — must specify every time phala ssh --cvm-id my-service # With phala.toml — automatic phala ssh ``` ## Legacy Identifier Fields For backward compatibility, these fields are supported. Use them only for existing deployments. | Field | Format | Example | | - | - | - | | `id` | Any string | `"my-custom-id"` | | `uuid` | UUID v4 | `"550e8400-e29b-41d4-a716-446655440000"` | | `app_id` | 40-char hex | `"50b0e827cc6c53f4010b57e588a18c5ef9388cc1"` | | `instance_id` | Instance ID | `"instance_abc123xyz"` | Priority when multiple fields exist: `id` > `uuid` > `app_id` > `instance_id` > `name`. Specify only one to avoid confusion. ### Migrating from UUID to Name ```toml theme={"system"} # Before uuid = "550e8400-e29b-41d4-a716-446655440000" # After — check your CVM's name with: phala cvms list name = "my-production-api" ``` ## Schema Reference ```typescript theme={"system"} { // CVM Identifiers (choose one) id?: string; uuid?: string; app_id?: string; instance_id?: string; name?: string; // Recommended // Gateway (optional) gateway_domain?: string; gateway_port?: number; // API Version (optional) api_version?: string; } ``` ## Troubleshooting **CVM not found** — Verify the name matches: `phala cvms list`. Check you're in the right workspace. **File not found** — Create `phala.toml` in your project root or ensure you're in the correct directory. **Validation errors** — Names must be 5–63 chars, lowercase, starting with a letter. UUIDs must be valid v4 format. Ports must be positive integers. # profiles Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/profiles List auth profiles ### Command: `phala profiles` #### Syntax ``` phala profiles ``` #### Description List auth profiles #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * Display help: ```bash theme={"system"} phala profiles --help ``` ### Subcommands | Command | Description | | - | - | | `use` | Switch to an auth profile | | `rename` | Rename an auth profile | | `delete` | Delete an auth profile | # profiles delete Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/profiles/delete Delete an auth profile ## Command: `phala profiles delete` ### Syntax ``` phala profiles delete ``` ### Description Delete an auth profile ### Arguments | Argument | Description | | - | - | | `` | Profile name | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Display help: ```bash theme={"system"} phala profiles delete --help ``` # profiles rename Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/profiles/rename Rename an auth profile ## Command: `phala profiles rename` ### Syntax ``` phala profiles rename ``` ### Description Rename an auth profile ### Arguments | Argument | Description | | - | - | | `` | Current profile name | | `` | New profile name | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Display help: ```bash theme={"system"} phala profiles rename --help ``` # profiles use Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/profiles/use Switch to an auth profile ## Command: `phala profiles use` ### Syntax ``` phala profiles use [options] ``` ### Description Switch to an auth profile ### Arguments | Argument | Description | | - | - | | `` | Profile name | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `-i, --interactive` | Select profile interactively | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Display help: ```bash theme={"system"} phala profiles use --help ``` # ps Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/ps List containers of a CVM ### Command: `phala ps` #### Syntax ``` phala ps [options] [] ``` #### Description List containers of a CVM #### Arguments | Argument | Description | | - | - | | `?` | CVM identifier (UUID, app\_id, instance\_id, or name) | #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `-i, --interactive` | Enable interactive mode | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * List containers interactively ```bash theme={"system"} phala ps ``` * List containers by app\_id ```bash theme={"system"} phala ps app_abc123 ``` * List containers by name ```bash theme={"system"} phala ps my-app ``` * Output as JSON ```bash theme={"system"} phala ps app_abc123 --json ``` # runtime-config Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/runtime-config Show the runtime configuration of a CVM ### Command: `phala runtime-config` #### Syntax ``` phala runtime-config [options] [] ``` #### Description Show the runtime configuration of a CVM #### Arguments | Argument | Description | | - | - | | `?` | CVM identifier (UUID, app\_id, instance\_id, or name) | #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `-i, --interactive` | Enable interactive mode | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * Show runtime config by app\_id ```bash theme={"system"} phala runtime-config app_123 ``` * Show runtime config by name ```bash theme={"system"} phala runtime-config my-app ``` # self Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/self CLI self-management > [!NOTE] > > This command is marked as unstable and may change in future releases. ### Command: `phala self` #### Syntax ``` phala self [options] ``` #### Description CLI self-management #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * Display help: ```bash theme={"system"} phala self --help ``` ### Subcommands | Command | Description | | - | - | | `update` | Update the Phala CLI | # self update Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/self/update Update the Phala CLI > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala self update` ### Syntax ``` phala self update [options] ``` ### Description Update the Phala CLI ### Options | Option | Description | | - | - | | `-y, --yes` | Skip confirmation prompt | | `--dry-run` | Print update command without executing | | `--package-manager NAME, --pm NAME` | Override package manager (npm\|pnpm\|yarn\|bun) | | `--channel TAG` | Release channel/dist-tag (e.g. latest, beta, next) | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Update CLI ```bash theme={"system"} phala self update ``` * Dry run ```bash theme={"system"} phala self update --dry-run ``` * Beta channel ```bash theme={"system"} phala self update --channel beta ``` # simulator Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/simulator TEE simulator commands > [!NOTE] > > This command is marked as unstable and may change in future releases. ### Command: `phala simulator` #### Syntax ``` phala simulator [options] ``` #### Description TEE simulator commands #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * Display help: ```bash theme={"system"} phala simulator --help ``` ### Subcommands | Command | Description | | - | - | | `start` | Start the TEE simulator | | `stop` | Stop the TEE simulator | # simulator start Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/simulator/start Start the TEE simulator > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala simulator start` ### Syntax ``` phala simulator start [options] ``` ### Description Start the TEE simulator ### Options | Option | Description | | - | - | | `-p, --port ` | Simulator port (default: 8090) | | `-v, --verbose` | Enable verbose output | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `--version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Display help: ```bash theme={"system"} phala simulator start --help ``` # simulator stop Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/simulator/stop Stop the TEE simulator > [!NOTE] > > This command is marked as unstable and may change in future releases. ## Command: `phala simulator stop` ### Syntax ``` phala simulator stop ``` ### Description Stop the TEE simulator ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Display help: ```bash theme={"system"} phala simulator stop --help ``` # ssh Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/ssh Connect to a CVM via SSH > [!NOTE] > > This command is marked as unstable and may change in future releases. ### Command: `phala ssh` #### Syntax ``` phala ssh [options] [] [--] [...] ``` #### Description Connect to a CVM via SSH #### Arguments | Argument | Description | | - | - | | `?` | CVM identifier (UUID, app\_id, instance\_id, or name) | #### Options | Option | Description | | - | - | | `-p, --port ` | Gateway port (priority: CLI > phala.toml > 443) | | `-g, --gateway ` | Gateway domain (priority: CLI > phala.toml > API) | | `-v, --verbose` | Show verbose connection details | | `--dry-run` | Print SSH command without executing | #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `--version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `-i, --interactive` | Enable interactive mode | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `-t, --timeout ` | Connection timeout in seconds (default: 30) | #### Pass-through Arguments All arguments after -- are passed directly to ssh. Common options: -i (identity file), -L (local forward), -R (remote forward), -D (SOCKS proxy), -N (no command), -v (ssh verbose). Any trailing arguments are executed as remote command. Note: -o ProxyCommand is blocked. #### Examples * Connect from phala.toml ```bash theme={"system"} phala ssh ``` * Connect to CVM ```bash theme={"system"} phala ssh app_123 ``` * Offline mode ```bash theme={"system"} phala ssh app_123 -g dstack-pha-prod7.phala.network -p 16185 ``` * Connect with custom SSH key ```bash theme={"system"} phala ssh app_123 -- -i ~/.ssh/custom_key ``` * Forward local port 8080 to remote port 80 ```bash theme={"system"} phala ssh app_123 -- -L 8080:localhost:80 ``` * SOCKS proxy without remote command ```bash theme={"system"} phala ssh app_123 -- -D 1080 -N ``` * Execute remote command ```bash theme={"system"} phala ssh app_123 -- ls -la /app ``` * Connect with verbose output for debugging ```bash theme={"system"} phala ssh app_123 -v ``` * Print the SSH command without executing ```bash theme={"system"} phala ssh app_123 --dry-run -- -L 8080:localhost:80 ``` # ssh-keys Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/ssh-keys Manage SSH keys ### Command: `phala ssh-keys` #### Syntax ``` phala ssh-keys [options] ``` #### Description Manage SSH keys #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * Display help: ```bash theme={"system"} phala ssh-keys --help ``` ### Subcommands | Command | Description | | - | - | | `list` | List SSH keys for the current user | | `add` | Add a local SSH public key to your account | | `remove` | Remove an SSH key from your account | | `import-github` | Import SSH keys from a GitHub user's public profile | # ssh-keys add Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/ssh-keys/add Add a local SSH public key to your account ## Command: `phala ssh-keys add` ### Syntax ``` phala ssh-keys add [options] ``` ### Description Add a local SSH public key to your account ### Options | Option | Description | | - | - | | `--name ` | Name for the SSH key (default: key file name) | | `--key-file ` | Path to SSH public key file (default: \~/.ssh/id\_ed25519.pub or \~/.ssh/id\_rsa.pub) | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Add default SSH key ```bash theme={"system"} phala ssh-keys add ``` * Add a specific key with a name ```bash theme={"system"} phala ssh-keys add --name my-laptop --key-file ~/.ssh/id_ed25519.pub ``` # ssh-keys import-github Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/ssh-keys/import-github Import SSH keys from a GitHub user's public profile ## Command: `phala ssh-keys import-github` ### Syntax ``` phala ssh-keys import-github ``` ### Description Import SSH keys from a GitHub user's public profile ### Arguments | Argument | Description | | - | - | | `` | GitHub username to import SSH keys from | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Import SSH keys from a GitHub profile ```bash theme={"system"} phala ssh-keys import-github octocat ``` # ssh-keys list Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/ssh-keys/list List SSH keys for the current user ## Command: `phala ssh-keys list` ### Syntax ``` phala ssh-keys list ``` ### Description List SSH keys for the current user ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * List all SSH keys ```bash theme={"system"} phala ssh-keys list ``` # ssh-keys remove Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/ssh-keys/remove Remove an SSH key from your account ## Command: `phala ssh-keys remove` ### Syntax ``` phala ssh-keys remove [options] [] ``` ### Description Remove an SSH key from your account ### Arguments | Argument | Description | | - | - | | `?` | SSH key ID to remove (from `phala ssh-keys list`) | ### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `-i, --interactive` | Enable interactive mode | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | ### Examples * Remove an SSH key by ID ```bash theme={"system"} phala ssh-keys remove sshkey_xxx ``` * Interactive selection ```bash theme={"system"} phala ssh-keys rm -i ``` # Deploy Your First CVM Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/start-from-cloud-cli Deploy a Jupyter notebook to Phala Cloud and test TEE functions using the CLI Deploy a Jupyter notebook to Phala Cloud and run code inside a TEE in under 10 minutes. You'll use the CLI to deploy, then test key derivation and remote attestation from inside the secure environment. ## Prerequisites * Node.js 18+ or [Bun](https://bun.sh) installed * A [Phala Cloud account](https://cloud.phala.network/register) ## Install the CLI Install the Phala Cloud CLI globally: ```bash theme={"system"} npm install -g phala ``` Or use `npx phala` / `bunx phala` to run commands without installing. ## Authenticate The CLI supports device flow authentication—run the login command and follow the browser prompt: ```bash theme={"system"} phala login ``` ``` ⟳ Starting device flow authentication... ✓ ℹ Opening browser to complete authentication... ✓ Authentication successful! Logged in as: yourname Workspace: yourname's projects ``` Alternatively, generate an API key manually from the [dashboard](https://cloud.phala.network/dashboard) by clicking your username → **API Tokens** → **Create Token**, then authenticate with: ```bash theme={"system"} phala login --manual ``` Verify your authentication: ```bash theme={"system"} phala status ``` ## Deploy a Jupyter Notebook Create a `docker-compose.yml` file: ```yaml theme={"system"} services: jupyter: image: quay.io/jupyter/base-notebook ports: - 8080:8888 volumes: - /var/run/dstack.sock:/var/run/dstack.sock environment: - GRANT_SUDO=yes user: root command: "start-notebook.sh --NotebookApp.token=${TOKEN}" ``` The `dstack.sock` volume mount enables your code to communicate with the TEE environment. Deploy with a name and access token: ```bash theme={"system"} phala deploy -c docker-compose.yml -n jupyter-notebook -e TOKEN=my-secret-token ``` ```json theme={"system"} { "success": true, "vm_uuid": "425f4f38-5c48-40c3-8a9c-1be22caba517", "name": "jupyter-notebook", "app_id": "d8d6db935df75104a825fb96b6bbbcfc8d1753ca", "dashboard_url": "https://cloud.phala.network/dashboard/cvms/..." } ``` ## Access Your Notebook Check deployment status: ```bash theme={"system"} phala cvms get jupyter-notebook ``` Once the status shows `running`, get the public URL: ```bash theme={"system"} phala cvms get jupyter-notebook --json | jq -r '.public_urls[0].app' ``` ``` https://d8d6db935df75104a825fb96b6bbbcfc8d1753ca-8080.dstack-pha-prod3.phala.network ``` Open this URL in your browser. You'll see a login page with a "Password or token" field—enter the token you set during deployment (`my-secret-token` in this example) and click **Log in**. View container logs if needed: ```bash theme={"system"} phala logs --cvm-id jupyter-notebook ``` ## Test TEE Functions Once logged in, click **Python 3 (ipykernel)** under "Notebook" to create a new notebook. In the first cell, install the dstack SDK: ```python theme={"system"} !pip install dstack-sdk ``` Run the cell with **Shift+Enter**. In a new cell, test TEE-native capabilities: ```python theme={"system"} from dstack_sdk import DstackClient import hashlib client = DstackClient() # Get TEE environment info info = client.info() print(f"App ID: {info.app_id}") print(f"MRTD: {info.tcb_info.mrtd}") # Derive a deterministic key key_result = client.get_key("my-app/encryption/v1") key_bytes = key_result.decode_key() # 32 bytes print(f"Derived key (hex): {key_result.key[:32]}...") # Generate a TDX attestation quote data = b"data-to-attest" hash_value = hashlib.sha256(data).digest() quote_result = client.get_quote(hash_value[:32]) print(f"Quote: {quote_result.quote[:64]}...") ``` Generate blockchain wallet addresses using TEE-derived keys. In a new cell, install the additional dependencies: ```python theme={"system"} !pip install "dstack-sdk[all]" ``` Then in another cell: ```python theme={"system"} from dstack_sdk import DstackClient, ethereum, solana client = DstackClient() # Derive Ethereum account eth_key = client.get_key("ethereum/main") eth_account = ethereum.to_account(eth_key) print(f"ETH Address: {eth_account.address}") # Derive Solana keypair sol_key = client.get_key("solana/main") sol_keypair = solana.to_keypair(sol_key) print(f"SOL Address: {sol_keypair.pubkey()}") ``` ## Clean Up When you're done experimenting, delete the CVM to stop billing: ```bash theme={"system"} phala cvms delete jupyter-notebook ``` Other useful commands: `phala cvms stop` to pause without deleting, `phala cvms start` to resume, and `phala cvms attestation` to view the TEE attestation report. ## Link Your Project for Faster Deploys After deploying, link your local directory to the CVM so subsequent commands don't need the CVM name: ```bash theme={"system"} phala link jupyter-notebook ``` This creates a `phala.toml` file in your project directory: ```toml theme={"system"} cvm_id = "d8d6db935df75104a825fb96b6bbbcfc8d1753ca" ``` Commit `phala.toml` to version control. Once linked, commands use the CVM from `phala.toml` automatically: ```bash theme={"system"} # These now target the linked CVM without specifying a name phala deploy # update the CVM phala logs # view logs phala ssh # SSH into the CVM phala cvms get # check status ``` The recommended workflow: 1. **First deploy**: `phala deploy -n my-app -c docker-compose.yml` 2. **Link**: `phala link my-app` 3. **Commit** `phala.toml` to your repo 4. **Subsequent deploys**: just `phala deploy` ## Next Steps * [Deploy a custom application](/phala-cloud/cvm/create-with-docker-compose) with your own Docker Compose file * [Set up CI/CD](/phala-cloud/phala-cloud-cli/ci-cd-automation/setup-a-ci-cd-pipeline) for automated deployments * Learn about [TEE attestation](/phala-cloud/attestation/overview) and verification # status Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/status Check authentication status ### Command: `phala status` #### Syntax ``` phala status [options] ``` #### Description Check authentication status #### Options | Option | Description | | - | - | | `-d, --debug` | Enable debug output | #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * Show login status ```bash theme={"system"} phala status ``` * Get status as JSON ```bash theme={"system"} phala status --json ``` # switch Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/switch Switch auth profiles > [!NOTE] > > This command is marked as unstable and may change in future releases. ### Command: `phala switch` #### Syntax ``` phala switch [options] ``` #### Description Switch auth profiles #### Arguments | Argument | Description | | - | - | | `` | Profile name | #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `-i, --interactive` | Select profile interactively | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * Display help: ```bash theme={"system"} phala switch --help ``` # whoami Source: https://docs.phala.com/phala-cloud/phala-cloud-cli/whoami Print the current user ### Command: `phala whoami` #### Syntax ``` phala whoami [options] ``` #### Description Print the current user #### Global Options | Option | Description | | - | - | | `-h, --help` | Show help information for the current command | | `-v, --version` | Show CLI version | | `--api-token TOKEN, --api-key TOKEN` | API token for authenticating with Phala Cloud | | `-j, --json, --no-json` | Output in JSON format | | `--interactive` | Enable interactive mode for commands that support it | | `--cvm-id ` | CVM identifier (UUID, app\_id, instance\_id, or name) | | `--profile PROFILE` | Temporarily use a different auth profile for this command | | `--api-version ` | API version to use (e.g. 2026-01-21, 2026-05-22, 2026-06-23) | | `--timeout SECONDS` | Request timeout in seconds (default 60) | #### Examples * Show current user ```bash theme={"system"} phala whoami ``` * JSON output ```bash theme={"system"} phala whoami --json ``` # Production Checklist Source: https://docs.phala.com/phala-cloud/production-checklist Production checklist for launch. Ensure your application is ready for a reliable, secure, and observable production deployment on Phala Cloud. This checklist helps you avoid common pitfalls and design your app for TEE, covering restart tolerance, secret management, observability, and safe upgrades. **Step 1** ## Prepare Your App for Restart ### 1.1. Prepare Your App for Restart Make sure your application can handle being stopped and started at any time. Avoid relying on in-memory state that would be lost on restart, and implement graceful shutdown handlers if possible so the app can clean up or save state when the container stops. This ensures a restart (or relocation to a new node) won’t corrupt your app’s workflow or data. ### 1.2. Persist data on volumes Use [Docker volumes](https://docs.docker.com/reference/compose-file/services/#volumes) for any data that needs to persist across restarts or upgrades. Write files (databases, user uploads, etc.) to a mounted volume rather than the container’s ephemeral filesystem. Phala Cloud preserves these volumes and encrypts the data at rest, so restarting or upgrading your CVM will not lose your stored data. Keep the default `zfs` storage filesystem, which also detects a modified block on the disk. Be sure to configure the volume in your docker-compose.yml to capture the right directories. **Step 2** ## Secrets Management ### 2.1. Use encrypted environment variables Store secrets (API keys, tokens, passwords) as [*Encrypted Variables*](/phala-cloud/cvm/set-secure-environment-variables) in your Docker Compose configuration. Phala Cloud’s deployment process encrypts your secrets on the client side and only decrypts them inside the TEE at runtime . This means even the Phala Cloud cannot read your plaintext secrets. ### 2.2. Prefer TEE-managed keys when possible Phala’s TEE-managed keys are stable across restarts and upgrades, so your encrypted data remains accessible without manual key handling. These keys are generated and sealed within the TEE using the dstack SDK, and cannot be accessed or exported by anyone, not even you as the developer. This ensures that only the TEE can use the key, unlike Nitro or Azure KMS where the developer retains access. It eliminates the risk of accidental exposure while preserving seamless availability across lifecycle events. **Step 3** ## App Upgrade ### 3.1. Understand the Upgrade Flow Phala Cloud handles upgrades by restarting your CVM with the new configuration (docker compose file and the secrets). When you deploy an update, the platform will restart the CVM, pull your updated Docker images, and then start it again with the new configurations. Any defined volume data is reattached to the new instance, so it carries over seamlessly. The entire CVM and all containers in your Compose will reboot during an upgrade, meaning there will be a brief downtime for that instance. ### 3.2. Manage secrets during upgrades If your secrets haven’t changed, you can skip re-entering them. Your CVM will reuse the previously stored encrypted variables. But if you update any secret, you must provide the full variable list again. The platform replaces all secrets during an upgrade. Partial updates will result in dropped variables, so always double-check that all required secrets are included. ### 3.3. Test for upgrade safety Even though Phala Cloud preserves your disk data on upgrade, your app update itself could introduce bugs or incompatibilities. A common pitfall is deploying a new version that accidentally wipes or misinterprets existing data (for example, a flawed migration script or a logic error that deletes files). To avoid surprises, always test the upgrade process in a staging environment or with sample data. Verify that your app comes back up correctly and that it handles existing persisted data as expected. This practice will catch any logical issues *before* they impact your production users. ### 3.4. Use rolling deployments for zero downtime Currently Phala Cloud doesn’t offer built-in support for rolling upgrades, but you can achieve minimal downtime by managing it yourself. If you run multiple CVMs with app-level load balancing, upgrade them one at a time to keep at least one instance online. This approach reduces downtime and makes it easier to resolve problems if something goes wrong, but it requires coordination in your deployment logic or orchestration setup. **Step 4** ## Observability ### 4.1. Export metrics from your app Include a metrics exporter (such as Prometheus Node Exporter) as a sidecar container in your Docker Compose to collect system and application metrics. For example, running a Node Exporter will expose CPU, memory, and other host metrics for your CVM . Ensure your application also exposes any custom metrics or health endpoints needed for monitoring.
Example Docker Compose for node-exporter ```yaml theme={"system"} services: node_exporter: image: quay.io/prometheus/node-exporter:latest container_name: node_exporter command: - '--path.rootfs=/host' network_mode: host pid: host restart: unless-stopped volumes: - '/:/host:ro,rslave' ``` The config will expose the metrics under the endpoint `https://{appd-id}-9100.dstack-prod{n}.phala.network` protected with TLS by default. You can then connect your Prometheus server to scrape the metrics. You may also want to set up HTTP basic auth to limit the read access to yourself, as [described here.](https://stackoverflow.com/questions/74490690/node-exporter-basic-auth-docker-compose)
### 4.2. Plan for log access Decide how you will handle application logs in production. When **Public Logs** is enabled, anyone with a container's log URL can read its output without a Phala Cloud session. Manage the setting under **Settings → Worker Attestation Visibility Settings → Public Logs**. If you keep logs private, set up a secure log viewer like [Dozzle](https://dozzle.dev/) or [Grafana Loki](https://grafana.com/oss/loki/) to forward logs to an external logging service so you can still debug issues. # CVM Deployment via API Source: https://docs.phala.com/phala-cloud/references/api-deployment-guide Overview of deploying Confidential Virtual Machines programmatically using the Phala Cloud REST API or SDKs. Deploy CVMs programmatically using the Phala Cloud API. The API exposes the same backend used by the Phala Cloud dashboard, so anything you can do in the UI you can automate via API. ## Authentication All API requests require an API key passed in the `X-API-Key` header. Generate your key at **Settings → API Keys** in the [Phala Cloud dashboard](https://cloud.phala.com). ## Deployment Flow CVM deployment follows a two-phase **provision → commit** workflow: 1. **Provision** — reserve resources and receive a `compose_hash` and `app_env_encrypt_pubkey` 2. **Commit** — finalize the deployment with the provisioned values Browse the interactive [API reference](/phala-cloud/phala-cloud-api/overview) for full request/response details on each endpoint. ## KMS Types | Feature | Built-in KMS | On-chain KMS | | - | - | - | | Setup | Automatic | Requires smart contract deployment | | App ID | Derived from compose hash | Contract address | | Best for | Development and standard production | Decentralized access control | For on-chain KMS details, see the [On-chain KMS guide](/phala-cloud/key-management/cloud-vs-onchain-kms). ## Using SDKs For a simpler experience, use one of the official SDKs instead of raw API calls: > [card] [JavaScript SDK](/phala-cloud/references/cloud-js-sdk/provision-cvm) > > `@phala/cloud` — provision, deploy, and manage CVMs > [card] [Python SDK](/phala-cloud/references/cloud-python-sdk/overview) > > `phala-cloud` — sync and async client > [card] [Go SDK](/phala-cloud/references/cloud-go-sdk/overview) > > `github.com/Phala-Network/phala-cloud/go` # Apps Source: https://docs.phala.com/phala-cloud/references/cloud-go-sdk/apps List applications, query app details, revisions, attestations, and device allowlists. App methods provide read access to your Phala Cloud applications. An "app" is a logical grouping that can contain one or more CVMs (e.g., the primary instance and its replicas). ## GetAppList `GET /apps` Returns all applications for the authenticated user. ```go theme={"system"} func (c *Client) GetAppList(ctx context.Context) (*GetAppListResponse, error) ``` **Returns:** `*GetAppListResponse` containing: | Field | Type | Description | | - | - | - | | `DstackApps` | `[]AppInfo` | List of applications | | `Page` | `int` | Current page | | `PageSize` | `int` | Items per page | | `Total` | `int` | Total number of apps | | `TotalPages` | `int` | Total number of pages | ```go theme={"system"} apps, err := client.GetAppList(ctx) if err != nil { log.Fatal(err) } for _, app := range apps.DstackApps { fmt.Printf("%s — %s (%d CVMs)\n", app.AppID, app.Name, app.CVMCount) } ``` *** ## GetAppInfo `GET /apps/{appId}` Returns detailed information about a specific application, including its current CVM and profile. ```go theme={"system"} func (c *Client) GetAppInfo(ctx context.Context, appID string) (*AppInfo, error) ``` **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `appID` | `string` | Yes | Application identifier | **Returns:** `*AppInfo` with these key fields: | Field | Type | Description | | - | - | - | | `ID` | `string` | Internal ID | | `Name` | `string` | App name | | `AppID` | `string` | Public app ID | | `KMSType` | `string` | KMS type (e.g., `"phala"`) | | `CurrentCVM` | `*CVMInfo` | Currently active CVM | | `CVMs` | `[]CVMInfo` | All CVMs under this app | | `CVMCount` | `int` | Number of CVMs | | `Profile` | `*AppProfile` | Display name, avatar, description | ```go theme={"system"} app, err := client.GetAppInfo(ctx, "app-abc123") if err != nil { log.Fatal(err) } fmt.Printf("App: %s, KMS: %s, CVMs: %d\n", app.Name, app.KMSType, app.CVMCount) ``` *** ## GetAppCVMs `GET /apps/{appId}/cvms` Returns all CVMs associated with an application. This is useful for apps that have replicas or multiple deployments. ```go theme={"system"} func (c *Client) GetAppCVMs(ctx context.Context, appID string) ([]GenericObject, error) ``` **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `appID` | `string` | Yes | Application identifier | **Returns:** `[]GenericObject` — a slice of CVM data as generic maps. ```go theme={"system"} cvms, err := client.GetAppCVMs(ctx, "app-abc123") if err != nil { log.Fatal(err) } fmt.Printf("Found %d CVMs\n", len(cvms)) ``` *** ## GetAppRevisions `GET /apps/{appId}/revisions` Returns the revision history for an application. Each revision represents a configuration change (deploy, update, restart, etc.). ```go theme={"system"} func (c *Client) GetAppRevisions(ctx context.Context, appID string, opts *PaginationOptions) (*AppRevisionsResponse, error) ``` **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `appID` | `string` | Yes | Application identifier | | `opts` | `*PaginationOptions` | No | Pagination (pass `nil` for defaults) | **PaginationOptions fields:** | Field | Type | Description | | - | - | - | | `Page` | `*int` | Page number | | `PageSize` | `*int` | Items per page | **Returns:** `*AppRevisionsResponse` containing: | Field | Type | Description | | - | - | - | | `Revisions` | `[]AppRevision` | List of revisions | | `Total` | `int` | Total revisions | | `Page` | `int` | Current page | | `PageSize` | `int` | Items per page | | `TotalPages` | `int` | Total pages | ```go theme={"system"} revisions, err := client.GetAppRevisions(ctx, "app-abc123", &phala.PaginationOptions{ Page: phala.Int(1), PageSize: phala.Int(10), }) if err != nil { log.Fatal(err) } for _, rev := range revisions.Revisions { fmt.Printf("[%s] %s — %s\n", rev.CreatedAt, rev.OperationType, rev.ComposeHash) } ``` *** ## GetAppRevisionDetail `GET /apps/{appId}/revisions/{revisionId}` Returns detailed information about a specific revision, including the full compose file and encrypted environment variables at that point in time. ```go theme={"system"} func (c *Client) GetAppRevisionDetail(ctx context.Context, appID, revisionID string) (*AppRevisionDetail, error) ``` **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `appID` | `string` | Yes | Application identifier | | `revisionID` | `string` | Yes | Revision identifier | **Returns:** `*AppRevisionDetail` ```go theme={"system"} detail, err := client.GetAppRevisionDetail(ctx, "app-abc123", "rev-xyz789") if err != nil { log.Fatal(err) } fmt.Printf("Operation: %s, Compose hash: %s\n", detail.OperationType, detail.ComposeHash) ``` *** ## GetAppAttestation `GET /apps/{appId}/attestations` Returns TEE attestation data for an application, including certificates and TCB info. ```go theme={"system"} func (c *Client) GetAppAttestation(ctx context.Context, appID string) (*AppAttestationResponse, error) ``` **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `appID` | `string` | Yes | Application identifier | **Returns:** `*AppAttestationResponse` (generic map) ```go theme={"system"} attestation, err := client.GetAppAttestation(ctx, "app-abc123") if err != nil { log.Fatal(err) } ``` *** ## GetAppDeviceAllowlist `GET /apps/{appId}/device-allowlist` Returns the device allowlist for an on-chain KMS application. This shows which TEE devices are authorized to run the app. ```go theme={"system"} func (c *Client) GetAppDeviceAllowlist(ctx context.Context, appID string) (*DeviceAllowlistResponse, error) ``` **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `appID` | `string` | Yes | Application identifier | **Returns:** `*DeviceAllowlistResponse` containing: | Field | Type | Description | | - | - | - | | `IsOnchainKMS` | `bool` | Whether the app uses on-chain KMS | | `AllowAnyDevice` | `*bool` | Whether any device is allowed | | `ChainID` | `*int` | Blockchain chain ID | | `AppContractAddress` | `*string` | On-chain app contract address | | `Devices` | `[]DeviceAllowlistItem` | List of allowed devices | ```go theme={"system"} allowlist, err := client.GetAppDeviceAllowlist(ctx, "app-abc123") if err != nil { log.Fatal(err) } if allowlist.IsOnchainKMS { fmt.Printf("On-chain KMS, %d devices allowed\n", len(allowlist.Devices)) } ``` *** ## GetAppFilterOptions `GET /apps/filter-options` Returns available filter options for the app list endpoint. Useful for building UI filters. ```go theme={"system"} func (c *Client) GetAppFilterOptions(ctx context.Context) (*AppFilterOptions, error) ``` **Returns:** `*AppFilterOptions` (generic map) ```go theme={"system"} filters, err := client.GetAppFilterOptions(ctx) ``` *** ## SetAppLaunchToken / ClearAppLaunchToken `POST /apps/{appId}/launch-token` / `DELETE /apps/{appId}/launch-token` `SetAppLaunchToken` sets or rotates the app's launch token and returns it once, with its hash. Leave `LaunchToken` nil, or pass a nil request, to have Phala Cloud generate one. Then update each CVM's `requirements.launch_token_hash` to the returned hash with [`PatchCVM`](/phala-cloud/references/cloud-go-sdk/cvm-configuration#patchcvm). `ClearAppLaunchToken` removes the token; remove the hash from every CVM first. Phala Cloud and the node operator can read the token. See [Launch Token](/phala-cloud/cvm/launch-token). ```go theme={"system"} func (c *Client) SetAppLaunchToken(ctx context.Context, appID string, req *SetAppLaunchTokenRequest) (*AppLaunchTokenResponse, error) func (c *Client) ClearAppLaunchToken(ctx context.Context, appID string) error ``` **SetAppLaunchTokenRequest fields:** | Field | Type | Description | | - | - | - | | `LaunchToken` | `*string` | Token to set, at least 32 bytes | **Returns:** `*AppLaunchTokenResponse` with `LaunchToken` and `LaunchTokenHash`. ```go theme={"system"} token, err := client.SetAppLaunchToken(ctx, "0123...cdef", nil) if err != nil { log.Fatal(err) } _, err = client.PatchCVM(ctx, "my-app", &phala.PatchCVMRequest{ Compose: &phala.ComposePatch{ Requirements: phala.PatchValue(phala.ComposeRequirementsPatch{ LaunchTokenHash: phala.PatchValue(token.LaunchTokenHash), }), }, }) ``` # Authentication Source: https://docs.phala.com/phala-cloud/references/cloud-go-sdk/authentication Configure API key authentication, environment variables, and custom headers for the Go SDK. Authenticate with an API key or a bearer token. `NewClient` returns an error if neither is configured. ## API Key via Option The most explicit way to authenticate is passing `WithAPIKey` when creating the client. ```go theme={"system"} client, err := phala.NewClient( phala.WithAPIKey("phak_your_api_key"), ) if err != nil { log.Fatal(err) } ``` ## API Key via Environment Variable For production deployments, storing the key in an environment variable is the standard approach. The SDK reads `PHALA_CLOUD_API_KEY` automatically when no explicit key is provided. ```bash theme={"system"} export PHALA_CLOUD_API_KEY="phak_your_api_key" ``` ```go theme={"system"} // No WithAPIKey needed — reads from PHALA_CLOUD_API_KEY client, err := phala.NewClient() if err != nil { log.Fatal(err) // Fails if env var is also unset } ``` > [!NOTE] > > If you pass `WithAPIKey` explicitly, it always takes priority over the environment variable. ## Bearer token and workspace Use `WithBearerToken` for bearer credentials, including an OIDC token, and `WithWorkspace` to select a workspace by slug. The SDK also reads `PHALA_OIDC_TOKEN` and `PHALA_CLOUD_WORKSPACE`. An API key takes precedence over a bearer token when both are configured. This also applies to credentials supplied with `WithHeader`: if the final request has an API key, the SDK removes its authorization header. ```go theme={"system"} client, err := phala.NewClient( phala.WithBearerToken(os.Getenv("PHALA_OIDC_TOKEN")), phala.WithWorkspace("my-workspace"), ) if err != nil { log.Fatal(err) } ``` ## RevokeSelfToken `DELETE /tokens/self` `client.RevokeSelfToken(ctx)` revokes the API token used for the request. The token stops working immediately and cannot be restored. ## Custom Base URL You can override the API endpoint with `WithBaseURL` or the `PHALA_CLOUD_API_PREFIX` environment variable. The SDK defaults to `https://cloud-api.phala.com/api/v1`. ```go theme={"system"} client, err := phala.NewClient( phala.WithAPIKey("phak_your_api_key"), phala.WithBaseURL("https://custom-api.example.com/api/v1"), ) ``` The environment variable takes effect when the configured URL is the SDK default, including when that default is passed explicitly. ## Custom Headers Use `WithHeader` to attach additional headers to every request. This is useful for tracing, correlation IDs, or internal routing. ```go theme={"system"} client, err := phala.NewClient( phala.WithAPIKey("phak_your_api_key"), phala.WithHeader("X-Request-ID", "trace-abc123"), phala.WithHeader("X-Custom-Header", "my-value"), ) ``` Each call to `WithHeader` adds one header. You can call it multiple times to set several headers. ## API Versioning The SDK sends an API version header with every request. The default is `"2026-06-23"`. Override it if you need an older response shape. ```go theme={"system"} client, err := phala.NewClient( phala.WithAPIKey("phak_your_api_key"), phala.WithAPIVersion("2026-05-22"), ) ``` ## Custom HTTP Client For advanced scenarios like custom TLS configuration, proxies, or instrumented transports, pass your own `*http.Client` with `WithHTTPClient`. ```go theme={"system"} transport := &http.Transport{ TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS13}, } httpClient := &http.Client{Transport: transport} client, err := phala.NewClient( phala.WithAPIKey("phak_your_api_key"), phala.WithHTTPClient(httpClient), ) ``` > [!WARNING] > > `WithHTTPClient` copies the provided client. `WithTimeout` modifies the SDK's copy, not the original client. ## User Agent The SDK sends a `User-Agent` header in the form `phala-cloud-sdk-go/ go/` by default. `phala.DefaultUserAgent()` returns this value. `WithUserAgent` replaces it entirely, so a value you supply overrides the default. Use it to identify your application in server logs. The log methods (`FetchCVMLogs`, `FetchCVMLogEntries`, `FollowCVMLogs`, `FollowCVMLogEntries`) use the same settings for all their requests, including the request that reads the log stream. They reuse your HTTP client and its transport and send your `User-Agent`. A one-shot fetch keeps the client's timeout. A follow clears only the timeout, so a long stream is not cut; cancel it with the `ctx` you pass in. ```go theme={"system"} client, err := phala.NewClient( phala.WithAPIKey("phak_your_api_key"), phala.WithUserAgent("my-automation/2.0"), ) ``` ## Resolution Priority The client resolves configuration in this order (first match wins): 1. Explicit option passed to `NewClient` (e.g., `WithAPIKey`, `WithBaseURL`) 2. Environment variable (`PHALA_CLOUD_API_KEY`, `PHALA_CLOUD_API_PREFIX`) 3. Built-in default (base URL: `https://cloud-api.phala.com/api/v1`) # Changelog Source: https://docs.phala.com/phala-cloud/references/cloud-go-sdk/changelog Version history and release notes for the Phala Cloud Go SDK. ## [v0.2.0](https://github.com/Phala-Network/phala-cloud/compare/sdks/go/v0.1.1...sdks/go/v0.2.0) (2026-07-26) ### Features * Added contract-centric KMS methods: `ListKMSContracts`, `GetKMSContract`, and `ListKMSContractNodes`. * Added `GetMrConfigId`, `GetMrConfigIdHex`, `GetMrConfigIdV1`, and `VerifyMrConfigId`. * Changed the default API version to `2026-06-23`. * Added versioned CVM response helpers and typed batch CVM status results. * Added `CreateAppInstance`, `RedeployAppRevision`, `UpdateCVMListed`, and the CVM creation resource graph. * Added KMS verification anchors, node device ID history, app attestation types, and GPU rental billing fields. ### Fixes * Aligned CVM schemas with hashed IDs and exposed request IDs on structured errors. * Added `APIError.ComposePrecondition` and `CvmKmsInfo.ChainName` helpers. * Moved resource updates to the unified `PATCH /cvms/{id}` flow. ## [v0.1.1](https://github.com/Phala-Network/phala-cloud/compare/go-v0.1.0...go-v0.1.1) (2026-03-27) ### Features * add webhook signature verification utilities ([e97b3a6](https://github.com/Phala-Network/phala-cloud/commit/e97b3a6)) * add is-allowed API ([1fa61f0](https://github.com/Phala-Network/phala-cloud/commit/1fa61f0581ce111213f721f1c2d2f4744c3c2f00)) * add structured error codes and idempotency support across all SDKs ([2dd6d0b](https://github.com/Phala-Network/phala-cloud/commit/2dd6d0bae4d5fd7acdef551c3c9bf507ac1b0e4e)) * add ReplicateAppCVM for app-scoped replica creation ([22acec1](https://github.com/Phala-Network/phala-cloud/commit/22acec1)) * add Region field to ProvisionCVMRequest ([ab5eaf1](https://github.com/Phala-Network/phala-cloud/commit/ab5eaf1)) * add visibility and storage fields to ComposeFile struct ([0443f82](https://github.com/Phala-Network/phala-cloud/commit/0443f82)) * enhance SDK types for Terraform provider integration ([ba9ecb4](https://github.com/Phala-Network/phala-cloud/commit/ba9ecb4)) ### Bug Fixes * add timestamp freshness check to VerifyWebhookSignature ([7e714bd](https://github.com/Phala-Network/phala-cloud/commit/7e714bd)) * preserve endpoint instance and error detail values ([d3fd65f](https://github.com/Phala-Network/phala-cloud/commit/d3fd65f)) * make WatchCVMState MaxRetries default to unlimited ([c4b7eb4](https://github.com/Phala-Network/phala-cloud/commit/c4b7eb4)) ## v0.1.0 *Initial release* The first public release of the Phala Cloud Go SDK, providing full coverage of the Phala Cloud REST API. ### Features * **Client initialization** with functional options pattern (`NewClient`, `WithAPIKey`, `WithBaseURL`, etc.) * **CVM lifecycle** — provision, commit, start, stop, shutdown, restart, delete, replicate * **CVM configuration** — update Docker Compose, pre-launch scripts, resources, visibility, env vars, OS images * **Multi-field patch** — `PatchCVM` and `ConfirmCVMPatch` for atomic multi-field updates with on-chain confirmation support * **Real-time state watching** — `WatchCVMState` via SSE with Go channels, automatic reconnection, and configurable retries * **App management** — list apps, get info, query CVMs, revisions, attestations, and device allowlists * **Workspace operations** — list workspaces, get details, query nodes and quotas * **KMS** — list servers, get info, fetch encryption public keys, query on-chain details * **SSH key management** — list, create, delete, import from GitHub profile, sync from linked GitHub account * **Automatic retries** — exponential backoff (1s base, 20s cap) for 409/429/503 responses * **Structured error handling** — `APIError` with classification methods, error codes, suggestions, and documentation links * **CVM ID resolution** — automatic normalization of UUIDs, app IDs, hashed IDs, and names * **Pointer helpers** — `String()`, `Int()`, `Int64()`, `Float64()`, `Bool()` for optional fields * **Environment variable fallbacks** — `PHALA_CLOUD_API_KEY` and `PHALA_CLOUD_API_PREFIX` ### Requirements * Go 1.25 or later * API version: `2026-01-21` # CVM Configuration Source: https://docs.phala.com/phala-cloud/references/cloud-go-sdk/cvm-configuration Update Docker Compose, pre-launch scripts, resources, visibility, environment variables, and OS images for CVMs. CVM configuration methods let you modify a running or stopped CVM without recreating it. > [!WARNING] > > **Some configuration updates restart a running CVM.** A change applied through `PATCH /cvms/{cvmId}` or the compose, environment and OS image endpoints stops the CVM, applies the change and starts it again. A stopped CVM stays stopped and runs the new configuration at its next start. A compose change that matches what the CVM already runs does not restart it: the API answers `no_change` and does nothing. [`UpdateCVMListed`](#updatecvmlisted) and annotations (`UpdateCVMAnnotations`) never restart the CVM, and SSH key changes without `ApplyNow` stay pending until the next power-on. `PatchCVM` sends any set of changes in one request to `PATCH /cvms/{cvmId}`. `UpdateCVMResources` and `UpdateCVMVisibility` send a subset of fields to the same endpoint. The other `UpdateXxxx` methods call their own endpoints. See [Update CVM Configuration](/phala-cloud/update/update-cvm-configuration) for what each field does and which settings cannot change after create. For CVMs using on-chain KMS, updates that affect the compose hash require an additional on-chain confirmation step. ## UpdateDockerCompose `PATCH /cvms/{cvmId}/docker-compose` Replaces the Docker Compose YAML for a CVM. The compose content is sent as `text/yaml`. For on-chain KMS CVMs, pass compose hash and transaction hash via the options parameter. ```go theme={"system"} func (c *Client) UpdateDockerCompose(ctx context.Context, cvmID, compose string, opts *ComposeUpdateOptions) (*UpdateResult, error) ``` **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `cvmID` | `string` | Yes | CVM identifier | | `compose` | `string` | Yes | Docker Compose YAML content | | `opts` | `*ComposeUpdateOptions` | No | Compose hash and transaction hash headers | **ComposeUpdateOptions fields:** | Field | Type | Description | | - | - | - | | `ComposeHash` | `string` | Compose hash for on-chain verification (sent as `X-Compose-Hash`) | | `TransactionHash` | `string` | On-chain transaction hash (sent as `X-Transaction-Hash`) | **Returns:** `*UpdateResult` when the update is accepted. For an on-chain KMS CVM whose new compose hash is not registered yet, the API answers HTTP 465 and the method returns an `*APIError`. Call `ComposePrecondition()` on it to read the compose hash to register, then call again with `opts`. ```go theme={"system"} result, err := client.UpdateDockerCompose(ctx, "my-app", composeYAML, nil) var apiErr *phala.APIError if errors.As(err, &apiErr) && apiErr.IsComposePrecondition() { precondition, _ := apiErr.ComposePrecondition() fmt.Println("Register compose hash:", precondition.ComposeHash) } else if err != nil { log.Fatal(err) } ``` *** ## UpdatePreLaunchScript `PATCH /cvms/{cvmId}/pre-launch-script` Updates the shell script that runs before CVM containers start. Sent as `text/plain`. ```go theme={"system"} func (c *Client) UpdatePreLaunchScript(ctx context.Context, cvmID, script string, opts *ComposeUpdateOptions) (*UpdateResult, error) ``` **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `cvmID` | `string` | Yes | CVM identifier | | `script` | `string` | Yes | Shell script content | | `opts` | `*ComposeUpdateOptions` | No | Compose hash and transaction hash headers | **Returns:** `*UpdateResult` ```go theme={"system"} script := "#!/bin/sh\necho 'Pre-launch setup complete'" result, err := client.UpdatePreLaunchScript(ctx, "my-app", script, nil) ``` *** ## CommitCVMUpdate `POST /cvms/{cvmId}/commit-update` Commit a prepared on-chain update with its token, compose hash, and transaction hash. The response contains `CorrelationID` and `Status`. ```go theme={"system"} result, err := client.CommitCVMUpdate(ctx, "my-app", &phala.CommitCVMUpdateRequest{ Token: token, ComposeHash: composeHash, TransactionHash: transactionHash, }) if err != nil { log.Fatal(err) } fmt.Println(result.CorrelationID, result.Status) ``` ## UpdateCVMResources `PATCH /cvms/{cvmId}` Updates the resource allocation (vCPUs, memory, disk) for a CVM. All fields are optional; only the fields you include will be changed. ```go theme={"system"} func (c *Client) UpdateCVMResources(ctx context.Context, cvmID string, req *UpdateResourcesRequest) (*UpdateResourcesResponse, error) ``` **UpdateResourcesRequest fields:** | Field | Type | Description | | - | - | - | | `VCPU` | `*int` | Number of vCPUs | | `Memory` | `*int` | Memory in MB | | `DiskSize` | `*int` | Disk size in GB. A disk cannot shrink. | | `InstanceType` | `*string` | Instance type override | | `AllowRestart` | `*bool` | Deprecated and not sent. The CVM restarts whenever a resize needs it. | **Returns:** `*UpdateResourcesResponse`, an alias of `CVMUpdateResponse` (`Message`, `CorrelationID`, `Status`). ```go theme={"system"} resp, err := client.UpdateCVMResources(ctx, "my-app", &phala.UpdateResourcesRequest{ VCPU: phala.Int(4), Memory: phala.Int(8192), DiskSize: phala.Int(50), }) if err != nil { log.Fatal(err) } fmt.Println(resp.CorrelationID) ``` *** ## UpdateCVMVisibility `PATCH /cvms/{cvmId}` Controls which information about a CVM is publicly accessible. All fields are optional. ```go theme={"system"} func (c *Client) UpdateCVMVisibility(ctx context.Context, cvmID string, req *UpdateVisibilityRequest) (*CVMUpdateResponse, error) ``` **UpdateVisibilityRequest fields:** | Field | Type | Description | | - | - | - | | `PublicSysinfo` | `*bool` | Make system info public | | `PublicLogs` | `*bool` | Make logs public | | `PublicTcbinfo` | `*bool` | Make TCB info public | **Returns:** `*CVMUpdateResponse` (`Message`, `CorrelationID`, `Status`). `Status` is `"no_change"` with an empty `CorrelationID` when the settings already match. These settings are part of the compose hash. For a CVM on Onchain KMS, the API answers HTTP 465 until the new hash is registered on-chain. Use [`PatchCVM`](#patchcvm), which returns the hash to register. ```go theme={"system"} resp, err := client.UpdateCVMVisibility(ctx, "my-app", &phala.UpdateVisibilityRequest{ PublicSysinfo: phala.Bool(true), PublicLogs: phala.Bool(true), }) if err != nil { log.Fatal(err) } ``` *** ## UpdateCVMListed `PATCH /cvms/{cvmId}/listed` Sets whether the app is listed on the public Trust Center. The listing applies to every CVM of the app. It only changes a record in Phala Cloud: no compose change and no restart. ```go theme={"system"} func (c *Client) UpdateCVMListed(ctx context.Context, cvmID string, listed bool) error ``` *** ## UpdateCVMEnvs `PATCH /cvms/{cvmId}/envs` Updates the encrypted environment variables for a CVM. Environment variables are encrypted client-side before being sent to the API. `ProvisionComposeUpdateRequest.EncryptedEnv` has been removed; use `UpdateCVMEnvs` for environment changes instead. ```go theme={"system"} func (c *Client) UpdateCVMEnvs(ctx context.Context, cvmID string, req *UpdateEnvsRequest) (*UpdateResult, error) ``` **UpdateEnvsRequest fields:** | Field | Type | Required | Description | | - | - | - | - | | `EncryptedEnv` | `string` | Yes | Hex-encoded encrypted environment variables | | `EnvKeys` | `[]string` | No | List of environment variable key names | | `ComposeHash` | `*string` | No | Compose hash for on-chain verification | | `TransactionHash` | `*string` | No | On-chain transaction hash | **Returns:** `*UpdateResult` ```go theme={"system"} result, err := client.UpdateCVMEnvs(ctx, "my-app", &phala.UpdateEnvsRequest{ EncryptedEnv: encryptedHex, EnvKeys: []string{"DATABASE_URL", "SECRET_KEY"}, }) ``` *** ## UpdateOSImage `PATCH /cvms/{cvmId}/os-image` Updates the OS image for a CVM. The CVM will need a restart to apply the new image. ```go theme={"system"} func (c *Client) UpdateOSImage(ctx context.Context, cvmID string, req *UpdateOSImageRequest) error ``` **UpdateOSImageRequest fields:** | Field | Type | Required | Description | | - | - | - | - | | `OSImageName` | `string` | Yes | Name of the target OS image | **Returns:** `error`. The API answers with `{message, correlation_id, status}`, but `UpdateOSImage` discards it. ```go theme={"system"} err := client.UpdateOSImage(ctx, "my-app", &phala.UpdateOSImageRequest{ OSImageName: "dstack-v0.4.0", }) ``` *** ## PatchCVM `PATCH /cvms/{cvmId}` Applies a multi-field update to a CVM in a single request. You can change compose, resources, visibility, and more in one call. `Compose` is a JSON Merge Patch of the app compose. Each `ComposePatch` key is a `Patch[T]`: leave it zero to keep the value, use `phala.PatchValue(v)` to set it, or `phala.PatchNull[T]()` to remove it. See [How does the compose patch work?](/phala-cloud/update/update-cvm-configuration#how-does-the-compose-patch-work) for the keys. To change a `bash` runner's script, set `ComposePatch.BashScript`. To change the Trust Center listing, use [`UpdateCVMListed`](#updatecvmlisted). ```go theme={"system"} func (c *Client) PatchCVM(ctx context.Context, cvmID string, req *PatchCVMRequest) (*PatchCVMResponse, error) ``` **PatchCVMRequest fields:** | Field | Type | Description | | - | - | - | | `DockerComposeFile` | `*string` | Docker Compose YAML | | `PreLaunchScript` | `*string` | Pre-launch shell script | | `EncryptedEnv` | `*string` | Encrypted environment variables | | `AllowedEnvs` | `[]string` | Allowed environment variable keys | | `PublicSysinfo` | `*bool` | Make system info public | | `PublicLogs` | `*bool` | Make logs public | | `PublicTcbinfo` | `*bool` | Make TCB info public | | `Compose` | `*ComposePatch` | Other compose settings as a merge patch | | `InitScripts` | `[]InitScriptSlug` | Platform init scripts the CVM runs (`InitScriptDockerCleanup`, `InitScriptEnvMerge`), replacing the current set. `nil` keeps them; an empty non-nil slice removes them all. | | `ConfirmDataWipe` | `bool` | Confirms turning on `docker_cleanup` or `requirements.ephemeral_data_disk`, which erase data on every boot | | `UserConfig` | `*string` | User configuration string | | `GPUs` | `*GPUConfig` | GPU assignment: `GPUs []GPUSpec{Slot, ProductID}` and `AttachMode`. `AttachMode` `"all"` attaches every GPU on the node. | | `VCPU` | `*int` | Number of vCPUs | | `Memory` | `*int` | Memory in MB | | `DiskSize` | `*int` | Disk size in GB | | `InstanceType` | `*string` | Instance type | | `Image` | `*string` | OS image name or slug, as listed by `GetAvailableOSImages` | | `OSImageName` | `*string` | Deprecated. Sent as `image`; an error if it differs from `Image`. | | `ShutdownTimeout` | `*int` | Seconds to wait for a clean shutdown (10 to 1200) | | `AllowForceStop` | `*bool` | Skip the clean shutdown and stop the CVM at once | | `PrepareOnly` | `bool` | Sent as the `X-Prepare-Only: true` header. When the API answers 465 (the new compose hash is not on the app contract yet), the response also carries a commit token for multisig approval. It is not a dry run: if no on-chain registration is needed, the update starts. | A nil `AllowedEnvs` slice omits the field; an explicitly empty slice sends `[]` to clear it. **Returns:** `*PatchCVMResponse`. A 465 answer is not an error: `RequiresOnChainHash` is `true` and the response carries `ComposeHash`, `AppID`, `DeviceID` and `KMSInfo`, plus `CommitToken`, `CommitURL`, `APICommitURL` and `OnchainStatus` with `PrepareOnly`. Otherwise it carries `CorrelationID` and `Status`; `Status` is `"no_change"` with an empty `CorrelationID` when nothing had to change. ```go theme={"system"} compose := "services:\n app:\n image: nginx:latest\n" resp, err := client.PatchCVM(ctx, "my-app", &phala.PatchCVMRequest{ DockerComposeFile: &compose, PublicSysinfo: phala.Bool(true), VCPU: phala.Int(4), Compose: &phala.ComposePatch{ SwapSize: phala.PatchValue("2G"), }, }) if err != nil { log.Fatal(err) } if resp.RequiresOnChainHash { // Handle on-chain confirmation — see ConfirmCVMPatch fmt.Printf("On-chain confirmation needed. Compose hash: %s\n", resp.ComposeHash) } ``` *** ## GetCVMInitScripts `GET /cvms/{cvmId}/init-scripts` Lists the platform init scripts, in run order, and for each one whether the CVM runs it (`Selected`), whether you can pick it for this CVM (`Selectable`) and, if not, why (`Reason`). Change the selection with `PatchCVM`'s `InitScripts`. See [Init scripts](/phala-cloud/cvm/advanced-settings#init-scripts). ```go theme={"system"} func (c *Client) GetCVMInitScripts(ctx context.Context, cvmID string) (*CVMInitScriptsResponse, error) ``` *** ## GetCVMAnnotations / UpdateCVMAnnotations `GET /cvms/{cvmId}/annotations` / `PUT /cvms/{cvmId}/annotations` Reads or replaces the CVM's annotations: key/value settings for tools on the host. They are not measured and attestation does not cover them. `UpdateCVMAnnotations` replaces every annotation, and an empty map clears them. It does not restart the CVM. Annotations sit behind a feature flag; without it, both calls fail with `ERR-03-049`. See [Annotations](/phala-cloud/cvm/advanced-settings#annotations). ```go theme={"system"} func (c *Client) GetCVMAnnotations(ctx context.Context, cvmID string) (*CVMAnnotationsResponse, error) func (c *Client) UpdateCVMAnnotations(ctx context.Context, cvmID string, annotations map[string]string) (*CVMAnnotationsResponse, error) ``` **Returns:** `*CVMAnnotationsResponse` with `Annotations`, the annotations the node now stores. *** ## ConfirmCVMPatch `PATCH /cvms/{cvmId}` Confirms a CVM patch that requires on-chain verification. Call this after `PatchCVM` returns `RequiresOnChainHash: true` and you have submitted the transaction on-chain. ```go theme={"system"} func (c *Client) ConfirmCVMPatch(ctx context.Context, cvmID string, req *ConfirmCVMPatchRequest) (*CVMActionResponse, error) ``` **ConfirmCVMPatchRequest fields:** | Field | Type | Required | Description | | - | - | - | - | | `ComposeHash` | `string` | Yes | Compose hash from PatchCVM response | | `TransactionHash` | `string` | Yes | On-chain transaction hash | The request sends an empty JSON object and supplies the hashes in the `X-Compose-Hash` and `X-Transaction-Hash` headers. The response retains the action fields and includes `CorrelationID`. `ConfirmCVMPatchV20260121` returns the earlier ID shape. **Returns:** `*CVMActionResponse` ```go theme={"system"} result, err := client.ConfirmCVMPatch(ctx, "my-app", &phala.ConfirmCVMPatchRequest{ ComposeHash: resp.ComposeHash, TransactionHash: transactionHash, }) if err != nil { log.Fatal(err) } fmt.Println(result.CorrelationID) ``` *** ## Compose File Operations These methods let you provision and commit compose file updates using the two-phase flow, similar to initial CVM provisioning. ### ProvisionCVMComposeFileUpdate `POST /cvms/{cvmId}/compose_file/provision` Provisions a compose file update without applying it yet. Returns a compose hash for the commit step. ```go theme={"system"} func (c *Client) ProvisionCVMComposeFileUpdate(ctx context.Context, cvmID string, req *ProvisionComposeUpdateRequest) (*ProvisionCVMResponse, error) ``` ### CommitCVMComposeFileUpdate `PATCH /cvms/{cvmId}/compose_file` Commits a previously provisioned compose file update. ```go theme={"system"} func (c *Client) CommitCVMComposeFileUpdate(ctx context.Context, cvmID string, req *CommitComposeUpdateRequest) error ``` **Example — two-phase compose update:** ```go theme={"system"} // Step 1: Provision the update provision, err := client.ProvisionCVMComposeFileUpdate(ctx, "my-app", &phala.ProvisionComposeUpdateRequest{ DockerComposeFile: newComposeYAML, }) if err != nil { log.Fatal(err) } // Step 2: Commit the update err = client.CommitCVMComposeFileUpdate(ctx, "my-app", &phala.CommitComposeUpdateRequest{ ComposeHash: provision.ComposeHash, }) if err != nil { log.Fatal(err) } ``` # CVM Lifecycle Source: https://docs.phala.com/phala-cloud/references/cloud-go-sdk/cvm-lifecycle Provision, start, stop, restart, delete, and replicate CVMs with the Go SDK. CVM lifecycle methods manage the full journey of a Confidential Virtual Machine, from initial provisioning through daily operations to deletion. All methods accept a `context.Context` as the first parameter and return Go-idiomatic `(result, error)` pairs. ## ProvisionCVM `POST /cvms` Provisions a new CVM by reserving resources and generating a compose hash. This is the first step of the two-phase deployment flow. The returned `AppID` and `ComposeHash` are needed to commit the provision. ```go theme={"system"} func (c *Client) ProvisionCVM(ctx context.Context, req *ProvisionCVMRequest) (*ProvisionCVMResponse, error) ``` **ProvisionCVMRequest fields:** | Field | Type | Required | Description | | - | - | - | - | | `Name` | `string` | Yes | Name for the CVM | | `InstanceType` | `string` | No | Instance type; an empty value is omitted and the server selects a type | | `ComposeFile` | `*ComposeFile` | Yes, unless `ComposeFileRaw` is set | Compose configuration | | `VCPU` | `*int` | No | Number of vCPUs | | `Memory` | `*int` | No | Memory in MB | | `DiskSize` | `*int` | No | Disk size in GB | | `Node` | `*string` | No | Physical node name for deployment | | `Image` | `*string` | No | OS image name | | `Region` | `*string` | No | Target region | | `KMS` | `*string` | No | KMS type | | `Listed` | `*bool` | No | Whether the CVM is publicly listed | | `SSHKeyIDs` | `[]string` | No | SSH key IDs to authorize | | `InitScripts` | `[]InitScriptSlug` | No | Platform init scripts the CVM runs on every boot: `InitScriptDockerCleanup` (needs dstack OS 0.6.x, `ext4` storage and the `docker-compose` runner) and `InitScriptEnvMerge` (dstack OS 0.6.0 or newer, available on request). The list is the whole set; Phala Cloud runs them in a fixed order, `docker_cleanup` first. See [Init scripts](/phala-cloud/cvm/advanced-settings#init-scripts). `EnabledInitScriptsDockerCleanup` is deprecated. | | `LaunchToken` | `*string` | No | Launch token, at least 32 bytes, that the CVM must have on every boot. See [Launch Token](/phala-cloud/cvm/launch-token). | | `GenerateLaunchToken` | `*bool` | No | Have Phala Cloud generate the launch token for a new app, or use the app's existing token. A new token is returned once, in `CommitCVMProvisionResponse.LaunchToken`. | | `Annotations` | `map[string]string` | No | Host-side settings for tools on the node, not measured. Needs a feature flag (`ERR-03-049` without it) and dstack VMM 0.6.1 or newer on the node (`ERR-03-050`). See [Annotations](/phala-cloud/cvm/advanced-settings#annotations). | | `ComposeFileRaw` | `*string` | No | A whole app-compose JSON file as one string, sent instead of `ComposeFile`. Needs a feature flag. Phala Cloud parses it with the same rules and writes it the same way, so the compose hash comes from that output, not from your bytes. See [Raw app-compose input](/phala-cloud/cvm/advanced-settings#raw-app-compose-input). | Additional typed fields include `KMSContractID`, `AppID`, `EnvKeys`, `Ports`, `GPUs`, `EncryptedEnv`, and `UserConfig`. `ComposeFile` also supports fields such as `Runner`, `BashScript`, `AllowedEnvs`, `Requirements`, and `PortPolicy`. `ProvisionCVMRequest.KMSType` and `ProvisionCVMRequest.SSHAuthorizedKeys` remain in the Go type, but the current backend ignores these top-level fields. Use `KMS` to select the KMS type and `SSHKeyIDs` to authorize registered SSH keys. For slice fields with `omitzero`, a nil slice is omitted and an explicitly empty slice is sent as `[]`. `ComposeFile.EncryptedEnv` has been removed. For creation, set `ProvisionCVMRequest.EncryptedEnv` instead. For changes to a CVM's encrypted environment, use `UpdateCVMEnvs`. `ComposeFile.InitScript` uses `ComposeInitScripts`, a string slice. It decodes historical single-string and array responses and encodes as an array. The server ignores `compose_file.init_script` during creation; use `ProvisionCVMRequest.InitScripts` to select platform-owned scripts. **Returns:** `*ProvisionCVMResponse` with `AppID`, `ComposeHash`, `AppEnvEncryptPubkey`, and other provisioning details. **Example:** ```go theme={"system"} provision, err := client.ProvisionCVM(ctx, &phala.ProvisionCVMRequest{ Name: "my-app", InstanceType: "tdx.small", ComposeFile: &phala.ComposeFile{ DockerComposeFile: "services:\n app:\n image: nginx:latest\n ports:\n - \"80:80\"\n", }, }) if err != nil { log.Fatal(err) } fmt.Printf("App ID: %s, Compose Hash: %s\n", provision.AppID, provision.ComposeHash) ``` *** ## CommitCVMProvision `POST /cvms` Commits a provisioned CVM, triggering deployment. Pass the provision response's `Token`, or supply its `AppID` and `ComposeHash`. ```go theme={"system"} func (c *Client) CommitCVMProvision(ctx context.Context, req *CommitCVMProvisionRequest) (*CommitCVMProvisionResponse, error) ``` **CommitCVMProvisionRequest fields:** | Field | Type | Required | Description | | - | - | - | - | | `Token` | `*string` | No | Commit token from the provision response | | `AppID` | `string` | Without token | App ID from the provision response | | `ComposeHash` | `string` | Without token | Compose hash from the provision response | | `TransactionHash` | `*string` | No | On-chain transaction hash (for on-chain KMS) | | `EncryptedEnv` | `*string` | No | Encrypted environment variables | | `EnvKeys` | `[]string` | No | Environment variable key names | **Returns:** `*CommitCVMProvisionResponse` with `ID`, `Name`, and `Status`. Use the `CvmID()` helper method to get the ID as a string. **Example — full two-phase deploy:** ```go theme={"system"} // Step 1: Provision provision, err := client.ProvisionCVM(ctx, &phala.ProvisionCVMRequest{ Name: "my-app", InstanceType: "tdx.small", ComposeFile: &phala.ComposeFile{ DockerComposeFile: composeYAML, }, }) if err != nil { log.Fatal(err) } // Step 2: Commit cvm, err := client.CommitCVMProvision(ctx, &phala.CommitCVMProvisionRequest{ AppID: provision.AppID, ComposeHash: provision.ComposeHash, }) if err != nil { log.Fatal(err) } fmt.Printf("CVM deployed: %s (status: %s)\n", cvm.CvmID(), cvm.Status) ``` *** ## StartCVM `POST /cvms/{cvmId}/start` Starts a stopped CVM. This method retries automatically on transient errors. ```go theme={"system"} func (c *Client) StartCVM(ctx context.Context, cvmID string) (*CVMActionResponse, error) ``` **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `cvmID` | `string` | Yes | CVM identifier (any format) | **Returns:** `*CVMActionResponse` with `ID`, `Name`, and `Status`. ```go theme={"system"} result, err := client.StartCVM(ctx, "my-app") if err != nil { log.Fatal(err) } fmt.Printf("Status: %s\n", result.Status) ``` *** ## StopCVM `POST /cvms/{cvmId}/stop` Force-stops a CVM immediately. Use `ShutdownCVM` if you need a graceful stop. ```go theme={"system"} func (c *Client) StopCVM(ctx context.Context, cvmID string) (*CVMActionResponse, error) ``` **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `cvmID` | `string` | Yes | CVM identifier | **Returns:** `*CVMActionResponse` *** ## ShutdownCVM `POST /cvms/{cvmId}/shutdown` Gracefully shuts down a CVM, allowing containers to stop cleanly before powering off. ```go theme={"system"} func (c *Client) ShutdownCVM(ctx context.Context, cvmID string) (*CVMActionResponse, error) ``` **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `cvmID` | `string` | Yes | CVM identifier | **Returns:** `*CVMActionResponse` ```go theme={"system"} _, err := client.ShutdownCVM(ctx, "my-app") ``` *** ## RestartCVM `POST /cvms/{cvmId}/restart` Restarts a CVM. By default, the restart is graceful. Set `Force: true` to skip the graceful shutdown phase. ```go theme={"system"} func (c *Client) RestartCVM(ctx context.Context, cvmID string, opts *RestartCVMOptions) (*CVMActionResponse, error) ``` **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `cvmID` | `string` | Yes | CVM identifier | | `opts` | `*RestartCVMOptions` | No | Pass `nil` for a graceful restart | **RestartCVMOptions fields:** | Field | Type | Default | Description | | - | - | - | - | | `Force` | `bool` | `false` | Force restart without graceful shutdown | ```go theme={"system"} // Graceful restart _, err := client.RestartCVM(ctx, "my-app", nil) // Force restart _, err = client.RestartCVM(ctx, "my-app", &phala.RestartCVMOptions{Force: true}) ``` *** ## DeleteCVM `DELETE /cvms/{cvmId}` Permanently deletes a CVM and all its data. Returns only an error (no response body). ```go theme={"system"} func (c *Client) DeleteCVM(ctx context.Context, cvmID string) error ``` **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `cvmID` | `string` | Yes | CVM identifier | > [!WARNING] > > This action is irreversible. All data associated with the CVM will be permanently deleted. ```go theme={"system"} err := client.DeleteCVM(ctx, "my-app") if err != nil { log.Fatal(err) } ``` *** ## ReplicateCVM `POST /cvms/{cvmId}/replicas` Creates a replica of an existing CVM. You can optionally target a specific node. The new CVM inherits the source's configuration. ```go theme={"system"} func (c *Client) ReplicateCVM(ctx context.Context, cvmID string, opts *ReplicateCVMOptions) (*CVMActionResponse, error) ``` **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `cvmID` | `string` | Yes | Source CVM identifier | | `opts` | `*ReplicateCVMOptions` | No | Replication options | **ReplicateCVMOptions fields:** | Field | Type | Description | | - | - | - | | `Node` | `*string` | Physical node name; omit to inherit the source placement | | `OSImage` | `string` | OS image override | ```go theme={"system"} replica, err := client.ReplicateCVM(ctx, "my-app", &phala.ReplicateCVMOptions{ Node: phala.String("prod6"), }) if err != nil { log.Fatal(err) } fmt.Printf("Replica status: %s\n", replica.Status) ``` > [!NOTE] > > You can also replicate a CVM within an app context using `ReplicateAppCVM(ctx, appID, vmUUID, opts)`, which ensures the replica is associated with the correct application. # Error Handling Source: https://docs.phala.com/phala-cloud/references/cloud-go-sdk/error-handling APIError struct, error classification methods, retry logic, and structured error codes in the Go SDK. The Go SDK returns all API errors as `*phala.APIError`, which implements the `error` interface. This gives you a single type to handle, with helper methods to classify the error and decide what to do next. This page covers how to catch and handle errors from the SDK. For the full list of `ERR-xxxx` error codes returned by the API, see the [Error Codes Reference](/phala-cloud/references/error-codes). ## The APIError Type Every non-2xx response from the API is wrapped in an `*APIError`. Use `errors.As` to extract it from the returned error. ```go theme={"system"} import "errors" info, err := client.GetCVMInfo(ctx, "nonexistent") if err != nil { var apiErr *phala.APIError if errors.As(err, &apiErr) { fmt.Printf("Status: %d\n", apiErr.StatusCode) fmt.Printf("Message: %s\n", apiErr.Message) } } ``` ### APIError Fields | Field | Type | Description | | - | - | - | | `StatusCode` | `int` | HTTP status code | | `Message` | `string` | Human-readable error message | | `ErrorCode` | `string` | Structured error code (e.g., `"ERR-01-001"`) | | `Detail` | `any` | Raw error detail from API | | `Body` | `string` | Raw response body | | `Headers` | `http.Header` | Response headers | | `Details` | `[]ErrorDetail` | Field-level validation errors | | `Suggestions` | `[]string` | Suggested fixes | | `Links` | `[]ErrorLink` | Documentation links | ## Error Classification `APIError` provides boolean methods to classify errors by category. These make it easy to write switch-style error handling without checking status codes directly. ```go theme={"system"} var apiErr *phala.APIError if errors.As(err, &apiErr) { switch { case apiErr.IsAuth(): // 401 or 403 — invalid or expired API key fmt.Println("Authentication failed:", apiErr.Message) case apiErr.IsValidation(): // 422 — request body failed validation for _, d := range apiErr.Details { fmt.Printf(" Field %s: %s\n", d.Field, d.Message) } case apiErr.IsBusiness(): // 4xx (non-auth, non-validation) — business logic error fmt.Println("Business error:", apiErr.Message) case apiErr.IsServer(): // 5xx — server-side failure fmt.Println("Server error:", apiErr.Message) } } ``` ### Classification Methods | Method | Status Codes | Description | | - | - | - | | `IsAuth()` | 401, 403 | Authentication or authorization failure | | `IsValidation()` | 422 | Request validation failure (field-level details in `Details`) | | `IsBusiness()` | 4xx (not auth/validation) | Business logic error | | `IsServer()` | 500+ | Server-side error | | `IsRetryable()` | 409, 429, 503 | Transient error worth retrying | | `IsConflict()` | 409 | Resource conflict | | `IsComposePrecondition()` | 465 | Compose hash precondition failure (requires on-chain confirmation) | | `IsStructured()` | any | Has a structured `ErrorCode` | > [!NOTE] > > A 409 Conflict with a structured `ErrorCode` is treated as a deterministic business error and is **not** retryable. Only bare 409 responses (without an error code) are retried automatically. ## Structured Errors Some API errors include a structured `ErrorCode` (like `ERR-01-001`) along with detailed suggestions and documentation links. Check for these with `IsStructured()` or `HasErrorCode()`. ```go theme={"system"} if apiErr.IsStructured() { fmt.Printf("Error code: %s\n", apiErr.ErrorCode) for _, s := range apiErr.Suggestions { fmt.Printf(" Suggestion: %s\n", s) } for _, l := range apiErr.Links { fmt.Printf(" See: %s (%s)\n", l.URL, l.Label) } } ``` ### HasErrorCode Check for a specific error code: ```go theme={"system"} if apiErr.HasErrorCode("ERR-01-001") { // Handle specific error } ``` ## FormatError The `FormatError` method produces a human-readable string that includes the error code, message, field-level details, suggestions, and reference links. ```go theme={"system"} if apiErr.IsStructured() { fmt.Println(apiErr.FormatError()) } // Output: // [ERR-01-001] The requested instance type does not exist // // Details: // - Instance type 'invalid' is not recognized (field: instance_type, value: invalid) // // Suggestions: // - Use a valid instance type: tdx.small, tdx.medium, or tdx.large // // References: // - View available instance types: https://cloud.phala.com/instances ``` ## Retry-After Header When the API returns a 429 (Too Many Requests) or 503 (Service Unavailable), it may include a `Retry-After` header. The `RetryAfter()` method parses this into a `time.Duration`. ```go theme={"system"} if apiErr.IsRetryable() { if wait := apiErr.RetryAfter(); wait > 0 { time.Sleep(wait) // Retry the request } } ``` The method handles both numeric seconds and HTTP date formats. Returns `0` if the header is absent or unparseable. ## Automatic Retries The SDK automatically retries requests that fail with retryable status codes (409, 429, 503). Retries use exponential backoff starting at 1 second with a 20-second cap. Configure the maximum number of retries when creating the client. ```go theme={"system"} client, err := phala.NewClient( phala.WithAPIKey("phak_your_api_key"), phala.WithMaxRetries(10), // Default is 30 ) ``` > [!WARNING] > > Not all methods use automatic retries. Read-only `GET` requests and non-idempotent operations like `CommitCVMProvision` do not retry automatically. Lifecycle operations (`StartCVM`, `StopCVM`, `RestartCVM`, etc.) and configuration updates do retry. ## Validation Error Details When `IsValidation()` is true, the `Details` field contains field-level error information. ```go theme={"system"} type ErrorDetail struct { Field string `json:"field"` Value any `json:"value"` Message string `json:"message"` } ``` ```go theme={"system"} if apiErr.IsValidation() { for _, d := range apiErr.Details { fmt.Printf("Field '%s': %s\n", d.Field, d.Message) } } ``` ## Complete Example Here is a comprehensive error handling pattern for a CVM provisioning flow: ```go theme={"system"} provision, err := client.ProvisionCVM(ctx, req) if err != nil { var apiErr *phala.APIError if errors.As(err, &apiErr) { switch { case apiErr.IsAuth(): return fmt.Errorf("invalid API key: %s", apiErr.Message) case apiErr.IsValidation(): for _, d := range apiErr.Details { log.Printf("validation: %s — %s", d.Field, d.Message) } return fmt.Errorf("invalid request") case apiErr.IsStructured(): log.Println(apiErr.FormatError()) return fmt.Errorf("provisioning failed: %s", apiErr.ErrorCode) case apiErr.IsServer(): return fmt.Errorf("server error (try again later): %s", apiErr.Message) default: return fmt.Errorf("API error %d: %s", apiErr.StatusCode, apiErr.Message) } } return fmt.Errorf("unexpected error: %w", err) } ``` # KMS Source: https://docs.phala.com/phala-cloud/references/cloud-go-sdk/kms List KMS contracts, inspect their nodes and verification anchors, and retrieve app encryption keys. The Go SDK v0.2.0 models KMS resources by contract. A KMS contract groups equivalent KMS node replicas that share one root key. ## ListKMSContracts `GET /kms` ```go theme={"system"} func (c *Client) ListKMSContracts(ctx context.Context) (*ListKMSContractsResponse, error) ``` **Parameters:** `ctx` controls cancellation and request lifetime. **Returns:** `*ListKMSContractsResponse`, a paginated list of `KMSContract` values, or an error. Returns the available KMS contracts. This method always requests API version `2026-06-23`. ```go theme={"system"} contracts, err := client.ListKMSContracts(ctx) if err != nil { log.Fatal(err) } for _, contract := range contracts.Items { fmt.Println(contract.ID, contract.ContractAddress, contract.NodeCount) } ``` Each `KMSContract` includes the contract ID, slug, contract address, chain ID, node count, `K256Pubkey`, and `CAPubkey`. For the off-chain Phala KMS, the contract address is `"phala"` and the chain ID is `0`. ## GetKMSContract `GET /kms/{slug}` ```go theme={"system"} func (c *Client) GetKMSContract(ctx context.Context, slug string) (*KMSContract, error) ``` **Parameters:** `ctx` controls cancellation; `slug` accepts a contract slug or `kc_`-prefixed contract ID. **Returns:** `*KMSContract` for the resolved contract, or an error. Returns one KMS contract by slug. A `kc_`-prefixed contract ID also resolves. ```go theme={"system"} contract, err := client.GetKMSContract(ctx, "base") if err != nil { log.Fatal(err) } fmt.Println(contract.ContractAddress) fmt.Println(contract.K256Pubkey, contract.CAPubkey) ``` ## ListKMSContractNodes `GET /kms/{slug}/nodes` ```go theme={"system"} func (c *Client) ListKMSContractNodes( ctx context.Context, slug string, ) (*ListKMSContractNodesResponse, error) ``` **Parameters:** `ctx` controls cancellation; `slug` accepts a contract slug or `kc_`-prefixed contract ID. **Returns:** `*ListKMSContractNodesResponse` with the contract's node replicas, or an error. Returns the KMS node replicas under a contract, including each node's RPC URL and version. ```go theme={"system"} nodes, err := client.ListKMSContractNodes(ctx, "base") if err != nil { log.Fatal(err) } for _, node := range nodes.Items { fmt.Println(node.ID, node.URL, node.Version) } ``` ## Legacy node methods ```go theme={"system"} func (c *Client) GetKMSList(ctx context.Context) (*GetKMSListResponse, error) func (c *Client) GetKMSInfo(ctx context.Context, kmsID string) (*KMSInfo, error) ``` `GetKMSList` takes a request context. `GetKMSInfo` also requires a KMS node ID or slug. They return the earlier node-centric KMS shapes or an error. Both methods are deprecated and remain pinned to API version `2026-05-22`. Use `ListKMSContracts`, `GetKMSContract`, and `ListKMSContractNodes` for new code. ## GetAppEnvEncryptPubKey `GET /kms/{kmsType}/pubkey/{appId}` ```go theme={"system"} func (c *Client) GetAppEnvEncryptPubKey( ctx context.Context, kmsType string, appID string, ) (*AppEnvPubKeyResponse, error) ``` **Parameters:** `ctx` controls cancellation, `kmsType` is a KMS node ID or slug, and `appID` is the app ID. **Returns:** `*AppEnvPubKeyResponse` containing the public key response, or an error. Returns the public key used to encrypt environment variables for an app. ```go theme={"system"} key, err := client.GetAppEnvEncryptPubKey( ctx, "phala", "ff22c67f5d3b4c8a9e1f0a2b3c4d5e6f7a8b9c0d", ) if err != nil { log.Fatal(err) } fmt.Println(key) ``` ## NextAppIDs `GET /kms/phala/next_app_id` ```go theme={"system"} func (c *Client) NextAppIDs(ctx context.Context) (*NextAppIDsResponse, error) ``` **Parameters:** `ctx` controls cancellation and request lifetime. **Returns:** `*NextAppIDsResponse` with the reserved app IDs, or an error. Reserves app IDs from the Phala KMS for deterministic provisioning. ```go theme={"system"} reserved, err := client.NextAppIDs(ctx) if err != nil { log.Fatal(err) } fmt.Println(reserved) ``` ## GetKMSOnChainDetail `GET /kms/on-chain/{chain}` ```go theme={"system"} func (c *Client) GetKMSOnChainDetail( ctx context.Context, chain string, ) (*KMSOnChainDetail, error) ``` **Parameters:** `ctx` controls cancellation; `chain` is the chain name, such as `"base"` or `"ethereum"`. **Returns:** `*KMSOnChainDetail` with the chain and its KMS contracts, or an error. Returns the contracts, registered devices, OS images, and verification anchors for an on-chain KMS. ```go theme={"system"} detail, err := client.GetKMSOnChainDetail(ctx, "base") if err != nil { log.Fatal(err) } for _, contract := range detail.Contracts { fmt.Println(contract.ContractAddress) fmt.Println(contract.K256Pubkey, contract.CAPubkey) } ``` ## Compute a compose hash `GetComposeHash` normalizes an `AppCompose` before hashing by default. Pass `false` as the second argument to hash the typed compose without normalization. This default differs from older SDK behavior. `AppCompose` models only a subset of fields. For a complete decoded document, use `GetComposeHashFromMap`; it normalizes a copy without changing the input. Decode JSON with `json.Decoder.UseNumber` to preserve numeric values. `DumpAppComposeFromMap` returns the normalized canonical JSON used for hashing. These two hash `manifest_version` and `init_script` as given. To get the hash Phala Cloud computes for a CVM, use `GetComposeHashFromMapForOSImage` (or `DumpAppComposeFromMapForOSImage`) with the CVM's OS image version, for example `"0.6.0"`: below 0.6.0 the compose carries `manifest_version` 2 and a single `init_script` string, from 0.6.0 `manifest_version` "3" and a list. ## Compute and verify mr\_config\_id Use `GetMrConfigIdHex` when your inputs are hex strings: ```go theme={"system"} func GetMrConfigId(input MrConfigIdInput) ([48]byte, error) func GetMrConfigIdHex( composeHashHex string, appIDHex string, kp KeyProviderKind, kpIDHex string, ) (string, error) func GetMrConfigIdV1(composeHash [32]byte) [48]byte func VerifyMrConfigId( mrConfigIDHex string, composeHashHex string, appIDHex string, kp KeyProviderKind, kpIDHex string, ) (bool, error) ``` For `KeyProviderKMS`, set `kpIDHex` to the contract's `K256Pubkey`, not its `CAPubkey`. ```go theme={"system"} mrConfigID, err := phala.GetMrConfigIdHex( "0x<64-hex-characters>", "0xff22c67f5d3b4c8a9e1f0a2b3c4d5e6f7a8b9c0d", phala.KeyProviderKMS, "0x", ) if err != nil { log.Fatal(err) } matches, err := phala.VerifyMrConfigId( mrConfigID, "0x<64-hex-characters>", "0xff22c67f5d3b4c8a9e1f0a2b3c4d5e6f7a8b9c0d", phala.KeyProviderKMS, "0x", ) if err != nil { log.Fatal(err) } fmt.Println(matches) ``` Use `GetMrConfigId` for fixed-size byte inputs and `GetMrConfigIdV1` for the V1 compose-hash-only format. ## Related * [CVM Configuration](/phala-cloud/references/cloud-go-sdk/cvm-configuration) * [Error Handling](/phala-cloud/references/cloud-go-sdk/error-handling) # Cloud Go SDK Source: https://docs.phala.com/phala-cloud/references/cloud-go-sdk/overview Go client for the Phala Cloud API — manage CVMs, deployments, and infrastructure programmatically. > [!NOTE] > > The Go SDK is currently in **beta**. The API surface may change between releases. The `phala` Go package provides a strongly-typed client for the Phala Cloud API. It handles authentication, automatic retries with exponential backoff, and structured error responses out of the box. ## Installation Requires Go 1.25 or later. ```bash theme={"system"} go get github.com/Phala-Network/phala-cloud/go ``` ## Quick Start ```go theme={"system"} package main import ( "context" "fmt" "log" phala "github.com/Phala-Network/phala-cloud/go" ) func main() { client, err := phala.NewClient( phala.WithAPIKey("phak_your_api_key"), ) if err != nil { log.Fatal(err) } user, err := client.GetCurrentUser(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Hello, %s!\n", user.User.Username) } ``` ## Client Creation ### `NewClient(opts ...Option) (*Client, error)` Creates a new Phala Cloud API client. The API key is resolved from options first, then falls back to the `PHALA_CLOUD_API_KEY` environment variable. Returns an error if no API key is available. ```go theme={"system"} // Minimal — reads API key from PHALA_CLOUD_API_KEY env var client, err := phala.NewClient() ``` ```go theme={"system"} // Explicit configuration client, err := phala.NewClient( phala.WithAPIKey("phak_your_api_key"), phala.WithBaseURL("https://cloud-api.phala.com/api/v1"), phala.WithTimeout(60 * time.Second), phala.WithMaxRetries(10), ) ``` ## Configuration Options Every option is a function passed to `NewClient`. They follow Go's functional options pattern, so you can combine as many as you need. | Option | Default | Description | | - | - | - | | `WithAPIKey(key)` | `PHALA_CLOUD_API_KEY` env var | API key for authentication | | `WithBaseURL(url)` | `https://cloud-api.phala.com/api/v1` | API base URL (or `PHALA_CLOUD_API_PREFIX` env var) | | `WithAPIVersion(v)` | `"2026-06-23"` | API version header value | | `WithTimeout(d)` | no timeout | HTTP client timeout as `time.Duration` | | `WithMaxRetries(n)` | `30` | Maximum retries for retryable errors (409/429/503) | | `WithHTTPClient(hc)` | `&http.Client{}` | Custom `*http.Client` for full control | | `WithUserAgent(ua)` | `DefaultUserAgent()` | Replace the User-Agent header | | `WithHeader(key, val)` | — | Add a custom header to all requests | ### User-Agent By default the client sends `User-Agent: phala-cloud-sdk-go/ go/`, for example `phala-cloud-sdk-go/0.5.0 go/1.24.2`. `phala.DefaultUserAgent()` returns this string. `WithUserAgent` replaces it entirely, so a value you supply overrides the default. To keep the SDK token and add your own, prepend to the default: ```go theme={"system"} client, err := phala.NewClient( phala.WithAPIKey("phak_your_api_key"), phala.WithUserAgent("my-automation/2.0 "+phala.DefaultUserAgent()), ) ``` ## Environment Variables | Variable | Description | | - | - | | `PHALA_CLOUD_API_KEY` | API key for authentication | | `PHALA_CLOUD_API_PREFIX` | Override base URL | The client resolves environment variables automatically. If you pass an explicit option, it takes priority over the corresponding environment variable. ## Pointer Helpers Many request structs use pointer fields for optional values. The SDK provides helper functions to make this ergonomic: ```go theme={"system"} phala.String("value") // *string phala.Int(4) // *int phala.Int64(100) // *int64 phala.Float64(3.14) // *float64 phala.Bool(true) // *bool ``` These are especially useful when constructing request structs inline: ```go theme={"system"} &phala.PatchCVMRequest{ PublicSysinfo: phala.Bool(true), VCPU: phala.Int(4), Memory: phala.Int(8192), } ``` ## CVM ID Resolution The SDK automatically normalizes CVM identifiers before sending them to the API. You can pass any of the following formats to any method that accepts a `cvmID` string: * **UUID** (with or without dashes) — dashes are stripped * **40-char hex app ID** — `app_` prefix is added * **Integer ID, hashed ID, or name** — used as-is This means you never need to worry about converting between ID formats yourself. ## Available Methods ### Authentication & User | Method | Description | | - | - | | `GetCurrentUser(ctx)` | Get current user, workspace, and credits | ### CVM Lifecycle | Method | Description | | - | - | | `ProvisionCVM(ctx, req)` | Provision a new CVM | | `CommitCVMProvision(ctx, req)` | Commit a provisioned CVM | | `StartCVM(ctx, id)` | Start a stopped CVM | | `StopCVM(ctx, id)` | Force-stop a CVM | | `ShutdownCVM(ctx, id)` | Gracefully shut down a CVM | | `RestartCVM(ctx, id, opts)` | Restart a CVM | | `DeleteCVM(ctx, id)` | Permanently delete a CVM | | `ReplicateCVM(ctx, id, opts)` | Replicate a CVM to another node | ### CVM Configuration | Method | Description | | - | - | | `UpdateDockerCompose(ctx, id, yaml, opts)` | Update Docker Compose config | | `UpdatePreLaunchScript(ctx, id, script, opts)` | Update pre-launch script | | `UpdateCVMResources(ctx, id, req)` | Update resource allocation | | `UpdateCVMVisibility(ctx, id, req)` | Update visibility settings | | `UpdateCVMEnvs(ctx, id, req)` | Update encrypted env vars | | `UpdateOSImage(ctx, id, req)` | Update OS image | | `PatchCVM(ctx, id, req)` | Multi-field update | | `ConfirmCVMPatch(ctx, id, req)` | Confirm patch with on-chain hash | | `UpdateCVMListed(ctx, id, listed)` | Update marketplace visibility in place | ### CVM Query | Method | Description | | - | - | | `GetCVMList(ctx, opts)` | List CVMs (paginated) | | `GetCVMInfo(ctx, id)` | Get CVM details | | `GetCVMState(ctx, id)` | Get CVM current state | | `GetCVMStats(ctx, id)` | Get CVM system stats | | `GetCVMNetwork(ctx, id)` | Get CVM network info | | `GetCVMContainersStats(ctx, id)` | Get container stats | | `GetCVMAttestation(ctx, id)` | Get TEE attestation | | `GetCVMUserConfig(ctx, id)` | Get user configuration | | `WatchCVMState(ctx, id, opts)` | Watch state changes via SSE | | `FetchCVMLogs(ctx, id, source, opts)` | Fetch a log snapshot as text | | `FetchCVMLogEntries(ctx, id, source, opts)` | Fetch container logs as entries | | `FollowCVMLogs(ctx, id, source, opts)` | Stream logs until the context ends | | `GetCVMStatusBatch(ctx, ids)` | Get typed status and resource usage for multiple CVMs | ### Apps | Method | Description | | - | - | | `GetAppList(ctx)` | List applications | | `GetAppInfo(ctx, appID)` | Get app details | | `GetAppCVMs(ctx, appID)` | List CVMs for an app | | `CreateAppInstance(ctx, appID, req)` | Create another instance for an app | | `GetAppRevisions(ctx, appID, opts)` | List revision history | | `RedeployAppRevision(ctx, appID, revisionID, req)` | Redeploy an app revision | | `GetAppAttestation(ctx, appID)` | Get app attestation | | `GetAppDeviceAllowlist(ctx, appID)` | Get device allowlist | ### Workspaces | Method | Description | | - | - | | `ListWorkspaces(ctx)` | List workspaces | | `GetWorkspace(ctx, slug)` | Get workspace details | | `GetWorkspaceNodes(ctx, slug, opts)` | List workspace nodes | | `GetWorkspaceQuotas(ctx, slug)` | Get workspace quotas | ### Nodes, Instance Types, and OS Images | Method | Description | | - | - | | `GetAvailableNodes(ctx)` | List available TEE nodes | | `GetCVMCreateResources(ctx)` | Get the CVM creation resource graph | | `ListAllInstanceTypeFamilies(ctx)` | List all instance type families | | `ListFamilyInstanceTypes(ctx, family)` | List instance types in a family | | `GetOSImages(ctx)` | List public OS images | ### KMS | Method | Description | | - | - | | `ListKMSContracts(ctx)` | List KMS contracts | | `GetKMSContract(ctx, slug)` | Get a KMS contract by slug or contract ID | | `ListKMSContractNodes(ctx, slug)` | List node replicas under a KMS contract | | `GetKMSList(ctx)` | List legacy node-centric KMS servers (deprecated) | | `GetKMSInfo(ctx, kmsID)` | Get legacy node-centric KMS details | | `GetAppEnvEncryptPubKey(ctx, kmsType, appID)` | Get env encryption public key | | `GetKMSOnChainDetail(ctx, chain)` | Get KMS on-chain detail | ### SSH Keys | Method | Description | | - | - | | `ListSSHKeys(ctx)` | List SSH keys | | `CreateSSHKey(ctx, req)` | Create an SSH key | | `DeleteSSHKey(ctx, keyID)` | Delete an SSH key | | `ImportGithubProfileSSHKeys(ctx, username)` | Import keys from GitHub profile | | `SyncGithubSSHKeys(ctx)` | Sync keys from GitHub | ### Measurement Utilities | Function | Description | | - | - | | `GetMrConfigId(input)` | Compute V2 `mr_config_id` from fixed-size byte inputs | | `GetMrConfigIdHex(...)` | Compute V2 `mr_config_id` from hex inputs | | `GetMrConfigIdV1(composeHash)` | Compute the V1 compose-hash-only format | | `VerifyMrConfigId(...)` | Verify a V2 `mr_config_id` | See [KMS](/phala-cloud/references/cloud-go-sdk/kms) for examples. ### Webhook Verification | Function | Description | | - | - | | `VerifyWebhookSignature(secret, timestamp, body, signature)` | Verify HMAC-SHA256 webhook signature | | `ParseWebhookEvent(headers, body, secret, tolerance...)` | Verify signature and parse webhook event | ```go theme={"system"} event, err := phala.ParseWebhookEvent(r.Header, body, secret) if err != nil { http.Error(w, "Invalid signature", http.StatusUnauthorized) return } fmt.Println(event.Event, string(event.Data)) ``` See [Webhooks](/phala-cloud/references/webhooks) for full payload format and delivery behavior. ## CVM Logs Available in Go SDK v0.5.0 and later. The behavior described here is complete in v0.5.4, so use v0.5.4 or later. `FetchCVMLogs` and `FollowCVMLogs` read serial, node, and container logs as text. `FetchCVMLogEntries` and `FollowCVMLogEntries` read container logs as entries with a channel and a message. ```go theme={"system"} // Last 100 lines of the serial console text, err := client.FetchCVMLogs(ctx, "my-app", phala.LogSource{Type: "node", Channel: phala.CVMLogSerial}, &phala.LogsOptions{Tail: 100}, ) // Follow the "api" container until ctx is cancelled ctx, cancel := context.WithCancel(context.Background()) defer cancel() lines, errs := client.FollowCVMLogs(ctx, "my-app", phala.LogSource{Type: "container", Name: "api"}, &phala.LogsOptions{Tail: 50}, ) for line := range lines { fmt.Print(line) } if err := <-errs; err != nil { var apiErr *phala.APIError if errors.As(err, &apiErr) { fmt.Println(apiErr.ErrorCode, apiErr.Suggestions) } } // Fetch the last 100 container records as entries entries, err := client.FetchCVMLogEntries(ctx, "my-app", phala.LogSource{Type: "container", Name: "api"}, &phala.LogsOptions{Tail: 100}, ) if err != nil { log.Fatal(err) } for _, entry := range entries { fmt.Printf("[%s] %s", entry.Channel, entry.Message) } // Follow the container as entries records, errs := client.FollowCVMLogEntries(ctx, "my-app", phala.LogSource{Type: "container", Name: "api"}, &phala.LogsOptions{Tail: 50}, ) for entry := range records { fmt.Printf("[%s] %s", entry.Channel, entry.Message) } if err := <-errs; err != nil { log.Fatal(err) } ``` ```go theme={"system"} func (c *Client) FetchCVMLogs(ctx context.Context, cvmID string, source LogSource, opts *LogsOptions) (string, error) func (c *Client) FetchCVMLogEntries(ctx context.Context, cvmID string, source LogSource, opts *LogsOptions) ([]LogEntry, error) func (c *Client) FollowCVMLogs(ctx context.Context, cvmID string, source LogSource, opts *LogsOptions) (<-chan string, <-chan error) func (c *Client) FollowCVMLogEntries(ctx context.Context, cvmID string, source LogSource, opts *LogsOptions) (<-chan LogEntry, <-chan error) ``` `opts` may be `nil`. | Method | Result | | - | - | | `FetchCVMLogs` | A `string`. For a container source, the SDK joins the entries into text. | | `FetchCVMLogEntries` | `[]LogEntry`. Container sources only; a node source returns an error. | | `FollowCVMLogs` | A channel of log text and a channel of errors. Cancel with the `ctx` you pass in. | | `FollowCVMLogEntries` | A channel of `LogEntry` and a channel of errors. Container sources only; a node source sends an error. Cancel with the `ctx` you pass in. | `FollowCVMLogs` and `FollowCVMLogEntries` close both channels when the follow ends. A cancelled context ends the follow without sending an error. Cancelling `ctx` also interrupts waits between reconnects. `FetchCVMLogs` and `FetchCVMLogEntries` stop when `ctx` is cancelled, including during their lookups. Any other failure is sent once on the error channel. Read the log channel until it closes, then read the error channel. **`LogSource`:** | Field | Type | Description | | - | - | - | | `Type` | `string` | `"node"` or `"container"`. Set it explicitly: any value other than `"container"` is treated as a node source. | | `Channel` | `CVMLogChannel` | Node channel: `CVMLogSerial`, `CVMLogStdout`, or `CVMLogStderr` | | `Name` | `string` | Container name or unique container ID prefix. If empty, the SDK uses the first container in the CVM composition. See [Container names](#container-names). | **`LogsOptions`:** | Field | Type | Description | | - | - | - | | `Tail` | `any` | Number of most recent lines as an `int`, or the string `"all"`. When `nil`, the server default applies. | | `Since` | `any` | Start time as Unix seconds (`int`, `int64`, or a numeric string), an RFC 3339 string, or a relative duration such as `"10m"` (`s`, `m`, `h`, `d`). Container logs only. A node source with `Since` returns an error. | | `Until` | `any` | End time. Same formats as `Since`. Container logs only. A node source with `Until` returns an error. | | `Timestamps` | `bool` | Keep the timestamp prefix on container lines. Container logs only. A node source with `Timestamps` returns an error. | | `ANSI` | `bool` | Keep ANSI escape sequences in the output. The default removes them from every line and entry, including NDJSON messages. This is an output option, so it never causes an error. | | `Format` | `string` | `"text"` or `"ndjson"`. `FetchCVMLogEntries` reads it (default `"ndjson"`; other values return an error). A node source with `"ndjson"` returns an error. `FetchCVMLogs` and `FollowCVMLogs` return text. For containers, they read NDJSON and join the messages unless `Format` is `"text"`, which uses the plain-text transport. `FollowCVMLogEntries` also reads `Format`: other values than `"ndjson"` return an error. | `LogEntry` has two fields: `Channel` (`"stdout"`, `"stderr"`, `"console"`, or `"stdin"`) and `Message`. `console` appears for containers started with a TTY. `Message` is exactly what the container wrote, usually ending in a newline. An empty message stays an empty string. **Container names:** The SDK resolves the container name once at the start of a follow, with one composition call. It tries these steps in order: 1. An exact match on a container name. 2. A unique match on the start of a container ID. 3. If `Name` is empty, the first container in the composition. If the prefix matches more than one container, the call returns an `*APIError` with `ErrorCode` `ERR-17-001` and the message `Ambiguous container prefix '': web, worker`, which lists the candidates. If nothing matches, it returns `ERR-17-007`. If the composition has no containers and returns an `error` string, for example because the CVM is stopped, the call returns an `*APIError` with that message. A name must be 1 to 128 characters, start with a letter or digit, and then use only letters, digits, `_`, `.`, and `-`. It must not contain `..`. Other names, such as `/app`, are rejected with `ERR-17-001` before any request is sent. **Behavior:** * Every connection uses a fresh signed URL, with one CVM info lookup per connection. * Follow reconnects after a stream ends or fails. Failures back off from 250 ms, doubling up to 5 s, and follow gives up after 5 consecutive failures. Starts of two connections are at least 1 s apart. * HTTP errors are handled by status. `5xx` and `429` are failures. `401` with `ERR-17-003` fetches a new URL and retries, up to 3 times in a row. The count resets after a connection that delivered records or ended cleanly. `401` with `ERR-17-002` fetches a new URL and counts as a failure. Any other `4xx` stops follow. * A gateway error line inside a `200` stream, or a network error, counts as a failure. A connection that delivered at least one record resets the failure count before its own failure is counted. * Container follow always requests timestamps internally, in both the NDJSON and the text transport. It sends the caller's `Tail` until the first connection is accepted. Every later request sends `tail=all` plus `since`, and skips lines it already delivered at the boundary second, so a reconnect does not repeat output. Before any timestamped record arrives, it uses your `Since` if you set one, otherwise the second the first connection was accepted. Timestamps are removed from the output unless you set `Timestamps`. * Container follow: if a stream ends cleanly with no new output within 10 s, it backs off and counts the end. After 5 such ends in a row, follow stops with `log stream keeps ending without new output; the container may have stopped`. A clean end after records, or after an idle connection of 10 s or more, reconnects at once and resets the count. * Node follow never stops on a clean end. After the first connection it requests `tail=0`. * If you set `Until`, follow finishes normally, without an error, when the stream reaches that time. * A missing container is not retried. * Node follow and fetch drop `[vmm heartbeat]` and `[teepod heartbeat]` lines. * A text-format record that looks like `{"error": ...}` is treated as a guest error only at the very start of the body. Use NDJSON (the default for entries) for reliable detection. * The helpers request CVM info with API version `2026-01-21` internally, so they work with clients configured for older versions. For the HTTP details behind these methods, see [Fetch Logs over HTTP](/phala-cloud/monitoring/log-api). **Errors:** Log gateway errors are returned as `*APIError`. Check `ErrorCode` for a log error code such as `ERR-17-005`, and use `errors.As` to reach it. `Message` holds the human-readable text only, without the code. `Suggestions`, `Details`, `Links`, and `RequestID` come from the API error envelope. `StatusCode` is the HTTP status and is set only for errors returned as an HTTP response. It is `0` for client-side errors (bad container name, bad time, unsupported option) and for errors read from the body of a stream, such as a guest agent error or the stalled-stream error. Those print as their message alone, without `phala api error (status N)`. Container logs require [Public Logs](/phala-cloud/monitoring/public-logs) to be enabled on the CVM. When it is off, container fetch and follow return an `*APIError` with `ErrorCode` `ERR-17-006` ("Container logs are disabled") before sending any log request. Follow checks this before its first log request and again on every reconnect, because each connection looks up the CVM info. Node channels are not affected. If the agent inside the CVM cannot read a container's logs, for example because the container uses a Docker logging driver that does not support reading, the method returns an `*APIError` with `ErrorCode` `ERR-17-009` and the agent's message. This applies to text and NDJSON, in fetch and in follow. Follow stops on it. A server-returned HTTP `502` with `ERR-17-009` is different: follow reconnects. See [Fetch Logs over HTTP](/phala-cloud/monitoring/log-api#errors) for the full error code list. ## Related * [Authentication](/phala-cloud/references/cloud-go-sdk/authentication) — API key setup and custom headers * [CVM Lifecycle](/phala-cloud/references/cloud-go-sdk/cvm-lifecycle) — provisioning, starting, stopping, deleting * [Error Handling](/phala-cloud/references/cloud-go-sdk/error-handling) — error types and retry logic * [Webhooks](/phala-cloud/references/webhooks) — webhook events, signatures, and delivery * [Cloud API Reference](/phala-cloud/phala-cloud-api/overview) — full REST API docs # SSH Keys Source: https://docs.phala.com/phala-cloud/references/cloud-go-sdk/ssh-keys Manage SSH keys for CVM access — list, create, delete, and import from GitHub. SSH key methods manage the public keys authorized for SSH access to your CVMs. You can add keys manually, import them from a GitHub profile, or sync them from your linked GitHub account. ## ListSSHKeys `GET /user/ssh-keys` Returns all SSH keys registered for the current user. ```go theme={"system"} func (c *Client) ListSSHKeys(ctx context.Context) ([]SSHKey, error) ``` **Returns:** `[]SSHKey` where each `SSHKey` contains: | Field | Type | Description | | - | - | - | | `ID` | `string` | Key identifier | | `Name` | `string` | Display name | | `PublicKey` | `string` | Public key content | | `Fingerprint` | `*string` | Key fingerprint | | `KeyType` | `*string` | Key type (e.g., `"ssh-ed25519"`) | | `Source` | `*string` | How the key was added (e.g., `"manual"`, `"github"`) | | `CreatedAt` | `*string` | Creation timestamp | ```go theme={"system"} keys, err := client.ListSSHKeys(ctx) if err != nil { log.Fatal(err) } for _, key := range keys { fmt.Printf("%s — %s (%s)\n", key.Name, key.ID, *key.KeyType) } ``` *** ## CreateSSHKey `POST /user/ssh-keys` Registers a new SSH public key. ```go theme={"system"} func (c *Client) CreateSSHKey(ctx context.Context, req *CreateSSHKeyRequest) (*SSHKey, error) ``` **CreateSSHKeyRequest fields:** | Field | Type | Required | Description | | - | - | - | - | | `Name` | `string` | Yes | Display name for the key | | `PublicKey` | `string` | Yes | SSH public key content | **Returns:** `*SSHKey` — the created key with its assigned ID and fingerprint. Replace the sample public key with your own key before using it for access. ```go theme={"system"} key, err := client.CreateSSHKey(ctx, &phala.CreateSSHKeyRequest{ Name: "my-laptop", PublicKey: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAID4dR/9d26lbwH5ViDEJgWZqaHI6/Mlr8QyTfE6w8ANk docs-example", }) if err != nil { log.Fatal(err) } fmt.Printf("Created key: %s (fingerprint: %s)\n", key.ID, *key.Fingerprint) ``` *** ## DeleteSSHKey `DELETE /user/ssh-keys/{keyId}` Removes an SSH key by its ID. Existing CVMs that were deployed with this key will retain access until they are restarted or updated. ```go theme={"system"} func (c *Client) DeleteSSHKey(ctx context.Context, keyID string) error ``` **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `keyID` | `string` | Yes | SSH key identifier | **Returns:** `error` (no response body on success) ```go theme={"system"} err := client.DeleteSSHKey(ctx, "key-abc123") if err != nil { log.Fatal(err) } ``` *** ## ImportGithubProfileSSHKeys `POST /user/ssh-keys/github-profile` Imports SSH public keys from any GitHub user's profile. This fetches the keys from `https://github.com/{username}.keys` and adds them to your account. ```go theme={"system"} func (c *Client) ImportGithubProfileSSHKeys(ctx context.Context, username string) (*ImportGithubResponse, error) ``` **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `username` | `string` | Yes | GitHub username | **Returns:** `*ImportGithubResponse` (generic map with import details) ```go theme={"system"} imported, err := client.ImportGithubProfileSSHKeys(ctx, "octocat") if err != nil { log.Fatal(err) } ``` > [!NOTE] > > This imports keys from any public GitHub profile. Use `SyncGithubSSHKeys` instead if you want to sync keys from your own linked GitHub account. *** ## SyncGithubSSHKeys `POST /user/ssh-keys/github-sync` Syncs SSH keys from the user's linked GitHub account. This requires that the user has connected their GitHub account to Phala Cloud. ```go theme={"system"} func (c *Client) SyncGithubSSHKeys(ctx context.Context) (*SyncGithubResponse, error) ``` **Returns:** `*SyncGithubResponse` (generic map with sync details) ```go theme={"system"} synced, err := client.SyncGithubSSHKeys(ctx) if err != nil { log.Fatal(err) } ``` ## CVM SSH keys `GetCVMSSHKeys(ctx, cvmID)` reads `GET /cvms/{cvmId}/ssh-keys`. It returns the configured `Keys` and `RestartRequired`. This is the stored configuration; `GetCVMUserConfig` reads the running VM's configuration. `UpdateCVMSSHKeys(ctx, cvmID, req)` sends `PUT /cvms/{cvmId}/ssh-keys` and returns the same response type. `SSHKeyIDs` is the replacement set: include every selected key you want to retain. An explicit empty slice removes all selected keys unless `Usernames` adds members' resolved keys. Changes take effect at the next power-on, or immediately if `ApplyNow` restarts the CVM. This example uses the key created above. Add any other key IDs you want to retain. ```go theme={"system"} result, err := client.UpdateCVMSSHKeys(ctx, "my-app", &phala.UpdateCVMSSHKeysRequest{ SSHKeyIDs: []string{key.ID}, ApplyNow: false, }) if err != nil { log.Fatal(err) } fmt.Println(result.RestartRequired) ``` # Watch CVM State Source: https://docs.phala.com/phala-cloud/references/cloud-go-sdk/watch-cvm-state Monitor CVM state changes in real-time using Server-Sent Events (SSE) with Go channels. The `WatchCVMState` method streams CVM state changes in real-time using Server-Sent Events (SSE). It returns a Go channel that emits events as the CVM transitions between states, making it natural to use with `for range` loops. ## WatchCVMState `GET /cvms/{cvmId}/state` (SSE stream) Opens an SSE connection and delivers events through a channel. A valid `complete` event ends the watch. The channel also closes on a terminal error or context cancellation. ```go theme={"system"} func (c *Client) WatchCVMState(ctx context.Context, cvmID string, opts *WatchCVMStateOptions) (<-chan CVMStateEvent, error) ``` **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `cvmID` | `string` | Yes | CVM identifier | | `opts` | `*WatchCVMStateOptions` | Yes | Stream options, including the required target | **WatchCVMStateOptions fields:** | Field | Type | Default | Description | | - | - | - | - | | `Target` | `string` | None | Required target state (e.g., `"running"`, `"stopped"`) | | `Interval` | `int` | `5` | Polling interval in seconds (5-30) | | `Timeout` | `int` | `300` | Server-side per-attempt timeout in seconds (10-600) | | `MaxRetries` | `*int` | `nil` (unlimited) | Max reconnection attempts; `nil` = unlimited, `0` = no retries | | `RetryDelay` | `time.Duration` | `5s` | Delay between reconnection attempts | **Returns:** `<-chan CVMStateEvent` — a receive-only channel of state events. ## CVMStateEvent Each event received from the channel has this structure: ```go theme={"system"} type CVMStateEvent struct { Event string // Event type: "state", "complete", "error", "timeout" Data map[string]any // Event payload (parsed from JSON) Error error // Non-nil if this is an error event } ``` The `Event` field indicates what happened: | Event | Meaning | | - | - | | `"state"` | A state update; `Data` contains the raw state | | `"complete"` | Completion event with a nonempty status; the stream closes | | `"error"` | An SSE or terminal request error; inspect `Error` | | `"timeout"` | Server-side attempt timed out; the watcher may reconnect | ## Basic Usage The simplest pattern is ranging over the channel until it closes: ```go theme={"system"} ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) defer cancel() ch, err := client.WatchCVMState(ctx, "my-app", &phala.WatchCVMStateOptions{ Target: "running", Interval: 5, Timeout: 300, }) if err != nil { log.Fatal(err) } for event := range ch { if event.Error != nil { log.Printf("Error: %v", event.Error) continue } fmt.Printf("[%s] %v\n", event.Event, event.Data) } fmt.Println("Stream ended") ``` ## Cancellation with Context Use context cancellation as the Go equivalent of JavaScript's `AbortController`. Cancelling the context closes the SSE connection and the channel. ```go theme={"system"} ctx, cancel := context.WithCancel(context.Background()) ch, err := client.WatchCVMState(ctx, "my-app", &phala.WatchCVMStateOptions{ Target: "running", }) if err != nil { log.Fatal(err) } // Cancel from another goroutine after some condition go func() { time.Sleep(30 * time.Second) cancel() // Stops the SSE stream }() for event := range ch { fmt.Printf("State: %s\n", event.Event) } ``` > [!NOTE] > > Always use a context with a timeout or deadline to avoid watching indefinitely. The server-side `Timeout` option is a safety net, but client-side context timeouts give you more control. ## Retry Behavior By default, the watcher reconnects indefinitely after a timeout or a stream ending before completion. Configure retries to limit this behavior. An SSE `error` event can be followed by more events; it does not itself close the stream. ```go theme={"system"} // Retry up to 3 times ch, err := client.WatchCVMState(ctx, "my-app", &phala.WatchCVMStateOptions{ Target: "running", MaxRetries: phala.Int(3), RetryDelay: 5 * time.Second, }) ``` ```go theme={"system"} // No retries — fail immediately on disconnect ch, err := client.WatchCVMState(ctx, "my-app", &phala.WatchCVMStateOptions{ Target: "running", MaxRetries: phala.Int(0), }) ``` When retries are exhausted, the channel receives a final `CVMStateEvent` with `Event: "error"` and the underlying error in `Error`. An incomplete EOF produces a `*WatchStreamError` that unwraps to `io.ErrUnexpectedEOF`. A permanent HTTP failure produces a terminal `*APIError` without retrying. The default watch client does not apply the ordinary 60-second total HTTP timeout. Explicit `WithTimeout` or `WithHTTPClient` settings still apply. Use a context deadline to limit total waiting time. ## Wait for Deployment A common pattern is to provision a CVM and then watch it until it reaches the `"running"` state: ```go theme={"system"} // Provision and commit... cvm, err := client.CommitCVMProvision(ctx, &phala.CommitCVMProvisionRequest{ AppID: provision.AppID, ComposeHash: provision.ComposeHash, }) if err != nil { log.Fatal(err) } // Watch until running watchCtx, cancel := context.WithTimeout(ctx, 10*time.Minute) defer cancel() ch, err := client.WatchCVMState(watchCtx, cvm.CvmID(), &phala.WatchCVMStateOptions{ Target: "running", Interval: 5, Timeout: 600, MaxRetries: phala.Int(5), }) if err != nil { log.Fatal(err) } for event := range ch { switch event.Event { case "complete": fmt.Println("CVM is running!") case "error": log.Printf("Watch error: %v", event.Error) case "timeout": log.Println("Watch attempt timed out; retry may follow") default: fmt.Printf("State update: %v\n", event.Data) } } ``` > [!WARNING] > > The `Timeout` option controls the server-side SSE stream timeout, not the overall watch duration. For long-running watches, set a generous server timeout and use the Go context for client-side control. # Workspaces Source: https://docs.phala.com/phala-cloud/references/cloud-go-sdk/workspaces List workspaces, get workspace details, nodes, and quotas. Workspace methods let you query your team workspaces and their associated resources. A workspace is a shared environment where team members collaborate on CVM deployments. Each workspace has its own nodes, quotas, and billing. ## ListWorkspaces `GET /workspaces` Returns all workspaces accessible to the authenticated user. ```go theme={"system"} func (c *Client) ListWorkspaces(ctx context.Context) (*ListWorkspacesResponse, error) ``` **Returns:** `*ListWorkspacesResponse` (generic map containing workspace data) ```go theme={"system"} workspaces, err := client.ListWorkspaces(ctx) if err != nil { log.Fatal(err) } ``` *** ## GetWorkspace `GET /workspaces/{slug}` Returns detailed information about a specific workspace, identified by its slug. ```go theme={"system"} func (c *Client) GetWorkspace(ctx context.Context, slug string) (*Workspace, error) ``` **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `slug` | `string` | Yes | Workspace slug (e.g., `"my-team"`) | **Returns:** `*Workspace` containing: | Field | Type | Description | | - | - | - | | `ID` | `string` | Workspace ID | | `Name` | `string` | Display name | | `Slug` | `*string` | URL-friendly slug | | `Tier` | `string` | Subscription tier | | `Avatar` | `*string` | Avatar URL | ```go theme={"system"} ws, err := client.GetWorkspace(ctx, "my-team") if err != nil { log.Fatal(err) } fmt.Printf("Workspace: %s (tier: %s)\n", ws.Name, ws.Tier) ``` *** ## GetWorkspaceNodes `GET /workspaces/{slug}/nodes` Returns TEE nodes available to a workspace, with optional pagination. ```go theme={"system"} func (c *Client) GetWorkspaceNodes(ctx context.Context, slug string, opts *PaginationOptions) (*WorkspaceNodes, error) ``` **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `slug` | `string` | Yes | Workspace slug | | `opts` | `*PaginationOptions` | No | Pagination (pass `nil` for defaults) | **Returns:** `*WorkspaceNodes` (generic map) ```go theme={"system"} nodes, err := client.GetWorkspaceNodes(ctx, "my-team", &phala.PaginationOptions{ Page: phala.Int(1), PageSize: phala.Int(20), }) if err != nil { log.Fatal(err) } ``` *** ## GetWorkspaceQuotas `GET /workspaces/{slug}/quotas` Returns resource quotas and current usage for a workspace. Use this to check how much capacity is available before provisioning new CVMs. ```go theme={"system"} func (c *Client) GetWorkspaceQuotas(ctx context.Context, slug string) (*WorkspaceQuotas, error) ``` **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `slug` | `string` | Yes | Workspace slug | **Returns:** `*WorkspaceQuotas` (generic map) ```go theme={"system"} quotas, err := client.GetWorkspaceQuotas(ctx, "my-team") if err != nil { log.Fatal(err) } ``` # addComposeHash Source: https://docs.phala.com/phala-cloud/references/cloud-js-sdk/add-compose-hash Register a compose hash on-chain for CVM updates with on-chain KMS ## addComposeHash Registers a new compose hash on the AppAuth smart contract. This is required when updating a CVM that uses on-chain KMS (ETHEREUM/BASE) — the updated compose hash must be registered on-chain before the Phala Cloud API will accept the update. This function interacts directly with the blockchain (not the Phala Cloud API). **When to use.** Call this function in either of these cases: * [`updateDockerCompose`](/phala-cloud/references/cloud-js-sdk/update-docker-compose), [`updateCvmEnvs`](/phala-cloud/references/cloud-js-sdk/update-cvm-envs), or [`updatePreLaunchScript`](/phala-cloud/references/cloud-js-sdk/cvm-configuration) returns `{ status: "precondition_required" }`. * [`provisionCvmComposeFileUpdate`](/phala-cloud/references/cloud-js-sdk/cvm-configuration#provisioncvmcomposefileupdate) returns `compose_hash_registered: false`, and you need to register the hash before calling `commitCvmComposeFileUpdate`. > [!NOTE] > > **Contract owner pre-check.** Before submitting the transaction, the function reads `owner()` from the AppAuth contract and throws if the sender address does not match. This fails fast so you don't waste gas on a transaction that would revert on-chain. Sign with the contract owner's private key, or pass a wallet client whose account is the contract owner. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `chain` | `Chain` | Conditional | Viem chain config (required if no `walletClient`) | | `kmsContractAddress` | `Address` | Yes | KMS contract address (for lookup) | | `appId` | `Address` | Yes | App identifier (AppAuth contract address) | | `composeHash` | `string` | Yes | Compose hash to register | | `privateKey` | `Hex` | Conditional | Caller private key (provide this or `walletClient`) | | `walletClient` | `WalletClient` | Conditional | Custom wallet client (provide this or `privateKey`) | | `rpcUrl` | `string` | No | Custom RPC URL | | `publicClient` | `PublicClient` | No | Custom public client | | `skipPrerequisiteChecks` | `boolean` | No | Skip balance checks (default: `false`) | | `minBalance` | `string` | No | Minimum ETH balance (default: `"0.001"`) | | `timeout` | `number` | No | Transaction timeout in ms | | `retryOptions` | `object` | No | Retry configuration | **Callbacks:** | Callback | Description | | - | - | | `onTransactionStateChange` | Called when transaction state changes | | `onTransactionSubmitted` | Called when transaction is submitted | | `onTransactionConfirmed` | Called when transaction is confirmed | **Returns:** `AddComposeHash` | Field | Type | Description | | - | - | - | | `composeHash` | `string` | The registered compose hash | | `appId` | `string` | App identifier | | `appAuthAddress` | `string` | AppAuth contract address | | `transactionHash` | `string` | On-chain transaction hash | | `blockNumber` | `bigint?` | Block number | | `gasUsed` | `bigint?` | Gas consumed | **Example:** ```typescript theme={"system"} import { addComposeHash } from "@phala/cloud"; // After updateDockerCompose returns precondition_required: const receipt = await addComposeHash({ chain: cvmInfo.kms_info.chain, kmsContractAddress: cvmInfo.kms_info.kms_contract_address, appId: cvmInfo.app_id as `0x${string}`, composeHash: preconditionResult.compose_hash, privateKey: "0xabc123...", }); // Now retry the update with the transaction hash await client.updateDockerCompose({ id: "my-app", docker_compose_file: newYaml, compose_hash: preconditionResult.compose_hash, transaction_hash: receipt.transactionHash, }); ``` *** ## safeAddComposeHash Safe variant that returns a `SafeResult` instead of throwing on errors. # API Versioning Source: https://docs.phala.com/phala-cloud/references/cloud-js-sdk/api-versioning Supported Phala Cloud API versions, the current default, and version-specific TypeScript response types. `@phala/cloud` v0.4.0 uses API version `2026-06-23` by default. The SDK sends the selected version in the `X-Phala-Version` header and returns matching TypeScript types. ## Supported versions | Version | Status | Response behavior | | - | - | - | | `2026-06-23` | **Default** | Uses the latest CVM and app schemas and enables the contract-centric KMS API | | `2026-05-22` | Supported | Uses hashed CVM IDs and the current CVM and app schemas | | `2026-01-21` | Supported | Uses the earlier workspace-aware CVM and app schemas | | `2025-10-28` | Legacy | Uses the legacy flat response schemas | ## Select a version Omit `version` to use `2026-06-23`: ```typescript theme={"system"} import { createClient } from "@phala/cloud"; const client = createClient({ apiKey: "phak_your_api_key" }); ``` Set `version` when you need an older response shape: ```typescript theme={"system"} const client = createClient({ apiKey: "phak_your_api_key", version: "2026-05-22", }); ``` Use `.withVersion()` to create another client with the same authentication and a different API version. The new client retains built-in actions and custom extensions, bound to the new version: ```typescript theme={"system"} const currentClient = createClient({ apiKey: "phak_your_api_key" }); const legacyClient = currentClient.withVersion("2025-10-28"); ``` For custom extensions, the factory's client is typed with the `ApiVersion` union. After `withVersion()`, custom methods remain callable with their original parameters, but their return types are `unknown`. Check or narrow those values before using them. This avoids assuming the old version's response shape applies to the new version. ## Version-aware return types The client version controls the return type for versioned actions such as `getCvmList`, `getCvmInfo`, `getAppList`, and lifecycle operations. ```typescript theme={"system"} const currentClient = createClient({ apiKey: "phak_your_api_key", version: "2026-06-23", }); const currentCvm = await currentClient.getCvmInfo({ id: "my-cvm" }); // CvmInfoDetailV20260522 const olderClient = currentClient.withVersion("2026-01-21"); const olderCvm = await olderClient.getCvmInfo({ id: "my-cvm" }); // CvmInfoDetailV20260121 ``` Versions `2026-05-22` and `2026-06-23` share the same CVM and app response types. Version `2026-06-23` changes the KMS resource model from individual KMS nodes to KMS contracts. The client's `version` overrides any `X-Phala-Version` value in `config.headers`, regardless of header casing. An action can still explicitly pin its own request to a different version, as the KMS methods below do. ## Contract-centric KMS methods The following methods always request API version `2026-06-23`, even when the client uses an older version: * `listKmsContracts()` * `getKmsContract({ slug })` * `listKmsContractNodes({ slug })` The deprecated `getKmsList()` and `getKmsInfo()` methods remain pinned to `2026-05-22` so existing code continues to receive the legacy node-centric response shape. ## Standalone actions Version-aware typing also works with a base client and standalone actions: ```typescript theme={"system"} import { createBaseClient, getCvmInfo } from "@phala/cloud"; const client = createBaseClient({ apiKey: "phak_your_api_key", version: "2026-06-23", }); const cvm = await getCvmInfo(client, { id: "my-cvm" }); ``` ## Related * [SDK Overview](/phala-cloud/references/cloud-js-sdk/overview) * [Schema Reference](/phala-cloud/references/cloud-js-sdk/schema-reference) * [KMS](/phala-cloud/references/cloud-js-sdk/kms) # Apps Source: https://docs.phala.com/phala-cloud/references/cloud-js-sdk/apps Functions for querying app information, CVMs, and revision history ## getAppList `GET /apps` Returns a paginated, filterable list of apps. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `page` | `number` | No | Page number | | `page_size` | `number` | No | Items per page (max 100) | | `search` | `string` | No | Search by name | | `status` | `string[]` | No | Filter by status | | `listed` | `boolean` | No | Filter by public listing | | `base_image` | `string` | No | Filter by OS image | | `instance_type` | `string` | No | Filter by instance type | | `kms_slug` | `string` | No | Filter by KMS slug | | `kms_type` | `string` | No | Filter by KMS type | | `node` | `string` | No | Filter by node | | `region` | `string` | No | Filter by region | **Returns:** Paginated list of apps (version-aware schema). **Example:** ```typescript theme={"system"} const apps = await client.getAppList({ page: 1, page_size: 20, status: ["running"], }); ``` *** ## getAppInfo `GET /apps/{app_id}` Returns detailed information about a specific app. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `app_id` | `string` | Yes | App identifier | **Returns:** `AppInfo` — version-aware app details. *** ## getAppCvms `GET /apps/{app_id}/cvms` Returns the list of CVMs associated with an app. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `app_id` | `string` | Yes | App identifier | **Returns:** Array of CVM objects. *** ## getAppRevisions `GET /apps/{app_id}/revisions` Returns the revision history for an app. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `app_id` | `string` | Yes | App identifier | **Returns:** Array of app revisions. *** ## getAppRevisionDetail `GET /apps/{app_id}/revisions/{revision_id}` Returns details about a specific app revision. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `app_id` | `string` | Yes | App identifier | | `revision_id` | `string` | Yes | Revision identifier | **Returns:** `AppRevisionDetail` — revision details including compose file and configuration. *** ## getAppFilterOptions `GET /apps/filter-options` Returns the available filter values for app list queries. **Parameters:** None **Returns:** `AppFilterOptions` — available values for status, base\_image, instance\_type, kms\_slug, etc. **Example:** ```typescript theme={"system"} const filters = await client.getAppFilterOptions(); console.log("Available statuses:", filters.statuses); console.log("Available regions:", filters.regions); ``` *** ## getAppAttestation `GET /apps/{appId}/attestations` Returns TEE attestation details for all CVM instances under an app. This includes per-instance certificates, TCB measurements, and KMS metadata, giving you a single view of the app's attestation posture. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `appId` | `string` | Yes | App identifier (hex) | **Returns:** `AppAttestationResponse` | Field | Type | Description | | - | - | - | | `app_id` | `string` | App identifier | | `contract_address` | `string` | App contract address | | `kms_info` | `object` | KMS details (contract address, chain, URL) | | `instances` | `array` | Per-instance attestation (vm\_uuid, tcb\_info, app\_certificates, compose\_file) | | `kms_guest_agent_info` | `object?` | KMS guest agent info | | `gateway_guest_agent_info` | `object?` | Gateway guest agent info | | `qemu_version` | `string?` | QEMU version | **Example:** ```typescript theme={"system"} const att = await client.getAppAttestation({ appId: "0xff22c67f5d3b4c8a9e1f0a2b3c4d5e6f7a8b9c0d" }); att.instances.forEach(inst => { console.log(inst.name, inst.status, inst.tcb_info?.app_compose); }); ``` *** ## getAppDeviceAllowlist `GET /apps/{appId}/device-allowlist` Returns the device allowlist status for all CVMs under an app. For on-chain KMS apps, this queries the blockchain in real-time to check which devices are registered in the app contract. For offchain KMS apps, returns basic info with `is_onchain_kms: false`. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `appId` | `string` | Yes | App identifier (hex) | **Returns:** `DeviceAllowlistResponse` | Field | Type | Description | | - | - | - | | `is_onchain_kms` | `boolean` | Whether the app uses on-chain KMS | | `allow_any_device` | `boolean?` | On-chain `allowAnyDevice` flag | | `chain_id` | `number?` | Blockchain chain ID | | `app_contract_address` | `string?` | App contract address | | `devices` | `array` | Device entries with `device_id`, `node_name`, `cvm_ids`, `allowed_onchain`, `status` | **Example:** ```typescript theme={"system"} const allowlist = await client.getAppDeviceAllowlist({ appId: "0xff22c67f5d3b4c8a9e1f0a2b3c4d5e6f7a8b9c0d" }); if (allowlist.is_onchain_kms) { allowlist.devices.forEach(d => { console.log(d.device_id, d.status, d.allowed_onchain); }); } ``` *** ## checkAppIsAllowed `POST /apps/{appId}/is-allowed` Checks whether a deployment is allowed by an on-chain dstack App contract. This queries the blockchain to verify that the compose hash and device are registered. You can use this for pre-flight checks before deploying or updating a CVM. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `appId` | `string` | Yes | App contract address | | `compose_hash` | `string` | Yes | Compose hash to check | | `node` | `string` | No | Physical node name used to resolve the device ID | | `device_id` | `string` | No | Device ID (hex, direct) | | `chain_id` | `number` | No | Chain ID for RPC URL resolution | **Returns:** `IsAllowedResult` | Field | Type | Description | | - | - | - | | `app_contract_address` | `string` | Contract address | | `compose_hash` | `string` | Checked compose hash | | `device_id` | `string` | Device ID checked | | `compose_hash_allowed` | `boolean` | Whether compose hash is registered | | `allow_any_device` | `boolean` | Whether any device is allowed | | `device_id_allowed` | `boolean?` | Whether specific device is registered | | `is_allowed` | `boolean` | Overall allowance result | | `error` | `string?` | Error message if check failed | **Example:** Replace the sample identifiers with values from your app, compose, and device. ```typescript theme={"system"} const result = await client.checkAppIsAllowed({ appId: "0xff22c67f5d3b4c8a9e1f0a2b3c4d5e6f7a8b9c0d", compose_hash: "0xff22c67f1c8d5e4a9b3d2c1e0f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f90", device_id: "0x7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4e5f6a7b80", }); console.log(`Allowed: ${result.is_allowed}`); ``` *** ## checkAppCvmsIsAllowed `POST /apps/{appId}/cvms/is-allowed` Batch-checks on-chain deployment allowance for all CVMs under an app. For on-chain KMS apps, this queries the blockchain via multicall to check compose hash and device allowance for each CVM in a single operation. For offchain KMS apps, returns `is_onchain: false` with no results. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `appId` | `string` | Yes | App identifier (hex) | **Returns:** `AppCvmsBatchIsAllowedResponse` | Field | Type | Description | | - | - | - | | `is_onchain` | `boolean` | Whether the app uses on-chain KMS | | `results` | `array` | Per-CVM allowance results (each with `cvm_id`, `is_allowed`, `compose_hash_allowed`, etc.) | | `total` | `number` | Total CVMs checked | | `allowed_count` | `number` | Number of allowed CVMs | | `denied_count` | `number` | Number of denied CVMs | | `error_count` | `number` | Number of errored checks | | `skipped_cvm_ids` | `number[]` | CVM IDs that were skipped | **Example:** ```typescript theme={"system"} const batch = await client.checkAppCvmsIsAllowed({ appId: "0xff22c67f5d3b4c8a9e1f0a2b3c4d5e6f7a8b9c0d" }); console.log(`${batch.allowed_count}/${batch.total} CVMs allowed`); batch.results.forEach(r => { console.log(`CVM ${r.cvm_id}: allowed=${r.is_allowed}`); }); ``` *** ## setAppLaunchToken / clearAppLaunchToken `POST /apps/{appId}/launch-token` / `DELETE /apps/{appId}/launch-token` `setAppLaunchToken` sets or rotates the app's launch token and returns it once, with its hash. Leave out `launchToken` to have Phala Cloud generate one. Then update each CVM's `requirements.launch_token_hash` to the returned hash with [`patchCvm`](/phala-cloud/references/cloud-js-sdk/cvm-configuration#patchcvm). `clearAppLaunchToken` removes the token; remove the hash from every CVM first. Phala Cloud and the node operator can read the token. See [Launch Token](/phala-cloud/cvm/launch-token). **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `appId` | `string` | Yes | App ID (hex) | | `launchToken` | `string` | No | `setAppLaunchToken` only. Token to set, at least 32 bytes. | **Returns:** `setAppLaunchToken` returns `{ launch_token, launch_token_hash }`. `clearAppLaunchToken` returns nothing. ```typescript theme={"system"} const { launch_token_hash } = await client.setAppLaunchToken({ appId: "0123...cdef" }); await client.patchCvm({ id: "my-app", compose: { requirements: { launch_token_hash } } }); ``` # Authentication Source: https://docs.phala.com/phala-cloud/references/cloud-js-sdk/authentication User authentication functions in the Cloud JS SDK ## getCurrentUser `GET /auth/me` Returns the authenticated user's profile, workspace, and the workspace's Balance. **Parameters:** None **Returns:** `CurrentUser` | Field | Type | Description | | - | - | - | | `user` | `object` | User info (username, email, avatar) | | `workspace` | `object` | Active workspace (name, slug, tier) | | `credits` | `object` | Money in the workspace: `balance` (Balance; pays for CVMs, GPU instances, and Private AI), `granted_balance` (Gifted credits; CVMs and GPU instances only, used first), `is_post_paid` (CVM usage beyond Balance is charged to the card), `outstanding_amount` (what the workspace owes) | **Example:** ```typescript theme={"system"} import { createClient } from "@phala/cloud"; const client = createClient(); const me = await client.getCurrentUser(); console.log(me.user.username, me.workspace.slug); ``` > [!NOTE] > > Response shape varies by API version. The `v2026-01-21` response uses nested objects; the legacy `v2025-10-28` response uses a flat structure. ## revokeCurrentApiToken `DELETE /tokens/self` Revokes the API token used for this request. This cannot be undone, and the token stops working immediately. ```typescript theme={"system"} import { createClient, revokeCurrentApiToken } from "@phala/cloud"; const client = createClient(); await revokeCurrentApiToken(client); ``` Use `safeRevokeCurrentApiToken` to receive a safe result instead of an exception. # Changelog Source: https://docs.phala.com/phala-cloud/references/cloud-js-sdk/changelog Release history for the @phala/cloud JavaScript SDK ## [0.4.0](https://github.com/Phala-Network/phala-cloud/compare/js-v0.3.0...js-v0.4.0) (2026-07-25) ### Breaking changes * Removed the deprecated `user_id`, `teepod_id`, and `node_id` filters from `getCvmList`. Use `family` and `instance_types` for supported list filtering. ### Features * Added contract-centric KMS methods: `listKmsContracts`, `getKmsContract`, and `listKmsContractNodes`. * Added `getMrConfigId`, `getMrConfigIdV1`, and `verifyMrConfigId` exports. * Changed the default API version to `2026-06-23`. * Added KMS verification anchors, `mr_config_id` attestation fields, workspace billing status fields, and richer CVM status resource usage. * Added `hourly_rate`, `billing_interval`, and `gpu_rental_order` to current CVM schemas. ### Fixes * Preserved structured API error details, including arrays and objects. * Corrected app attestation `chain_id` typing and KMS environment-key verification. * Moved resource updates to the unified `PATCH /cvms/{id}` flow. ## [0.3.0](https://github.com/Phala-Network/phala-cloud/compare/js-v0.2.10...js-v0.3.0) (2026-06-02) * Added version-based schema selection for versioned action responses. ## [0.2.10](https://github.com/Phala-Network/phala-cloud/compare/js-v0.2.9...js-v0.2.10) (2026-06-02) * Added hashed CVM ID schemas and a CVM creation resource graph. * Added pre-launch script upgrade status and upgrade actions. * Added app instance names, TCB identity fields, request IDs on structured errors, and a 60-second default request timeout. ## [0.2.9](https://github.com/Phala-Network/phala-cloud/compare/js-v0.2.8...js-v0.2.9) (2026-04-17) ### feat * **sdk,cli:** add POST /apps//instances support ([80498ab](https://github.com/Phala-Network/phala-cloud/commit/80498ab02f56610a21cbbc807b92d878304a1eb2)) ## [0.2.7](https://github.com/Phala-Network/phala-cloud/compare/js-v0.2.6...js-v0.2.7) (2026-04-10) ### feat * add compose\_hash\_registered to provision response schema ([be02cf9](https://github.com/Phala-Network/phala-cloud/commit/be02cf903d1219c63693d2e355ea86114bdf4841)) ### fix * **js:** update addComposeHash test mock for owner pre-check ([456ce00](https://github.com/Phala-Network/phala-cloud/commit/456ce0022f23e315e6e0b06341026fa1ec1a73c0)) * parse StructuredError details array in 465 error handlers ([50129dc](https://github.com/Phala-Network/phala-cloud/commit/50129dcc87803e979fde0d624f3187e0547a5aca)) * preserve StructuredError response body in error conversion ([ae7eecc](https://github.com/Phala-Network/phala-cloud/commit/ae7eecc487ea1c6f0892b383e2a22e41e0e6593d)) * **sdk:** chain resolution, owner pre-check, and ABI error definitions ([0c6a50c](https://github.com/Phala-Network/phala-cloud/commit/0c6a50c7fc57370ecb61359f34f04210c645ca18)) ### refactor * add transaction progress logging and RPC transport timeouts ([29849a2](https://github.com/Phala-Network/phala-cloud/commit/29849a283025fe74543254e75afae888ab29f848)) ## [0.2.6](https://github.com/Phala-Network/phala-cloud/compare/js-v0.2.5...js-v0.2.6) (2026-03-27) ### feat * add is-allowed API to JS, Python, and Go SDKs ([1fa61f0](https://github.com/Phala-Network/phala-cloud/commit/1fa61f0581ce111213f721f1c2d2f4744c3c2f00)) * add structured error codes and idempotency support across all SDKs ([2dd6d0b](https://github.com/Phala-Network/phala-cloud/commit/2dd6d0bae4d5fd7acdef551c3c9bf507ac1b0e4e)), closes [#1041](https://github.com/Phala-Network/phala-cloud/issues/1041) * display on-chain status in --prepare-only output ([f98f614](https://github.com/Phala-Network/phala-cloud/commit/f98f6149f13b9452099e23409964dcedbfb82ff7)) * **js-sdk:** add webhook signature verification via @phala/cloud/webhook ([3544694](https://github.com/Phala-Network/phala-cloud/commit/3544694efbd70a7f2cbd123b2ca92ccbf3c99428)) * **js,cli:** add on-chain prerequisite checks and improve update flow ([d3209e1](https://github.com/Phala-Network/phala-cloud/commit/d3209e1fd2b0be61455f5ec69de64a7919b1b7e2)) * **js:** add patchCvm and confirmCvmPatch for unified PATCH /cvms/ ([30cabaf](https://github.com/Phala-Network/phala-cloud/commit/30cabaf7084e72dbda656504d9f4359db95e2a16)) * **sdk:** add prepareOnly support to patchCvm and new commitCvmUpdate action ([38d6bf4](https://github.com/Phala-Network/phala-cloud/commit/38d6bf40b9209f4fcfae70fcc4c5db2d0de379e8)) ### fix * **js,cli:** add missing files and fix compose hash tx verification ([7656a45](https://github.com/Phala-Network/phala-cloud/commit/7656a459ced2843a03146d6757fd019ede2f1f53)) * **js:** handle FormData Content-Type in post/put/patch methods ([68d77ef](https://github.com/Phala-Network/phala-cloud/commit/68d77ef29a865c4cf8fb8dd91afc703064dac416)) * **js:** send empty body in confirmCvmPatch instead of undefined ([a228001](https://github.com/Phala-Network/phala-cloud/commit/a22800121b6d4db6fa719864f8775cd70c28801d)) * **js:** use toMatchObject for viem Chain comparisons in tests ([5b5d00c](https://github.com/Phala-Network/phala-cloud/commit/5b5d00c0b8f32d8147e2d784e9a10ad7fcaf152e)) ## [0.2.5](https://github.com/Phala-Network/phala-cloud/compare/js-v0.2.4...js-v0.2.5) (2026-03-14) ### docs * **js:** fix ETHEREUM typo in provision example ([15c3940](https://github.com/Phala-Network/phala-cloud/commit/15c394024467085491438fa5a52d0a1eafb565bf)) ### feat * add device management blockchain actions to SDK and CLI ([290ca2a](https://github.com/Phala-Network/phala-cloud/commit/290ca2a8d4b246b8d9d4b87281132bf573128989)) * add getAppAttestation action for app-level attestation API ([4d534e9](https://github.com/Phala-Network/phala-cloud/commit/4d534e91bb3a845ab4a13549bb271f51bf85bc21)) * add getAppDeviceAllowlist SDK action ([9b6fbf4](https://github.com/Phala-Network/phala-cloud/commit/9b6fbf4553a03308fc36783e7911806dd10b9624)) * add os-images listing, kms on-chain detail to SDK and CLI ([9fe5c9a](https://github.com/Phala-Network/phala-cloud/commit/9fe5c9a845ca6c46d3c8777eeb8eec50476a396b)) * **cli,sdk:** add --fs option to deploy command for filesystem selection ([716723d](https://github.com/Phala-Network/phala-cloud/commit/716723d5e6a4ca3f443ee073dc8f74c44af162d6)) * export attestation Zod schemas for frontend reuse ([cbd3245](https://github.com/Phala-Network/phala-cloud/commit/cbd3245bec7448790b4016816cca20ac1bb0c56c)) * **js-sdk:** add instance-id refresh actions and v20260121 field ([038810a](https://github.com/Phala-Network/phala-cloud/commit/038810a87350a00c719c430091b2a1882aed031b)) * **js:** add confidential\_models\_enabled to WorkspaceResponseSchema ([6a8b924](https://github.com/Phala-Network/phala-cloud/commit/6a8b9244d103a5fafdec931270d45259780666ea)) * **kms:** simplify CLI output and include device node names ([e48019c](https://github.com/Phala-Network/phala-cloud/commit/e48019cb972c96c049aadc2e285f4b3a06de0c14)) * query and display contract owner in allow-devices list ([37fe2e1](https://github.com/Phala-Network/phala-cloud/commit/37fe2e124880f59b3e9bb0087cafb71b350781f5)) * **sdk:** add replicateCvm action for CVM scaling ([1cb8203](https://github.com/Phala-Network/phala-cloud/commit/1cb820395a9d835146a034aa33f18062a6c8db40)) ### fix * **js-sdk:** add listed field to CvmInfoV20260121Schema ([a85adaf](https://github.com/Phala-Network/phala-cloud/commit/a85adaf3e650a6af41c27d50748a1a117f29037b)) * make base\_image optional in VMSchema ([043b81b](https://github.com/Phala-Network/phala-cloud/commit/043b81b6be0662d195b202cc28b08fc249f0ceaf)) * replace event scanning with readContract for device allowlist ([fb2a4b2](https://github.com/Phala-Network/phala-cloud/commit/fb2a4b275912d4bd2931c1b12d3b5b1368a26458)) * replay events chronologically in getAllowedDevices ([cccb120](https://github.com/Phala-Network/phala-cloud/commit/cccb120b9af2651e1468d98862bd0a7b713b1a59)) ### perf * use multicall for batch device allowlist checks ([4fb338f](https://github.com/Phala-Network/phala-cloud/commit/4fb338f0f7e383fdfee016e02712075c22ae3af0)) ## [0.2.4](https://github.com/Phala-Network/phala-cloud/compare/js-v0.2.3...js-v0.2.4) (2026-02-25) ### feat * **sdk+cli:** add SSH key and CVM runtime-config commands ([692321a](https://github.com/Phala-Network/phala-cloud/commit/692321a05bacdbc4da9bcfbc9b82ab8fcfc9d25a)) * **sdk:** add create, delete, and sync SSH key actions ([a688f29](https://github.com/Phala-Network/phala-cloud/commit/a688f2909932500be88ac238d5fcb894f7af98d6)) ## [0.2.3](https://github.com/Phala-Network/phala-cloud/compare/js-v0.2.2...js-v0.2.3) (2026-02-07) ### feat * add 200KB size limit for compose file + pre-launch script ([fe45765](https://github.com/Phala-Network/phala-cloud/commit/fe4576593cc08c2576e4c91d1c2b6b68cb3b9601)) * add profile field to app schemas and getAppFilterOptions action ([cf3c2eb](https://github.com/Phala-Network/phala-cloud/commit/cf3c2eb2e1ddc1b9984484630bc603e48f48aafb)) * add public\_tcbinfo to update visibility action ([39cfd3f](https://github.com/Phala-Network/phala-cloud/commit/39cfd3f0c5f0628d8c13a25fb99a400a32cecb06)) ### fix * rename teepod\_name to node in get\_app\_list action ([f863436](https://github.com/Phala-Network/phala-cloud/commit/f8634367fb5b03eb3f84877b56c8e914dc03fd55)) ### refactor * **js:** add revision\_id to app revisions and use revisionId for detail ([8d72149](https://github.com/Phala-Network/phala-cloud/commit/8d72149e69a71bfc11eb35c2240753b4ecc014b7)) ## [0.2.2](https://github.com/Phala-Network/phala-cloud/compare/js-v0.2.1...js-v0.2.2) (2026-01-31) ### feat * **sdk-js:** add is\_default to workspaces response schema ([85996b3](https://github.com/Phala-Network/phala-cloud/commit/85996b395c5fa7efdfe37dbf1a300964d4d441fd)) * use workspace slug as profile name, add profiles command, update default API dom ([5c150a0](https://github.com/Phala-Network/phala-cloud/commit/5c150a024d575414e60d6ead26f19a1fc9eaad4a)) ### refactor * sync NodeRef schema from backend ([f699002](https://github.com/Phala-Network/phala-cloud/commit/f699002fc24785c58cfa0452c0ab151d6c661117)) ## [0.2.1](https://github.com/Phala-Network/phala-cloud/compare/js-v0.2.1-beta.4...js-v0.2.1) (2026-01-31) ### feat * add standalone patch api for docker compose & prelaunch script ([efc9a05](https://github.com/Phala-Network/phala-cloud/commit/efc9a052c2fb0b4cf6eedce628c81ef86826fa4d)) * add validate rule to cvm name when creating cvm ([92138c0](https://github.com/Phala-Network/phala-cloud/commit/92138c0de0021aa06e597aa321c9a293bb078e2a)) * **js:** add batch CVM status action ([e99e0d8](https://github.com/Phala-Network/phala-cloud/commit/e99e0d86b79b9cf871f58d0e878a569e4808d6bc)) * **js:** add workspace nodes and quotas API ([2adf971](https://github.com/Phala-Network/phala-cloud/commit/2adf971646d0b628ad68e9a07a28b98bba02e88d)) * **sdk:** add apps API actions and fix versioned client types ([3ee04e9](https://github.com/Phala-Network/phala-cloud/commit/3ee04e9611047a47890e852bdf6f3244fd457c98)) * **sdk:** add generic request methods with full response support ([b15c2c6](https://github.com/Phala-Network/phala-cloud/commit/b15c2c627ece4472edf1ecb8a877cd619808e662)) * **sdk:** add versioned API client with type-safe return types ([4378e37](https://github.com/Phala-Network/phala-cloud/commit/4378e373966efbd72d987d399e0f7c9136c2d9dd)) * unify name convention across cli & sdk ([9f0d1e5](https://github.com/Phala-Network/phala-cloud/commit/9f0d1e5d5f7b600a1c963816ce38bd1b402885ef)) ### fix * api path for batch cvm status query ([5764b05](https://github.com/Phala-Network/phala-cloud/commit/5764b05be417e568f91b88235d7f1511b62b4724)) * **js:** expose instance\_type in CVM response ([0c30066](https://github.com/Phala-Network/phala-cloud/commit/0c300668e821a58d30cceff5dff264dcbedbddee)) * migrate URLs from cloud.phala.network to cloud.phala.com ([cd48ed4](https://github.com/Phala-Network/phala-cloud/commit/cd48ed4a69ffc3bd4f4c8483946cf21c2b5d38a6)) * **sdk,cli:** send update\_env\_vars flag when updating CVM env vars ([26077d1](https://github.com/Phala-Network/phala-cloud/commit/26077d17e418182d96b995e23e26a48da697d3ea)) * **sdk:** add missing kms\_info field to ProvisionCvmSchema ([6fc3b6a](https://github.com/Phala-Network/phala-cloud/commit/6fc3b6aa9d0c733ad2394108e388ebb907324e22)) * **sdk:** smart default for instance\_type to allow vcpu/memory params to work ([9f0780d](https://github.com/Phala-Network/phala-cloud/commit/9f0780d892d43bcb354a5ada1b8edf7c2912e0fc)) ## [0.2.0](https://github.com/Phala-Network/phala-cloud/compare/js-v0.1.2...js-v0.2.0) (2025-11-05) ### feat * added actions get\_available\_os\_images and update\_os\_image ([95e5688](https://github.com/Phala-Network/phala-cloud/commit/95e5688c14f9451791fd8b59bef6950a5e326652)) * added getCvmState & safeGetCvmState ([fc791ac](https://github.com/Phala-Network/phala-cloud/commit/fc791acc28834f1255b5a8def32494cc128935cf)) * added next-app-ids API ([26d9dfc](https://github.com/Phala-Network/phala-cloud/commit/26d9dfce02e29f80bf572aff1268e60db314d580)) * experimental watchCvmState implementation ([ce316d9](https://github.com/Phala-Network/phala-cloud/commit/ce316d9d3af9c865c7b27471a8844f5d8e025485)) ## [0.1.2](https://github.com/Phala-Network/phala-cloud/compare/js-v0.1.1...js-v0.1.2) (2025-10-29) ### feat * **sdk:** redesign errors & added event emitter support ([c2036fa](https://github.com/Phala-Network/phala-cloud/commit/c2036fa6a87587269c516538ea9573bed7596f9a)) ### fix * **cvms:** include update\_env\_vars in compose file update request body ([f3eb2cd](https://github.com/Phala-Network/phala-cloud/commit/f3eb2cd40ae7515e5e26fd8543e088da780d579c)) ## [0.1.1](https://github.com/Phala-Network/phala-cloud/compare/js-v0.1.1-beta.3...js-v0.1.1) (2025-10-24) ### feat * attach getHash & toString to AppCompose object ([d013f99](https://github.com/Phala-Network/phala-cloud/commit/d013f99ac269a5bea196c801104e1868fcaa91df)) * export utils function in get\_compose\_hash ([4c4c5fc](https://github.com/Phala-Network/phala-cloud/commit/4c4c5fcce1c2cfe2aaaad48f7539512d220e4621)) ## [0.0.12](https://github.com/Phala-Network/phala-cloud/compare/57cb8ef05d2227ee6f9fb9135aa9f1ff5dfbd021...js-v0.0.12) (2025-10-11) Initial release with action functions for deploy, provision, authentication, CVM management, KMS integration, and workspace APIs. # commitCvmProvision Source: https://docs.phala.com/phala-cloud/references/cloud-js-sdk/commit-cvm-provision Commit a CVM provision — second phase of the two-phase deployment flow ## commitCvmProvision `POST /cvms` Commits a CVM provision, finalizing the deployment. This is the **second phase** of the two-phase flow started by [`provisionCvm`](/phala-cloud/references/cloud-js-sdk/provision-cvm). The required parameters differ based on the KMS type: * **PHALA KMS:** `app_id` comes from the `provisionCvm` response. * **On-chain KMS (ETHEREUM/BASE):** `app_id` comes from deploying an AppAuth contract via [`deployAppAuth`](/phala-cloud/references/cloud-js-sdk/deploy-app-auth). You must also provide `kms_id`, `contract_address`, and `deployer_address`. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `app_id` | `string` | Yes | App ID from provision (PHALA) or contract deployment (on-chain) | | `compose_hash` | `string` | Yes | Hash from `provisionCvm` | | `encrypted_env` | `string` | No | Hex-encoded encrypted environment variables | | `env_keys` | `string[]` | No | Allowed environment variable keys | | `kms_id` | `string` | No | KMS instance slug (required for on-chain KMS) | | `contract_address` | `string` | No | AppAuth contract address (on-chain KMS only) | | `deployer_address` | `string` | No | Deployer wallet address (on-chain KMS only) | **Returns:** `CommitCvmProvision` | Field | Type | Description | | - | - | - | | `id` | `number` | CVM ID | | `name` | `string` | CVM name | | `status` | `string` | Initial status (typically `"starting"`) | | `app_id` | `string?` | App ID | | `app_url` | `string?` | Public URL for the CVM | | `vm_uuid` | `string?` | VM unique identifier | | `instance_id` | `string?` | Instance identifier | | `vcpu` | `number` | Allocated vCPUs | | `memory` | `number` | Allocated memory (MB) | | `disk_size` | `number` | Disk size (GB) | | `created_at` | `string` | ISO 8601 creation timestamp | | `encrypted_env_pubkey` | `string?` | Public key for encrypting environment variables | | `app_auth_contract_address` | `string?` | AppAuth contract address (on-chain KMS only) | | `deployer_address` | `string?` | Deployer wallet address (on-chain KMS only) | After a successful commit, the CVM begins booting. Track progress with [`watchCvmState`](/phala-cloud/references/cloud-js-sdk/watch-cvm-state) or subscribe to [`cvm.created`](/phala-cloud/references/webhooks) / [`cvm.create_failed`](/phala-cloud/references/webhooks) webhook events. **Example — PHALA KMS:** ```typescript theme={"system"} const result = await client.commitCvmProvision({ app_id: provision.app_id!, compose_hash: provision.compose_hash, encrypted_env: encryptedEnvHex, env_keys: ["API_KEY"], }); ``` **Example — On-chain KMS:** ```typescript theme={"system"} const result = await client.commitCvmProvision({ app_id: deployedContract.appId, compose_hash: provision.compose_hash, encrypted_env: encryptedEnvHex, env_keys: ["API_KEY"], kms_id: kmsSlug, contract_address: deployedContract.appAuthAddress, deployer_address: deployedContract.deployer, }); ``` *** ## safeCommitCvmProvision Safe variant that returns a `SafeResult` instead of throwing on errors. # CVM Configuration Source: https://docs.phala.com/phala-cloud/references/cloud-js-sdk/cvm-configuration Functions for updating CVM resources, visibility, OS images, and compose files > [!WARNING] > > **Some configuration updates restart a running CVM.** A change applied through `PATCH /cvms/{cvmId}` or the compose, environment and OS image endpoints stops the CVM, applies the change and starts it again. A stopped CVM stays stopped and runs the new configuration at its next start. A compose change that matches what the CVM already runs does not restart it: the API answers `no_change` and does nothing. Annotations (`updateCvmAnnotations`) never restart the CVM, and SSH key changes without `apply_now` stay pending until the next power-on. `patchCvm` sends any set of changes in one request to `PATCH /cvms/{cvmId}`. `updateCvmResources` and `updateCvmVisibility` send a subset of fields to the same endpoint. The other `updateXxxx` methods call their own endpoints. See [Update CVM Configuration](/phala-cloud/update/update-cvm-configuration) for what each field does and which settings cannot change after create. ## updateCvmResources `PATCH /cvms/{cvmId}` Updates CVM compute resources (vCPU, memory, disk, instance type). It sends only these four fields. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier | | `vcpu` | `number` | No | Number of vCPUs | | `memory` | `number` | No | Memory in MB | | `disk_size` | `number` | No | Disk size in GB. A disk cannot shrink. | | `instance_type` | `string` | No | Instance type, for example `tdx.medium` | | `allow_restart` | `boolean` | No | Deprecated and not sent. The CVM restarts whenever a resize needs it. | **Returns:** `{ message, correlation_id, status }`. `correlation_id` tracks the update. **Example:** ```typescript theme={"system"} await client.updateCvmResources({ id: "my-app", vcpu: 4, memory: 8192, disk_size: 100, }); ``` *** ## updateCvmVisibility `PATCH /cvms/{cvmId}` Sets what the public can see about the CVM: system info, logs and TCB info. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier | | `public_sysinfo` | `boolean` | Yes | Make system info public | | `public_logs` | `boolean` | Yes | Make container logs public | | `public_tcbinfo` | `boolean` | No | Make TCB info public | **Returns:** `{ message, correlation_id, status }`. `status` is `"in_progress"`, or `"no_change"` with an empty `correlation_id` when the settings already match. These settings are part of the compose hash. For a CVM on Onchain KMS, the request fails with HTTP 465 until the new hash is registered on-chain. Register it and call again, or use [`patchCvm`](#patchcvm), which returns the hash to register and supports `prepareOnly`. The Trust Center listing is not a visibility setting. Change it with `PATCH /cvms/{cvmId}/listed`. *** ## updatePreLaunchScript `PATCH /cvms/{cvmId}/pre-launch-script` Updates the pre-launch script for a CVM. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier | | `pre_launch_script` | `string` | Yes | Script content | | `compose_hash` | `string` | No | For on-chain KMS (Phase 2) | | `transaction_hash` | `string` | No | For on-chain KMS (Phase 2) | **Returns:** Union type: * `{ status: "in_progress", message, correlation_id }` — update accepted * `{ status: "precondition_required", message, compose_hash, app_id, device_id, kms_info }` — on-chain KMS requires compose hash registration first > [!NOTE] > > For CVMs using on-chain KMS, this function may return `precondition_required`. You must register the `compose_hash` on-chain using [`addComposeHash`](/phala-cloud/references/cloud-js-sdk/add-compose-hash) before retrying with the `compose_hash` and `transaction_hash` parameters. *** ## updateOsImage `PATCH /cvms/{cvmId}/os-image` Updates the OS image for a CVM. The CVM will restart with the new image. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier | | `os_image_name` | `string` | Yes | OS image name | **Returns:** `undefined`. The API answers `202` with `{ message, correlation_id, status }`, but `updateOsImage` discards it. *** ## getAvailableOsImages `GET /os-images` Returns the list of available OS images. **Parameters:** None (optional filters). **Returns:** `GetAvailableOSImagesResponse` — array of OS image variants with version info. **Example:** ```typescript theme={"system"} const images = await client.getAvailableOsImages(); images.forEach(img => console.log(img.name, img.version)); ``` *** ## refreshCvmInstanceId `POST /cvms/{cvmId}/refresh-instance-id` Generates a new instance ID for a CVM. This invalidates the old instance ID. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier | **Returns:** `InstanceIdRefreshResult` with the new `instance_id`. *** ## refreshCvmInstanceIds `POST /cvms/refresh-instance-ids` Generates new instance IDs for multiple CVMs in a single request. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `ids` | `string[]` | Yes | Array of CVM identifiers | **Returns:** `RefreshCvmInstanceIdsResponse` — batch results. *** ## provisionCvmComposeFileUpdate `POST /cvms/{cvmId}/compose_file/provision` Provisions a compose file update — the first phase of a two-phase compose file change. Returns a `compose_hash` needed for the commit step. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier (also accepts `uuid`) | | `app_compose` | `object` | Yes | Updated compose file object | **Returns:** `ProvisionCvmComposeFileUpdateResult` | Field | Type | Description | | - | - | - | | `compose_hash` | `string` | Hash of the provisioned compose file. Pass it to `commitCvmComposeFileUpdate`. | | `compose_hash_registered` | `boolean` | On-chain KMS only: `true` if the hash is already registered on the AppAuth contract. When `true`, skip [`addComposeHash`](/phala-cloud/references/cloud-js-sdk/add-compose-hash) and call `commitCvmComposeFileUpdate` directly. | | `app_id` | `string \| null` | App identifier of the target CVM. | | `device_id` | `string \| null` | Device identifier of the target CVM. | | `kms_info` | `object \| null` | KMS metadata for the target CVM. Present for on-chain KMS CVMs. | **Example:** ```typescript theme={"system"} import { addComposeHash } from "@phala/cloud"; const compose = await client.getCvmComposeFile({ id: "my-app" }); compose.docker_compose_file = newYaml; const provision = await client.provisionCvmComposeFileUpdate({ uuid: "my-app", app_compose: compose, }); if (provision.kms_info && !provision.compose_hash_registered) { // On-chain KMS: register the new hash before commit. // See addComposeHash docs for the full parameter set. await addComposeHash({ chain: provision.kms_info.chain, kmsContractAddress: provision.kms_info.kms_contract_address, appId: provision.app_id as `0x${string}`, composeHash: provision.compose_hash, privateKey: process.env.ETH_PRIVATE_KEY as `0x${string}`, }); } await client.commitCvmComposeFileUpdate({ id: "my-app", compose_hash: provision.compose_hash, }); ``` *** ## commitCvmComposeFileUpdate `POST /cvms/{cvmId}/compose_file/commit` Commits a compose file update — the second phase. For on-chain KMS, the `compose_hash` must be registered on-chain before calling this. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier | | `compose_hash` | `string` | Yes | From `provisionCvmComposeFileUpdate` | | `encrypted_env` | `string` | No | Hex-encoded encrypted env vars | | `env_keys` | `string[]` | No | Allowed env variable keys | | `transaction_hash` | `string` | No | On-chain transaction hash | **Returns:** `CommitCvmComposeFileUpdate` — update details. *** ## patchCvm `PATCH /cvms/{cvmId}` Applies partial updates to a CVM via the unified PATCH endpoint. Only fields present in the request body are applied. You can update compose files, environment variables, resources, visibility, and OS images all in a single call. `compose` is a JSON Merge Patch of the app compose: a key you set changes that value, `null` removes the key, and a key you leave out stays as it is. See [How does the compose patch work?](/phala-cloud/update/update-cvm-configuration#how-does-the-compose-patch-work) for the keys and the settings that cannot change after create. For CVMs with on-chain KMS (ETHEREUM/BASE), a change to the compose needs a second step only when the new compose hash is not on the app contract yet. The API then answers HTTP 465, and `patchCvm` returns `{ requiresOnChainHash: true, composeHash, ... }` with the hash to register. After registration, call [`confirmCvmPatch`](#confirmcvmpatch) with the transaction proof. If the hash is already allowed, or the patch does not change the compose (for example a resize), the update starts at once and you get `correlationId`. `prepareOnly` is not a dry run: an update that needs no registration starts right away. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier | | `docker_compose_file` | `string` | No | New Docker Compose YAML | | `pre_launch_script` | `string` | No | New pre-launch script | | `allowed_envs` | `string[]` | No | Allowed env variable keys | | `public_logs` | `boolean` | No | Make logs publicly accessible | | `public_sysinfo` | `boolean` | No | Make system info public | | `public_tcbinfo` | `boolean` | No | Make TCB info public | | `compose` | `ComposePatch` | No | Other compose settings as a merge patch, for example `{ swap_size: "2G", requirements: { health_check: true } }` | | `init_scripts` | `"docker_cleanup"[]` | No | Platform init scripts the CVM runs, replacing the current set. `[]` removes them all. | | `confirm_data_wipe` | `boolean` | No | Confirms turning on `docker_cleanup` or `requirements.ephemeral_data_disk`, which erase data on every boot | | `encrypted_env` | `string` | No | Hex-encoded encrypted env vars | | `user_config` | `string` | No | User configuration string | | `gpus` | `object` | No | GPU assignment: `{ gpus: [{ slot, product_id? }], attach_mode? }`. `attach_mode: "all"` attaches every GPU on the node instead of the listed slots. | | `vcpu` | `number` | No | Number of vCPUs | | `memory` | `number` | No | Memory in MB | | `disk_size` | `number` | No | Disk size in GB | | `instance_type` | `string` | No | Instance type, for example `tdx.medium` | | `image` | `string` | No | OS image name | | `shutdown_timeout` | `number` | No | Seconds to wait for a clean shutdown (10 to 1200) | | `allow_force_stop` | `boolean` | No | Skip the clean shutdown and stop the CVM at once | | `prepareOnly` | `boolean` | No | Sent as the `X-Prepare-Only: true` header. On Onchain KMS, the hash-required result then carries a commit token for multisig approval. | **Returns:** Discriminated union on `requiresOnChainHash`: **Accepted (`requiresOnChainHash: false`):** | Field | Type | Description | | - | - | - | | `requiresOnChainHash` | `false` | Update accepted directly | | `correlationId` | `string` | Tracking ID. Empty when the API answers `no_change`. | **Hash required (`requiresOnChainHash: true`):** | Field | Type | Description | | - | - | - | | `requiresOnChainHash` | `true` | On-chain registration needed | | `composeHash` | `string` | Hash to register on-chain | | `appId` | `string` | App ID for contract interaction | | `deviceId` | `string` | Device ID | | `kmsInfo` | `KmsInfo` | KMS details for chain interaction | | `commitToken` | `string?` | One-time token for multisig commit | | `commitUrl` | `string?` | Dashboard page where the update can be committed | | `apiCommitUrl` | `string?` | API URL for [`commitCvmUpdate`](#commitcvmupdate) | | `onchainStatus` | `object?` | Current on-chain allowance status | **Example — simple update (PHALA KMS):** ```typescript theme={"system"} const result = await client.patchCvm({ id: "my-app", vcpu: 4, memory: 8192, }); console.log(result.correlationId); ``` **Example — on-chain KMS compose update (two-phase):** ```typescript theme={"system"} import { addComposeHash } from "@phala/cloud"; const result = await client.patchCvm({ id: "my-app", docker_compose_file: newComposeYaml, }); if (result.requiresOnChainHash) { const tx = await addComposeHash({ chain: result.kmsInfo.chain, kmsContractAddress: result.kmsInfo.kms_contract_address, appId: result.appId as `0x${string}`, composeHash: result.composeHash, privateKey: privateKey, }); await client.confirmCvmPatch({ id: "my-app", composeHash: result.composeHash, transactionHash: tx.transactionHash, }); } ``` *** ## getCvmInitScripts `GET /cvms/{cvmId}/init-scripts` Lists the platform init scripts, in run order, and for each one whether the CVM runs it (`selected`), whether you can pick it for this CVM (`selectable`) and, if not, why (`reason`). Change the selection with `patchCvm`'s `init_scripts`. See [Init scripts](/phala-cloud/cvm/advanced-settings#init-scripts). **Parameters:** `id` (CVM identifier). **Returns:** `{ items: [{ slug, selected, selectable, reason }] }` *** ## getCvmAnnotations / updateCvmAnnotations `GET /cvms/{cvmId}/annotations` / `PUT /cvms/{cvmId}/annotations` Reads or replaces the CVM's annotations: key/value settings for tools on the host. They are not measured and attestation does not cover them. `updateCvmAnnotations` replaces every annotation, and `{}` clears them. It does not restart the CVM. Annotations sit behind a feature flag; without it, both calls fail with `ERR-03-049`. See [Annotations](/phala-cloud/cvm/advanced-settings#annotations). **Parameters:** `id` (CVM identifier), plus `annotations` (`Record`) for `updateCvmAnnotations`. **Returns:** `{ annotations }`, the annotations the node now stores. ```typescript theme={"system"} await client.updateCvmAnnotations({ id: "my-app", annotations: { memory_tier: "fast" } }); ``` *** ## confirmCvmPatch `PATCH /cvms/{cvmId}` (with `X-Compose-Hash` and `X-Transaction-Hash` headers) Completes the second phase of an on-chain KMS CVM update. Call this after `patchCvm` returns `{ requiresOnChainHash: true }` and you have registered the compose hash on-chain via [`addComposeHash`](/phala-cloud/references/cloud-js-sdk/add-compose-hash). **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier | | `composeHash` | `string` | Yes | Compose hash from `patchCvm` Phase 1 response | | `transactionHash` | `string` | Yes | Transaction hash proving on-chain registration | **Returns:** `ConfirmCvmPatchResult` | Field | Type | Description | | - | - | - | | `correlationId` | `string` | Tracking ID | **Example:** ```typescript theme={"system"} const confirmed = await client.confirmCvmPatch({ id: "my-app", composeHash: patchResult.composeHash, transactionHash: txReceipt.transactionHash, }); console.log(`Update started: ${confirmed.correlationId}`); ``` *** ## commitCvmUpdate `POST /cvms/{cvmId}/commit-update` Completes a two-phase CVM update using a one-time commit token. This enables multisig workflows where the on-chain signer is different from the original API caller. The token is generated when you call `patchCvm` with `prepareOnly: true`. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier | | `token` | `string` | Yes | One-time commit token from prepare-only flow | | `composeHash` | `string` | Yes | Compose hash from Phase 1 response | | `transactionHash` | `string` | Yes | Transaction hash proving on-chain registration | **Returns:** `CommitCvmUpdateResult` | Field | Type | Description | | - | - | - | | `correlationId` | `string` | Tracking ID | | `status` | `string` | Update status | **Example:** ```typescript theme={"system"} // Phase 1: prepare-only const result = await client.patchCvm({ id: "my-app", docker_compose_file: newComposeYaml, prepareOnly: true, }); if (result.requiresOnChainHash && result.commitToken) { // ... multisig approval and on-chain registration happen externally ... // Phase 2: commit with token const committed = await client.commitCvmUpdate({ id: "my-app", token: result.commitToken, composeHash: result.composeHash, transactionHash: "0x...", }); console.log(`Update started: ${committed.correlationId}`); } ``` # CVM Lifecycle Source: https://docs.phala.com/phala-cloud/references/cloud-js-sdk/cvm-lifecycle Functions for starting, stopping, restarting, and deleting CVMs ## startCvm `POST /cvms/{cvmId}/start` Starts a stopped CVM. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier | **Returns:** `VMSchema` — updated CVM details. **Example:** ```typescript theme={"system"} const result = await client.startCvm({ id: "my-app" }); console.log(result.status); // "starting" ``` *** ## stopCvm `POST /cvms/{cvmId}/stop` Force-stops a CVM immediately. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier | **Returns:** `VMSchema` — updated CVM details. *** ## shutdownCvm `POST /cvms/{cvmId}/shutdown` Gracefully shuts down a CVM, allowing containers to stop cleanly. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier | **Returns:** `VMSchema` — updated CVM details. *** ## restartCvm `POST /cvms/{cvmId}/restart` Restarts a CVM. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier | | `force` | `boolean` | No | Force restart without graceful shutdown | **Returns:** `VMSchema` — updated CVM details. **Example:** ```typescript theme={"system"} await client.restartCvm({ id: "my-app", force: true }); ``` *** ## deleteCvm `DELETE /cvms/{cvmId}` Permanently deletes a CVM and all its data. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier | **Returns:** `void` (HTTP 204) > [!WARNING] > > This action is irreversible. All data associated with the CVM will be permanently deleted. **Example:** ```typescript theme={"system"} await client.deleteCvm({ id: "my-app" }); ``` *** ## replicateCvm `POST /cvms/{cvmId}/replicas` Creates a replica of an existing CVM. If you omit `node`, the replica inherits the source placement. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | Source CVM identifier | | `node` | `string` | No | Physical node name for the replica | | `os_image` | `string` | No | OS image override | **Returns:** Replicated CVM details. **Example:** ```typescript theme={"system"} const replica = await client.replicateCvm({ id: "my-app", node: "prod6", }); ``` # CVM Query Source: https://docs.phala.com/phala-cloud/references/cloud-js-sdk/cvm-query Functions for querying CVM information, state, and metrics All CVM query functions accept a CVM identifier. The SDK auto-detects the format: | Format | Example | | - | - | | Name | `my-app` | | UUID | `550e8400-e29b-41d4-a716-446655440000` | | App ID | `0x1234abcd...` (40 hex chars, optional `0x` prefix) | | Instance ID | `instance-abc123` | ## getCvmInfo `GET /cvms/{cvmId}` Returns full CVM details including configuration, status, and metadata. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier (any format above) | **Returns:** `CvmInfo` — version-aware response with CVM details. **Example:** ```typescript theme={"system"} const cvm = await client.getCvmInfo({ id: "my-app" }); console.log(cvm.name, cvm.status); ``` The detail response includes a `logs` object with complete presigned URLs for the serial, stdout, and stderr channels, plus the pieces needed to build container log URLs. If the requester cannot access the CVM, the request fails with HTTP `404`. The `logs` fields are `null` when signed log URLs are not available for that CVM yet, for example when it has no VM. You do not need to use these URLs yourself: the log helpers below read them for you. ### Read CVM logs Available in `@phala/cloud` 0.6.0 and later. The behavior described here is complete in 0.6.4, so use 0.6.4 or later. `fetchCvmLogs` and `followCvmLogs` read logs from a CVM. They are standalone functions exported from `@phala/cloud`, not methods on the client, so pass the client as the first argument. ```typescript theme={"system"} import { createClient, fetchCvmLogs, followCvmLogs, type CvmLogEntry, } from "@phala/cloud"; const client = createClient({ apiKey: "phak_your_api_key" }); // Last 100 lines of the serial console const serial = await fetchCvmLogs( client, "my-app", { type: "node", channel: "serial" }, { tail: 100 }, ); console.log(serial); // Fetch container records as entries const entries = await fetchCvmLogs( client, "my-app", { type: "container", name: "api" }, { tail: 100, format: "ndjson" }, ); for (const entry of entries as CvmLogEntry[]) { console.log(entry.channel, entry.message); } // Follow the "api" container as entries until the signal is aborted const controller = new AbortController(); for await (const entry of followCvmLogs( client, "my-app", { type: "container", name: "api" }, { tail: 50, signal: controller.signal }, )) { const { channel, message } = entry as CvmLogEntry; process.stdout.write(`[${channel}] ${message}`); } // Follow the same container as text lines for await (const line of followCvmLogs( client, "my-app", { type: "container", name: "api" }, { format: "text", signal: controller.signal }, )) { process.stdout.write(line as string); } ``` ```typescript theme={"system"} function fetchCvmLogs( client: Client, id: CvmIdInput | string, source: CvmLogSource, options?: CvmLogsOptions, ): Promise function followCvmLogs( client: Client, id: CvmIdInput | string, source: CvmLogSource, options?: CvmLogsOptions, ): AsyncGenerator ``` **Parameters:** | Name | Type | Description | | - | - | - | | `client` | `Client` | A client from `createClient` or `createBaseClient` | | `id` | `CvmIdInput \| string` | CVM identifier (name, UUID, or App ID) | | `source` | `CvmLogSource` | Which logs to read (see below) | | `options` | `CvmLogsOptions` | Optional display and time-window settings | **`CvmLogSource`:** | Shape | Description | | - | - | | `{ type: "node", channel: "serial" \| "stdout" \| "stderr" }` | A CVM-level channel: serial console, stdout, or stderr | | `{ type: "container", name?: string, matchContainerIdPrefix?: boolean }` | A container. `name` is a container name or ID prefix. If you omit it, the SDK uses the first container in the CVM composition. `matchContainerIdPrefix` defaults to `true`; set it to `false` to match names only. See [Container names](#container-names). | **`CvmLogsOptions`:** | Field | Type | Description | | - | - | - | | `tail` | `number \| "all"` | Number of most recent lines, or `"all"`. When omitted, the server default applies. | | `since` | `string \| number` | Start time: RFC 3339 timestamp, Unix seconds, or relative duration such as `"10m"` (`s`, `m`, `h`, `d`). | | `until` | `string \| number` | End time. Same formats as `since`. | | `timestamps` | `boolean` | Prefix each container line with its timestamp. | | `ansi` | `boolean` | Keep ANSI escape sequences in the output. The default is `false`, which removes them from every line and entry, including NDJSON messages. This is an output option, so it never causes an error. | | `format` | `"text" \| "ndjson"` | For containers, `fetchCvmLogs` returns a string unless this is `"ndjson"`, which returns entries. `followCvmLogs` yields entries unless this is `"text"`, which yields strings. | | `signal` | `AbortSignal` | Cancels the request, or ends a follow. | `since`, `until`, `timestamps`, and `format: "ndjson"` apply to container logs only. Passing them with a node source throws a `LogAccessError` with code `ERR-17-001` before any request is sent. **Return types:** | Call | Source | Result | | - | - | - | | `fetchCvmLogs` | Node | `string` | | `fetchCvmLogs` | Container | `string`, or `CvmLogEntry[]` when `format` is `"ndjson"` | | `followCvmLogs` | Node | Yields `string` lines, each delivered with its original newline (or lack of one), after heartbeat lines are dropped and ANSI escapes are stripped (unless `ansi` is `true`) | | `followCvmLogs` | Container | Yields `CvmLogEntry` objects, or `string` lines when `format` is `"text"` | `CvmLogEntry` is `{ channel: "stdout" | "stderr" | "console" | "stdin"; message: string }`. `console` appears for containers started with a TTY. `message` is exactly what the container wrote, usually ending in a newline. An empty message stays an empty string. #### Container names The SDK resolves the container name once at the start of a follow, with one composition call. It tries these steps in order: 1. An exact match on a container name. 2. A unique match on the start of a container ID, unless `matchContainerIdPrefix` is `false`. 3. If you gave no name, the first container in the composition. If the prefix matches more than one container, the SDK throws a `LogAccessError` with code `ERR-17-001` and the message `Ambiguous container prefix '': web, worker`, which lists the candidates. If nothing matches, it throws a `LogAccessError` with code `ERR-17-007`. If the composition has no containers and returns an `error` string, for example because the CVM is stopped, the SDK throws a `LogAccessError` with that message. A name you pass must be 1 to 128 characters, start with a letter or digit, and then use only letters, digits, `_`, `.`, and `-`. It must not contain `..`. Other names, such as `/app`, are rejected with `ERR-17-001` before any request is sent. The SDK does not strip a leading `/` from a name you pass. #### Cancellation Pass an `AbortSignal` in `options.signal`. Aborting it during a follow ends the follow without throwing, and so does leaving the `for await` loop or calling `return()` on the generator. Waits between reconnects are interrupted at once. The signal also applies to a one-shot `fetchCvmLogs`, including its lookups. A signal that is already aborted before a follow starts makes the iteration throw an `AbortError` without sending any request. A fetch that is aborted rejects with an `AbortError`. **Behavior:** * Every connection uses a fresh signed URL, with one CVM info lookup per connection. * Follow reconnects after a stream ends or fails. Failures back off from 250 ms, doubling up to 5 s, and follow gives up after 5 consecutive failures. Starts of two connections are at least 1 s apart. * HTTP errors are handled by status. `5xx` and `429` are failures. `401` with `ERR-17-003` fetches a new URL and retries, up to 3 times in a row. The count resets after a connection that delivered records or ended cleanly. `401` with `ERR-17-002` fetches a new URL and counts as a failure. Any other `4xx` stops follow. * A gateway error line inside a `200` stream, or a network error, counts as a failure. A connection that delivered at least one record resets the failure count before its own failure is counted. * Container follow always requests timestamps internally. It sends the caller's `tail` until the first connection is accepted. Every later request sends `tail=all` plus `since`, and skips lines it already delivered at the boundary second, so a reconnect does not repeat output. Before any timestamped record arrives, it uses your `since` if you set one, otherwise the second the first connection was accepted. Timestamps are removed from the output unless you set `timestamps: true`. * Container follow: if a stream ends cleanly with no new output within 10 s, it backs off and counts the end. After 5 such ends in a row, follow stops with `log stream keeps ending without new output; the container may have stopped`. A clean end after records, or after an idle connection of 10 s or more, reconnects at once and resets the count. * Node follow never stops on a clean end. After the first connection it requests `tail=0`. * If you set `until`, follow finishes normally, without an error, when the stream reaches that time. * A missing container is not retried. * Node follow and fetch drop `[vmm heartbeat]` and `[teepod heartbeat]` lines. * A text-format record that looks like `{"error": ...}` is treated as a guest error only at the very start of the body. Use NDJSON (the default for entries) for reliable detection. * The helpers request CVM info with API version `2026-01-21` internally, so they work with clients configured for older versions. For the HTTP details behind these helpers, see [Fetch Logs over HTTP](/phala-cloud/monitoring/log-api). **Errors:** Log gateway errors are thrown as `LogAccessError`, which extends `ResourceError`. Match on `code` rather than the message. | Property | Type | Description | | - | - | - | | `code` | `string \| undefined` | Log error code such as `ERR-17-005`. The code is not repeated in `message`, which holds the human-readable text only. | | `httpStatus` | `number \| undefined` | HTTP status, set only for errors returned as an HTTP response. `undefined` for client-side errors (bad container name, bad time, unsupported option) and for errors read from the body of a stream. | | `suggestions` | `string[]` | Suggested fixes from the API | `LogAccessError` also carries `errorCode`, `structuredDetails`, `links`, and `requestId` from the API error envelope. ```typescript theme={"system"} import { LogAccessError, fetchCvmLogs } from "@phala/cloud"; try { await fetchCvmLogs(client, "my-app", { type: "container", name: "api" }); } catch (error) { if (error instanceof LogAccessError && error.code === "ERR-17-005") { console.error("The CVM is not running; container logs are unavailable."); } else { throw error; } } ``` Container logs require [Public Logs](/phala-cloud/monitoring/public-logs) to be enabled on the CVM. When it is off, container fetch and follow throw `LogAccessError` with code `ERR-17-006` ("Container logs are disabled") before sending any log request. Follow checks this before its first log request and again on every reconnect, because each connection looks up the CVM info. Node channels are not affected. A missing container throws a `LogAccessError` with code `ERR-17-007` (see [Container names](#container-names)). If the agent inside the CVM cannot read a container's logs, for example because the container uses a Docker logging driver that does not support reading, the helper throws `LogAccessError` with code `ERR-17-009` and the agent's message. This applies to text and NDJSON, in fetch and in follow. Follow stops on it. A server-returned HTTP `502` with `ERR-17-009` is different: follow reconnects. See [Fetch Logs over HTTP](/phala-cloud/monitoring/log-api#errors) for the full error code list. **Lower-level exports:** `@phala/cloud` also exports `fetchCvmChannelLogs`, `streamCvmChannelLogs`, `fetchContainerLogs`, `fetchContainerLogsEntries`, `streamContainerLogs`, `streamContainerLogsEntries`, `getCvmLogEndpoint`, and `resolveLogTimeWindow`. Prefer `fetchCvmLogs` and `followCvmLogs` unless you need one of these for a specific case. ### Without the helper If you are not using the JS SDK, or need full control, you can read the URLs from `getCvmInfo` and make the HTTP requests yourself. Use API version `2026-01-21` or later so the response includes `logs`. You then handle URL expiry, reconnects, and heartbeat lines in your own code. See [Fetch Logs over HTTP](/phala-cloud/monitoring/log-api) for the URL format, query parameters, and reconnect rules. *** ## getCvmList `GET /cvms/paginated` Returns a paginated list of CVMs. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `page` | `number` | No | Page number | | `page_size` | `number` | No | Items per page | | `family` | `"all" \| "cpu" \| "gpu"` | No | Filter by instance family | | `instance_types` | `string[]` | No | Filter by instance type IDs | **Returns:** Paginated list of CVM objects. **Example:** ```typescript theme={"system"} const list = await client.getCvmList({ page: 1, page_size: 10, family: "gpu", }); ``` *** ## getCvmState `GET /cvms/{cvmId}/state` Returns the current state of a CVM (non-streaming, immediate response). **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier | **Returns:** `CvmState` | Field | Type | Description | | - | - | - | | `id` | `string` | CVM ID | | `instance_id` | `string` | Instance ID | | `name` | `string` | CVM name | | `status` | `string` | Current status | | `uptime` | `string?` | Uptime duration | | `boot_progress` | `string?` | Boot progress percentage | | `boot_error` | `string?` | Boot error if failed | **Example:** ```typescript theme={"system"} const state = await client.getCvmState({ id: "my-app" }); console.log(state.status); // "running", "stopped", etc. ``` *** ## getCvmStats `GET /cvms/{cvmId}/stats` Returns system information and resource usage for a CVM. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier | **Returns:** `CvmSystemInfo` | Field | Type | Description | | - | - | - | | `is_online` | `boolean` | Whether CVM is reachable | | `is_public` | `boolean` | Whether stats are public | | `sysinfo` | `object?` | CPU, memory, disk usage | | `status` | `string?` | Current status | | `boot_progress` | `string?` | Boot progress | **Example:** ```typescript theme={"system"} const stats = await client.getCvmStats({ id: "my-app" }); if (stats.sysinfo) { console.log(`CPU: ${stats.sysinfo.cpu_usage}%`); } ``` *** ## getCvmNetwork `GET /cvms/{cvmId}/network` Returns network information including public URLs and internal IP. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier | **Returns:** `CvmNetwork` | Field | Type | Description | | - | - | - | | `is_online` | `boolean` | Whether CVM is reachable | | `internal_ip` | `string?` | WireGuard internal IP | | `public_urls` | `array?` | Public URL mappings | **Example:** ```typescript theme={"system"} const net = await client.getCvmNetwork({ id: "my-app" }); console.log(net.public_urls); ``` *** ## getCvmContainersStats `GET /cvms/{cvmId}/composition` Returns container-level information including running state and log endpoints. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier | **Returns:** `CvmContainersStats` | Field | Type | Description | | - | - | - | | `is_online` | `boolean` | Whether CVM is reachable | | `docker_compose_file` | `string?` | Active compose YAML | | `containers` | `array?` | Container info (id, names, image, state, status, log\_endpoint) | **Example:** ```typescript theme={"system"} const stats = await client.getCvmContainersStats({ id: "my-app" }); stats.containers?.forEach(c => console.log(c.names, c.state)); ``` *** ## getCvmAttestation `GET /cvms/{cvmId}/attestation` Returns TEE attestation details including certificates and TCB info. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier | **Returns:** `CvmAttestation` | Field | Type | Description | | - | - | - | | `is_online` | `boolean` | Whether CVM is reachable | | `app_certificates` | `array?` | TLS certificates with attestation | | `tcb_info` | `object?` | TCB measurements (mrtd, rtmr0-3, event\_log, app\_compose hash) | **Example:** ```typescript theme={"system"} const att = await client.getCvmAttestation({ id: "my-app" }); console.log(att.tcb_info?.app_compose); ``` *** ## getCvmDockerCompose `GET /cvms/{cvmId}/docker-compose` Returns the raw docker-compose configuration as a string. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier | **Returns:** `string` — raw docker-compose YAML content. **Example:** ```typescript theme={"system"} const compose = await client.getCvmDockerCompose({ id: "my-app" }); console.log(compose); ``` *** ## getCvmComposeFile `GET /cvms/{cvmId}/compose_file` Returns the full compose file object with utility methods for hashing. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier | **Returns:** `LooseAppCompose` — compose file object with `getHash()` and `toString()` methods. **Example:** ```typescript theme={"system"} const compose = await client.getCvmComposeFile({ id: "my-app" }); console.log(compose.docker_compose_file); console.log(compose.getHash()); ``` *** ## getCvmPreLaunchScript `GET /cvms/{cvmId}/pre-launch-script` Returns the pre-launch script content. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier | **Returns:** `string` — pre-launch script content. *** ## getCvmStatusBatch `GET /cvms/status/batch` Returns the status of multiple CVMs in a single request. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `ids` | `string[]` | Yes | Array of CVM IDs | **Returns:** `GetCvmStatusBatchResponse` | Field | Type | Description | | - | - | - | | `statuses` | `CvmStatus[]` | Status for each requested CVM | **Example:** ```typescript theme={"system"} const batch = await client.getCvmStatusBatch({ ids: ["id-1", "id-2"] }); batch.statuses.forEach(s => console.log(s.id, s.status)); ``` *** ## getCvmUserConfig `GET /cvms/{cvmId}/user-config` Returns the user-level configuration for a CVM. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier | **Returns:** `CvmUserConfig` — user configuration details. *** ## checkCvmIsAllowed `POST /cvms/{cvmId}/is-allowed` Checks whether a CVM's current deployment is allowed by its on-chain dstack App contract. This queries the blockchain to verify that the compose hash and device ID are registered. Useful for diagnosing on-chain KMS permission issues. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `cvmId` | `string` | Yes | CVM identifier | | `compose_hash` | `string` | No | Override compose hash to check | | `node` | `string` | No | Override physical node name used to resolve the device ID | | `device_id` | `string` | No | Override device ID (hex) | **Returns:** `IsAllowedResult` | Field | Type | Description | | - | - | - | | `app_contract_address` | `string` | Contract address | | `compose_hash` | `string` | Checked compose hash | | `device_id` | `string` | Checked device ID | | `compose_hash_allowed` | `boolean` | Whether compose hash is registered | | `allow_any_device` | `boolean` | Whether any device is allowed | | `device_id_allowed` | `boolean?` | Whether specific device is registered | | `is_allowed` | `boolean` | Overall allowance result | | `error` | `string?` | Error message if check failed | **Example:** ```typescript theme={"system"} const result = await client.checkCvmIsAllowed({ cvmId: "my-app" }); if (!result.is_allowed) { console.log(`Compose hash allowed: ${result.compose_hash_allowed}`); console.log(`Device allowed: ${result.device_id_allowed}`); } ``` # deployAppAuth Source: https://docs.phala.com/phala-cloud/references/cloud-js-sdk/deploy-app-auth Deploy an AppAuth smart contract for on-chain KMS ## deployAppAuth Deploys an AppAuth smart contract on Ethereum or Base. This is required for on-chain KMS deployments — the contract acts as the access-control layer and generates the `app_id` used in [`commitCvmProvision`](/phala-cloud/references/cloud-js-sdk/commit-cvm-provision). This function interacts directly with the blockchain (not the Phala Cloud API). **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `chain` | `Chain` | Conditional | Viem chain config (required if no `walletClient`) | | `kmsContractAddress` | `Address` | Yes | KMS factory contract address | | `privateKey` | `Hex` | Conditional | Deployer private key (provide this or `walletClient`) | | `walletClient` | `WalletClient` | Conditional | Custom wallet client (provide this or `privateKey`) | | `rpcUrl` | `string` | No | Custom RPC URL | | `publicClient` | `PublicClient` | No | Custom public client | | `deviceId` | `string` | No | Device ID for access control (default: 32 zero bytes) | | `composeHash` | `string` | No | App compose hash (default: 32 zero bytes) | | `allowAnyDevice` | `boolean` | No | Allow any device (default: `false`) | | `disableUpgrades` | `boolean` | No | Make contract immutable (default: `false`) | | `skipPrerequisiteChecks` | `boolean` | No | Skip balance/chain checks (default: `false`) | | `minBalance` | `string` | No | Minimum ETH balance required (default: `"0.001"`) | | `timeout` | `number` | No | Transaction timeout in ms | | `retryOptions` | `object` | No | Retry configuration | **Callbacks:** | Callback | Description | | - | - | | `onTransactionStateChange` | Called when transaction state changes | | `onTransactionSubmitted` | Called when transaction is submitted to mempool | | `onTransactionConfirmed` | Called when transaction is confirmed on-chain | **Returns:** `DeployAppAuth` | Field | Type | Description | | - | - | - | | `appId` | `string` | Generated app ID (use in `commitCvmProvision`) | | `appAuthAddress` | `string` | Deployed contract address | | `deployer` | `string` | Deployer wallet address | | `transactionHash` | `string` | Deployment transaction hash | | `blockNumber` | `bigint?` | Block number of confirmation | | `gasUsed` | `bigint?` | Gas consumed | **Example:** ```typescript theme={"system"} import { deployAppAuth } from "@phala/cloud"; const result = await deployAppAuth({ chain: kmsInfo.chain, kmsContractAddress: kmsInfo.kms_contract_address, privateKey: "0xabc123...", deviceId: provision.device_id, composeHash: provision.compose_hash, onTransactionSubmitted: (hash) => { console.log(`Transaction submitted: ${hash}`); }, }); console.log(`App ID: ${result.appId}`); console.log(`Contract: ${result.appAuthAddress}`); ``` > [!WARNING] > > This function requires ETH on the target chain to pay for gas. The default minimum balance check is 0.001 ETH. *** ## safeDeployAppAuth Safe variant that returns a `SafeResult` instead of throwing on errors. # Error Handling Source: https://docs.phala.com/phala-cloud/references/cloud-js-sdk/error-handling Error classes, safe methods, and error formatting utilities in the Phala Cloud JS SDK. The `@phala/cloud` SDK provides a structured error hierarchy and two error handling patterns: throwing (default) and safe (result-based). This page covers **how to catch and handle errors** in the SDK. For the full list of `ERR-xxxx` error codes (returned by both the API and the CLI), see the [Error Codes Reference](/phala-cloud/references/error-codes). ## Error Hierarchy All API errors extend `PhalaCloudError`: ``` PhalaCloudError (base) ├── RequestError — HTTP/network errors ├── ValidationError — 422 validation errors (Pydantic) ├── AuthError — 401/403 authentication errors ├── BusinessError — 400/409 business logic errors │ └── ResourceError — Structured errors with ERR-xxxx codes ├── ServerError — 500+ server errors └── UnknownError — Network issues, unexpected errors ``` ## Catching Errors ### Using `instanceof` ```typescript theme={"system"} import { PhalaCloudError, ValidationError, AuthError, BusinessError, ResourceError, ServerError, } from "@phala/cloud"; try { await client.provisionCvm(payload); } catch (error) { if (error instanceof ResourceError) { // Structured error with error code console.error(`Error [${error.errorCode}]: ${error.message}`); error.suggestions?.forEach((s) => console.log("Suggestion:", s)); } else if (error instanceof ValidationError) { // Field-level validation errors error.validationErrors.forEach((e) => { console.error(`${e.field}: ${e.message}`); }); } else if (error instanceof AuthError) { console.error("Authentication failed:", error.message); } else if (error instanceof BusinessError) { console.error("Business error:", error.message); } else if (error instanceof ServerError) { console.error("Server error:", error.message); } } ``` ### Using Discriminator Properties Each error class has a boolean discriminator property: ```typescript theme={"system"} try { await client.provisionCvm(payload); } catch (error) { if (error.isValidationError) { // error is ValidationError } else if (error.isAuthError) { // error is AuthError } else if (error.isResourceError) { // error is ResourceError (extends BusinessError) } else if (error.isBusinessError) { // error is BusinessError } else if (error.isServerError) { // error is ServerError } else if (error.isUnknownError) { // error is UnknownError } } ``` ## Error Classes ### PhalaCloudError Base class for all errors. Properties: | Property | Type | Description | | - | - | - | | `message` | `string` | Error message | | `status` | `number` | HTTP status code | | `statusText` | `string` | HTTP status text | | `detail` | `string \| Record \| Array<{ msg: string }>` | Raw error detail from API | ### ValidationError Thrown on HTTP 422. Contains parsed field-level validation errors from FastAPI/Pydantic. | Property | Type | Description | | - | - | - | | `isValidationError` | `true` | Discriminator | | `validationErrors` | `ValidationErrorItem[]` | Parsed validation errors | Each `ValidationErrorItem`: ```typescript theme={"system"} { field: string; // e.g., "name", "resources.memory" message: string; // e.g., "String should have at least 4 characters" type: string; // e.g., "string_too_short", "greater_than_equal" context?: Record; // e.g., { min_length: 4 } } ``` ### AuthError Thrown on HTTP 401 or 403. | Property | Type | Description | | - | - | - | | `isAuthError` | `true` | Discriminator | ### BusinessError Thrown on HTTP 400, 409, and other 4xx errors. | Property | Type | Description | | - | - | - | | `isBusinessError` | `true` | Discriminator | ### ResourceError Extends `BusinessError`. Thrown for structured errors with `ERR-xxxx` codes. | Property | Type | Description | | - | - | - | | `isResourceError` | `true` | Discriminator | | `errorCode` | `string` | Error code (e.g., `"ERR-01-001"`) | | `structuredDetails` | `StructuredErrorDetail[]` | Field-level details | | `suggestions` | `string[]` | Suggested fixes | | `links` | `ErrorLink[]` | Links to documentation | ### ServerError Thrown on HTTP 500+. | Property | Type | Description | | - | - | - | | `isServerError` | `true` | Discriminator | ### UnknownError Thrown for network issues or unexpected errors. | Property | Type | Description | | - | - | - | | `isUnknownError` | `true` | Discriminator | ## Safe Methods Every action has a `safe` variant that returns `SafeResult` instead of throwing: ```typescript theme={"system"} const result = await client.safeProvisionCvm(payload); if (result.success) { console.log("Created:", result.data); } else { // result.error is PhalaCloudError if (result.error instanceof ValidationError) { result.error.validationErrors.forEach((e) => { console.error(`${e.field}: ${e.message}`); }); } } ``` All safe methods follow the naming convention `safe`: ```typescript theme={"system"} client.safeGetCurrentUser() client.safeGetCvmInfo({ id: "..." }) client.safeProvisionCvm(payload) client.safeDeleteCvm({ id: "..." }) // etc. ``` ## Formatting Utilities ### `formatValidationErrors(errors, options?)` Format validation errors for display: ```typescript theme={"system"} import { ValidationError, formatValidationErrors } from "@phala/cloud"; if (error instanceof ValidationError) { const formatted = formatValidationErrors(error.validationErrors, { numbered: true, indent: 2, showFields: true, }); console.error(formatted); } // Output: // 1. name: String should have at least 4 characters // 2. memory: Input should be greater than or equal to 1024 ``` Options: | Option | Type | Default | Description | | - | - | - | - | | `numbered` | `boolean` | `true` | Number each error | | `indent` | `number` | `2` | Indent size in spaces | | `showFields` | `boolean` | `true` | Show field names | ### `formatErrorMessage(error, options?)` Format any `PhalaCloudError` for display: ```typescript theme={"system"} import { PhalaCloudError, formatErrorMessage } from "@phala/cloud"; if (error instanceof PhalaCloudError) { console.error(formatErrorMessage(error)); } ``` Options: | Option | Type | Default | Description | | - | - | - | - | | `showFields` | `boolean` | `true` | Show field names in validation errors | | `showType` | `boolean` | `false` | Include error class name | ### `formatStructuredError(error, options?)` Format `ResourceError` with codes, details, suggestions, and links: ```typescript theme={"system"} import { ResourceError, formatStructuredError } from "@phala/cloud"; if (error instanceof ResourceError) { console.error(formatStructuredError(error)); } // Output: // Error [ERR-02-001]: The requested instance type does not exist // // Details: // - Instance type 'invalid' is not recognized // // Suggestions: // - Use a valid instance type: tdx.small, tdx.medium, or tdx.large // // Learn more: // - View available instance types: https://cloud.phala.com/instances ``` Options: | Option | Type | Default | Description | | - | - | - | - | | `showErrorCode` | `boolean` | `true` | Show error code in output | | `showSuggestions` | `boolean` | `true` | Show suggestions | | `showLinks` | `boolean` | `true` | Show documentation links | ## Event-Based Error Handling Listen to errors globally via the client event system: ```typescript theme={"system"} const client = createClient({ apiKey: "phak_your_api_key" }); client.on("error", (error) => { // Called for every API error, even when using safe methods if (error instanceof AuthError) { // Redirect to login } }); ``` ## Related * [SDK Overview](/phala-cloud/references/cloud-js-sdk/overview) — getting started * [Error Codes Reference](/phala-cloud/references/error-codes) — full list of `ERR-xxxx` codes # getAppEnvEncryptPubKey Source: https://docs.phala.com/phala-cloud/references/cloud-js-sdk/get-app-env-encrypt-pubkey Retrieve the KMS-managed encryption public key for encrypting environment variables ## getAppEnvEncryptPubKey `GET /kms/{kms}/pubkey/{app_id}` Retrieves the encryption public key managed by a KMS instance for a specific app. This key is used to encrypt environment variables before sending them to the Phala Cloud API. For **PHALA KMS**, the public key is returned directly in the [`provisionCvm`](/phala-cloud/references/cloud-js-sdk/provision-cvm) response as `app_env_encrypt_pubkey`. You only need to call this function explicitly when using **on-chain KMS** (ETHEREUM/BASE), where the app ID comes from deploying a contract. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `kms` | `string` | Yes | KMS ID or slug | | `app_id` | `string` | Yes | App ID (40 hex chars, optional `0x` prefix) | **Returns:** `GetAppEnvEncryptPubKey` | Field | Type | Description | | - | - | - | | `public_key` | `string` | RSA public key for encrypting env vars | | `signature` | `string` | KMS signature over the public key | **Example:** ```typescript theme={"system"} import { encryptEnvVars, parseEnvVars } from "@phala/cloud"; // Get the encryption key from KMS const { public_key } = await client.getAppEnvEncryptPubKey({ kms: "ethereum-mainnet", app_id: "0x1234abcd...", }); // Encrypt environment variables const envVars = parseEnvVars("API_KEY=secret\nDB_URL=postgres://..."); const encrypted = await encryptEnvVars(envVars, public_key); // Use the encrypted env in commitCvmProvision or updateCvmEnvs await client.commitCvmProvision({ app_id: "0x1234abcd...", compose_hash: provision.compose_hash, encrypted_env: encrypted, env_keys: ["API_KEY", "DB_URL"], }); ``` *** ## safeGetAppEnvEncryptPubKey Safe variant that returns a `SafeResult` instead of throwing on errors. # KMS Source: https://docs.phala.com/phala-cloud/references/cloud-js-sdk/kms List KMS contracts, inspect their nodes and verification anchors, and retrieve app encryption keys. `@phala/cloud` v0.4.0 models KMS resources by contract. A KMS contract groups equivalent KMS node replicas that share one root key. ## listKmsContracts `GET /kms` ```typescript theme={"system"} client.listKmsContracts( request?: ListKmsContractsRequest, ): Promise ``` **Parameters:** `page`, `page_size`, and `is_onchain` are optional filters in `request`. **Returns:** `ListKmsContractsResponse`, a paginated list of `KmsContractInfo` objects. Returns the available KMS contracts. This method always requests API version `2026-06-23`. ```typescript theme={"system"} const contracts = await client.listKmsContracts({ page: 1, page_size: 20, is_onchain: true, }); for (const contract of contracts.items) { console.log(contract.slug, contract.chain_id, contract.node_count); } ``` Each `KmsContractInfo` includes the contract `id`, `slug`, `contract_address`, `chain_id`, `node_count`, `k256_pubkey`, and `ca_pubkey`. For the off-chain Phala KMS, `contract_address` is `"phala"` and `chain_id` is `0`. ## getKmsContract `GET /kms/{slug}` ```typescript theme={"system"} client.getKmsContract( request: GetKmsContractRequest, ): Promise ``` **Parameters:** `request.slug` accepts a contract slug or `kc_`-prefixed contract ID. **Returns:** `KmsContractInfo` for the resolved contract. Returns one KMS contract by slug. A `kc_`-prefixed contract ID also resolves. ```typescript theme={"system"} const contract = await client.getKmsContract({ slug: "base" }); console.log(contract.contract_address); console.log(contract.k256_pubkey, contract.ca_pubkey); ``` Use the public keys as verification anchors when you validate KMS responses. ## listKmsContractNodes `GET /kms/{slug}/nodes` ```typescript theme={"system"} client.listKmsContractNodes( request: ListKmsContractNodesRequest, ): Promise ``` **Parameters:** `request.slug` accepts a contract slug or `kc_`-prefixed contract ID. **Returns:** `ListKmsContractNodesResponse` with the contract's node replicas. Returns the KMS node replicas under a contract, including each node's RPC URL and version. ```typescript theme={"system"} const nodes = await client.listKmsContractNodes({ slug: "base" }); for (const node of nodes.items) { console.log(node.slug, node.url, node.version); } ``` ## Legacy node methods ```typescript theme={"system"} client.getKmsList(request?: GetKmsListRequest): Promise client.getKmsInfo(request: GetKmsInfoRequest): Promise ``` `getKmsList()` accepts optional pagination and `is_onchain` filters. `getKmsInfo()` requires `request.kms_id`. They return the earlier node-centric KMS shapes. Both methods are deprecated and remain pinned to API version `2026-05-22`. Use `listKmsContracts()`, `getKmsContract()`, and `listKmsContractNodes()` for new code. ## getAppEnvEncryptPubKey `GET /kms/{kms}/pubkey/{appId}` ```typescript theme={"system"} client.getAppEnvEncryptPubKey( request: GetAppEnvEncryptPubKeyRequest, ): Promise ``` **Parameters:** `request.kms` is a KMS node ID or slug, and `request.app_id` is a 20-byte app ID with or without the `0x` prefix. **Returns:** `GetAppEnvEncryptPubKey` with `public_key` and `signature`. Returns the public key used to encrypt environment variables for an app. Fetch and verify this key before encrypting secrets. ```typescript theme={"system"} const key = await client.getAppEnvEncryptPubKey({ kms: "phala", app_id: "ff22c67f5d3b4c8a9e1f0a2b3c4d5e6f7a8b9c0d", }); console.log(key.public_key, key.signature); ``` ## nextAppIds `GET /kms/phala/next_app_id` ```typescript theme={"system"} client.nextAppIds(request?: NextAppIdsRequest): Promise ``` **Parameters:** `request.counts` requests 1 to 20 IDs and defaults to `1`. **Returns:** `NextAppIds` with the reserved `app_id` and `nonce` pairs. Reserves app IDs from the Phala KMS for deterministic provisioning. ```typescript theme={"system"} const reserved = await client.nextAppIds({ counts: 3 }); console.log(reserved.app_ids); ``` ## getKmsOnChainDetail `GET /kms/on-chain/{chain}` ```typescript theme={"system"} client.getKmsOnChainDetail( request: GetKmsOnChainDetailRequest, ): Promise ``` **Parameters:** `request.chain` is the chain name, such as `"base"` or `"ethereum"`. **Returns:** `GetKmsOnChainDetailResponse` with the chain and its KMS contracts. Returns the contracts, registered devices, OS images, and verification anchors for an on-chain KMS. ```typescript theme={"system"} const detail = await client.getKmsOnChainDetail({ chain: "base" }); for (const contract of detail.contracts) { console.log(contract.contract_address); console.log(contract.k256_pubkey, contract.ca_pubkey); } ``` ## Compute and verify mr\_config\_id Import the measurement helpers from `@phala/cloud`: ```typescript theme={"system"} getMrConfigId(input: MrConfigIdInput): Hex getMrConfigIdV1(composeHash: Hex): Hex verifyMrConfigId(mrConfigId: Hex, input: MrConfigIdInput): boolean ``` For `key_provider_type: "kms"`, set `key_provider_id` to the contract's `k256_pubkey`, not its `ca_pubkey`. ```typescript theme={"system"} import { getMrConfigId, verifyMrConfigId } from "@phala/cloud"; const input = { compose_hash: "0x<64-hex-characters>", app_id: "0xff22c67f5d3b4c8a9e1f0a2b3c4d5e6f7a8b9c0d", key_provider_type: "kms" as const, key_provider_id: "0x", }; const mrConfigId = getMrConfigId(input); const matches = verifyMrConfigId(mrConfigId, input); ``` `getMrConfigIdV1(composeHash)` remains available for the V1 compose-hash-only format. ## Related * [API Versioning](/phala-cloud/references/cloud-js-sdk/api-versioning) * [CVM Configuration](/phala-cloud/references/cloud-js-sdk/cvm-configuration) * [Error Handling](/phala-cloud/references/cloud-js-sdk/error-handling) # Nodes & Instance Types Source: https://docs.phala.com/phala-cloud/references/cloud-js-sdk/nodes-and-instance-types Functions for querying available TEE nodes and instance type configurations ## getAvailableNodes `GET /teepods/available` Returns available TEE nodes with capacity information and KMS details. **Parameters:** None **Returns:** `AvailableNodes` | Field | Type | Description | | - | - | - | | `tier` | `string` | Workspace tier | | `capacity` | `object` | Max limits: `max_instances`, `max_vcpu`, `max_memory`, `max_disk` | | `nodes` | `array` | Available nodes with resource info | | `kms_list` | `array` | Available KMS instances | **Example:** ```typescript theme={"system"} const available = await client.getAvailableNodes(); console.log(`Tier: ${available.tier}`); available.nodes.forEach(node => { console.log(`Node ${node.node}: ${node.region_identifier}`); }); ``` *** ## listAllInstanceTypeFamilies `GET /instance-types` Returns all instance type families and their configurations. **Parameters:** None **Returns:** `AllFamiliesResponse` — families with their instance types. **Example:** ```typescript theme={"system"} const families = await client.listAllInstanceTypeFamilies(); families.forEach(family => { console.log(`${family.name}:`); family.instance_types.forEach(t => { console.log(` ${t.slug}: ${t.vcpu} vCPU, ${t.memory_mb}MB`); }); }); ``` *** ## listFamilyInstanceTypes `GET /instance-types/{family}` Returns instance types for a specific family (e.g., `cpu`, `gpu`). **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `family` | `string` | Yes | Family name (e.g., `"cpu"`, `"gpu"`) | **Returns:** `FamilyInstanceTypesResponse` — instance types in the family. **Example:** ```typescript theme={"system"} const cpuTypes = await client.listFamilyInstanceTypes({ family: "cpu" }); ``` *** ## getOsImages `GET /os-images` Returns a paginated list of publicly available OS images. Each image includes metadata like the image hash, GPU requirement flag, and whether it is a dev image. Use this when you need the full catalog of images with pagination support. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `page` | `number` | No | Page number (default: 1) | | `page_size` | `number` | No | Items per page | | `is_dev` | `boolean` | No | Filter for dev images only | **Returns:** `GetOsImagesResponse` | Field | Type | Description | | - | - | - | | `items` | `array` | OS images with `name`, `slug`, `version`, `os_image_hash`, `is_dev`, `requires_gpu` | | `total` | `number` | Total number of images | | `page` | `number` | Current page | | `page_size` | `number` | Items per page | | `pages` | `number` | Total pages | **Example:** ```typescript theme={"system"} const images = await client.getOsImages({ page: 1, page_size: 10 }); images.items.forEach(img => { console.log(`${img.name} v${img.version} (hash: ${img.os_image_hash})`); }); ``` # Cloud JS SDK Source: https://docs.phala.com/phala-cloud/references/cloud-js-sdk/overview JavaScript/TypeScript SDK for Phala Cloud API — manage CVMs, deployments, and resources programmatically. The `@phala/cloud` SDK provides a type-safe JavaScript/TypeScript client for the Phala Cloud API. It includes built-in API versioning, Zod schema validation, and comprehensive error handling. ## Installation ```bash theme={"system"} npm install @phala/cloud ``` ```bash theme={"system"} pnpm add @phala/cloud ``` ```bash theme={"system"} yarn add @phala/cloud ``` ## Quick Start ```typescript theme={"system"} import { createClient } from "@phala/cloud"; const client = createClient({ apiKey: "phak_your_api_key" }); // Get current user info const user = await client.getCurrentUser(); console.log(user.user.username); // List all CVMs const cvms = await client.getCvmList(); console.log(cvms.items); ``` ## Client Creation ### `createClient(config?)` Creates a full-featured client with all action methods. ```typescript theme={"system"} import { createClient } from "@phala/cloud"; // Minimal — reads API key from PHALA_CLOUD_API_KEY env var const client = createClient(); ``` ```typescript theme={"system"} // Explicit configuration const client = createClient({ apiKey: "phak_your_api_key", baseURL: "https://cloud-api.phala.com/api/v1", version: "2026-06-23", timeout: 60000, }); ``` ### Configuration Options | Option | Type | Default | Description | | - | - | - | - | | `apiKey` | `string` | `PHALA_CLOUD_API_KEY` env var | API key for authentication | | `baseURL` | `string` | `https://cloud-api.phala.com/api/v1` | API base URL (or `PHALA_CLOUD_API_PREFIX` env var) | | `version` | `ApiVersion` | `"2026-06-23"` | [API version](/phala-cloud/references/cloud-js-sdk/api-versioning) to use | | `timeout` | `number` | `60000` | Request timeout in milliseconds | | `useCookieAuth` | `boolean` | `false` | Use cookie-based auth instead of API key | | `headers` | `Record` | — | Additional request headers | | `onResponseError` | `function` | — | Custom response error handler | ### User-Agent In Node.js, Bun, Deno, and Cloudflare Workers, the client sends `User-Agent: phala-cloud-sdk-js/ /`, where the runtime token is `node/`, `bun/`, `deno/`, or `workerd`. In browsers it sends no `User-Agent`. To use your own value, pass a `User-Agent` entry in `headers`. A header you supply overrides the default. ```typescript theme={"system"} const client = createClient({ apiKey: "phak_your_api_key", headers: { "User-Agent": "my-automation/2.0" }, }); ``` ### Tree-Shaking with `createBaseClient` For smaller bundles, use `createBaseClient` with individual action imports: ```typescript theme={"system"} import { createBaseClient, getCurrentUser, getCvmList } from "@phala/cloud"; const client = createBaseClient({ apiKey: "phak_your_api_key" }); // Call actions as standalone functions const user = await getCurrentUser(client); const cvms = await getCvmList(client); ``` ### Extending the Base Client `createClient` already includes all built-in actions as methods. The `.extend()` method on `createBaseClient` is useful when you want to selectively include actions (for tree-shaking) or add your own custom actions: ```typescript theme={"system"} import { createBaseClient, getCurrentUser, getCvmList } from "@phala/cloud"; const client = createBaseClient({ apiKey: "phak_your_api_key" }).extend({ getCurrentUser, getCvmList, }); // Only the actions you included are available as methods const user = await client.getCurrentUser(); ``` ## Available Actions Actions marked with **V** return different response types depending on the client's [API version](/phala-cloud/references/cloud-js-sdk/api-versioning). ### Authentication & User | Method | Description | | - | - | | `getCurrentUser()` **V** | Get current user, workspace, and credits info | ### CVM Query | Method | Description | | - | - | | `getCvmList(request?)` **V** | List all CVMs (paginated) | | `getCvmInfo(request)` **V** | Get single CVM details | | `getCvmStats(request)` | Get CVM system stats | | `getCvmNetwork(request)` | Get CVM network info | | `getCvmState(request)` | Get CVM current state | | `getCvmDockerCompose(request)` | Get Docker Compose config | | `getCvmComposeFile(request)` | Get compose file content | | `getCvmContainersStats(request)` | Get container stats | | `getCvmAttestation(request)` | Get TEE attestation | | `getCvmPreLaunchScript(request)` | Get pre-launch script | | `getCvmStatusBatch(request)` | Get status of multiple CVMs | | `getCvmUserConfig(request)` | Get user-level CVM config | | `checkCvmIsAllowed(request)` | Check on-chain deployment allowance | To read CVM logs, use the standalone `fetchCvmLogs` and `followCvmLogs` functions. See [CVM Query](/phala-cloud/references/cloud-js-sdk/cvm-query#read-cvm-logs). ### CVM Lifecycle | Method | Description | | - | - | | `provisionCvm(request)` | Create a new CVM | | `commitCvmProvision(request)` | Commit a CVM provision | | `startCvm(request)` | Start a CVM | | `stopCvm(request)` | Stop a CVM | | `shutdownCvm(request)` | Shutdown a CVM | | `restartCvm(request)` | Restart a CVM | | `deleteCvm(request)` | Delete a CVM | | `replicateCvm(request)` | Create a copy of a CVM | | `watchCvmState(request)` | Watch CVM state changes via SSE | ### CVM Configuration | Method | Description | | - | - | | `updateCvmEnvs(request)` | Update environment variables | | `updateDockerCompose(request)` | Update Docker Compose config | | `updatePreLaunchScript(request)` | Update pre-launch script | | `updateCvmResources(request)` | Update resource allocation | | `updateCvmVisibility(request)` | Update visibility settings | | `updateOsImage(request)` | Update OS image | | `getAvailableOsImages(request?)` | List available OS images | | `provisionCvmComposeFileUpdate(request)` | Provision a compose file update | | `commitCvmComposeFileUpdate(request)` | Commit a compose file update | | `patchCvm(request)` | Unified partial CVM update | | `confirmCvmPatch(request)` | Confirm on-chain KMS patch (Phase 2) | | `commitCvmUpdate(request)` | Commit update with token (multisig) | | `refreshCvmInstanceId(request)` | Refresh a CVM instance ID | | `refreshCvmInstanceIds(request)` | Batch refresh CVM instance IDs | ### Apps | Method | Description | | - | - | | `getAppList(request?)` **V** | List apps | | `getAppInfo(request)` **V** | Get app details | | `getAppCvms(request)` **V** | List CVMs for an app | | `createAppInstance(request)` **V** | Create another instance for an app | | `getAppRevisions(request)` | List app revision history | | `getAppRevisionDetail(request)` | Get app revision details | | `getAppFilterOptions()` | Get available filter options for app list | | `getAppAttestation(request)` | Get app TEE attestation | | `getAppDeviceAllowlist(request)` | Get app device allowlist status | | `checkAppIsAllowed(request)` | Check on-chain app allowance | | `checkAppCvmsIsAllowed(request)` | Batch check app CVMs allowance | ### Workspace | Method | Description | | - | - | | `listWorkspaces(request?)` | List workspaces | | `getWorkspace(request)` | Get workspace details | | `getWorkspaceNodes(request)` | Get workspace nodes | | `getWorkspaceQuotas(request)` | Get workspace resource quotas | ### Nodes, Instance Types & OS Images | Method | Description | | - | - | | `getAvailableNodes()` | List available TEE nodes | | `getCvmCreateResources()` | Get the CVM creation resource graph | | `listAllInstanceTypeFamilies()` | List all instance type families | | `listFamilyInstanceTypes(request)` | List instance types in a family | | `getOsImages(request?)` | List public OS images (paginated) | ### KMS (Key Management) | Method | Description | | - | - | | `listKmsContracts(request?)` | List KMS contracts | | `getKmsContract(request)` | Get a KMS contract by slug or contract ID | | `listKmsContractNodes(request)` | List node replicas under a KMS contract | | `getKmsInfo(request)` | Get legacy node-centric KMS info (deprecated) | | `getKmsList(request?)` | List legacy node-centric KMS instances (deprecated) | | `getKmsOnChainDetail(request)` | Get on-chain KMS details and verification anchors | | `getAppEnvEncryptPubKey(request)` | Get env encryption public key | | `nextAppIds(request?)` | Get next available app IDs | ### SSH Keys | Method | Description | | - | - | | `listSshKeys()` | List SSH keys | | `createSshKey(request)` | Add an SSH key | | `deleteSshKey(request)` | Remove an SSH key | | `importGithubProfileSshKeys(request)` | Import SSH keys from GitHub profile | | `syncGithubSshKeys()` | Sync SSH keys from GitHub | ### On-Chain Contract Actions These functions interact directly with the blockchain, not the Phala Cloud API. They require ETH for gas (write operations) or a public client (read operations). | Method | Description | | - | - | | `deployAppAuth(request)` | Deploy an AppAuth smart contract | | `addComposeHash(request)` | Register a compose hash on-chain | | `addDevice(request)` | Add a device to the on-chain allowlist | | `removeDevice(request)` | Remove a device from the on-chain allowlist | | `setAllowAnyDevice(request)` | Toggle the allow-any-device flag | | `getAllowedDevices(request)` | Query the on-chain device allowlist | | `checkDeviceAllowed(request)` | Check if a device is allowed on-chain | | `checkComposeHashAllowed(request)` | Check if a compose hash is allowed on-chain | | `checkOnChainPrerequisites(request)` | Batch check all on-chain prerequisites | ## Measurement Utilities Import measurement helpers from `@phala/cloud`: | Function | Description | | - | - | | `getMrConfigId(input)` | Compute a V2 `mr_config_id` from the compose hash, app ID, and key provider | | `getMrConfigIdV1(composeHash)` | Compute the V1 compose-hash-only format | | `verifyMrConfigId(mrConfigId, input)` | Verify a V2 `mr_config_id` | See [KMS](/phala-cloud/references/cloud-js-sdk/kms) for examples. ## Safe Methods Every action has a `safe` variant that returns a `SafeResult` instead of throwing: ```typescript theme={"system"} const result = await client.safeGetCvmInfo({ id: "cvm-abc123" }); if (result.success) { console.log(result.data); } else { console.error(result.error.message); } ``` The `SafeResult` type: ```typescript theme={"system"} type SafeResult = | { success: true; data: T; error?: never } | { success: false; data?: never; error: E }; ``` ## Custom Schema Validation Every action accepts an optional `schema` parameter for custom response validation. For actions **without** required request parameters, pass `schema` as the first argument: ```typescript theme={"system"} import { z } from "zod"; const MySchema = z.object({ username: z.string() }); const user = await client.getCurrentUser({ schema: MySchema }); // user is typed as { username: string } // Disable validation (returns unknown) const raw = await client.getCurrentUser({ schema: false }); ``` For actions **with** required request parameters, pass `schema` as the second argument: ```typescript theme={"system"} const MyCvmSchema = z.object({ id: z.string(), name: z.string() }); const cvm = await client.getCvmInfo({ id: "cvm-abc123" }, { schema: MyCvmSchema }); ``` ## Event Handling Listen for error events across all API calls: ```typescript theme={"system"} client.on("error", (error) => { console.error("API Error:", error.message); }); // Listen once client.once("error", (error) => { console.error("First error:", error.message); }); // Remove listener client.off("error", handler); ``` ## Debug Logging Enable detailed cURL-format request/response logging: ```bash theme={"system"} DEBUG=phala::api-client node your-script.js ``` ## Environment Variables | Variable | Description | | - | - | | `PHALA_CLOUD_API_KEY` | API key for authentication | | `PHALA_CLOUD_API_PREFIX` | Base URL for the API | ## Webhook Signature Verification The SDK provides utilities for verifying webhook signatures, exported from a separate subpath to avoid bundling `node:crypto` into browser builds: ```typescript theme={"system"} import { verifyWebhookSignature, parseWebhookEvent } from "@phala/cloud/webhook"; // Verify a single signature const isValid = verifyWebhookSignature({ secret: "whsec_...", timestamp: req.headers["x-webhook-timestamp"], body: rawBody, signature: req.headers["x-webhook-signature"], }); // Or parse and verify in one step const event = parseWebhookEvent({ headers: req.headers, body: rawBody, secret: "whsec_...", }); ``` See [Webhooks](/phala-cloud/references/webhooks) for full payload format and delivery behavior. ## Related * [API Versioning](/phala-cloud/references/cloud-js-sdk/api-versioning) — version management and migration * [Schema Reference](/phala-cloud/references/cloud-js-sdk/schema-reference) — response schema details per version * [Error Handling](/phala-cloud/references/cloud-js-sdk/error-handling) — error classes and safe methods * [Webhooks](/phala-cloud/references/webhooks) — webhook events, signatures, and delivery * [Cloud API Reference](/phala-cloud/phala-cloud-api/overview) — full REST API docs # provisionCvm Source: https://docs.phala.com/phala-cloud/references/cloud-js-sdk/provision-cvm Provision a new CVM — first phase of the two-phase deployment flow ## provisionCvm `POST /cvms` Provisions a new CVM. This is the **first phase** of the two-phase deployment flow — call [`commitCvmProvision`](/phala-cloud/references/cloud-js-sdk/commit-cvm-provision) to finalize. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `name` | `string` | Yes | CVM name (5-63 chars, must start with a letter) | | `compose_file` | `object` | Yes, unless `compose_file_raw` is sent | Compose file configuration (see below) | | `instance_type` | `string` | No | Instance type (default: `"tdx.small"`) | | `node` | `string` | No | Physical node name for deployment | | `region` | `string` | No | Region filter | | `image` | `string` | No | OS image name | | `disk_size` | `number` | No | Disk size in GB | | `kms` | `string` | No | KMS type: `"PHALA"` (default), `"ETHEREUM"`, or `"BASE"` | | `kms_contract` | `string` | No | KMS contract address (on-chain KMS only) | | `env_keys` | `string[]` | No | Allowed environment variable keys | | `nonce` | `number` | No | Nonce for deterministic `app_id` (PHALA KMS only) | | `app_id` | `string` | No | Expected `app_id` (must match nonce) | | `listed` | `boolean` | No | List CVM in public directory | | `init_scripts` | `"docker_cleanup"[]` | No | Platform init scripts the CVM runs on every boot: `docker_cleanup` (needs dstack OS 0.6.x, `ext4` storage and the `docker-compose` runner). The list is the whole set. See [Init scripts](/phala-cloud/cvm/advanced-settings#init-scripts). | | `launch_token` | `string` | No | Launch token, at least 32 bytes, that the CVM must have on every boot. See [Launch Token](/phala-cloud/cvm/launch-token). | | `generate_launch_token` | `boolean` | No | Have Phala Cloud generate the launch token for a new app, or use the app's existing token. A new token is returned once, as `launch_token` in the commit response. | | `annotations` | `Record` | No | Host-side settings for tools on the node, not measured. Needs a feature flag (`ERR-03-049` without it) and dstack VMM 0.6.1 or newer on the node (`ERR-03-050`). See [Annotations](/phala-cloud/cvm/advanced-settings#annotations). | | `compose_file_raw` | `string` | No | A whole app-compose JSON file as one string, sent instead of `compose_file`. Needs a feature flag. Phala Cloud parses it with the same rules and writes it the same way, so the compose hash comes from that output, not from your bytes. See [Raw app-compose input](/phala-cloud/cvm/advanced-settings#raw-app-compose-input). | **`compose_file` object:** | Field | Type | Required | Description | | - | - | - | - | | `docker_compose_file` | `string` | Yes | Docker Compose YAML content | | `allowed_envs` | `string[]` | No | Env var keys the CVM may receive | | `pre_launch_script` | `string` | No | Script to run before containers start | | `gateway_enabled` | `boolean` | No | Enable gateway/proxy | | `kms_enabled` | `boolean` | No | Enable KMS integration | | `public_logs` | `boolean` | No | Make container logs public | | `public_sysinfo` | `boolean` | No | Make system info public | **Returns:** `ProvisionCvm` | Field | Type | Description | | - | - | - | | `compose_hash` | `string` | Hash of the compose configuration — pass to `commitCvmProvision` | | `app_id` | `string?` | App ID (only for PHALA KMS) | | `app_env_encrypt_pubkey` | `string?` | Encryption public key (only for PHALA KMS) | | `kms_id` | `string?` | KMS instance ID | | `kms_info` | `KmsInfo?` | KMS details | | `device_id` | `string?` | Device ID for on-chain KMS | | `fmspc` | `string?` | FMSPC of the selected node | | `os_image_hash` | `string?` | OS image hash | | `instance_type` | `string?` | Selected instance type | | `node_id` | `number?` | Selected node ID | **Example — PHALA KMS (default):** ```typescript theme={"system"} import { createClient, encryptEnvVars, parseEnvVars } from "@phala/cloud"; const client = createClient(); const provision = await client.provisionCvm({ name: "my-app", instance_type: "tdx.small", compose_file: { docker_compose_file: composeYaml, allowed_envs: ["API_KEY", "SECRET"], }, }); // PHALA KMS returns app_id and pubkey directly const encrypted = await encryptEnvVars(envVars, provision.app_env_encrypt_pubkey!); await client.commitCvmProvision({ app_id: provision.app_id!, compose_hash: provision.compose_hash, encrypted_env: encrypted, env_keys: ["API_KEY", "SECRET"], }); ``` **Example — On-chain KMS (ETHEREUM/BASE):** ```typescript theme={"system"} import { deployAppAuth } from "@phala/cloud"; // Step 1: Provision — reserves the CVM but does not start it const provision = await client.provisionCvm({ name: "my-app", compose_file: { docker_compose_file: composeYaml }, kms: "ETHEREUM", }); // Step 2: Deploy an AppAuth contract to obtain an app_id const deployed = await deployAppAuth({ chain: provision.kms_info!.chain, rpcUrl: "https://...", kmsContractAddress: provision.kms_info!.kms_contract_address, privateKey: "0x...", deviceId: provision.device_id, composeHash: provision.compose_hash, }); // Step 3: Commit — finalizes the deployment and starts the CVM await client.commitCvmProvision({ app_id: deployed.appId, compose_hash: provision.compose_hash, kms_id: provision.kms_id!, contract_address: deployed.appAuthAddress, deployer_address: deployed.deployer, }); ``` For the full on-chain KMS flow including environment encryption and wallet setup, see [Deploying with Onchain KMS](/phala-cloud/key-management/deploying-with-onchain-kms). > [!NOTE] > > The combined size of `docker_compose_file` and `pre_launch_script` must not exceed 200KB. *** ## safeProvisionCvm Safe variant that returns a `SafeResult` instead of throwing on errors. ```typescript theme={"system"} const result = await client.safeProvisionCvm({ ... }); if (result.success) { console.log(result.data.compose_hash); } else { console.error(result.error); } ``` # Schema Reference Source: https://docs.phala.com/phala-cloud/references/cloud-js-sdk/schema-reference Zod schema definitions for Phala Cloud API responses — CVM info, user info, and pagination schemas across API versions. The `@phala/cloud` SDK uses [Zod](https://zod.dev) schemas for runtime validation of all API responses. API version `2026-06-23` is the default. Its CVM and app endpoints use the `V20260522` schemas, while its KMS endpoints use the contract-centric schemas documented on the [KMS page](/phala-cloud/references/cloud-js-sdk/kms). ## Schema Validation By default, every action validates the API response against the version-specific Zod schema. You can customize this: ```typescript theme={"system"} import { z } from "zod"; // Default: uses built-in schema const user = await client.getCurrentUser(); // Custom schema: validate with your own Zod schema const MySchema = z.object({ username: z.string() }); const user = await client.getCurrentUser({ schema: MySchema }); // No validation: returns raw response as unknown const raw = await client.getCurrentUser({ schema: false }); ``` ## Version `2026-01-21` ### CurrentUserV20260121 Three-layer user response with separate user, workspace, and credits objects. ```typescript theme={"system"} { user: { username: string; email: string; role: "admin" | "user"; avatar: string; email_verified: boolean; totp_enabled: boolean; has_backup_codes: boolean; flag_has_password: boolean; }; workspace: { id: string; name: string; slug: string | null; tier: string; role: string; avatar?: string | null; }; credits: { balance: string | number; // Balance: pays for CVMs, GPU instances, and Private AI granted_balance: string | number; // Gifted credits: CVMs and GPU instances only, used first is_post_paid: boolean; // CVM usage beyond Balance is charged to the card outstanding_amount: string | number | null; // what the workspace owes }; } ``` ### CvmInfoV20260121 Compact CVM info returned in list endpoints. ```typescript theme={"system"} { id: string; // Hashed CVM ID name: string; app_id?: string | null; vm_uuid?: string | null; instance_id?: string | null; resource: CvmResourceInfoV20260121; node_info?: NodeRef | null; os?: CvmOsInfoV20260121 | null; kms_type?: "phala" | "ethereum" | "base" | "legacy" | null; kms_info?: CvmKmsInfoV20260121 | null; status: string; progress?: CvmProgressInfoV20260121 | null; compose_hash?: string | null; gateway: CvmGatewayInfoV20260121; services: Array>; endpoints?: Array<{ app: string; instance: string }> | null; public_logs?: boolean; public_sysinfo?: boolean; public_tcbinfo?: boolean; gateway_enabled?: boolean; secure_time?: boolean; listed: boolean; storage_fs?: string; workspace?: WorkspaceRef | null; creator?: UserRef | null; } ``` ### CvmInfoDetailV20260121 Extended CVM info returned by single-CVM endpoints. The `logs` object contains the log URLs described below. ```typescript theme={"system"} CvmInfoV20260121 & { compose_file?: Record | string | null; logs?: CvmLogUrlsV20260121; } ``` ### CvmLogUrlsV20260121 The `serial`, `stdout`, and `stderr` fields are complete presigned URLs for the corresponding CVM logs. Phala Cloud signs them for the requesting user. Each signature is valid for 5 minutes and is checked only when the connection opens. A stream lasts at most 1 hour. If a request returns `401` (`ERR-17-002` or `ERR-17-003`), fetch fresh URLs with a CVM detail request and retry. Do not modify the signature parameters. See [Fetch Logs over HTTP](/phala-cloud/monitoring/log-api) for query parameters, reconnect behavior, and errors. ```typescript theme={"system"} { serial?: string | null; // Complete presigned URL for serial logs stdout?: string | null; // Complete presigned URL for CVM stdout stderr?: string | null; // Complete presigned URL for CVM stderr container_log_base?: string | null; // Container URL base with no query string auth_query?: string | null; // Query string that authorizes container log requests } ``` A container log URL is `{container_log_base}/{container_name}?{auth_query}`. All log fields are `null` when the requester cannot read logs. The container fields are also `null` when `public_logs` is `false` (container requests are rejected with `ERR-17-006`) or the CVM has no `vm_uuid`. Node logs are not affected by `public_logs`. Clients should accept `auth_query` being omitted or `null`. In the legacy `2025-10-28` response, `syslog_endpoint` is a complete presigned serial log URL, not a URL base. ### PaginatedCvmInfosV20260121 Paginated list of CVMs. ```typescript theme={"system"} { items: CvmInfoV20260121[]; total: number; page: number; page_size: number; pages: number; } ``` ### Nested Objects #### CvmResourceInfoV20260121 ```typescript theme={"system"} { instance_type?: string | null; vcpu?: number | null; memory_in_gb?: number | null; disk_in_gb?: number | null; gpus?: number | null; compute_billing_price?: string | null; billing_period?: "skip" | "hourly" | "monthly" | null; } ``` #### CvmOsInfoV20260121 ```typescript theme={"system"} { name?: string | null; version?: string | null; is_dev?: boolean | null; os_image_hash?: string | null; } ``` #### CvmKmsInfoV20260121 ```typescript theme={"system"} { chain_id?: number | null; dstack_kms_address?: string | null; dstack_app_address?: string | null; deployer_address?: string | null; rpc_endpoint?: string | null; encrypted_env_pubkey?: string | null; } ``` #### CvmProgressInfoV20260121 ```typescript theme={"system"} { target?: string | null; started_at?: string | null; correlation_id?: string | null; } ``` #### CvmGatewayInfoV20260121 ```typescript theme={"system"} { base_domain?: string | null; cname?: string | null; } ``` #### NodeRef ```typescript theme={"system"} { object_type: "node"; id?: number | null; name?: string | null; region?: string | null; device_id?: string | null; ppid?: string | null; status?: string | null; version?: string | null; } ``` #### WorkspaceRef ```typescript theme={"system"} { object_type: "workspace"; id: string; name: string; slug?: string | null; avatar_url?: string | null; } ``` #### UserRef ```typescript theme={"system"} { object_type: "user"; id?: string | null; username?: string | null; avatar_url?: string | null; } ``` ## Version `2025-10-28` (Legacy) ### CurrentUserV20251028 Flat user response. ```typescript theme={"system"} { username: string; email: string; credits: number; granted_credits: number; avatar: string; team_name: string; team_tier: string; } ``` ### KmsInfoLegacy Legacy KMS information. Used in `CvmInfoV20251028` and `CvmDetailV20251028`. ```typescript theme={"system"} { id: string; slug: string | null; url: string; version: string; chain_id: number | null; kms_contract_address: string | null; // Hex address gateway_app_id: string | null; // Hex } ``` ### CvmInfoV20251028 Legacy CVM info with nested `hosted` VM object. ```typescript theme={"system"} { hosted: { id: string; name: string; status: string; uptime: string; app_url: string | null; app_id: string; instance_id: string | null; configuration?: any; exited_at: string | null; boot_progress: string | null; boot_error: string | null; shutdown_progress: string | null; image_version: string | null; }; name: string; managed_user: { id: number; username: string } | null; node: { id: number; name: string; region_identifier?: string | null } | null; listed: boolean; status: string; in_progress: boolean; dapp_dashboard_url: string | null; syslog_endpoint: string | null; allow_upgrade: boolean; project_id: string | null; project_type: string | null; billing_period: string | null; kms_info: KmsInfoLegacy | null; vcpu: number | null; memory: number | null; disk_size: number | null; gateway_domain: string | null; public_urls: Array<{ app: string; instance: string }>; machine_info?: { vcpu: number; memory: number; disk_size: number; gpu_count: number } | null; updated_at?: string | null; } ``` ### CvmDetailV20251028 Legacy CVM detail for single-CVM endpoints. ```typescript theme={"system"} { id: number; name: string; status: string; in_progress: boolean; teepod_id: number | null; teepod?: { id: number; name: string; region_identifier?: string | null } | null; app_id: string; vm_uuid: string | null; instance_id: string | null; vcpu: number; memory: number; disk_size: number; base_image: string | null; encrypted_env_pubkey: string | null; listed: boolean; instance_type?: string | null; public_sysinfo: boolean; public_logs: boolean; kms_info?: KmsInfoLegacy | null; public_urls: Array<{ app: string; instance: string }>; gateway_domain?: string | null; machine_info?: { vcpu: number; memory: number; disk_size: number; gpu_count: number } | null; } ``` ### PaginatedCvmInfosV20251028 ```typescript theme={"system"} { items: CvmInfoV20251028[]; total: number; page: number; page_size: number; pages: number; } ``` ## Importing Schemas All Zod schemas are exported from `@phala/cloud`: ```typescript theme={"system"} import { // v2026-01-21 CvmInfoV20260121Schema, CvmInfoDetailV20260121Schema, PaginatedCvmInfosV20260121Schema, CurrentUserV20260121Schema, // v2025-10-28 CvmInfoV20251028Schema, CvmDetailV20251028Schema, PaginatedCvmInfosV20251028Schema, CurrentUserV20251028Schema, } from "@phala/cloud"; ``` Use them for custom validation or to build derivative schemas: ```typescript theme={"system"} import { CvmInfoV20260121Schema } from "@phala/cloud"; // Pick only the fields you need const MyCvmSchema = CvmInfoV20260121Schema.pick({ id: true, name: true, status: true, }); const cvm = await client.getCvmInfo({ id: "cvm-abc123" }, { schema: MyCvmSchema }); // cvm: { id: string; name: string; status: string } ``` ## Related * [API Versioning](/phala-cloud/references/cloud-js-sdk/api-versioning) — how versions affect response types * [Error Handling](/phala-cloud/references/cloud-js-sdk/error-handling) — error schemas and handling # SSH Keys Source: https://docs.phala.com/phala-cloud/references/cloud-js-sdk/ssh-keys Functions for managing SSH keys used for CVM access ## listSshKeys `GET /user/ssh-keys` Returns all SSH keys associated with the authenticated user. **Parameters:** None **Returns:** Array of `SshKey` objects. | Field | Type | Description | | - | - | - | | `id` | `string` | Key identifier | | `name` | `string` | Key name | | `public_key` | `string` | Public key content | | `fingerprint` | `string` | Key fingerprint | | `created_at` | `string` | Creation timestamp | **Example:** ```typescript theme={"system"} const keys = await client.listSshKeys(); keys.forEach(k => console.log(k.name, k.fingerprint)); ``` *** ## createSshKey `POST /user/ssh-keys` Adds a new SSH public key to the user's account. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `name` | `string` | Yes | Display name for the key | | `public_key` | `string` | Yes | SSH public key content | **Returns:** `SshKey` — the created key with computed fingerprint. **Example:** Replace the sample public key with your own key before using it for access. ```typescript theme={"system"} const key = await client.createSshKey({ name: "my-laptop", public_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAID4dR/9d26lbwH5ViDEJgWZqaHI6/Mlr8QyTfE6w8ANk docs-example", }); console.log(key.fingerprint); ``` *** ## deleteSshKey `DELETE /user/ssh-keys/{key_id}` Removes an SSH key from the user's account. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | Key identifier | **Returns:** `void` *** ## importGithubProfileSshKeys `POST /user/ssh-keys/import/github-profile` Imports SSH public keys from a GitHub user's profile. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `github_username` | `string` | Yes | GitHub username | **Returns:** `ImportGithubProfileResponse` — import results with count of keys added. **Example:** ```typescript theme={"system"} const result = await client.importGithubProfileSshKeys({ github_username: "octocat", }); console.log(`Imported ${result.imported} keys`); ``` *** ## syncGithubSshKeys `POST /user/ssh-keys/sync/github` Syncs SSH keys with the authenticated user's linked GitHub account. **Parameters:** None **Returns:** `SyncGithubSshKeysResponse` — sync results. *** ## getCvmSshKeys `GET /cvms/{cvmId}/ssh-keys` Returns the SSH keys configured for a CVM and a `restart_required` flag. This is the stored configuration; use `getCvmUserConfig` to inspect the running VM's configuration. ```typescript theme={"system"} import { createClient, getCvmSshKeys } from "@phala/cloud"; const client = createClient(); const result = await getCvmSshKeys(client, { id: "my-app" }); console.log(result.keys, result.restart_required); ``` ## updateCvmSshKeys `PUT /cvms/{cvmId}/ssh-keys` Replaces the configured key set. `ssh_key_ids` is required. Optional `usernames` resolve to members' keys and are added to the set. Keys take effect at the next power-on; set `apply_now` to restart the CVM and apply them immediately. ```typescript theme={"system"} import { createClient, updateCvmSshKeys } from "@phala/cloud"; const client = createClient(); const result = await updateCvmSshKeys(client, { id: "my-app", ssh_key_ids: [process.env.SSH_KEY_ID!], apply_now: false, }); console.log(result.restart_required); ``` Both actions also have safe variants: `safeGetCvmSshKeys` and `safeUpdateCvmSshKeys`. # updateCvmEnvs Source: https://docs.phala.com/phala-cloud/references/cloud-js-sdk/update-cvm-envs Update encrypted environment variables for a CVM ## updateCvmEnvs `PATCH /cvms/{cvmId}/envs` Updates the encrypted environment variables for a running CVM. This function uses a **two-phase flow** when the set of allowed env keys changes on a CVM with on-chain KMS: 1. **Phase 1:** Call with `encrypted_env` and `env_keys`. If the env keys changed and the CVM uses on-chain KMS, the API returns `precondition_required` with a `compose_hash`. 2. **Register on-chain:** Call [`addComposeHash`](/phala-cloud/references/cloud-js-sdk/add-compose-hash) to register the new compose hash on the blockchain. 3. **Phase 2:** Retry the call with the original parameters plus `compose_hash` and `transaction_hash`. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier | | `encrypted_env` | `string` | Yes | Hex-encoded encrypted environment variables | | `env_keys` | `string[]` | No | Allowed environment variable keys | | `compose_hash` | `string` | No | Compose hash (Phase 2, after on-chain registration) | | `transaction_hash` | `string` | No | On-chain transaction hash (Phase 2) | **Returns:** Union of two possible responses: **Success (`in_progress`):** | Field | Type | Description | | - | - | - | | `status` | `"in_progress"` | Update accepted | | `message` | `string` | Status message | | `correlation_id` | `string` | Tracking ID | | `allowed_envs_changed` | `boolean` | Whether env keys changed | **Precondition required (`precondition_required`):** | Field | Type | Description | | - | - | - | | `status` | `"precondition_required"` | On-chain registration needed | | `message` | `string` | Instructions | | `compose_hash` | `string` | Hash to register on-chain | | `app_id` | `string` | App ID for contract interaction | | `device_id` | `string` | Device ID | | `kms_info` | `KmsInfo` | KMS details for chain interaction | **Example — PHALA KMS (single phase):** ```typescript theme={"system"} import { encryptEnvVars, parseEnvVars } from "@phala/cloud"; const envVars = parseEnvVars("API_KEY=secret\nDB_URL=postgres://..."); const pubkey = cvm.encrypted_env_pubkey; const encrypted = await encryptEnvVars(envVars, pubkey); const result = await client.updateCvmEnvs({ id: "my-app", encrypted_env: encrypted, env_keys: ["API_KEY", "DB_URL"], }); // result.status === "in_progress" ``` **Example — On-chain KMS (two phases):** ```typescript theme={"system"} // Phase 1: attempt update const result = await client.updateCvmEnvs({ id: "my-app", encrypted_env: encrypted, env_keys: ["API_KEY", "NEW_VAR"], }); if (result.status === "precondition_required") { // Register compose hash on-chain const receipt = await addComposeHash({ chain: result.kms_info.chain, kmsContractAddress: result.kms_info.kms_contract_address, appId: result.app_id as `0x${string}`, composeHash: result.compose_hash, privateKey: privateKey, }); // Phase 2: retry with transaction proof await client.updateCvmEnvs({ id: "my-app", encrypted_env: encrypted, env_keys: ["API_KEY", "NEW_VAR"], compose_hash: result.compose_hash, transaction_hash: receipt.transactionHash, }); } ``` *** ## safeUpdateCvmEnvs Safe variant that returns a `SafeResult` instead of throwing on errors. # updateDockerCompose Source: https://docs.phala.com/phala-cloud/references/cloud-js-sdk/update-docker-compose Update the Docker Compose configuration for a CVM ## updateDockerCompose `PATCH /cvms/{cvmId}/docker-compose` Updates the Docker Compose file for a running CVM. The request body is sent as `text/yaml`. This function uses a **two-phase flow** for CVMs with on-chain KMS: 1. **Phase 1:** Call with the new `docker_compose_file`. If the CVM uses on-chain KMS, the API returns `precondition_required` with a `compose_hash`. 2. **Register on-chain:** Call [`addComposeHash`](/phala-cloud/references/cloud-js-sdk/add-compose-hash) to register the new compose hash on the blockchain. 3. **Phase 2:** Retry the call with the original YAML plus `compose_hash` and `transaction_hash`. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier | | `docker_compose_file` | `string` | Yes | New Docker Compose YAML content | | `compose_hash` | `string` | No | Compose hash (Phase 2, sent via `X-Compose-Hash` header) | | `transaction_hash` | `string` | No | On-chain transaction hash (Phase 2, sent via `X-Transaction-Hash` header) | **Returns:** Union of two possible responses: **Success (`in_progress`):** | Field | Type | Description | | - | - | - | | `status` | `"in_progress"` | Update accepted | | `message` | `string` | Status message | | `correlation_id` | `string` | Tracking ID | **Precondition required (`precondition_required`):** | Field | Type | Description | | - | - | - | | `status` | `"precondition_required"` | On-chain registration needed | | `message` | `string` | Instructions | | `compose_hash` | `string` | Hash to register on-chain | | `app_id` | `string` | App ID for contract interaction | | `device_id` | `string` | Device ID | | `kms_info` | `KmsInfo` | KMS details for chain interaction | **Example — PHALA KMS:** ```typescript theme={"system"} const result = await client.updateDockerCompose({ id: "my-app", docker_compose_file: newComposeYaml, }); // result.status === "in_progress" ``` **Example — On-chain KMS (two phases):** ```typescript theme={"system"} import { addComposeHash } from "@phala/cloud"; // Phase 1 const result = await client.updateDockerCompose({ id: "my-app", docker_compose_file: newComposeYaml, }); if (result.status === "precondition_required") { // Register on-chain const receipt = await addComposeHash({ chain: result.kms_info.chain, kmsContractAddress: result.kms_info.kms_contract_address, appId: result.app_id as `0x${string}`, composeHash: result.compose_hash, privateKey: privateKey, }); // Phase 2 await client.updateDockerCompose({ id: "my-app", docker_compose_file: newComposeYaml, compose_hash: result.compose_hash, transaction_hash: receipt.transactionHash, }); } ``` *** ## safeUpdateDockerCompose Safe variant that returns a `SafeResult` instead of throwing on errors. # watchCvmState Source: https://docs.phala.com/phala-cloud/references/cloud-js-sdk/watch-cvm-state Watch CVM state changes via Server-Sent Events until a target status is reached ## watchCvmState `GET /cvms/{cvmId}/state` (Server-Sent Events) Watches CVM state changes in real-time via Server-Sent Events (SSE). Resolves when a completion event confirms the target status. A timeout applies to one attempt; the client retries by default without a limit. It also retries when the stream ends before completion. Cancellation aborts the watch. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | CVM identifier | | `target` | `string` | Yes | Target status to wait for (e.g., `"running"`, `"stopped"`) | | `interval` | `number` | No | Polling interval in seconds (5-30, default: 5) | | `timeout` | `number` | No | Per-attempt timeout in seconds (10-600, default: 300) | | `maxRetries` | `number` | No | Maximum retries after the first request (default: `Infinity`); `0` still makes one request | | `retryDelay` | `number` | No | Delay between retries in ms (default: 5000) | **Options:** | Field | Type | Description | | - | - | - | | `signal` | `AbortSignal` | Cancellation signal | | `onEvent` | `(event) => void` | Callback for each SSE event | **Returns:** `CvmState` — the latest state received when a completion event confirms the target. The state's raw `status` can differ from the derived status used for that comparison. | Field | Type | Description | | - | - | - | | `id` | `string` | CVM ID | | `instance_id` | `string` | Instance ID | | `name` | `string` | CVM name | | `status` | `string` | Raw CVM status | | `uptime` | `string?` | Uptime duration | | `boot_progress` | `string?` | Boot progress | | `boot_error` | `string?` | Boot error if failed | **Errors:** | Error | Description | | - | - | | `WatchAbortedError` | Thrown when the operation is cancelled via `AbortSignal` | | `MaxRetriesExceededError` | Thrown when retries are exhausted after a timeout or an incomplete stream | A server `error` event may be followed by more events. When `MaxRetriesExceededError` is raised, `lastServerError` may contain the latest server error event data, which is also included in the error message. `lastAttemptError` may contain the last transport error. If retries end on a transport error without a server diagnostic, that error is thrown directly. **Example — Wait for CVM to start:** ```typescript theme={"system"} import { createClient, watchCvmState } from "@phala/cloud"; const client = createClient(); const state = await watchCvmState(client, { id: "my-app", target: "running", timeout: 120, }, { onEvent: (event) => { if (event.type === "state") { console.log(`Status: ${event.data.status}`); } }, }); console.log(`Latest raw CVM status: ${state.status}`); ``` **Example — With abort support:** ```typescript theme={"system"} import { createClient, watchCvmState, WatchAbortedError } from "@phala/cloud"; const client = createClient(); const controller = new AbortController(); // Cancel after 60 seconds setTimeout(() => controller.abort(), 60_000); try { const state = await watchCvmState(client, { id: "my-app", target: "running", }, { signal: controller.signal }); } catch (error) { if (error instanceof WatchAbortedError) { console.log("Watch was cancelled"); } } ``` > [!NOTE] > > Unlike other SDK functions, `watchCvmState` does not have a `safe` variant. Use try/catch for error handling. # Workspaces Source: https://docs.phala.com/phala-cloud/references/cloud-js-sdk/workspaces Functions for querying workspace information, nodes, and quotas ## listWorkspaces `GET /workspaces` Returns a paginated list of workspaces the user has access to. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `cursor` | `string` | No | Pagination cursor | | `limit` | `number` | No | Items per page | **Returns:** `ListWorkspaces` | Field | Type | Description | | - | - | - | | `data` | `WorkspaceResponse[]` | Workspace list | | `pagination` | `object` | `{ has_more, next_cursor, total }` | **Example:** ```typescript theme={"system"} const workspaces = await client.listWorkspaces({ limit: 10 }); workspaces.data.forEach(ws => console.log(ws.name, ws.slug)); ``` *** ## getWorkspace `GET /workspaces/{teamSlug}` Returns details about a specific workspace. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `teamSlug` | `string` | Yes | Workspace slug | **Returns:** `WorkspaceResponse` — workspace details. *** ## getWorkspaceNodes `GET /workspaces/{teamSlug}/nodes` Returns the list of nodes available to a workspace. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `teamSlug` | `string` | Yes | Workspace slug | **Returns:** Array of node information. *** ## getWorkspaceQuotas `GET /workspaces/{teamSlug}/quotas` Returns resource quotas and usage for a workspace. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `teamSlug` | `string` | Yes | Workspace slug | **Returns:** `GetWorkspaceQuotas` | Field | Type | Description | | - | - | - | | `team_slug` | `string` | Workspace slug | | `tier` | `string` | Workspace tier | | `quotas` | `object` | Resource limits: `vm_slots`, `vcpu`, `memory_mb`, `disk_gb` (each has `limit` and `remaining`) | | `reserved_nodes` | `object` | `{ limit, remaining }` | | `reserved_gpu` | `object` | `{ gpus, in_use, misconfigured }` | **Example:** ```typescript theme={"system"} const quotas = await client.getWorkspaceQuotas({ teamSlug: "my-team" }); console.log(`VM slots: ${quotas.quotas.vm_slots.remaining}/${quotas.quotas.vm_slots.limit}`); ``` # Apps Source: https://docs.phala.com/phala-cloud/references/cloud-python-sdk/apps List apps, retrieve app details, query revision history, and manage device allowlists. App methods let you query and inspect applications deployed on Phala Cloud. An app is the logical grouping that contains one or more CVMs running the same compose configuration. ## get\_app\_list `GET /apps` Lists all apps visible to the authenticated user. Supports optional filtering via query parameters. **Parameters:** Optional dictionary of filter parameters (passed as query params). **Returns:** App list response. **Example:** ```python Sync theme={"system"} apps = client.get_app_list() for app in apps.items: print(app.app_id, app.name) ``` ```python Async theme={"system"} apps = await client.get_app_list() for app in apps.items: print(app.app_id, app.name) ``` *** ## get\_app\_info `GET /apps/{appId}` Retrieves detailed information about a specific app. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `app_id` | `str` | Yes | App identifier | **Returns:** App info response with full details. **Example:** ```python Sync theme={"system"} app = client.get_app_info({"app_id": "app-123"}) print(app.name, app.status) ``` ```python Async theme={"system"} app = await client.get_app_info({"app_id": "app-123"}) print(app.name, app.status) ``` *** ## get\_app\_cvms `GET /apps/{appId}/cvms` Lists all CVMs that belong to a specific app. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `app_id` | `str` | Yes | App identifier | **Returns:** List of CVM objects. **Example:** ```python theme={"system"} cvms = client.get_app_cvms({"app_id": "app-123"}) for cvm in cvms: print(cvm.id, cvm.status) ``` *** ## get\_app\_revisions `GET /apps/{appId}/revisions` Lists the revision history for an app. Each revision represents a configuration change (compose file update, env change, etc.). Supports pagination. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `app_id` | `str` | Yes | App identifier | | `page` | `int` | No | Page number (1-based) | | `page_size` | `int` | No | Items per page | **Returns:** Paginated list of revision summaries. **Example:** ```python theme={"system"} revisions = client.get_app_revisions({ "app_id": "app-123", "page": 1, "page_size": 10, }) for rev in revisions.items: print(rev.revision_id, rev.created_at) ``` *** ## get\_app\_revision\_detail `GET /apps/{appId}/revisions/{revisionId}` Retrieves the full details of a specific revision, optionally including the raw compose file. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `app_id` | `str` | Yes | App identifier | | `revision_id` | `str` | Yes | Revision identifier | | `raw_compose_file` | `bool` | No | Include raw compose file content | **Returns:** Revision detail response. **Example:** ```python theme={"system"} detail = client.get_app_revision_detail({ "app_id": "app-123", "revision_id": "rev-456", "raw_compose_file": True, }) ``` *** ## get\_app\_attestation `GET /apps/{appId}/attestations` Retrieves TEE attestation information for an app. This includes the attestation report that proves the app is running inside a genuine TEE environment. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `app_id` | `str` | Yes | App identifier | **Returns:** App attestation response. **Example:** ```python theme={"system"} attestation = client.get_app_attestation({"app_id": "app-123"}) ``` *** ## get\_app\_device\_allowlist `GET /apps/{appId}/device-allowlist` Retrieves the device allowlist for an app. The allowlist controls which TEE devices are permitted to run the app. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `app_id` | `str` | Yes | App identifier | **Returns:** Device allowlist response. **Example:** ```python theme={"system"} allowlist = client.get_app_device_allowlist({"app_id": "app-123"}) ``` *** ## get\_app\_filter\_options `GET /apps/filter-options` Returns the available filter options for the app list endpoint. Useful for building UI filters. **Parameters:** None. **Returns:** Filter options response with available values. **Example:** ```python theme={"system"} options = client.get_app_filter_options() ``` *** ## check\_app\_is\_allowed `POST /apps/{appId}/is-allowed` Checks whether an app is allowed to run based on device allowlist constraints. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `app_id` | `str` | Yes | App identifier | **Returns:** Allowance check response. *** ## check\_app\_cvms\_is\_allowed `POST /apps/{appId}/cvms/is-allowed` Batch-checks whether all CVMs under an app are allowed to run. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `app_id` | `str` | Yes | App identifier | **Returns:** Batch allowance check response. ## set\_app\_launch\_token / clear\_app\_launch\_token `POST /apps/{appId}/launch-token` / `DELETE /apps/{appId}/launch-token` `set_app_launch_token` sets or rotates the app's launch token and returns it once, with its hash. Leave out `launch_token` to have Phala Cloud generate one. Then update each CVM's `requirements.launch_token_hash` to the returned hash with [`patch_cvm`](/phala-cloud/references/cloud-python-sdk/cvm-configuration#patch_cvm). `clear_app_launch_token` removes the token; remove the hash from every CVM first. Phala Cloud and the node operator can read the token. See [Launch Token](/phala-cloud/cvm/launch-token). **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `app_id` | `str` | Yes | App ID (hex). Also accepted as `appId`. | | `launch_token` | `str` | No | `set_app_launch_token` only. Token to set, at least 32 bytes. | **Returns:** `set_app_launch_token` returns `AppLaunchTokenResponse` with `launch_token` and `launch_token_hash`. `clear_app_launch_token` returns `None`. ```python theme={"system"} token = client.set_app_launch_token({"app_id": "0123...cdef"}) client.patch_cvm({ "id": "my-app", "compose": {"requirements": {"launch_token_hash": token.launch_token_hash}}, }) ``` ## Related * [CVM Lifecycle](/phala-cloud/references/cloud-python-sdk/cvm-lifecycle) — managing individual CVMs * [Workspaces](/phala-cloud/references/cloud-python-sdk/workspaces) — workspace-level operations # Authentication Source: https://docs.phala.com/phala-cloud/references/cloud-python-sdk/authentication Configure API key, bearer, and workspace authentication for the Phala Cloud Python SDK. Authenticate with an API key or a bearer token. Configure credentials directly or through environment variables. ## API Key ### Environment Variable (Recommended) Set `PHALA_CLOUD_API_KEY` in your environment and the SDK picks it up automatically: ```bash theme={"system"} export PHALA_CLOUD_API_KEY="phak_your_api_key" ``` ```python theme={"system"} from phala_cloud import create_client # No api_key argument needed client = create_client() me = client.get_current_user() ``` This is the recommended approach for production deployments and CI/CD pipelines. It keeps credentials out of your source code. ### Explicit API Key Pass the key directly when creating the client: ```python theme={"system"} from phala_cloud import create_client client = create_client(api_key="phak_your_api_key") ``` The explicit `api_key` parameter takes precedence over the environment variable. ## Bearer token and workspace Set `bearer_token` to authenticate with a bearer token, including an OIDC token. Set `workspace` to select a workspace by slug. The SDK also reads `PHALA_OIDC_TOKEN` and `PHALA_CLOUD_WORKSPACE`. ```python theme={"system"} import os from phala_cloud import create_client client = create_client( bearer_token=os.environ["PHALA_OIDC_TOKEN"], workspace="my-workspace", ) ``` A nonempty explicit value takes precedence over its environment variable. If both an API key and a bearer token are configured, the API key is used. Workspace names are stripped of surrounding whitespace. ## Environment Variables | Variable | Description | | - | - | | `PHALA_CLOUD_API_KEY` | API key for authentication | | `PHALA_OIDC_TOKEN` | Bearer token for authentication | | `PHALA_CLOUD_WORKSPACE` | Workspace slug | | `PHALA_CLOUD_API_PREFIX` | Base URL override (defaults to `https://cloud-api.phala.com/api/v1`) | These variables are read at client creation time. Changing them after the client is created has no effect. ## Cookie-Based Auth For browser-like environments, the SDK supports cookie-based authentication instead of API keys. When enabled, the SDK does not add an API key or bearer authorization header. Authentication relies on cookies managed by the HTTP client. ```python theme={"system"} client = create_client(use_cookie_auth=True) ``` > [!NOTE] > > Cookie-based auth is primarily for internal use. Most users should stick with API key authentication. ## revoke\_current\_api\_token `DELETE /tokens/self` Call `client.revoke_current_api_token()` to revoke the API token used for the request. It returns `None`. The token stops working immediately and cannot be restored. The async client supports `await client.revoke_current_api_token()`; a `safe_revoke_current_api_token` variant is also available. ## Custom Headers You can add extra headers to every request. This is useful for tracing, debugging, or passing custom metadata. ```python theme={"system"} client = create_client( api_key="phak_your_api_key", headers={"X-Request-Source": "my-automation"}, ) ``` ## Verifying Authentication Call `get_current_user()` to verify your credentials are valid: ```python Sync theme={"system"} from phala_cloud import create_client, AuthError client = create_client() try: user = client.get_current_user() print(f"Authenticated as {user.model_dump()}") except AuthError as e: print(f"Auth failed: {e}") ``` ```python Async theme={"system"} from phala_cloud import create_async_client, AuthError client = create_async_client() try: user = await client.get_current_user() print(f"Authenticated as {user.model_dump()}") except AuthError as e: print(f"Auth failed: {e}") ``` ## Bring Your Own HTTP Client If you need full control over transport settings (proxies, certificates, connection pooling), pass a pre-configured `httpx` client: ```python theme={"system"} import httpx from phala_cloud import create_client http = httpx.Client( verify="/path/to/ca-bundle.crt", proxy="http://proxy.internal:8080", ) client = create_client(api_key="phak_your_api_key", http_client=http) ``` > [!WARNING] > > The SDK applies its configured authentication, workspace, and version headers to requests made with the provided client. Configure that client with a base URL for relative API paths. The SDK does not close it automatically. You are responsible for calling `http.close()` when done. ## Related * [SDK Overview](/phala-cloud/references/cloud-python-sdk/overview) — installation and quick start * [Error Handling](/phala-cloud/references/cloud-python-sdk/error-handling) — handling `AuthError` # Changelog Source: https://docs.phala.com/phala-cloud/references/cloud-python-sdk/changelog Version history for the Phala Cloud Python SDK. ## [0.2.0](https://github.com/Phala-Network/phala-cloud/compare/python-v0.1.3...python-v0.2.0) (2026-07-26) ### Breaking changes * Removed the deprecated `user_id`, `teepod_id`, and `node_id` filters from CVM list requests. ### Features * Added contract-centric KMS methods for listing contracts, retrieving one contract, and listing its node replicas. * Added `get_mr_config_id`, `get_mr_config_id_hex`, `get_mr_config_id_v1`, and `verify_mr_config_id`. * Changed the default API version to `2026-06-23`. * Added typed app attestation and batch CVM status responses. * Added KMS verification anchors, node device ID history, and GPU rental billing fields to response models. ### Fixes * Added the KMS `k256_pubkey` field and locked the `pysha3` dependency used for measurement computation. * Moved resource updates to the unified `PATCH /cvms/{id}` flow. ## [0.1.2](https://github.com/Phala-Network/phala-cloud/compare/python-v0.1.1...python-v0.1.2) (2026-03-27) ### Features * add webhook signature verification utilities ([45df4da](https://github.com/Phala-Network/phala-cloud/commit/45df4da)) * add is-allowed API ([1fa61f0](https://github.com/Phala-Network/phala-cloud/commit/1fa61f0581ce111213f721f1c2d2f4744c3c2f00)) * add structured error codes and idempotency support across all SDKs ([2dd6d0b](https://github.com/Phala-Network/phala-cloud/commit/2dd6d0bae4d5fd7acdef551c3c9bf507ac1b0e4e)) * add `patch_cvm` and `confirm_cvm_patch` for unified PATCH endpoint ([7e167e2](https://github.com/Phala-Network/phala-cloud/commit/7e167e2)) ### Bug Fixes * use AliasModel for request types with field aliases ([b4e8ac0](https://github.com/Phala-Network/phala-cloud/commit/b4e8ac0)) * dispatch error subclasses in `_to_api_error` ([b36b7f2](https://github.com/Phala-Network/phala-cloud/commit/b36b7f2)) * fix Pydantic alias models and CI format issues ([8814d7f](https://github.com/Phala-Network/phala-cloud/commit/8814d7f)) * fix SDK bugs found by e2e tests and rewrite e2e test suite ([04a4638](https://github.com/Phala-Network/phala-cloud/commit/04a4638)) ## [0.1.1](https://github.com/Phala-Network/phala-cloud/compare/python-v0.1.0...python-v0.1.1) (2026-03-14) ### Features * Added `patch_cvm` and `confirm_cvm_patch` for batch CVM updates with on-chain hash support * Added `replicate_cvm` for creating CVM replicas * Added `check_cvm_is_allowed`, `check_app_is_allowed`, and `check_app_cvms_is_allowed` for device allowlist checks * Added `refresh_cvm_instance_id` and `refresh_cvm_instance_ids` for instance ID management * Added `get_os_images` for listing all available OS images * Added `get_app_device_allowlist` for querying device allowlists * Added `watch_cvm_state` for polling CVM state transitions via SSE ## 0.1.0 Initial release. * Sync (`PhalaCloud`) and async (`AsyncPhalaCloud`) clients * Full CVM lifecycle: `provision_cvm`, `commit_cvm_provision`, `start_cvm`, `stop_cvm`, `shutdown_cvm`, `restart_cvm`, `delete_cvm` * CVM configuration: `update_docker_compose`, `update_cvm_envs`, `update_pre_launch_script`, `update_cvm_resources`, `update_cvm_visibility`, `update_os_image` * Compose file update flow: `provision_cvm_compose_file_update`, `commit_cvm_compose_file_update` * App queries: `get_app_list`, `get_app_info`, `get_app_cvms`, `get_app_revisions`, `get_app_revision_detail`, `get_app_attestation`, `get_app_filter_options` * Workspace queries: `list_workspaces`, `get_workspace`, `get_workspace_nodes`, `get_workspace_quotas` * KMS operations: `get_kms_info`, `get_kms_list`, `get_kms_on_chain_detail`, `get_app_env_encrypt_pub_key`, `next_app_ids` * SSH key management: `list_ssh_keys`, `create_ssh_key`, `delete_ssh_key`, `import_github_profile_ssh_keys`, `sync_github_ssh_keys` * Node and instance types: `get_available_nodes`, `list_all_instance_type_families`, `list_family_instance_types` * Utility functions: `encrypt_env_vars`, `get_compose_hash`, `verify_env_encrypt_public_key`, `parse_env`, `parse_env_vars` * Blockchain helpers: `add_compose_hash`, `deploy_app_auth` * `safe_*` variants for all action methods returning `SafeResult` * Pydantic-validated responses * API versioning support (`2025-10-28`, `2026-01-21`) * Structured error hierarchy with `error_codes` module * Python 3.10+ support # CVM Configuration Source: https://docs.phala.com/phala-cloud/references/cloud-python-sdk/cvm-configuration Update Docker Compose files, environment variables, resources, visibility, and OS images on running CVMs. Configuration methods let you modify a CVM after it has been provisioned. You can update the Docker Compose file, environment variables, resource allocation, visibility settings, and OS image independently. > [!WARNING] > > **Some configuration updates restart a running CVM.** A change applied through `PATCH /cvms/{cvmId}` or the compose, environment and OS image endpoints stops the CVM, applies the change and starts it again. A stopped CVM stays stopped and runs the new configuration at its next start. A compose change that matches what the CVM already runs does not restart it: the API answers `no_change` and does nothing. Annotations (`update_cvm_annotations`) never restart the CVM, and SSH key changes without `apply_now` stay pending until the next power-on. `patch_cvm` sends any set of changes in one request to `PATCH /cvms/{cvmId}`. `update_cvm_resources` and `update_cvm_visibility` send a subset of fields to the same endpoint. The other `update_*` methods call their own endpoints. See [Update CVM Configuration](/phala-cloud/update/update-cvm-configuration) for what each field does and which settings cannot change after create. ## update\_docker\_compose `PATCH /cvms/{cvmId}/docker-compose` Updates the Docker Compose configuration for a CVM. If the CVM has on-chain hash verification enabled, you need to pass `compose_hash` and `transaction_hash`. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `str` | Yes | CVM identifier | | `docker_compose_file` | `str` | Yes | Docker Compose YAML content | | `compose_hash` | `str` | No | On-chain compose hash (if required) | | `transaction_hash` | `str` | No | On-chain transaction hash (if required) | **Returns:** A `CloudModel` with the API response when the update is accepted. For an on-chain KMS CVM whose new compose hash is not registered yet, the API answers HTTP 465 and the method returns a `CloudModel` with `status="precondition_required"` and `compose_hash`, `app_id`, `device_id` and `kms_info`, instead of raising. The sync and async clients behave the same. **Example:** ```python Sync theme={"system"} result = client.update_docker_compose({ "id": "my-app", "docker_compose_file": """ services: app: image: nginx:latest ports: - "80:80" """, }) ``` ```python Async theme={"system"} result = await client.update_docker_compose({ "id": "my-app", "docker_compose_file": """ services: app: image: nginx:latest ports: - "80:80" """, }) ``` *** ## update\_cvm\_envs `PATCH /cvms/{cvmId}/envs` Updates encrypted environment variables for a CVM. Environment variables must be encrypted using the KMS public key before being sent. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `str` | Yes | CVM identifier | | `encrypted_env` | `str` | Yes | Encrypted environment variable payload | | `env_keys` | `list[str]` | No | List of environment variable keys | | `compose_hash` | `str` | No | On-chain compose hash (if required) | | `transaction_hash` | `str` | No | On-chain transaction hash (if required) | **Returns:** `InProgressResponse` on success, or precondition response if on-chain verification is needed. **Example:** ```python theme={"system"} from phala_cloud import encrypt_env_vars # Encrypt env vars using KMS public key pubkey_resp = client.get_app_env_encrypt_pub_key({ "kms": "phala", "app_id": "my-app-id", }) encrypted = encrypt_env_vars( envs=[{"key": "SECRET", "value": "my-secret"}], public_key_hex=pubkey_resp.public_key, ) client.update_cvm_envs({ "id": "my-app", "encrypted_env": encrypted, "env_keys": ["SECRET"], }) ``` *** ## update\_pre\_launch\_script `PATCH /cvms/{cvmId}/pre-launch-script` Updates the pre-launch script that runs before Docker containers start. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `str` | Yes | CVM identifier | | `pre_launch_script` | `str` | Yes | Script content | | `compose_hash` | `str` | No | On-chain compose hash (if required) | | `transaction_hash` | `str` | No | On-chain transaction hash (if required) | **Returns:** `InProgressResponse` on success. *** ## get\_cvm\_docker\_compose `GET /cvms/{cvmId}/docker-compose.yml` Retrieves the current Docker Compose YAML for a CVM as a raw string. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `str` | Yes | CVM identifier | **Returns:** `str` — Docker Compose YAML content. **Example:** ```python theme={"system"} yaml_content = client.get_cvm_docker_compose({"id": "my-app"}) print(yaml_content) ``` *** ## get\_cvm\_compose\_file `GET /cvms/{cvmId}/compose_file` Retrieves the compose file with metadata (including hash info and structure). **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `str` | Yes | CVM identifier | **Returns:** Compose file response with metadata. *** ## commit\_cvm\_update `POST /cvms/{cvmId}/commit-update` Commit a prepared update using its token. `compose_hash` and `transaction_hash` are optional request fields. The returned `CommitCvmUpdateResult` contains `correlation_id` and `status`. ```python theme={"system"} result = client.commit_cvm_update({ "cvm_id": "my-app", "token": token, }) print(result.correlation_id, result.status) ``` The async client supports `await client.commit_cvm_update(...)`. A `safe_commit_cvm_update` variant is also available. ## update\_cvm\_resources `PATCH /cvms/{cvmId}` Changes the resource allocation (CPU, memory, disk, instance type) for a CVM. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `str` | Yes | CVM identifier | | `vcpu` | `float` | No | Number of vCPUs | | `memory` | `float` | No | Memory in MB | | `disk_size` | `float` | No | Disk size in GB. A disk cannot shrink. | | `instance_type` | `str` | No | Instance type name | | `allow_restart` | `bool` | No | Deprecated and not sent. The CVM restarts whenever a resize needs it. | **Returns:** The API response, `{"message", "correlation_id", "status"}`. **Example:** ```python Sync theme={"system"} client.update_cvm_resources({ "id": "my-app", "vcpu": 4, "memory": 4096, "instance_type": "tdx.medium", }) ``` ```python Async theme={"system"} await client.update_cvm_resources({ "id": "my-app", "vcpu": 4, "memory": 4096, "instance_type": "tdx.medium", }) ``` *** ## update\_cvm\_visibility `PATCH /cvms/{cvmId}` Controls which CVM information is publicly accessible. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `str` | Yes | CVM identifier | | `public_sysinfo` | `bool` | Yes | Whether system info is public | | `public_logs` | `bool` | Yes | Whether logs are public | | `public_tcbinfo` | `bool` | No | Whether TCB info is public | **Returns:** `{"message", "correlation_id", "status"}`. `status` is `"in_progress"`, or `"no_change"` with an empty `correlation_id` when the settings already match. These settings are part of the compose hash. For a CVM on Onchain KMS, the request fails with HTTP 465 until the new hash is registered on-chain. Use [`patch_cvm`](#patch_cvm), which returns the hash to register. The Trust Center listing is not a visibility setting; it has its own endpoint, `PATCH /cvms/{cvmId}/listed`. **Example:** ```python theme={"system"} client.update_cvm_visibility({ "id": "my-app", "public_sysinfo": True, "public_logs": False, }) ``` *** ## update\_os\_image `PATCH /cvms/{cvmId}/os-image` Changes the OS image for a CVM. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `str` | Yes | CVM identifier | | `os_image_name` | `str` | Yes | Name of the target OS image | **Returns:** `None` **Example:** ```python theme={"system"} client.update_os_image({ "id": "my-app", "os_image_name": "ubuntu-24.04-tee", }) ``` *** ## get\_available\_os\_images `GET /cvms/{cvmId}/available-os-images` Lists OS images available for a specific CVM. The available images depend on the CVM's node and configuration. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `str` | Yes | CVM identifier | **Returns:** List of available OS image objects. *** ## patch\_cvm `PATCH /cvms/{cvmId}` A batch update method that can modify multiple CVM fields in a single request. This is useful when you need to change several settings atomically. `compose` is a JSON Merge Patch of the app compose, typed as `ComposePatch`. Only the keys you set are sent, and a key set to `None` is sent as `null`, which removes it. See [How does the compose patch work?](/phala-cloud/update/update-cvm-configuration#how-does-the-compose-patch-work) for the keys. To change a `bash` runner's script, set `ComposePatch(bash_script=...)`. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `str` | Yes | CVM identifier | | `docker_compose_file` | `str` | No | Docker Compose YAML | | `pre_launch_script` | `str` | No | Pre-launch script content | | `allowed_envs` | `list[str]` | No | Allowed environment variable keys | | `public_logs` | `bool` | No | Whether logs are public | | `public_sysinfo` | `bool` | No | Whether system info is public | | `public_tcbinfo` | `bool` | No | Whether TCB info is public | | `compose` | `ComposePatch` | No | Other compose settings as a merge patch, for example `{"swap_size": "2G", "requirements": {"health_check": True}}` | | `init_scripts` | `list[str]` | No | Platform init scripts the CVM runs (`"docker_cleanup"`), replacing the current set. `[]` removes them all. | | `confirm_data_wipe` | `bool` | No | Confirms turning on `docker_cleanup` or `requirements.ephemeral_data_disk`, which erase data on every boot | | `encrypted_env` | `str` | No | Encrypted environment variables | | `user_config` | `str` | No | User configuration string | | `gpus` | `dict` | No | GPU assignment: `{"gpus": [{"slot": ..., "product_id": ...}], "attach_mode": ...}`. `attach_mode: "all"` attaches every GPU on the node. Other shapes fail validation. | | `vcpu` | `int` | No | Number of vCPUs | | `memory` | `int` | No | Memory in MB | | `disk_size` | `int` | No | Disk size in GB | | `instance_type` | `str` | No | Instance type, for example `tdx.medium` | | `image` | `str` | No | OS image name | | `shutdown_timeout` | `int` | No | Seconds to wait for a clean shutdown (10 to 1200) | | `allow_force_stop` | `bool` | No | Skip the clean shutdown and stop the CVM at once | | `prepare_only` | `bool` | No | Sent as the `X-Prepare-Only: true` header, not in the body. Also accepted as `prepareOnly`. | **Returns:** A dict with `requires_on_chain_hash` (bool). When it is `False`, the dict has `correlation_id`, which is empty when the API answers `no_change`. When it is `True`, it has `compose_hash`, `app_id`, `device_id` and `kms_info`, plus `commit_token`, `commit_url`, `api_commit_url` and `onchain_status` for a `prepare_only` call. > [!NOTE] > > On Onchain KMS, a change to the compose returns `requires_on_chain_hash: True` only when the new compose hash is not on the app contract yet (HTTP 465). If the hash is already allowed, or the patch does not change the compose (for example a resize), the update starts at once and you get `correlation_id`. After a 465, register `compose_hash` on-chain, then call `confirm_cvm_patch` with the compose hash and transaction hash. With `prepare_only`, the 465 result also carries `commit_token`, and anyone holding it can finish the update. `prepare_only` is not a dry run: an update that needs no registration starts right away. See [Multisig and Governance](/phala-cloud/key-management/multisig-governance). *** ## get\_cvm\_init\_scripts `GET /cvms/{cvmId}/init-scripts` Lists the platform init scripts, in run order, and for each one whether the CVM runs it (`selected`), whether you can pick it for this CVM (`selectable`) and, if not, why (`reason`). Change the selection with `patch_cvm`'s `init_scripts`. See [Init scripts](/phala-cloud/cvm/advanced-settings#init-scripts). **Parameters:** `id` (CVM identifier). **Returns:** `CvmInitScriptsResponse` with `items`. *** ## get\_cvm\_annotations / update\_cvm\_annotations `GET /cvms/{cvmId}/annotations` / `PUT /cvms/{cvmId}/annotations` Reads or replaces the CVM's annotations: key/value settings for tools on the host. They are not measured and attestation does not cover them. `update_cvm_annotations` replaces every annotation, and `{}` clears them. It does not restart the CVM. Annotations sit behind a feature flag; without it, both calls fail with `ERR-03-049`. See [Annotations](/phala-cloud/cvm/advanced-settings#annotations). **Parameters:** `id` (CVM identifier), plus `annotations` (`dict[str, str]`) for `update_cvm_annotations`. **Returns:** `CvmAnnotationsResponse` with `annotations`, the annotations the node now stores. ```python theme={"system"} client.update_cvm_annotations({"id": "my-app", "annotations": {"memory_tier": "fast"}}) ``` *** ## Compose File Update Flow For updates that require on-chain hash verification, the SDK provides a two-step flow similar to CVM provisioning: ### provision\_cvm\_compose\_file\_update `POST /cvms/{cvmId}/compose_file/provision` Provisions a compose file update and returns the new compose hash. ### commit\_cvm\_compose\_file\_update `PATCH /cvms/{cvmId}/compose_file` Commits the compose file update with the verified hash. ```python theme={"system"} # Step 1: Provision the update provision = client.provision_cvm_compose_file_update({ "id": "my-app", "app_compose": { "docker_compose_file": "services:\n app:\n image: nginx:latest", }, }) # Step 2: After on-chain verification, commit the update client.commit_cvm_compose_file_update({ "id": "my-app", "compose_hash": provision.compose_hash, "encrypted_env": "...", "env_keys": ["KEY1", "KEY2"], }) ``` ## Related * [CVM Lifecycle](/phala-cloud/references/cloud-python-sdk/cvm-lifecycle) — provisioning and managing CVMs * [KMS](/phala-cloud/references/cloud-python-sdk/kms) — encryption keys for environment variables # CVM Lifecycle Source: https://docs.phala.com/phala-cloud/references/cloud-python-sdk/cvm-lifecycle Provision, start, stop, restart, delete, and replicate CVMs using the Python SDK. CVM lifecycle methods control the creation and state transitions of your Confidential Virtual Machines. Provisioning is a two-step process (provision then commit), while other operations are single calls. ## CVM Identifiers Most lifecycle methods accept a CVM identifier. You can pass any of these fields — the SDK resolves them automatically: | Field | Description | | - | - | | `id` | CVM ID (most common) | | `app_id` | App ID associated with the CVM | | `uuid` | CVM UUID | | `instance_id` | Instance ID | | `cvm_id` | Alias for `id` | ```python theme={"system"} # All equivalent client.get_cvm_info({"id": "my-app"}) client.get_cvm_info({"app_id": "my-app"}) client.get_cvm_info({"cvm_id": "my-app"}) ``` *** ## provision\_cvm `POST /cvms` Creates a CVM provision request. This is step one of the two-step provisioning flow. Use the response's `token` in `commit_cvm_provision`. **Parameters:** The request is a dictionary with the CVM configuration. The exact fields depend on your deployment, but typically include: | Field | Type | Required | Description | | - | - | - | - | | `name` | `str` | Yes | CVM display name | | `compose_file` | `dict` | Yes, unless `compose_file_raw` is sent | Docker Compose configuration | | `vcpu` | `int` | No | Number of vCPUs | | `memory` | `int` | No | Memory in MB | | `disk_size` | `int` | No | Disk size in GB | | `node` | `str` | No | Physical node name for deployment | | `init_scripts` | `list[str]` | No | Platform init scripts the CVM runs on every boot: `docker_cleanup` (needs dstack OS 0.6.x, `ext4` storage and the `docker-compose` runner). The list is the whole set. See [Init scripts](/phala-cloud/cvm/advanced-settings#init-scripts). `enabled_init_scripts_docker_cleanup` is deprecated. | | `launch_token` | `str` | No | Launch token, at least 32 bytes, that the CVM must have on every boot. See [Launch Token](/phala-cloud/cvm/launch-token). | | `generate_launch_token` | `bool` | No | Have Phala Cloud generate the launch token for a new app, or use the app's existing token. A new token is returned once, as `launch_token` in the commit response. | | `annotations` | `dict[str, str]` | No | Host-side settings for tools on the node, not measured. Needs a feature flag (`ERR-03-049` without it) and dstack VMM 0.6.1 or newer on the node (`ERR-03-050`). See [Annotations](/phala-cloud/cvm/advanced-settings#annotations). | | `compose_file_raw` | `str` | No | A whole app-compose JSON file as one string, sent instead of `compose_file`. Needs a feature flag. Phala Cloud parses it with the same rules and writes it the same way, so the compose hash comes from that output, not from your bytes. See [Raw app-compose input](/phala-cloud/cvm/advanced-settings#raw-app-compose-input). | **Returns:** Provision response with `token`, `compose_hash`, and `app_id`. **Example:** ```python Sync theme={"system"} result = client.provision_cvm({ "name": "my-cvm", "compose_file": { "docker_compose_file": "services:\n app:\n image: nginx:latest", }, "vcpu": 2, "memory": 2048, "disk_size": 20, "node": "prod6", }) print(result.compose_hash) ``` ```python Async theme={"system"} result = await client.provision_cvm({ "name": "my-cvm", "compose_file": { "docker_compose_file": "services:\n app:\n image: nginx:latest", }, "vcpu": 2, "memory": 2048, "disk_size": 20, "node": "prod6", }) print(result.compose_hash) ``` *** ## commit\_cvm\_provision `POST /cvms` Commits a provisioned CVM, creating the actual instance. Pass the token returned by `provision_cvm`. For the legacy flow, pass the provision response's `app_id` and `compose_hash` instead. On-chain KMS deployments may also need a transaction hash. This endpoint is idempotent: submitting the same `app_id` + `compose_hash` again returns the existing CVM. A different `compose_hash` for the same `app_id` raises a `ResourceError` with error code `CVM_APP_ID_CONFLICT`. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `token` | `str` | Preferred | Token from the provision response | | `app_id` | `str` | Without token | App ID from the provision response | | `compose_hash` | `str` | Without token | Hash from the provision response | | `transaction_hash` | `str` | For on-chain KMS when needed | Transaction hash for on-chain verification | **Returns:** Committed CVM details. **Example:** ```python Sync theme={"system"} cvm = client.commit_cvm_provision({ "token": result.token, }) ``` ```python Async theme={"system"} cvm = await client.commit_cvm_provision({ "token": result.token, }) ``` *** ## start\_cvm `POST /cvms/{cvmId}/start` Starts a stopped CVM. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `str` | Yes | CVM identifier | **Returns:** CVM action response with updated status. **Example:** ```python Sync theme={"system"} result = client.start_cvm({"id": "my-app"}) print(result.status) # "starting" ``` ```python Async theme={"system"} result = await client.start_cvm({"id": "my-app"}) print(result.status) ``` *** ## stop\_cvm `POST /cvms/{cvmId}/stop` Force-stops a CVM immediately. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `str` | Yes | CVM identifier | **Returns:** CVM action response with updated status. *** ## shutdown\_cvm `POST /cvms/{cvmId}/shutdown` Gracefully shuts down a CVM, allowing containers to stop cleanly. Prefer this over `stop_cvm` unless you need an immediate halt. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `str` | Yes | CVM identifier | **Returns:** CVM action response with updated status. *** ## restart\_cvm `POST /cvms/{cvmId}/restart` Restarts a CVM. Supports an optional `force` flag to skip graceful shutdown. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `str` | Yes | CVM identifier | | `force` | `bool` | No | Force restart without graceful shutdown (default: `False`) | **Returns:** CVM action response with updated status. **Example:** ```python Sync theme={"system"} client.restart_cvm({"id": "my-app", "force": True}) ``` ```python Async theme={"system"} await client.restart_cvm({"id": "my-app", "force": True}) ``` *** ## delete\_cvm `DELETE /cvms/{cvmId}` Permanently deletes a CVM and all its data. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `str` | Yes | CVM identifier | **Returns:** `None` > [!WARNING] > > This action is irreversible. All data associated with the CVM will be permanently deleted. **Example:** ```python Sync theme={"system"} client.delete_cvm({"id": "my-app"}) ``` ```python Async theme={"system"} await client.delete_cvm({"id": "my-app"}) ``` *** ## replicate\_cvm `POST /cvms/{cvmId}/replicas` Creates a copy of an existing CVM. The replica shares the same compose configuration but runs as an independent instance. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `str` | Yes | Source CVM identifier | | `node` | `str` | No | Physical node name; omit to inherit the source placement | | `os_image` | `str` | No | OS image override | **Returns:** Replicated CVM details. **Example:** ```python Sync theme={"system"} replica = client.replicate_cvm({"id": "my-app", "node": "prod6"}) ``` ```python Async theme={"system"} replica = await client.replicate_cvm({"id": "my-app", "node": "prod6"}) ``` *** ## watch\_cvm\_state `GET /cvms/{cvmId}/state` (SSE) Watches CVM state via Server-Sent Events. Both sync and async clients support this method. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `id` | `str` | Yes | CVM identifier | | `target` | `str` | Yes | Target state to wait for (e.g., `"running"`) | | `interval` | `int` | No | Polling interval in seconds (default: `5`, range: 5-30) | | `timeout` | `int` | No | Server-side timeout in seconds (default: `300`, range: 10-600) | | `max_retries` | `int \| None` | No | Retries after an interrupted attempt; default `None` is unlimited, `0` disables retries | | `retry_delay` | `float` | No | Delay between retries in seconds (default: `5.0`) | The SDK returns the `complete` event payload. A raw state status is not necessarily the derived status used by the server to determine completion, and a matching state alone does not complete the watch. A `complete` event whose `status` differs from `target` does not succeed; the SDK treats it as an interrupted attempt and reconnects within the retry budget. The server may emit an `error` event and continue. On a timeout event, an EOF without completion, or a transient transport error, the SDK reconnects within the retry budget. Exhausted retries raise `RequestError`, retaining the latest server error and transport diagnostics when available. HTTP errors use SDK error types and are not retried. The stream read timeout is `timeout + interval + 5` seconds. Other HTTPX timeout settings remain in effect. Cancelling an async task closes the stream and propagates cancellation. `maxRetries` and `retryDelay` are also accepted as aliases. **Example:** ```python Sync theme={"system"} result = client.watch_cvm_state({ "id": "my-app", "target": "running", "timeout": 120, "max_retries": 3, }) print(result.status) ``` ```python Async theme={"system"} result = await client.watch_cvm_state({ "id": "my-app", "target": "running", "timeout": 120, "max_retries": 3, }) print(result.status) ``` ## Related * [CVM Configuration](/phala-cloud/references/cloud-python-sdk/cvm-configuration) — updating compose files and resources * [Error Handling](/phala-cloud/references/cloud-python-sdk/error-handling) — handling provisioning errors # Error Handling Source: https://docs.phala.com/phala-cloud/references/cloud-python-sdk/error-handling Error hierarchy, safe methods, and structured error codes in the Phala Cloud Python SDK. The Python SDK provides a structured error hierarchy and two error handling patterns: exceptions (default) and safe results. Most actions have a `safe_*` variant that returns a result object instead of raising. `watch_cvm_state` does not have a safe variant. This page covers how to catch and handle errors in the SDK. For the full list of `ERR-xxxx` error codes returned by the API, see the [Error Codes Reference](/phala-cloud/references/error-codes). ## Error Hierarchy All SDK exceptions inherit from `PhalaCloudError`: ```text theme={"system"} PhalaCloudError (base) ├── RequestError — Network/transport failures (httpx errors) ├── ValidationError — Response validation failures (Pydantic) └── ApiError — HTTP errors from the API ├── AuthError — 401/403 authentication errors ├── ServerError — 500+ server errors └── BusinessError — 400/409 business logic errors ├── ConflictError — 409 conflicts (transient, may be retryable) └── ResourceError — Structured errors with ERR-xxxx codes ``` ## Catching Errors ### Basic Exception Handling ```python theme={"system"} from phala_cloud import ( PhalaCloudError, AuthError, BusinessError, ResourceError, ServerError, RequestError, ) try: client.provision_cvm(payload) except ResourceError as e: # Structured error with error code and suggestions print(f"Error [{e.error_code}]: {e}") if e.suggestions: for s in e.suggestions: print(f" Suggestion: {s}") except AuthError as e: print(f"Authentication failed: {e}") except BusinessError as e: print(f"Business error ({e.status_code}): {e}") except ServerError as e: print(f"Server error ({e.status_code}): {e}") except RequestError as e: print(f"Network error: {e}") except PhalaCloudError as e: print(f"Unexpected SDK error: {e}") ``` > [!NOTE] > > Order matters when catching exceptions. Catch more specific subclasses first — `ResourceError` before `BusinessError`, and `BusinessError` before `ApiError`. ## Error Classes ### PhalaCloudError Base class for all SDK exceptions. Catches everything. ### RequestError Raised when the HTTP request itself fails (DNS resolution, connection timeout, TLS errors). This wraps `httpx.HTTPError`. ### ApiError Base class for all HTTP error responses from the API. | Property | Type | Description | | - | - | - | | `status_code` | `int` | HTTP status code | | `code` | `str \| None` | Error code string from response | | `detail` | `Any` | Raw error detail from API response | ### AuthError Raised on HTTP 401 or 403. Usually means the API key is invalid or expired. ### BusinessError Raised on HTTP 400, 409, and other 4xx client errors that are not auth-related. ### ConflictError Subclass of `BusinessError`. Raised on HTTP 409 when there is no structured error code. These conflicts are typically transient — for example, another operation is already in progress on the same CVM. Retrying after a short delay often resolves the issue. ### ResourceError Subclass of `BusinessError`. Raised when the API returns a structured error with an `error_code` field. These are deterministic business errors with additional context. | Property | Type | Description | | - | - | - | | `error_code` | `str \| None` | Structured code (e.g., `"ERR-01-001"`) | | `structured_details` | `list[dict] \| None` | Field-level error details | | `suggestions` | `list[str] \| None` | Suggested fixes | | `links` | `list[dict] \| None` | Links to documentation | ### ServerError Raised on HTTP 500+. Indicates a problem on the Phala Cloud side. ### ValidationError Raised when a response passes HTTP validation but fails Pydantic model validation. This is rare and usually indicates an API response format change. ## Safe Methods Most action methods have a `safe_*` counterpart that wraps the result in a `SafeResult` dataclass instead of raising exceptions. ```python theme={"system"} result = client.safe_get_cvm_info({"id": "my-app"}) if result.ok: print(result.data.status) else: print(f"Error: {result.error}") ``` ### SafeResult ```python theme={"system"} @dataclass class SafeResult(Generic[T]): ok: bool data: T | None = None error: Exception | None = None def unwrap(self) -> T: """Return data if ok, otherwise re-raise the error.""" ``` The `unwrap()` method gives you a quick escape hatch when you want safe handling in most cases but still want to raise in unexpected situations: ```python theme={"system"} # Returns data if ok, raises the original exception if not cvm = client.safe_get_cvm_info({"id": "my-app"}).unwrap() ``` For a successful action with no return value, `unwrap()` returns `None`. Safe methods catch `PhalaCloudError` and Pydantic `ValidationError`. Other exceptions (like `KeyboardInterrupt`) still propagate normally. ### Async Safe Methods The async client works identically: ```python theme={"system"} result = await client.safe_get_cvm_info({"id": "my-app"}) if result.ok: print(result.data) ``` ## Error Codes The `phala_cloud.error_codes` module provides constants for all structured error codes. Use these to match specific errors in your error handling logic. ```python theme={"system"} from phala_cloud import ResourceError from phala_cloud.error_codes import ( CVM_APP_ID_CONFLICT, INSUFFICIENT_BALANCE, NODE_NOT_FOUND, QUOTA_EXCEEDED, ) try: client.commit_cvm_provision(payload) except ResourceError as e: if e.error_code == CVM_APP_ID_CONFLICT: print("App ID already in use with a different compose hash") elif e.error_code == INSUFFICIENT_BALANCE: print("Top up your Balance") elif e.error_code == QUOTA_EXCEEDED: print("Workspace quota exceeded") elif e.error_code == NODE_NOT_FOUND: print("The specified node doesn't exist") else: raise ``` ### Available Error Code Modules | Module | Prefix | Category | | - | - | - | | 01 | `ERR-01-xxx` | CVM preflight and compose hash | | 02 | `ERR-02-xxx` | Inventory and resource allocation | | 03 | `ERR-03-xxx` | CVM operations | | 04 | `ERR-04-xxx` | Workspace and billing | | 05 | `ERR-05-xxx` | Credentials and tokens | | 06 | `ERR-06-xxx` | Authentication — returned as OAuth redirect responses, not JSON API errors | ## Practical Patterns ### Retry on Conflict `ConflictError` (409 without structured code) is often transient. A simple retry loop handles it: ```python theme={"system"} import time from phala_cloud import ConflictError for attempt in range(3): try: client.restart_cvm({"id": "my-app"}) break except ConflictError: if attempt < 2: time.sleep(2 ** attempt) else: raise ``` ### Combining Safe + Exception Handling Use safe methods for expected failures and exceptions for unexpected ones: ```python theme={"system"} result = client.safe_provision_cvm(payload) if result.ok: print("Provisioned:", result.data) elif isinstance(result.error, ResourceError): print(f"Known issue [{result.error.error_code}]: {result.error}") else: # Re-raise unexpected errors result.unwrap() ``` ## Related * [SDK Overview](/phala-cloud/references/cloud-python-sdk/overview) — getting started * [Error Codes Reference](/phala-cloud/references/error-codes) — full list of `ERR-xxxx` codes # KMS Source: https://docs.phala.com/phala-cloud/references/cloud-python-sdk/kms List KMS contracts, inspect their nodes and verification anchors, and retrieve app encryption keys. `phala-cloud` v0.2.0 models KMS resources by contract. A KMS contract groups equivalent KMS node replicas that share one root key. Every example works with both `PhalaCloud` and `AsyncPhalaCloud`. Add `await` when you use the async client. ## list\_kms\_contracts `GET /kms` ```python theme={"system"} list_kms_contracts() -> ListKmsContractsResponse ``` **Parameters:** None. **Returns:** `ListKmsContractsResponse`, a paginated list of `KmsContract` objects. Returns the available KMS contracts. This method always requests API version `2026-06-23`. ```python Sync theme={"system"} contracts = client.list_kms_contracts() for contract in contracts.items: print(contract.slug, contract.chain_id, contract.node_count) ``` ```python Async theme={"system"} contracts = await client.list_kms_contracts() for contract in contracts.items: print(contract.slug, contract.chain_id, contract.node_count) ``` Each `KmsContract` includes the contract `id`, `slug`, `contract_address`, `chain_id`, `node_count`, `k256_pubkey`, and `ca_pubkey`. For the off-chain Phala KMS, `contract_address` is `"phala"` and `chain_id` is `0`. ## get\_kms\_contract `GET /kms/{slug}` ```python theme={"system"} get_kms_contract(slug: str) -> KmsContract ``` **Parameters:** `slug` accepts a contract slug or `kc_`-prefixed contract ID. **Returns:** `KmsContract` for the resolved contract. Returns one KMS contract by slug. A `kc_`-prefixed contract ID also resolves. ```python Sync theme={"system"} contract = client.get_kms_contract("base") print(contract.contract_address) print(contract.k256_pubkey, contract.ca_pubkey) ``` ```python Async theme={"system"} contract = await client.get_kms_contract("base") print(contract.contract_address) print(contract.k256_pubkey, contract.ca_pubkey) ``` ## list\_kms\_contract\_nodes `GET /kms/{slug}/nodes` ```python theme={"system"} list_kms_contract_nodes(slug: str) -> ListKmsContractNodesResponse ``` **Parameters:** `slug` accepts a contract slug or `kc_`-prefixed contract ID. **Returns:** `ListKmsContractNodesResponse` with the contract's node replicas. Returns the KMS node replicas under a contract, including each node's RPC URL and version. ```python Sync theme={"system"} nodes = client.list_kms_contract_nodes("base") for node in nodes.items: print(node.slug, node.url, node.version) ``` ```python Async theme={"system"} nodes = await client.list_kms_contract_nodes("base") for node in nodes.items: print(node.slug, node.url, node.version) ``` ## Legacy node methods ```python theme={"system"} get_kms_list( request: GetKmsListRequest | Mapping[str, Any] | None = None, ) -> GetKmsListResponse get_kms_info(request: KmsInfoRequest | Mapping[str, Any]) -> KmsInfo ``` `get_kms_list()` accepts optional pagination and `is_onchain` filters. `get_kms_info()` requires `kms_id`. They return the earlier node-centric KMS shapes. Both methods are deprecated and remain pinned to API version `2026-05-22`. Use `list_kms_contracts()`, `get_kms_contract()`, and `list_kms_contract_nodes()` for new code. ## get\_app\_env\_encrypt\_pub\_key `GET /kms/{kms}/pubkey/{appId}` ```python theme={"system"} get_app_env_encrypt_pub_key( request: KmsPubkeyRequest | Mapping[str, Any], ) -> AppEnvPubkeyResponse ``` **Parameters:** `kms` is a KMS node ID or slug, and `app_id` is a 20-byte app ID with or without the `0x` prefix. **Returns:** `AppEnvPubkeyResponse` with `public_key` and `signature`. Returns the public key used to encrypt environment variables for an app. ```python Sync theme={"system"} key = client.get_app_env_encrypt_pub_key({ "kms": "phala", "app_id": "ff22c67f5d3b4c8a9e1f0a2b3c4d5e6f7a8b9c0d", }) print(key.public_key, key.signature) ``` ```python Async theme={"system"} key = await client.get_app_env_encrypt_pub_key({ "kms": "phala", "app_id": "ff22c67f5d3b4c8a9e1f0a2b3c4d5e6f7a8b9c0d", }) print(key.public_key, key.signature) ``` ## next\_app\_ids `GET /kms/phala/next_app_id` ```python theme={"system"} next_app_ids( request: NextAppIdsRequest | Mapping[str, Any] | None = None, ) -> NextAppIdsResponse ``` **Parameters:** `counts` requests 1 to 20 IDs and defaults to `1`. **Returns:** `NextAppIdsResponse` with the reserved `app_id` and `nonce` pairs. Reserves app IDs from the Phala KMS for deterministic provisioning. ```python theme={"system"} reserved = client.next_app_ids({"counts": 3}) print(reserved.model_dump()) ``` ## get\_kms\_on\_chain\_detail `GET /kms/on-chain/{chain}` ```python theme={"system"} get_kms_on_chain_detail( request: KmsOnChainDetailRequest | Mapping[str, Any], ) -> GetKmsOnChainDetailResponse ``` **Parameters:** `chain` is the chain name, such as `"base"` or `"ethereum"`. **Returns:** `GetKmsOnChainDetailResponse` with the chain and its KMS contracts. Returns the contracts, registered devices, OS images, and verification anchors for an on-chain KMS. ```python theme={"system"} detail = client.get_kms_on_chain_detail({"chain": "base"}) for contract in detail.contracts: print(contract.contract_address) print(contract.k256_pubkey, contract.ca_pubkey) ``` ## Compute and verify mr\_config\_id The SDK exports byte-oriented and hex-oriented helpers: ```python theme={"system"} get_mr_config_id( compose_hash: bytes, app_id: bytes, key_provider_type: KeyProviderKind, key_provider_id: bytes, ) -> bytes get_mr_config_id_hex( compose_hash_hex: str, app_id_hex: str, key_provider_type: KeyProviderKind, key_provider_id_hex: str = "", ) -> str get_mr_config_id_v1(compose_hash: bytes) -> bytes verify_mr_config_id( mr_config_id_hex: str, compose_hash_hex: str, app_id_hex: str, key_provider_type: KeyProviderKind, key_provider_id_hex: str = "", ) -> bool ``` For `key_provider_type="kms"`, set `key_provider_id_hex` to the contract's `k256_pubkey`, not its `ca_pubkey`. ```python theme={"system"} from phala_cloud import get_mr_config_id_hex, verify_mr_config_id mr_config_id = get_mr_config_id_hex( compose_hash_hex="0x<64-hex-characters>", app_id_hex="0xff22c67f5d3b4c8a9e1f0a2b3c4d5e6f7a8b9c0d", key_provider_type="kms", key_provider_id_hex="0x", ) matches = verify_mr_config_id( mr_config_id, "0x<64-hex-characters>", "0xff22c67f5d3b4c8a9e1f0a2b3c4d5e6f7a8b9c0d", "kms", "0x", ) ``` Use `get_mr_config_id()` for byte inputs and `get_mr_config_id_v1()` for the V1 compose-hash-only format. ## Related * [CVM Configuration](/phala-cloud/references/cloud-python-sdk/cvm-configuration) * [Error Handling](/phala-cloud/references/cloud-python-sdk/error-handling) # Cloud Python SDK Source: https://docs.phala.com/phala-cloud/references/cloud-python-sdk/overview Python SDK for Phala Cloud API — sync and async clients with Pydantic validation, safe error handling, and REPL-friendly design. > [!NOTE] > > The Python SDK is currently in **beta**. The API surface may change between releases. The `phala-cloud` SDK gives you a Pythonic interface to the Phala Cloud API. It ships with both sync and async clients, Pydantic-validated responses, and a `safe_*` method pattern that lets you handle errors without try/except blocks. ## Installation ```bash theme={"system"} pip install phala-cloud ``` ```bash theme={"system"} uv add phala-cloud ``` ```bash theme={"system"} poetry add phala-cloud ``` > [!NOTE] > > Requires Python 3.10 or later. The SDK depends on `httpx`, `pydantic`, and `dstack-sdk`. ## Quick Start ```python Sync theme={"system"} from phala_cloud import create_client client = create_client(api_key="phak_your_api_key") me = client.get_current_user() print(me.model_dump()) ``` ```python Async theme={"system"} import asyncio from phala_cloud import create_async_client async def main(): client = create_async_client(api_key="phak_your_api_key") me = await client.get_current_user() print(me.model_dump()) await client.aclose() asyncio.run(main()) ``` ## Client Creation ### `create_client(**kwargs)` / `create_async_client(**kwargs)` Factory functions that return a `PhalaCloud` (sync) or `AsyncPhalaCloud` (async) instance. Both accept the same configuration options. ```python theme={"system"} from phala_cloud import create_client, create_async_client # Minimal — reads API key from PHALA_CLOUD_API_KEY env var client = create_client() # Explicit configuration client = create_client( api_key="phak_your_api_key", base_url="https://cloud-api.phala.com/api/v1", version="2026-06-23", timeout=30.0, ) ``` ### Configuration Options | Option | Type | Default | Description | | - | - | - | - | | `api_key` | `str` | `PHALA_CLOUD_API_KEY` env var | API key for authentication | | `bearer_token` | `str` | `PHALA_OIDC_TOKEN` env var | Bearer token; API key takes precedence | | `workspace` | `str` | `PHALA_CLOUD_WORKSPACE` env var | Workspace slug | | `base_url` | `str` | `https://cloud-api.phala.com/api/v1` | API base URL (or `PHALA_CLOUD_API_PREFIX` env var) | | `version` | `ApiVersion` | `"2026-06-23"` | API version to use | | `timeout` | `float` | `60.0` | Request timeout in seconds | | `use_cookie_auth` | `bool` | `False` | Use cookie-based auth instead of API key | | `headers` | `dict[str, str]` | `None` | Additional request headers | | `http_client` | `httpx.Client` / `httpx.AsyncClient` | `None` | Bring your own httpx client | ### User-Agent By default the SDK sends `User-Agent: phala-cloud-sdk-python/ python/ httpx/`, for example `phala-cloud-sdk-python/0.4.0 python/3.13.1 httpx/0.28.1`. To use your own value, pass a `User-Agent` entry in `headers`. A header you supply overrides the default. ```python theme={"system"} client = create_client( api_key="phak_your_api_key", headers={"User-Agent": "my-automation/2.0"}, ) ``` ### API Versions The SDK supports four API versions. The version affects response shapes for endpoints such as `get_current_user()` and `get_cvm_list()`. ```python theme={"system"} from phala_cloud import SUPPORTED_API_VERSIONS, DEFAULT_API_VERSION print(SUPPORTED_API_VERSIONS) # ("2025-10-28", "2026-01-21", "2026-05-22", "2026-06-23") print(DEFAULT_API_VERSION) # "2026-06-23" ``` You can switch versions on an existing client without creating a new one from scratch: ```python theme={"system"} legacy_client = client.with_version("2025-10-28") ``` ## Sync vs. Async Almost every method on the sync `PhalaCloud` client has an identical counterpart on `AsyncPhalaCloud`. The async version simply requires `await`. The one difference is `follow_cvm_logs`: on the async client you do not await it, you iterate the result with `async for` (see [CVM Logs](#cvm-logs)). ```python Sync theme={"system"} client = create_client(api_key="phak_your_api_key") cvms = client.get_cvm_list() client.close() ``` ```python Async theme={"system"} client = create_async_client(api_key="phak_your_api_key") cvms = await client.get_cvm_list() await client.aclose() ``` Both clients support context managers for automatic cleanup: ```python Sync theme={"system"} with create_client(api_key="phak_your_api_key") as client: cvms = client.get_cvm_list() ``` ```python Async theme={"system"} async with create_async_client(api_key="phak_your_api_key") as client: cvms = await client.get_cvm_list() ``` ## Safe Methods Most action methods have a `safe_*` variant that returns a `SafeResult` instead of raising exceptions. `watch_cvm_state` does not have a safe variant. This is useful when you want to handle errors as values rather than control flow. ```python theme={"system"} result = client.safe_get_cvm_info({"id": "my-app"}) if result.ok: print(result.data) else: print(result.error) ``` Read more in [Error Handling](/phala-cloud/references/cloud-python-sdk/error-handling). ## Available Actions ### Authentication & User | Method | Description | | - | - | | `get_current_user()` | Get current user, workspace, and credits info | | `revoke_current_api_token()` | Revoke the token used for the request | ### CVM Query | Method | Description | | - | - | | `get_cvm_list(request?)` | List all CVMs (paginated) | | `get_cvm_info(request)` | Get single CVM details | | `get_cvm_state(request)` | Get CVM current state | | `get_cvm_stats(request)` | Get CVM system stats | | `get_cvm_network(request)` | Get CVM network info | | `get_cvm_docker_compose(request)` | Get Docker Compose YAML | | `get_cvm_compose_file(request)` | Get compose file content | | `get_cvm_containers_stats(request)` | Get container stats | | `get_cvm_attestation(request)` | Get TEE attestation | | `get_cvm_pre_launch_script(request)` | Get pre-launch script | | `get_cvm_user_config(request)` | Get user config | | `get_cvm_status_batch(request)` | Get typed status and resource usage for multiple CVMs | | `fetch_cvm_logs(cvm_id, source, ...)` | Fetch serial, node, or container logs | | `follow_cvm_logs(cvm_id, source, ...)` | Stream logs as an iterator (an async iterator on the async client) | ### CVM Lifecycle | Method | Description | | - | - | | `provision_cvm(request)` | Create a new CVM | | `commit_cvm_provision(request)` | Commit a CVM provision | | `start_cvm(request)` | Start a CVM | | `stop_cvm(request)` | Stop a CVM | | `shutdown_cvm(request)` | Gracefully shut down a CVM | | `restart_cvm(request)` | Restart a CVM | | `delete_cvm(request)` | Delete a CVM | | `replicate_cvm(request)` | Create a replica of a CVM | ### CVM Configuration | Method | Description | | - | - | | `update_cvm_envs(request)` | Update environment variables | | `update_docker_compose(request)` | Update Docker Compose config | | `update_pre_launch_script(request)` | Update pre-launch script | | `update_cvm_resources(request)` | Update resource allocation | | `update_cvm_visibility(request)` | Update visibility settings | | `update_os_image(request)` | Update OS image | | `get_available_os_images(request)` | List available OS images | | `patch_cvm(request)` | Patch multiple CVM fields at once | | `commit_cvm_update(request)` | Commit a prepared CVM update | ### Apps | Method | Description | | - | - | | `get_app_list(request?)` | List apps | | `get_app_info(request)` | Get app details | | `get_app_cvms(request)` | List CVMs for an app | | `create_app_instance(request)` | Create another instance for an app | | `get_app_revisions(request)` | List app revision history | | `get_app_revision_detail(request)` | Get revision details | | `get_app_filter_options()` | Get available filter options | | `get_app_attestation(request)` | Get app attestation | | `get_app_device_allowlist(request)` | Get device allowlist | ### Workspaces | Method | Description | | - | - | | `list_workspaces(request?)` | List workspaces | | `get_workspace(request)` | Get workspace details | | `get_workspace_nodes(request)` | List workspace nodes | | `get_workspace_quotas(request)` | Get workspace quotas | ### KMS (Key Management) | Method | Description | | - | - | | `list_kms_contracts()` | List KMS contracts | | `get_kms_contract(slug)` | Get a KMS contract by slug or contract ID | | `list_kms_contract_nodes(slug)` | List node replicas under a KMS contract | | `get_kms_info(request)` | Get legacy node-centric KMS info (deprecated) | | `get_kms_list(request?)` | List legacy node-centric KMS instances (deprecated) | | `get_kms_on_chain_detail(request)` | Get on-chain KMS details and verification anchors | | `get_app_env_encrypt_pub_key(request)` | Get env encryption public key | | `next_app_ids(request?)` | Get next available app IDs | ### SSH Keys | Method | Description | | - | - | | `list_ssh_keys()` | List SSH keys | | `create_ssh_key(request)` | Add an SSH key | | `delete_ssh_key(request)` | Remove an SSH key | | `import_github_profile_ssh_keys(request)` | Import SSH keys from GitHub profile | | `sync_github_ssh_keys()` | Sync SSH keys from GitHub | | `get_cvm_ssh_keys(request)` | Get the configured CVM SSH keys | | `update_cvm_ssh_keys(request)` | Replace the configured CVM SSH keys | ### Nodes & Instance Types | Method | Description | | - | - | | `get_available_nodes()` | List available TEE nodes | | `list_all_instance_type_families()` | List all instance type families | | `list_family_instance_types(request)` | List instance types in a family | ## CVM Logs Available in `phala-cloud` 0.4.0 and later. The behavior described here is complete in 0.4.4, so use 0.4.4 or later. `fetch_cvm_logs` and `follow_cvm_logs` read serial, node, and container logs. Both `PhalaCloud` and `AsyncPhalaCloud` have them. On `AsyncPhalaCloud`, `fetch_cvm_logs` is a coroutine and `follow_cvm_logs` returns an async iterator. ```python theme={"system"} from phala_cloud import LogAccessError, create_client client = create_client(api_key="phak_your_api_key") # Last 100 lines of the serial console serial = client.fetch_cvm_logs( "my-app", {"type": "node", "channel": "serial"}, tail=100, ) print(serial) # Follow the "api" container; the with block closes the stream when it exits try: with client.follow_cvm_logs( "my-app", {"type": "container", "name": "api"}, tail=50, ) as follow: for entry in follow: print(entry["message"], end="") except LogAccessError as error: print(error.code, error.suggestions) ``` The async client has the same methods: ```python theme={"system"} import asyncio from phala_cloud import LogAccessError, create_async_client async def main() -> None: async with create_async_client(api_key="phak_your_api_key") as client: # Container entries as a list entries = await client.fetch_cvm_logs( "my-app", {"type": "container", "name": "api"}, tail=100, format="ndjson", ) for entry in entries: print(entry["channel"], entry["message"], end="") # Follow as entries; aclose() runs when the loop exits follow = client.follow_cvm_logs( "my-app", {"type": "container", "name": "api"}, tail=50, ) try: async for entry in follow: print(entry["message"], end="") except LogAccessError as error: print(error.code, error.suggestions) finally: await follow.aclose() asyncio.run(main()) ``` ```python theme={"system"} def fetch_cvm_logs( self, cvm_id: str, source: CvmLogSource, *, tail: int | str | None = None, since: str | int | None = None, until: str | int | None = None, timestamps: bool = False, ansi: bool = False, format: CvmLogFormat | None = None, log_http: httpx.Client | None = None, ) -> str | list[CvmLogEntry]: ... def follow_cvm_logs( self, cvm_id: str, source: CvmLogSource, *, tail: int | str | None = None, since: str | int | None = None, until: str | int | None = None, timestamps: bool = False, ansi: bool = False, format: CvmLogFormat | None = None, log_http: httpx.Client | None = None, ) -> LogFollowIterator[str | CvmLogEntry]: ... ``` `AsyncPhalaCloud` has the same parameters. Its `log_http` is an `httpx.AsyncClient`, `fetch_cvm_logs` is declared `async def`, and `follow_cvm_logs` returns `AsyncGenerator[str | CvmLogEntry, None]`. `LogFollowIterator` and the entry types are importable from `phala_cloud.logs`. **Parameters:** | Name | Type | Default | Description | | - | - | - | - | | `cvm_id` | `str` | None | CVM identifier (name, UUID, or App ID) | | `source` | `CvmLogSource` | None | Which logs to read (see below) | | `tail` | `int \| str \| None` | `None` | Number of most recent lines, or `"all"`. When `None`, the server default applies. | | `since` | `str \| int \| None` | `None` | Start time: RFC 3339 timestamp, Unix seconds, or relative duration such as `"10m"` (`s`, `m`, `h`, `d`). | | `until` | `str \| int \| None` | `None` | End time. Same formats as `since`. | | `timestamps` | `bool` | `False` | Prefix each container line with its timestamp. | | `ansi` | `bool` | `False` | Keep ANSI escape sequences in the output. The default removes them from every line and entry, including NDJSON messages. This is an output option, so it never causes an error. | | `format` | `"text" \| "ndjson"` | `None` | For a container, `fetch_cvm_logs` returns a `str` (the messages joined) unless you pass `"ndjson"`, which returns a list of entries. `follow_cvm_logs` yields entries unless you pass `"text"`, which yields text lines. Without a format, containers are read as NDJSON; `"text"` uses the plain-text transport. `"ndjson"` with a node source raises `LogAccessError`. | | `log_http` | `httpx.Client \| None` | `None` | Your own `httpx.Client` for the log requests. When omitted, the SDK creates one and closes it when the call finishes. | **`CvmLogSource`** is a dictionary: | Shape | Description | | - | - | | `{"type": "node", "channel": "serial" \| "stdout" \| "stderr"}` | A CVM-level channel | | `{"type": "container", "name": str, "matchContainerIdPrefix": bool}` | A container. Both `name` and `matchContainerIdPrefix` are optional. `name` is a container name or ID prefix; if you omit it, the SDK uses the first container in the CVM composition. `matchContainerIdPrefix` defaults to `True`. See [Container names](#container-names). | `since`, `until`, and `timestamps` apply to container logs only. Passing them with a node source raises `LogAccessError` with code `ERR-17-001` before any request is sent. An invalid time value does the same. **Return types:** | Call | Source | Result | | - | - | - | | `fetch_cvm_logs` | Node | `str` | | `fetch_cvm_logs` | Container | `str`, or `list[CvmLogEntry]` when `format="ndjson"` | | `follow_cvm_logs` | Node | Iterator of `str` lines, each delivered with its original newline (or lack of one), after heartbeat lines are dropped and ANSI escapes are stripped (unless `ansi` is `True`) | | `follow_cvm_logs` | Container | Iterator of `CvmLogEntry`, or `str` lines when `format="text"` | `CvmLogEntry` is a dictionary: `{"channel": "stdout" | "stderr" | "console" | "stdin", "message": str}`. `console` appears for containers started with a TTY. `message` is exactly what the container wrote, usually ending in a newline. An empty message stays an empty string. The types are importable from `phala_cloud.logs`. ### Container names The SDK resolves the container name once at the start of a follow, with one composition call. It tries these steps in order: 1. An exact match on a container name. 2. A unique match on the start of a container ID, unless `matchContainerIdPrefix` is `False`. 3. If you gave no name, the first container in the composition. If the prefix matches more than one container, the SDK raises `LogAccessError` with code `ERR-17-001` and the message `Ambiguous container prefix '': web, worker`, which lists the candidates. If nothing matches, it raises `LogAccessError` with code `ERR-17-007`. If the composition has no containers and returns an `error` string, for example because the CVM is stopped, the SDK raises `LogAccessError` with that message. A name you pass must be 1 to 128 characters, start with a letter or digit, and then use only letters, digits, `_`, `.`, and `-`. It must not contain `..`. Other names, such as `/app`, are rejected with `ERR-17-001` before any request is sent. ### Cancellation * Sync follow: leaving the loop with `break` does not close the HTTP response. Call `close()` on the returned iterator, or use it in a `with` block, which calls `close()` for you. `close()` also works from another thread and interrupts a wait between reconnects. * Async follow: leave the loop and call `await follow.aclose()`, or cancel the task that is iterating. Waits between reconnects are interrupted. * Async `fetch_cvm_logs`: cancel the task that is awaiting it. * Sync `fetch_cvm_logs` is a single blocking call. It cannot be cancelled while a request is in progress. **Behavior:** * Every connection uses a fresh signed URL, with one CVM info lookup per connection. * Follow reconnects after a stream ends or fails. Failures back off from 250 ms, doubling up to 5 s, and follow gives up after 5 consecutive failures. Starts of two connections are at least 1 s apart. * HTTP errors are handled by status. `5xx` and `429` are failures. `401` with `ERR-17-003` fetches a new URL and retries, up to 3 times in a row. The count resets after a connection that delivered records or ended cleanly. `401` with `ERR-17-002` fetches a new URL and counts as a failure. Any other `4xx` stops follow. * A gateway error line inside a `200` stream, or a network error, counts as a failure. A connection that delivered at least one record resets the failure count before its own failure is counted. * Container follow always requests timestamps internally. It sends the caller's `tail` until the first connection is accepted. Every later request sends `tail=all` plus `since`, and skips lines it already delivered at the boundary second, so a reconnect does not repeat output. Before any timestamped record arrives, it uses your `since` if you set one, otherwise the second the first connection was accepted. Timestamps are removed from the output unless you set `timestamps=True`. * Container follow: if a stream ends cleanly with no new output within 10 s, it backs off and counts the end. After 5 such ends in a row, follow raises `LogAccessError` with the message `log stream keeps ending without new output; the container may have stopped`. A clean end after records, or after an idle connection of 10 s or more, reconnects at once and resets the count. * Node follow never stops on a clean end. After the first connection it requests `tail=0`. * If you set `until`, follow finishes normally, without an error, when the stream reaches that time. * A missing container is not retried. * Node follow and fetch drop `[vmm heartbeat]` and `[teepod heartbeat]` lines. * A text-format record that looks like `{"error": ...}` is treated as a guest error only at the very start of the body. Use NDJSON (the default for entries) for reliable detection. * The helpers request CVM info with API version `2026-01-21` internally, so they work with clients configured for older versions. For the HTTP details behind these methods, see [Fetch Logs over HTTP](/phala-cloud/monitoring/log-api). **Errors:** Log gateway errors are raised as `LogAccessError`, a subclass of `ResourceError`. Match on `code` rather than the message. | Attribute | Type | Description | | - | - | - | | `code` | `str \| None` | Log error code such as `ERR-17-005`. The code is not repeated in the message, which holds the human-readable text only. | | `http_status` | `int \| None` | HTTP status, set only for errors returned as an HTTP response. `None` for client-side errors (bad container name, bad time, unsupported option) and for errors read from the body of a stream. | | `suggestions` | `list[str] \| None` | Suggested fixes from the API | `LogAccessError` is a `ResourceError`, so it also carries `error_code`, `structured_details`, `links`, and `request_id` from the API error envelope. Container logs require [Public Logs](/phala-cloud/monitoring/public-logs) to be enabled on the CVM. When it is off, container fetch and follow raise `LogAccessError` with code `ERR-17-006` ("Container logs are disabled") before sending any log request. Follow checks this before its first log request and again on every reconnect, because each connection looks up the CVM info. Node channels are not affected. A missing container raises `LogAccessError` with code `ERR-17-007` (see [Container names](#container-names)). If the agent inside the CVM cannot read a container's logs, for example because the container uses a Docker logging driver that does not support reading, the method raises `LogAccessError` with code `ERR-17-009` and the agent's message. This applies to text and NDJSON, in fetch and in follow. Follow stops on it. A server-returned HTTP `502` with `ERR-17-009` is different: follow reconnects. See [Fetch Logs over HTTP](/phala-cloud/monitoring/log-api#errors) for the full error code list. ## Utility Functions The SDK also exports standalone utility functions for working with CVM configurations: ```python theme={"system"} from phala_cloud import ( async_encrypt_env_vars, encrypt_env_vars, get_compose_hash, get_mr_config_id_hex, parse_env, parse_env_vars, verify_env_encrypt_public_key, ) ``` | Function | Description | | - | - | | `encrypt_env_vars(envs, public_key_hex)` | Encrypt environment variables synchronously | | `async_encrypt_env_vars(envs, public_key_hex)` | Encrypt environment variables asynchronously | | `get_compose_hash(...)` | Compute the hash of canonicalized `app-compose.json` | | `get_mr_config_id(...)` | Compute V2 `mr_config_id` from byte inputs | | `get_mr_config_id_hex(...)` | Compute V2 `mr_config_id` from hex inputs | | `get_mr_config_id_v1(...)` | Compute the V1 compose-hash-only format | | `verify_mr_config_id(...)` | Verify a V2 `mr_config_id` | | `verify_env_encrypt_public_key(...)` | Verify KMS encryption public key | | `parse_env(path)` | Parse a `.env` file into key-value pairs | | `parse_env_vars(content)` | Parse dotenv content string into key-value pairs | | `verify_webhook_signature(...)` | Verify HMAC-SHA256 webhook signature with timestamp tolerance | | `parse_webhook_event(...)` | Verify signature and parse webhook event in one step | ### Encrypt environment variables Pass the output of `parse_env_vars` or a sequence of `dstack_sdk.EnvVar` objects to either helper. The public key must be a hex string. ```python theme={"system"} from phala_cloud import encrypt_env_vars, parse_env_vars envs = parse_env_vars("API_TOKEN=secret") encrypted = encrypt_env_vars(envs, public_key_hex) ``` In async code, use `await async_encrypt_env_vars(envs, public_key_hex)`. Both helpers return the encrypted string. > [!WARNING] > > `encrypt_env_vars` now returns a string synchronously. If you previously awaited it, replace `await encrypt_env_vars(...)` with `await async_encrypt_env_vars(...)`. ### On-chain operations The Python SDK removed the nonfunctional `add_compose_hash` and `deploy_app_auth` wrappers and their safe variants. For on-chain registration, use the [JavaScript SDK](/phala-cloud/references/cloud-js-sdk/add-compose-hash) or your own web3 integration. ### Webhook Verification Example ```python theme={"system"} from phala_cloud import verify_webhook_signature, parse_webhook_event # Verify and parse a webhook request event = parse_webhook_event( headers=dict(request.headers), body=request.body.decode(), secret="whsec_...", ) print(event.event, event.data) ``` See [Webhooks](/phala-cloud/references/webhooks) for full payload format and delivery behavior. ## Related * [Authentication](/phala-cloud/references/cloud-python-sdk/authentication) — API key configuration * [CVM Lifecycle](/phala-cloud/references/cloud-python-sdk/cvm-lifecycle) — provisioning and managing CVMs * [Error Handling](/phala-cloud/references/cloud-python-sdk/error-handling) — error classes and safe methods * [Webhooks](/phala-cloud/references/webhooks) — webhook events, signatures, and delivery * [Cloud API Reference](/phala-cloud/phala-cloud-api/overview) — full REST API docs # SSH Keys Source: https://docs.phala.com/phala-cloud/references/cloud-python-sdk/ssh-keys List, create, delete SSH keys and import them from GitHub. SSH key methods manage the public keys associated with your Phala Cloud account. These keys are injected into CVMs at boot time, giving you SSH access to your running instances. ## list\_ssh\_keys `GET /user/ssh-keys` Lists all SSH keys registered to your account. **Parameters:** None. **Returns:** List of SSH key objects. **Example:** ```python Sync theme={"system"} keys = client.list_ssh_keys() for key in keys: print(key.id, key.name, key.fingerprint) ``` ```python Async theme={"system"} keys = await client.list_ssh_keys() for key in keys: print(key.id, key.name, key.fingerprint) ``` *** ## create\_ssh\_key `POST /user/ssh-keys` Adds a new SSH public key to your account. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `name` | `str` | Yes | Display name for the key | | `public_key` | `str` | Yes | SSH public key content | **Returns:** The created SSH key object. **Example:** Replace the sample public key with your own key before using it for access. ```python Sync theme={"system"} key = client.create_ssh_key({ "name": "my-laptop", "public_key": "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAID4dR/9d26lbwH5ViDEJgWZqaHI6/Mlr8QyTfE6w8ANk docs-example", }) print(key.id) ``` ```python Async theme={"system"} key = await client.create_ssh_key({ "name": "my-laptop", "public_key": "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAID4dR/9d26lbwH5ViDEJgWZqaHI6/Mlr8QyTfE6w8ANk docs-example", }) print(key.id) ``` *** ## delete\_ssh\_key `DELETE /user/ssh-keys/{keyId}` Removes an SSH key from your account. Existing CVMs that were provisioned with this key will retain it until they are restarted. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `key_id` | `str` | Yes | SSH key identifier | **Returns:** `None` **Example:** ```python Sync theme={"system"} client.delete_ssh_key({"key_id": "key-abc123"}) ``` ```python Async theme={"system"} await client.delete_ssh_key({"key_id": "key-abc123"}) ``` *** ## import\_github\_profile\_ssh\_keys `POST /user/ssh-keys/github-profile` Imports SSH public keys from a GitHub user profile. This fetches the keys listed at `https://github.com/{username}.keys` and adds them to your account. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `github_username` | `str` | Yes | GitHub username to import keys from | **Returns:** Import response with the number of keys imported. **Example:** ```python Sync theme={"system"} result = client.import_github_profile_ssh_keys({ "github_username": "octocat", }) print(result.model_dump()) ``` ```python Async theme={"system"} result = await client.import_github_profile_ssh_keys({ "github_username": "octocat", }) ``` *** ## sync\_github\_ssh\_keys `POST /user/ssh-keys/github-sync` Syncs SSH keys from your connected GitHub account. This requires that your Phala Cloud account is linked to GitHub via OAuth. Unlike `import_github_profile_ssh_keys`, this uses your authenticated GitHub connection and keeps keys in sync. **Parameters:** None. **Returns:** Sync response with details of added/removed keys. **Example:** ```python Sync theme={"system"} result = client.sync_github_ssh_keys() print(result.model_dump()) ``` ```python Async theme={"system"} result = await client.sync_github_ssh_keys() print(result.model_dump()) ``` ## CVM SSH keys `get_cvm_ssh_keys({"cvm_id": "my-app"})` reads `GET /cvms/{cvmId}/ssh-keys`. It returns a `CvmSshKeysResponse` with `keys` and `restart_required`. This is the stored configuration; use `get_cvm_user_config` for the running VM's configuration. `update_cvm_ssh_keys` sends `PUT /cvms/{cvmId}/ssh-keys` and replaces the configured key set. `ssh_key_ids` is required: include every selected key you want to retain. An empty list removes all selected keys unless `usernames` adds members' resolved keys. Changes take effect at the next power-on, or immediately if `apply_now` restarts the CVM. This example uses the key created above. Add any other key IDs you want to retain. ```python theme={"system"} result = client.update_cvm_ssh_keys({ "cvm_id": "my-app", "ssh_key_ids": [key.id], "apply_now": False, }) print(result.restart_required) ``` The async client supports the same calls with `await`. Both methods also have `safe_` variants. ## Related * [Authentication](/phala-cloud/references/cloud-python-sdk/authentication) — account setup * [CVM Lifecycle](/phala-cloud/references/cloud-python-sdk/cvm-lifecycle) — provisioning CVMs with SSH access # Workspaces Source: https://docs.phala.com/phala-cloud/references/cloud-python-sdk/workspaces List workspaces, get workspace details, query nodes, and check quotas. Workspace methods let you query the workspaces (teams) you belong to, inspect their nodes, and check resource quotas. Every CVM belongs to a workspace, and quotas are enforced at the workspace level. ## list\_workspaces `GET /workspaces` Lists all workspaces the authenticated user has access to. **Parameters:** Optional dictionary of query parameters. **Returns:** List of workspace summaries. **Example:** ```python Sync theme={"system"} workspaces = client.list_workspaces() for ws in workspaces.items: print(ws.slug, ws.name) ``` ```python Async theme={"system"} workspaces = await client.list_workspaces() for ws in workspaces.items: print(ws.slug, ws.name) ``` *** ## get\_workspace `GET /workspaces/{teamSlug}` Retrieves detailed information about a specific workspace. You can pass the team slug as a plain string or as a dictionary. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `team_slug` | `str` | Yes | Workspace slug identifier | **Returns:** Workspace detail response. **Example:** ```python Sync theme={"system"} # Pass slug directly as a string ws = client.get_workspace("my-team") # Or pass as a dict ws = client.get_workspace({"team_slug": "my-team"}) print(ws.name) ``` ```python Async theme={"system"} ws = await client.get_workspace("my-team") print(ws.name) ``` *** ## get\_workspace\_nodes `GET /workspaces/{teamSlug}/nodes` Lists the TEE nodes available to a workspace. Supports pagination. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `team_slug` | `str` | Yes | Workspace slug identifier | | `page` | `int` | No | Page number (1-based) | | `page_size` | `int` | No | Items per page | **Returns:** Paginated list of workspace nodes. **Example:** ```python Sync theme={"system"} nodes = client.get_workspace_nodes({ "team_slug": "my-team", "page": 1, "page_size": 20, }) for node in nodes.items: print(node.id, node.name) ``` ```python Async theme={"system"} nodes = await client.get_workspace_nodes({ "team_slug": "my-team", "page": 1, "page_size": 20, }) ``` *** ## get\_workspace\_quotas `GET /workspaces/{teamSlug}/quotas` Returns the resource quotas and current usage for a workspace. This includes limits on CVMs, vCPUs, memory, and other resources. Like `get_workspace`, you can pass the team slug as a string or dictionary. **Parameters:** | Field | Type | Required | Description | | - | - | - | - | | `team_slug` | `str` | Yes | Workspace slug identifier | **Returns:** Workspace quotas response with limits and current usage. **Example:** ```python Sync theme={"system"} quotas = client.get_workspace_quotas("my-team") print(quotas.model_dump()) ``` ```python Async theme={"system"} quotas = await client.get_workspace_quotas("my-team") print(quotas.model_dump()) ``` ## Related * [Apps](/phala-cloud/references/cloud-python-sdk/apps) — app-level operations * [SDK Overview](/phala-cloud/references/cloud-python-sdk/overview) — full method listing # Error Codes Source: https://docs.phala.com/phala-cloud/references/error-codes Reference for Phala Cloud API error codes # Error Code Catalog This document lists all error codes used by Phala Cloud API. Error codes follow the format `ERR-{MODULE}-{CODE}` where: * **MODULE**: Two-digit module identifier (01, 02, 03, ...) * **CODE**: Three-digit sequential error number within the module ## Modules * **Module 01** - CVM API / Preflight * **Module 02** - Inventory * **Module 03** - CVM Operations * **Module 04** - Workspace * **Module 05** - Credentials * **Module 06** - Auth * **Module 09** - Billing * **Module 10** - GPU Rental * **Module 11** - Centralized KMS * **Module 12** - KMS * **Module 14** - Confidential AI * **Module 16** - Trust Center * **Module 17** - Log Access *** ## Module 01: CVM API / Preflight | Error Code | Message | | - | - | | `ERR-01-001` | The requested node is not available | | `ERR-01-002` | The request contains invalid parameters | | `ERR-01-003` | The Docker Compose file contains errors | | `ERR-01-004` | (dynamic: A CVM with name '...) | | `ERR-01-005` | Compose hash registration required on-chain | | `ERR-01-006` | The provided compose hash is invalid or has expired | | `ERR-01-007` | Transaction verification failed | | `ERR-01-008` | The compose hash is not allowed by the on-chain contract | | `ERR-01-009` | VM creation failed on the target node | | `ERR-01-010` | The deployment violates the terms of use | | `ERR-01-011` | node\_id and teepod\_id are not supported for node selection | ## Module 02: Inventory | Error Code | Message | | - | - | | `ERR-02-001` | The requested instance type does not exist | | `ERR-02-002` | No available resources match your requirements | | `ERR-02-003` | The selected node does not have enough CPU capacity | | `ERR-02-004` | The selected node does not have enough memory | | `ERR-02-005` | The selected node has reached its maximum capacity | | `ERR-02-006` | The selected node does not have enough GPU resources | | `ERR-02-007` | The selected node does not have enough GPU resources | | `ERR-02-008` | The request contains invalid parameters | | `ERR-02-009` | The configuration parameters are not compatible with each other | | `ERR-02-010` | The requested operating system image is not available | | `ERR-02-011` | The requested security configuration is not available on this node | | `ERR-02-012` | The requested node is not available | | `ERR-02-013` | The requested operating system image is not available | | `ERR-02-014` | The requested node is not available | | `ERR-02-015` | Your account has reached its resource quota | | `ERR-02-016` | GPUs are available but currently occupied at device level | | `ERR-02-017` | No enabled gateway is available for the selected node | | `ERR-02-018` | This node has multiple device IDs; specify which one to use | | `ERR-02-019` | This node has no device ID configured | | `ERR-02-020` | Failed to allocate an app ID from the centralized KMS | | `ERR-02-021` | The requested KMS was not found | | `ERR-02-022` | The requested KMS node was not found | | `ERR-02-023` | The KMS node did not respond | | `ERR-02-024` | Invalid GPU product requirement | | `ERR-02-025` | GPU instance type has no configured GPU product requirement | | `ERR-02-026` | (dynamic: This CVM's active GPU allocation does not match th...) | | `ERR-02-027` | (dynamic: A GPU CVM cannot be resized into an instance type ...) | | `ERR-02-028` | (dynamic: Instance type '...) | | `ERR-02-029` | (dynamic: This instance type requires ...) | | `ERR-02-030` | The requested KMS is disabled | | `ERR-02-031` | The requested KMS contract is disabled | | `ERR-02-032` | (dynamic message) | | `ERR-02-033` | Port mappings cannot be set at creation for an instance type that uses bridge networking. | ## Module 03: CVM Operations | Error Code | Message | | - | - | | `ERR-03-001` | No CVM found with the specified name in this workspace | | `ERR-03-002` | Multiple CVMs have the same name in this workspace | | `ERR-03-003` | No CVM found in this workspace | | `ERR-03-004` | The requested CVM was not found | | `ERR-03-005` | The requested CVM was not found | | `ERR-03-006` | The source CVM's OS image is not available on the target node | | `ERR-03-007` | This app\_id already has an active CVM with a different configuration. Provision again to get a new app\_id, or use the existing CVM. | | `ERR-03-008` | The source CVM instance was not found in this workspace or access is denied | | `ERR-03-009` | This app has multiple live CVM instances. Please specify compose\_hash to choose which revision to replicate. | | `ERR-03-010` | Multiple CVMs match this identifier in the workspace | | `ERR-03-014` | The target OS image is not compatible with the source CVM | | `ERR-03-015` | Another operation is already in progress for this CVM | | `ERR-03-016` | Port mappings were saved, but the node firewall still has a rule that should have been created or removed. | | `ERR-03-017` | The revision expects different environment variable names. Provide a re-encrypted encrypted\_env value or set allow\_env\_mismatch to true to continue. | | `ERR-03-018` | This machine cannot start with the selected OS image, node version, and key provider pin. Choose a compatible combination and try again. | | `ERR-03-019` | The current compose revision for this CVM could not be found | | `ERR-03-020` | The current compose revision failed integrity validation | | `ERR-03-022` | We could not set up the GPU for this CVM. The problem is on our side, so changing your compose file will not fix it. | | `ERR-03-023` | We could not stop this CVM. The host did not finish the stop. The problem is on our side. | | `ERR-03-024` | This CVM could not get its keys from KMS while it was booting, so it did not start. The problem is on our side, so changing your compose file will not fix it. | | `ERR-03-025` | This CVM booted, but it could not register with the Phala Cloud gateway, so the start failed. The problem is on our side, so changing your compose file will not fix it. | | `ERR-03-026` | The container registry rejected the login when this CVM tried to pull an image from your compose file. | | `ERR-03-027` | KMS did not let this CVM boot. Its compose hash is not on your app's allow list. | | `ERR-03-028` | This CVM did not boot because one of its environment variables was rejected. A name or a value is empty, too long, or not valid. | | `ERR-03-029` | (dynamic: The ...) | | `ERR-03-030` | Guest agent access for this app is restricted to Phala Cloud. Relaxing the restriction requires Phala Cloud support. | | `ERR-03-031` | Manifest version 3 is not supported by this legacy endpoint. Use app-compose.json instead. | | `ERR-03-032` | This CVM's configuration on our side is incomplete, so we cannot reach it right now. Please contact support. | | `ERR-03-033` | The CVM has no resumable in-progress operation | | `ERR-03-034` | The operation's task is still running | | `ERR-03-035` | The operation changed while it was being resumed | | `ERR-03-036` | This CVM is protected from deletion | | `ERR-03-037` | This CVM is protected from shutdown | | `ERR-03-038` | This CVM cannot start while its host is being decommissioned. | | `ERR-03-039` | This CVM is being deleted. | | `ERR-03-040` | (dynamic: cannot be changed on an existing CVM....) | | `ERR-03-041` | tproxy\_enabled cannot be set when creating a CVM. Use gateway\_enabled instead. | | `ERR-03-042` | requirements.gpu\_policy is not enabled for this account or workspace. | | `ERR-03-043` | requirements.launch\_token\_hash does not match this app's launch token. | | `ERR-03-044` | This app already has a different launch token. | | `ERR-03-045` | (dynamic: is not enabled for this account or workspace....) | | `ERR-03-046` | (dynamic: Runner ...) | | `ERR-03-047` | (dynamic: The ...) | | `ERR-03-048` | (dynamic: Turning on ...) | | `ERR-03-049` | CVM annotations are not enabled for this account or workspace. | | `ERR-03-050` | (dynamic: The node runs dstack VMM ...) | | `ERR-03-051` | (dynamic: The node could not read or update the CVM annotati...) | | `ERR-03-052` | This CVM has no staged changes. | | `ERR-03-053` | The CVM changed after these changes were staged. | | `ERR-03-054` | The staged changes were changed by another request. Load them and try again. | | `ERR-03-055` | CVMs of this app still require the launch token, so it cannot be cleared. | | `ERR-03-056` | This app\_id is reserved and cannot be deployed | | `ERR-03-057` | This CVM is not reachable via its node right now. Retry in a moment, or contact support if it persists. | | `ERR-03-058` | Send either init\_script or init\_scripts, not both. | ## Module 04: Workspace | Error Code | Message | | - | - | | `ERR-04-001` | Top up your Balance before launching a CVM. | | `ERR-04-002` | Your account has reached the maximum number of instances | | `ERR-04-003` | The requested resources exceed your account limits | | `ERR-04-004` | Workspace billing is suspended. Please settle your outstanding balance before proceeding. | | `ERR-04-005` | This workspace has been closed. Contact support if you wish to recover it. | | `ERR-04-006` | You have an unpaid workspace. Settle the balance before creating a new workspace. | | `ERR-04-007` | A webhook with this URL already exists in this workspace. | | `ERR-04-008` | This workspace already has 10 webhooks. Delete one before adding another. | | `ERR-04-009` | Add a payment method or create a CVM before adding a webhook. | | `ERR-04-010` | We could not check your payment methods. Try again later. | ## Module 05: Credentials | Error Code | Message | | - | - | | `ERR-05-001` | (dynamic: You have reached the maximum of ...) | | `ERR-05-002` | (dynamic: Rate limit exceeded: maximum ...) | ## Module 06: Auth | Error Code | Message | | - | - | | `ERR-06-001` | Your email address did not pass our security verification. | | `ERR-06-002` | Account is disabled. | | `ERR-06-003` | Account deleted and in cooling-off period. Contact support for assistance. | | `ERR-06-004` | Account is disabled | | `ERR-06-005` | Account deleted and in cooling-off period. Contact support for assistance. | | `ERR-06-006` | You do not have permission to perform this action. | | `ERR-06-007` | Access denied | | `ERR-06-008` | Your workspace role does not grant this permission | | `ERR-06-009` | This API key is not allowed to use this permission | | `ERR-06-010` | API keys cannot access this user route | | `ERR-06-012` | API keys cannot access slug-resolved workspace routes | ## Module 09: Billing | Error Code | Message | | - | - | | `ERR-09-001` | Post-paid billing and direct billing for Private AI cannot be enabled for the same workspace | | `ERR-09-009` | Payments are paused for this workspace because its billing profile needs a manual fix on our side | | `ERR-09-010` | Workspace not found | | `ERR-09-011` | Too many payment attempts. | | `ERR-09-012` | Payments are temporarily unavailable. Try again shortly. | | `ERR-09-013` | This payment was declined. Try another card. | | `ERR-09-014` | Monthly invoice contains Private AI lines; One Balance cannot allocate this invoice as CVM-only | | `ERR-09-015` | One Balance was enabled while the monthly invoice was being generated | | `ERR-09-017` | App not found | ## Module 10: GPU Rental | Error Code | Message | | - | - | | `ERR-10-020` | The GPU rental order is not active | | `ERR-10-021` | The GPU rental's machines changed during the request. | ## Module 11: Centralized KMS | Error Code | Message | | - | - | | `ERR-11-001` | This workspace has no signing wallet yet, so the next app ID cannot be predicted. | | `ERR-11-002` | Could not predict the next app ID. Please try again. | | `ERR-11-003` | Wallet provisioning is unavailable. Please try again later. | ## Module 12: KMS | Error Code | Message | | - | - | | `ERR-12-001` | The app ID is not a valid KMS app identifier | | `ERR-12-002` | The KMS did not return the environment encryption public key | | `ERR-12-003` | The KMS replica did not pass its health check | ## Module 14: Confidential AI | Error Code | Message | | - | - | | `ERR-14-001` | Private AI API key not found | | `ERR-14-002` | Could not create the Private AI API key | | `ERR-14-004` | usage mapping missing | | `ERR-14-005` | Invalid usage time range | | `ERR-14-006` | Private AI is already being connected for this workspace. Try again in a moment. | ## Module 16: Trust Center | Error Code | Message | | - | - | | `ERR-16-001` | The app or instance was not found. | | `ERR-16-002` | The CVM is not running. | | `ERR-16-003` | The guest agent timed out. | | `ERR-16-004` | The guest agent is unreachable. | ## Module 17: Log Access | Error Code | Message | | - | - | | `ERR-17-001` | Invalid log request | | `ERR-17-002` | Missing or invalid log access signature | | `ERR-17-003` | Log access signature expired | | `ERR-17-004` | CVM not found or access denied | | `ERR-17-005` | CVM is not running | | `ERR-17-006` | Container logs are disabled | | `ERR-17-007` | Container not found | | `ERR-17-008` | Node VMM unreachable or returned a bad response | | `ERR-17-009` | Guest agent or gateway unreachable | | `ERR-17-010` | Log upstream timed out | | `ERR-17-011` | Too many concurrent log streams | | `ERR-17-012` | Node or gateway routing data is unavailable | | `ERR-17-013` | VM no longer exists on the node | *** ## Retired Codes Retired codes are never reused. | Error Code | Retired | | - | - | | `ERR-03-021` | 2026-10-22 | *** # Migration from dstack v0.3 Source: https://docs.phala.com/phala-cloud/references/migration-from-dstack-v03 Complete migration guide from dstack OS v0.3.x to v0.5.x This guide covers all breaking changes when upgrading from dstack OS v0.3.x to v0.5.x. ## Docker Compose Changes ### Socket Path Update Update your `docker-compose.yml` file: ```yaml theme={"system"} # OLD (v0.3.x) services: app: volumes: - /var/run/tappd.sock:/var/run/tappd.sock # NEW (v0.5.x) services: app: volumes: - /var/run/dstack.sock:/var/run/dstack.sock ``` ## Guest SDK Changes ### Client Initialization **JavaScript:** ```javascript theme={"system"} // OLD (v0.3.x): TappdClient import { TappdClient } from '@phala/dstack-sdk'; const client = new TappdClient(); // NEW (v0.5.x): DstackClient import { DstackClient } from '@phala/dstack-sdk'; const client = new DstackClient(); ``` **Python:** ```python theme={"system"} # OLD (v0.3.x): TappdClient from tappd_client import TappdClient client = TappdClient() # NEW (v0.5.x): DstackClient from dstack_sdk import DstackClient client = DstackClient() ``` ### Key Derivation Methods The ambiguous `deriveKey()` method is now split for clarity: **JavaScript:** ```javascript theme={"system"} // OLD (v0.3.x): Single method for all key types const key = await client.deriveKey('some-id'); // NEW (v0.5.x): Purpose-specific methods const cryptoKey = await client.getKey('wallet/ethereum/v1'); // For deterministic keys // Note: getTlsKey() is available for TLS certificates but is for advanced use only ``` **Python:** ```python theme={"system"} # OLD (v0.3.x): Single method for all key types key = client.derive_key('some-id') # NEW (v0.5.x): Purpose-specific methods crypto_key = client.get_key('wallet/ethereum/v1') # For deterministic keys # Note: get_tls_key() is available for TLS certificates but is for advanced use only ``` ### ⚠️ CRITICAL: Wallet Helper Functions - ADDRESS WILL CHANGE **Important:** The secure functions apply SHA256 hashing which results in DIFFERENT wallet addresses. Plan your migration carefully! **JavaScript Migration:** ```javascript theme={"system"} // OLD (v0.3.x): Insecure functions import { TappdClient } from '@phala/dstack-sdk'; import { toViemAccount, toKeypair } from '@phala/dstack-sdk'; const client = new TappdClient(); const keyResult = await client.deriveKey('wallet'); const ethAccount = toViemAccount(keyResult); // ❌ Uses raw key directly const solKeypair = toKeypair(keyResult); // ❌ Uses raw key directly // ethAccount.address = 0xAAA... // NEW (v0.5.x): Secure functions with SHA256 hashing import { DstackClient } from '@phala/dstack-sdk'; import { toViemAccountSecure } from '@phala/dstack-sdk/viem'; import { toKeypairSecure } from '@phala/dstack-sdk/solana'; const client = new DstackClient(); const keyResult = await client.getKey('wallet/ethereum/v1'); const ethAccount = toViemAccountSecure(keyResult); // ✅ SHA256 hashed for security const solKeypair = toKeypairSecure(keyResult); // ✅ SHA256 hashed for security // ethAccount.address = 0xBBB... (DIFFERENT ADDRESS!) ``` **Python Migration:** ```python theme={"system"} # OLD (v0.3.x): Legacy helper methods from tappd_client import TappdClient client = TappdClient() key_result = client.derive_key('wallet') eth_account = client.to_account(key_result) # Uses raw key directly sol_keypair = client.to_keypair(key_result) # Uses raw key directly # eth_account.address = 0xAAA... # NEW (v0.5.x): Secure helper methods from dstack_sdk import DstackClient client = DstackClient() key_result = client.get_key('wallet/ethereum/v1') eth_account = client.to_account_secure(key_result) # SHA256 hashed for security sol_keypair = client.to_keypair_secure(key_result) # SHA256 hashed for security # eth_account.address = 0xBBB... (DIFFERENT ADDRESS!) ``` ### Migration Strategy for Wallets Since wallet addresses will change, you need to plan your migration: 1. **For new applications**: Use secure functions from the start 2. **For existing applications with funds**: * Deploy both old and new wallet systems in parallel * Transfer funds from old wallets to new secure wallets * Update all references to wallet addresses * Only deprecate old system after confirming all funds are migrated 3. **If you must keep the same address** (NOT RECOMMENDED): ```javascript theme={"system"} // You can still use the insecure function with DstackClient // BUT THIS IS A SECURITY RISK - only use temporarily during migration import { toViemAccount } from '@phala/dstack-sdk/viem'; // Legacy, insecure const account = toViemAccount(keyResult); // Same address as before, but vulnerable ``` ### Remote Attestation Quote generation now requires manual hashing for data larger than 64 bytes: **JavaScript:** ```javascript theme={"system"} // OLD (v0.3.x): Automatic hashing with algorithm selection const quote = await client.tdxQuote(largeData, 'sha256'); // NEW (v0.5.x): Manual hashing required, max 64 bytes import crypto from 'crypto'; const hash = crypto.createHash('sha256').update(largeData).digest(); const quote = await client.getQuote(hash.slice(0, 32)); ``` **Python:** ```python theme={"system"} # OLD (v0.3.x): Automatic hashing with algorithm selection quote = client.tdx_quote(large_data, 'sha256') # NEW (v0.5.x): Manual hashing required, max 64 bytes import hashlib hash_value = hashlib.sha256(large_data).digest() quote = client.get_quote(hash_value[:32]) ``` ## New Features in v0.5.x ### Event Emission (Advanced) Extends RTMR3 with custom events. This is an advanced feature for attestation purposes. ```javascript theme={"system"} // JavaScript await client.emitEvent('custom_event', { data: 'value' }); ``` ```python theme={"system"} # Python client.emit_event('custom_event', {'data': 'value'}) ``` **Note:** Not available in simulator. Requires dstack OS v0.5.0+. ### KMS Public Key Verification When deploying with encrypted environment variables, the SDK now includes a function to verify that encryption keys from the KMS are legitimate, preventing man-in-the-middle attacks. **JavaScript:** ```javascript theme={"system"} import { verifyEnvEncryptPublicKey } from '@phala/dstack-sdk'; // When deploying, you'll receive a public key and signature from the KMS API const kmsResponse = await fetch('https://kms-api/GetAppEnvEncryptPubKey', { method: 'POST', body: JSON.stringify({ app_id: 'your-app-id' }) }); const { public_key, signature } = await kmsResponse.json(); // Verify the key is legitimate before using it const publicKeyBytes = Buffer.from(public_key, 'hex'); const signatureBytes = Buffer.from(signature, 'hex'); const kmsIdentity = verifyEnvEncryptPublicKey( publicKeyBytes, signatureBytes, 'your-app-id' ); if (!kmsIdentity) { throw new Error('Invalid KMS key - potential security risk!'); } // Now safe to use public_key to encrypt your environment variables ``` **Python:** ```python theme={"system"} from dstack_sdk import verify_env_encrypt_public_key import requests # When deploying, you'll receive a public key and signature from the KMS API response = requests.post('https://kms-api/GetAppEnvEncryptPubKey', json={'app_id': 'your-app-id'}) data = response.json() # Verify the key is legitimate before using it public_key_bytes = bytes.fromhex(data['public_key']) signature_bytes = bytes.fromhex(data['signature']) kms_identity = verify_env_encrypt_public_key( public_key_bytes, signature_bytes, 'your-app-id' ) if not kms_identity: raise Exception('Invalid KMS key - potential security risk!') # Now safe to use public_key to encrypt your environment variables ``` ## HTTP API Changes ### Endpoint Format ```bash theme={"system"} # OLD (v0.3.x) curl --unix-socket /var/run/tappd.sock \ http://localhost/prpc/Tappd.DeriveKey # NEW (v0.5.x) curl --unix-socket /var/run/dstack.sock \ http://dstack/GetKey ``` ## Migration Checklist 1. **Update SDK version** ```bash theme={"system"} # JavaScript npm install @phala/dstack-sdk@latest # Python pip install dstack-sdk --upgrade ``` 2. **Update docker-compose.yml** * Change socket mount from `/var/run/tappd.sock` to `/var/run/dstack.sock` 3. **Update client code** * Replace `TappdClient` with `DstackClient` * Replace `deriveKey()` with `getKey()` 4. **⚠️ CRITICAL: Plan wallet migration** * Wallet addresses WILL change with secure functions * Transfer funds from old to new wallets * Update all address references 5. **Update attestation code** * Add manual hashing for `getQuote()` if data > 64 bytes 6. **Test thoroughly** * Verify new wallet addresses * Test fund transfers * Test attestation flows ## Common Issues and Solutions ### Issue: Wallet addresses changed unexpectedly **Cause**: Using secure functions changes the address due to SHA256 hashing\ **Solution**: This is expected. Plan migration of funds and update address references ### Issue: Need to keep old wallet address temporarily **Cause**: Cannot migrate funds immediately\ **Solution**: Use legacy functions temporarily (security risk) while planning migration ### Issue: Socket connection errors **Cause**: Old socket path in docker-compose.yml\ **Solution**: Update volume mount to `/var/run/dstack.sock` ### Issue: Quote generation fails **Cause**: Data exceeds 64 bytes without hashing\ **Solution**: Hash data before passing to `getQuote()` ## Need Help? * [Key Management Guide](/phala-cloud/key-management/get-a-key) * [Create Crypto Wallets](/phala-cloud/key-management/create-crypto-wallet) * [Attestation Guide](/phala-cloud/attestation/overview) # Overview Source: https://docs.phala.com/phala-cloud/references/overview Reference documentation for Phala Cloud — Cloud JS SDK, CLI, API error codes, and performance benchmarks. Welcome to the Phala Cloud References section. This comprehensive documentation provides detailed information about Phala Cloud's tools, performance characteristics, and technical specifications to help you effectively deploy and manage confidential applications. ## What's Included ### 🛠️ Cloud JS SDK The [`@phala/cloud`](/phala-cloud/references/cloud-js-sdk/overview) package is a type-safe JavaScript/TypeScript SDK for the Phala Cloud API. It features built-in [API versioning](/phala-cloud/references/cloud-js-sdk/api-versioning), [Zod schema validation](/phala-cloud/references/cloud-js-sdk/schema-reference), and a structured [error handling](/phala-cloud/references/cloud-js-sdk/error-handling) system. ### ⌨️ Command Line Interface (CLI) The [Phala Cloud CLI](/phala-cloud/phala-cloud-cli/overview) (`phala`) is your primary tool for managing deployments and interacting with the platform from the command line. ### 🚨 Error Codes The [Error Codes Reference](/phala-cloud/references/error-codes) documents all API error codes with their meanings. Useful for debugging deployment failures and API integration issues. ### 📊 Performance Reports Comprehensive performance analysis of Phala Cloud's TEE infrastructure, including: #### Key Performance Metrics * **Compute Performance**: CPU efficiency, GPU acceleration, and scaling characteristics * **Storage I/O**: Random and sequential read/write performance in TEE environments * **Network Gateway**: Throughput and latency under various load conditions * **Security Overhead**: Impact of zero-knowledge proofs and cryptographic operations # Performance Report Source: https://docs.phala.com/phala-cloud/references/performance-report Comprehensive performance analysis of Phala Cloud's TEE infrastructure. **TL;DR** - Performance overhead compared to non-TEE environments: * **CPU**: 5-10% slower in single-threaded, scales to 80% efficiency at 32 cores * **GPU**: 6.9x faster than AWS GPUs for INT8 workloads. For LLM inference, TEE adds 5-20% overhead * **IO**: Matches bare-metal for sequential I/O (36.2 GB/s), 40% higher latency on random reads * **Network**: 5-7x higher latency for HTTPS, but gateway handles 1,244 QPS at 1,000 concurrent connections ### I. Introduction **TEE Performance Overview** Phala Cloud's TEE infrastructure delivers enterprise-grade performance with strong security guarantees. The following sections detail our comprehensive benchmarks across key performance dimensions. * **Compute Performance**\ Phala's TEE environment demonstrates exceptional computational efficiency: * **CPU**: 1,271 MIPS for per-core compression * **Scaling**: 79.91% scaling efficiency at 32 threads * **Multi-core**: \< 10% slower than bare-metal at 8 threads * **GPU**: 3,341 TFLOPS for INT8 operations (6.9x AWS GPUs) * **Storage I/O**\ Storage performance shows minimal overhead for most real-world scenarios: * **Random Read**: \~40% latency increase in TEE * **Sequential I/O**: Outperforms bare-metal at 36.2 GB/s * **Caching**: Significantly improves random read performance * **Network & Security**\ The architecture maintains robust performance under demanding conditions: * **Gateway**: 1,244 QPS at 1,000 concurrent connections * **HTTPS**: 702% latency increase vs HTTP (mitigated by optimizations) * **Zero-Knowledge Proofs**\ Our implementation balances security and performance: * **Baseline**: 5.12x slowdown (18.3 kHz vs non-TEE) * **GPU Acceleration**: Reduces overhead to \< 1.8x * **Throughput**: 25.1k proofs/second (GPU-accelerated) **Performance Highlights** | **Component** | **Key Metric** | **Performance** | **Key Insight** | | - | - | - | - | | **GPU Performance** | INT8 Compute | 3,341 TFLOPS | **6.9x faster** than AWS GPUs | | **Single-thread CPU** | Compression Speed | 1,271 MIPS | **5% - 10% slower** than bare metal | | **Multi-core Scaling** | 32-core Efficiency | 79.91% | **Near-linear scaling** with core count | | **Sequential I/O** | Write Throughput | 36.2 GB/s | **Outperforms bare-metal** performance | | **Network Throughput** | QPS @1000cc | 1,245 | **6x higher** than standard web servers | | **Security Overhead** | zkProof Verification | 18.3 kHz | **5.1x** security overhead (vs non-TEE) | *** ### II. Storage Performance Analysis [\[1\]](#ref1) **Experiment Setup** ```bash theme={"system"} # Run docker run -it --rm -v /fio:/data infrabuilder/fio # https://github.com/InfraBuilder/docker-fio/blob/main/benchmark.sh ``` **Performance Summary** | Metric | H200 Host | H200 CVM | TDX-Lab Host | TDX-Lab CVM | TDX-Lab VM | | - | - | - | - | - | - | | **Random R/W IOPS (k)** | 259/156 | 33/34 | 97.3/32 | 43/37 | 72/75 | | **Random R/W Bandwidth (MiB/s)** | 3642/3356 | 2071/1389 | 519/381 | 1080/1193 | 12253/4215 | | **Avg Latency R/W (μs)** | 85/24 | 892/955 | 213/99 | 482/190 | 63/68 | | **Sequential R/W (MiB/s)** | 4338/3413 | 9973/2293 | 526/377 | 1168/412 | 36230/3829 | | **Mixed R/W IOPS (k)** | 129/43 | 18.7/6.2 | 67.7/23.5 | 43.6/14.5 | 71/23 | **Key Findings** 1. TEE CVM shows 60-80% I/O performance degradation vs bare-metal 2. Memory encryption extends I/O path and introduces context-switching overhead 3. Random operations most impacted (20% of bare-metal performance) 4. Sequential Read speed is faster in TEE VM due to that qemu may cache the memory *** ### III. Network Gateway Performance [\[2\]](#ref2) **Experiment Setup** ```jsx theme={"system"} ab -n 5000 -c CONCURRENCY_NUMBER https://e7cc25b0992a0e16b3377652efca9c0a6559d407-8090.app.kvin.wang:12004/prpc/Version ``` **Core Performance: Prod5 vs TDX-Lab** | Metric | Concurrency | Prod5 | TDX-Lab | Gain | Latency Advantage | | - | - | - | - | - | - | | **QPS** | 200 | 206.46 | 1189.93 | +476% | 5.76x | | | 500 | 194.70 | 1228.82 | +531% | 6.31x | | | 1000 | 179.33 | 1244.85 | +594% | 6.94x | | | 2000 | 182.39 | 1038.60 | +469% | 5.70x | | **P99 Latency (ms)** | 200 | 1,254 | 173 | -86% | 7.25x | | | 500 | 4,099 | 455 | -89% | 9.01x | | | 1000 | 7,768 | 822 | -89% | 9.45x | | | 2000 | 19,950 | 1,672 | -92% | 11.93x | | **Error Rate** | 2000 | 1.36% | 0% | -100% | Absolute advantage | | **Max Connect Time (ms)** | 2000 | 27,084 | 1,677 | -94% | 16.15x | **TProxy Overhead Analysis** | Access Method | Environment | QPS | Avg Latency | Overhead Source | | - | - | - | - | - | | Direct (HTTP) | TDX-Lab | 11,132 | 89.8ms | Baseline | | TProxy (HTTPS) | TDX-Lab | 1,264 | 791.3ms | **+702% latency** | **Multi-process AB Test** * **Experiment Setup** * gateway ver: git 7bc9eea958bd8aaca228341139f2cff5fab1d8d9 ``` URL=https://health.app.kvin.wang:18714/ AB="ab -n 5000 -c 40 $URL" for _ in `seq 1 50`; do $AB & done $AB sleep 1 ``` * **Results** | Environment | Gateway Ver. | Log Level | Total QPS | CPU Usage | Bottleneck | | - | - | - | - | - | - | | TDX-Lab | 7bc9eea | error | 15,000 | 94.5% | **CPU saturation** | | Prod8 | 7bc9eea | error | 22,400 | 19.2% | Network interrupt | | Prod8 | 7bc9eea | info | 15,000 | 14.7% | **Log I/O blocking** | **Conclusions** 1. TDX-Lab outperforms Prod5 across all concurrency levels 2. TLS handshake accounts for 70% of TProxy overhead 3. Info-level logging reduces Prod8 performance by 33% *** ### IV. zkTLS Performance in TEE [\[3\]](#ref3) **Core Performance (2048-bit Verification)** | Environment | Total Time (s) | Proof Time (s) | Speed (kHz) | Proof Size (bytes) | TEE Overhead | | - | - | - | - | - | - | | CPU | 166.54 | 166.30 | 98,479 | 8,340,752 | Baseline | | TEE CPU | 628.78 | 628.58 | 24,704 | 25,123,323 | 3.78x | | TEE GPU | 852.98 | 852.73 | 18,312 | 25,123,323 | 5.12x | **Memory Encryption Impact** | Environment | Hash Speed (MB/s) | Memory BW Utilization | | - | - | - | | CPU | 44.50 | 100% | | TEE CPU | 11.77 | 26.4% | | TEE GPU | 8.68 | 19.5% | **Key Findings** 1. Memory encryption causes 70-80% bandwidth degradation 2. Data structure padding increases proof size by 289% 3. Data migration overhead increases by 200% in TEE GPU *** ### V. Multi-threaded Computing Capability [\[4\]](#ref4) **Experiment Setup** ```bash theme={"system"} 7z b -mmt8 ``` **Compression Performance Benchmark** | System Config | Compress MIPS | Cores | Per-core Efficiency | | - | - | - | - | | TDX-Lab | 40,677 | 32 | 1,271 | | Prod8 | 31,658 | 288 | 110 | | Prod5 | 12,654 | 128 | 99 | **Conclusions** 1. TDX-Lab excels in compute-intensive tasks (high single-core frequency) 2. Prod8 leads in memory-bound operations (DDR5 advantage) 3. Prod5 suffers from frequency instability (48.7% fluctuation) ### VI. zkVM + TEE GPU Integration [\[5\]](#ref5) **Hardware Comparison** | Metric | H200 NVL | AWS G6 (L4) | Advantage | | - | - | - | - | | Memory Capacity | 141GB | 24GB | 5.9x | | Memory Bandwidth | 4.8TB/s | 300GB/s | 16x | | INT8 Compute | 3341 TFLOPS | 485 TFLOPS | 6.9x | | Hourly Cost | \$2.5 | \$0.805 | 3.1x | | **Cost-Performance Ratio** | **1.0** | **0.45** | **2.2x** | > Cost-Performance Ratio = (Compute/Cost) / H200 Baseline **Integration Benefits** 1. **Seamless deployment**: SP1 zkVM runs on TEE GPU without code modifications 2. **Dual security**: Hardware encryption + cryptographic verifiability 3. **Memory advantage**: Supports complex workloads (zkEVMs, 100B+ parameter models) 4. **Optimization headroom**: Current utilization \< 30% of available resources *** ### VII. TEE Scalability in Large-Scale LLM Inference [\[6\]](#ref6) **Performance Metrics Across Models** * Table 1: Throughput Comparison (Tokens/Requests per Second)\* | **GPU** | **Model** | **TPS (TEE-on)** | **TPS (TEE-off)** | **TPS Overhead** | **QPS (TEE-on)** | **QPS (TEE-off)** | **QPS Overhead** | | - | - | - | - | - | - | - | - | | H100 | Llama-3.1-8B | 123.30 | 132.36 | +6.85% | 18.21 | 18.82 | +3.22% | | | Phi3-14B-128k | 66.58 | 69.78 | +4.58% | 7.18 | 7.35 | +2.31% | | | Llama-3.1-70B | 2.48 | 2.48 | **-0.13%** | 0.83 | 0.83 | **-0.36%** | | H200 | Llama-3.1-8B | 121.04 | 132.78 | +8.84% | 29.60 | 32.01 | +7.55% | | | Phi3-14B-128k | 68.43 | 72.98 | +6.24% | 12.83 | 13.86 | +7.41% | | | Llama-3.1-70B | 4.08 | 4.18 | +2.29% | 2.19 | 2.20 | +0.63% | *Table 2: Latency Metrics (Time in Seconds)* | **GPU** | **Model** | **TTFT (TEE-on)** | **TTFT (TEE-off)** | **TTFT Overhead** | **ITL (TEE-on)** | **ITL (TEE-off)** | **ITL Overhead** | | - | - | - | - | - | - | - | - | | H100 | Llama-3.1-8B | 0.0288 | 0.0242 | +19.03% | 1.6743 | 1.5549 | +7.67% | | | Phi3-14B-128k | 0.0546 | 0.0463 | +18.02% | 3.7676 | 3.5784 | +5.29% | | | Llama-3.1-70B | 0.5108 | 0.5129 | **-0.41%** | 94.8714 | 95.2395 | **-0.39%** | | H200 | Llama-3.1-8B | 0.0364 | 0.0301 | +20.95% | 1.7158 | 1.5552 | +10.33% | | | Phi3-14B-128k | 0.0524 | 0.0417 | +25.60% | 3.6975 | 3.4599 | +6.87% | | | Llama-3.1-70B | 0.4362 | 0.4204 | +3.75% | 57.3855 | 55.9771 | +2.52% | **Key Findings** 1. **Inverse Efficiency Scaling** * Overhead **decreases exponentially** with model size * 70B models show **near-zero overhead** (H100: -0.13% TPS, -0.41% TTFT) * 8B models sustain 6-25% overhead due to shorter compute phases 2. **Computation/IO Asymmetry** | **Model** | **GPU Time Dominance** | **TEE Overhead** | | - | - | - | | Llama-3.1-70B | 99.2% | \< 0.5% | | Phi3-14B-128k | 95.7% | 2-7% | | Llama-3.1-8B | 88.3% | 7-26% | 3. **Token Volume Law** * Every 10k token increase reduces overhead by 37% * At >50k tokens, TEE efficiency exceeds 95% * Phi3-128k demonstrates **5.29% ITL overhead** vs 10.33% for 8B model ### VIII. CPU Scaling Efficiency Analysis [\[7\]](#ref7) **Experiment Setup** ```bash theme={"system"} for threads in 1 2 4 8 16 32; do echo -e "\n=== Running with $threads threads ===\n"; 7z b -mmt$threads; done ``` **Comparative Multi-threading Performance** * Table 1: TEE CVM Scaling Performance (7-Zip Benchmark)\* | **Threads** | **CPU Usage (%)** | **Compression (KiB/s)** | **Decompression (KiB/s)** | **Total Rating** | **Scaling Efficiency** | | - | - | - | - | - | - | | 1 | 100 | 2,511 | 34,387 | 2,803 | 100.00% | | 2 | 200 | 9,450 | 68,316 | 7,889 | 140.75% | | 4 | 383 | 14,048 | 135,014 | 13,100 | 116.90% | | 8 | 760 | 27,361 | 268,126 | 25,821 | 115.17% | | 16 | 1,432 | 44,535 | 443,829 | 42,322 | 94.38% | | 32 | 2,811 | 72,284 | 783,537 | 71,665 | 79.91% | * Table 2: Bare Metal Scaling Performance (7-Zip Benchmark)\* | **Threads** | **CPU Usage (%)** | **Compression (KiB/s)** | **Decompression (KiB/s)** | **Total Rating** | **Scaling Efficiency** | | - | - | - | - | - | - | | 1 | 100 | 4,992 | 43,200 | 4,544 | 100% (baseline) | | 2 | 183 | 9,791 | 63,936 | 7,935 | 87.3% | | 4 | 382 | 18,895 | 109,687 | 14,689 | 80.9% | | 8 | 787 | 34,001 | 217,465 | 27,279 | 75.1% | | 16 | 1,559 | 71,892 | 437,145 | 56,853 | 78.1% | | 32 | 2,662 | 121,055 | 797,133 | 97,853 | 67.4% | **Key Findings** 1. **Superlinear Scaling in TEE** * At 2 threads: **140.75% efficiency** vs bare metal's 87.3% * At 4 threads: **116.9% efficiency** (+36% advantage over bare metal) 2. **Memory Encryption Optimization** | **Thread Range** | **Efficiency Delta** | **Primary Benefit** | | - | - | - | | 1-8 threads | +35.2% avg | Cache locality optimization | | 16-32 threads | +12.1% avg | Reduced context-switching | 3. **Total Performance Impact** * Single-thread penalty: **45% performance loss** in TEE (2,803 vs 4,544) * 32-thread recovery: **73.2% of bare metal** throughput (71,665 vs 97,853) **Scaling Characteristics** | **Metric** | **TEE Advantage** | **Technical Cause** | | - | - | - | | Initial Scaling | +52.45% (2-thread) | Memory-bound workload optimization | | Mid-range | +41.8% (4-thread) | Reduced hypervisor interference | | High-core | +12.5% (32-thread) | NUMA-aware scheduling | **Conclusions** 1. TEE demonstrates **superior scaling efficiency** (avg +35% at ≤8 threads) due to encrypted memory access optimizations 2. Scaling beyond 16 threads becomes memory-bound, reducing TEE's relative advantage 3. Maximum throughput reaches **73% of bare metal** in fully-loaded scenarios *** ## References 1. [IO Benchmark with FIO](https://www.notion.so/phalanetwork/IO-Benchmark-with-FIO-1700317e04a180728b15cd034a3b3c52?source=copy_link) 2. [Gateway Benchmark Analysis](https://www.notion.so/phalanetwork/Gateway-benchmark-1ed0317e04a180598914d6729ae169ab?source=copy_link) 3. [zkTLS in TEE zkVM Benchmark](https://www.notion.so/phalanetwork/Benchmark-zktls-in-TEE-zkvm-1dd0317e04a18006a1b3c8c8fc1c1b1a?source=copy_link) 4. [TDX Host Benchmark](https://www.notion.so/phalanetwork/TDX-Host-benchmark-2090317e04a180a5b5f0f9b3c1301c4a?source=copy_link) 5. [SP1 zkVM in TEE H200 Performance Benchmark](https://www.notion.so/phalanetwork/Performance-Benchmark-Running-SP1-zkVM-in-TEE-H200-with-Low-Overhead-1bb0317e04a18005ad08eee35e2fc0cc?source=copy_link) 6. [TEE Scalability in Large-Scale LLM Inference](https://arxiv.org/pdf/2409.03992). (2024). arXiv:2409.03992 7. [dstack CPU Benchmark](https://www.notion.so/phalanetwork/dstack-CPU-Benchmark-21c0317e04a18090a1e1f0d91718b80d?source=copy_link) *Note: Internal reports are available upon request. Please contact the Phala Team for access to the full documentation.* *** # phala_app Resource Source: https://docs.phala.com/phala-cloud/references/terraform-provider/app-resource Reference for the phala_app resource — deploy and manage Phala Cloud apps with Docker Compose, environment variables, replicas, and CVM lifecycle. `phala_app` is the primary lifecycle resource in the Phala Cloud Terraform provider. It manages a single application identity (`app_id`) with shared Docker Compose configuration, shared environment variables, and one or more CVM replicas. This is the resource you use for every deployment. ## Example Usage ```hcl theme={"system"} resource "phala_app" "web" { name = "web-app" size = "tdx.medium" region = "US-WEST-1" image = "dstack-dev-0.5.7-9b6a5239" disk_size = 40 replicas = 2 env = { APP_SECRET = "replace-me" } public_logs = false public_sysinfo = false public_tcbinfo = false gateway_enabled = true docker_compose = <<-YAML services: web: image: nginx:stable ports: - "80:80" YAML wait_for_ready = true wait_timeout_seconds = 900 } ``` ## Required Attributes | Attribute | Type | Description | | - | - | - | | `name` | String | Application name. **Force-new** — changing this destroys and recreates the resource. | | `docker_compose` | String | Docker Compose YAML content defining your services. | | `size` | String | Instance type slug (e.g. `tdx.small`, `tdx.medium`). Discover valid values with `data.phala_sizes`. | ## Optional Attributes ### Placement and Identity | Attribute | Type | Description | | - | - | - | | `region` | String | Preferred region slug (e.g. `US-WEST-1`). **Force-new.** Discover values with `data.phala_regions`. | | `image` | String | OS image slug. Updatable in-place. Use exact slugs from `data.phala_images`. | | `node` | String | Pin placement to a physical node by name, for example `usw5`. Omit it for automatic placement. Omitting it later keeps the current placement. **Force-new.** Discover names with `data.phala_nodes`. Needs provider 0.3.0-beta.5 or newer. | | `kms` | String | KMS type for provisioning: `phala` (default), `ethereum`, or `base`. **Force-new.** | | `custom_app_id` | String | Custom app ID for deterministic identity flow (PHALA KMS). **Force-new.** | | `nonce` | Number | Nonce paired with `custom_app_id` for deterministic identity. **Force-new.** | > [!NOTE] > > `node_id` is replaced by `node`. Change `node_id` in your configuration to the node name shown by `data.phala_nodes`, then run a normal plan with refresh on. A matching name does not replace the resource. If no current CVM reports the old node, the plan stops without changing placement. \| `listed` | Boolean | Whether the app is publicly listed. **Force-new.** | ### Infrastructure | Attribute | Type | Description | | - | - | - | | `disk_size` | Number | Disk size in GB. Can only grow — shrink attempts are rejected by the provider. | | `replicas` | Number | Desired replica count. All replicas share the same compose, env, and settings. | | `storage_fs` | String | Filesystem for the data disk: `zfs` (default) or `ext4`. `ext4` has lower I/O overhead; only `zfs` detects a modified block on the encrypted disk. **Immutable after create** — changing forces replacement. | | `ssh_authorized_keys` | List of String | SSH public keys injected at launch. **Force-new** — runtime mutation is not supported. | | `pre_launch_script` | String | Optional script content run before the CVM starts. | ### Compose Runtime Settings These attributes control compose-level runtime behavior. Changing any of them triggers a compose update and CVM restart. | Attribute | Type | Default | Description | | - | - | - | - | | `public_logs` | Boolean | `false` | Expose container logs publicly. | | `public_sysinfo` | Boolean | `false` | Expose system info publicly. | | `public_tcbinfo` | Boolean | `false` | Expose TCB attestation info publicly. | | `gateway_enabled` | Boolean | — | Enable public gateway routing. | | `secure_time` | Boolean | — | Enable secure time mode. | ### Compose Settings, Init Scripts, Annotations and Launch Token > [!NOTE] > > These attributes need provider 0.3.0-beta.5 or newer. The provider sends every compose change of one apply as a single [`PATCH /cvms/{id}`](/phala-cloud/update/update-cvm-configuration) merge patch. Only changed keys are sent, and compose keys the provider does not manage stay as they are. The provider keeps these settings as configured in state and does not read them back from Phala Cloud. | Attribute | Type | Description | | - | - | - | | `port_policy` | Object | Which guest ports the gateway forwards: `restrict_mode` (Boolean) and `ports` (list of `{ port, pp }`, where `pp` sends the PROXY protocol header). | | `swap_size` | String | Guest swap size, for example `2G`. | | `storage_discard` | Boolean | Pass discard (TRIM) through to the data disk. | | `snapshotter` | String | `overlayfs` or `stargz`. Only with `runner = "nerdctl-compose"`. | | `event_log_version` | Number | Event log format, `1` or `2`. Every verifier that checks the app must support the version you pick. | | `requirements` | Object | Guest requirements: `health_check`, `health_status_file`, `platforms`, `tdx_measure_acpi_tables`, `ephemeral_data_disk` and `gpu_policy`. Only the keys you set are written. `gpu_policy` needs a feature flag and is **force-new**. | | `init_scripts` | Set of String | Platform init scripts every CVM of the app runs on boot: `docker_cleanup`. See [Init scripts](/phala-cloud/cvm/advanced-settings#init-scripts). | | `confirm_data_wipe` | Boolean | Confirms an update that turns on `docker_cleanup` or `requirements.ephemeral_data_disk`, which erase data on every boot. Not needed on create. | | `runner` | String | `docker-compose` (default), `nerdctl-compose` or `bash`. The other runners need a feature flag. **Force-new.** | | `bash_script` | String | Script the `bash` runner runs; set `docker_compose = ""` with it. **Force-new.** | | `annotations` | Map of String | Host-side settings for the app's CVMs, behind a feature flag. Not measured, so attestation does not cover them. See [Annotations](/phala-cloud/cvm/advanced-settings#annotations). | | `launch_token` | String (Sensitive) | App launch token, at least 32 bytes. Stored in state. Phala Cloud and the node operator can read it. See [Launch Token](/phala-cloud/cvm/launch-token). | | `generate_launch_token` | Boolean | Have Phala Cloud generate the launch token when `launch_token` is not set. The generated token is stored in state. | Changing `port_policy`, `swap_size`, `storage_discard`, `snapshotter`, `event_log_version`, `requirements` (except `gpu_policy`) or `init_scripts` updates the app in place and restarts its running CVMs. `annotations` are applied to the bootstrap CVM at create. A change replaces the whole map on the app's existing CVMs, without a restart or a compose change. CVMs added later, such as `phala_app_instance` slots, start without them. Removing the attribute clears them. Changing `launch_token` sets the new token on the app first, then updates each CVM's `requirements.launch_token_hash`. A CVM that restarts in between fails to boot until its compose is updated. Removing it removes the hash from every CVM, then clears the token. ### Environment Variables The provider offers two modes for managing environment variables. You must pick one — they cannot be combined in the same resource. **Auto-encryption mode (recommended):** ```hcl theme={"system"} resource "phala_app" "web" { # ... env = { DATABASE_URL = "postgres://..." API_SECRET = "s3cr3t" } } ``` | Attribute | Type | Description | | - | - | - | | `env` | Map of String, Sensitive | Plaintext env vars. The provider auto-derives `env_keys` and encrypts values before sending to the API. | > [!WARNING] > > Even in auto-encryption mode, plaintext values are stored in your Terraform state file. If you cannot tolerate plaintext in state storage, use manual encrypted mode instead. **Manual encrypted mode:** ```hcl theme={"system"} resource "phala_app" "web" { # ... encrypted_env = var.pre_encrypted_hex_blob env_keys = ["DATABASE_URL", "API_SECRET"] } ``` | Attribute | Type | Description | | - | - | - | | `encrypted_env` | String, Sensitive | Hex-encoded encrypted env payload. Must be valid hex. | | `env_keys` | List of String | Allowed environment variable keys for the encrypted payload. | **On-chain KMS fields (advanced):** | Attribute | Type | Description | | - | - | - | | `env_compose_hash` | String | Compose hash for phase-2 env update flow with contract-owned KMS. | | `env_transaction_hash` | String | On-chain transaction hash for phase-2 env update flow. | ### Wait Behavior | Attribute | Type | Description | | - | - | - | | `wait_for_ready` | Boolean | Wait until the app reports running replicas before Terraform returns. | | `wait_timeout_seconds` | Number | Timeout in seconds for the readiness wait. | > [!NOTE] > > Setting `wait_for_ready = true` is recommended for production workflows. Without it, Terraform returns immediately after the API call, and subsequent resources that depend on the endpoint may see incomplete values. ## Read-Only (Computed) Attributes | Attribute | Type | Description | | - | - | - | | `app_id` | String | The Phala app identifier. | | `id` | String | Terraform resource ID (same as `app_id`). | | `primary_cvm_id` | String | Primary CVM identifier, used for patch operations and as input to `phala_cvm_power`. | | `cvm_ids` | List of String | All CVM identifiers attached to this app. | | `endpoint` | String | Primary public endpoint URL. | | `status` | String | Current CVM status from the API. | ## Lifecycle Behavior ### Force-New Fields Changing any of these attributes destroys the existing resource and creates a new one: * `name` * `region` * `listed` * `ssh_authorized_keys` * `storage_fs` * `kms` * `custom_app_id` * `nonce` * `node` * `runner`, `bash_script` and `requirements.gpu_policy` ### In-Place Updates These attributes can be updated without replacement: * `size` (CPU/RAM changes) * `disk_size` (grow only) * `image` (OS image swap via API patch) * `docker_compose` * `pre_launch_script` * `replicas` * `env` / `encrypted_env` * Compose runtime settings (`public_logs`, `public_sysinfo`, `public_tcbinfo`, `gateway_enabled`, `secure_time`) * The compose settings, `init_scripts`, `annotations` and `launch_token` described [above](#compose-settings-init-scripts-annotations-and-launch-token) ### Replica Scaling Set `replicas` to scale your app horizontally. All replicas share the same compose file, environment, and settings. The provider manages replica creation and deletion to match your desired count. ```hcl theme={"system"} resource "phala_app" "api" { name = "api-service" size = "tdx.medium" region = "US-WEST-1" replicas = 3 docker_compose = <<-YAML services: api: image: myregistry/api:latest ports: - "8080:8080" YAML } ``` ### Create Flow The provider follows Phala's two-step API: first `POST /cvms/provision` to allocate resources, then `POST /cvms` to commit the deployment. This happens automatically during `terraform apply`. ## Related * [CVM Power Control](/phala-cloud/references/terraform-provider/cvm-power) * [Data Sources](/phala-cloud/references/terraform-provider/data-sources) * [Examples](/phala-cloud/references/terraform-provider/examples) # Changelog Source: https://docs.phala.com/phala-cloud/references/terraform-provider/changelog Version history for the Phala Cloud Terraform provider — new features, breaking changes, and bug fixes. All notable changes to the Phala Cloud Terraform provider are documented here. The provider is currently in **beta** maturity. See the [feature maturity matrix](#feature-maturity) at the bottom for per-resource status. ## Unreleased ### Added * `phala_app` supports the newer app compose settings: `port_policy`, `swap_size`, `storage_discard`, `snapshotter`, `event_log_version`, `requirements` (`health_check`, `health_status_file`, `platforms`, `tdx_measure_acpi_tables`, `ephemeral_data_disk`, and create-only `gpu_policy`), create-only `runner` and `bash_script`, and `init_scripts` with `confirm_data_wipe` for updates that erase data on every boot. Compose changes are sent as one `PATCH /cvms/{id}` merge patch. * `phala_app.annotations` sets host-side CVM annotations (behind a feature flag). The bootstrap CVM gets them at create, a change replaces the whole map on the app's existing CVMs without a restart, and CVMs added later start without them. * `phala_app.launch_token` gates every CVM of the app with a launch token that you supply, or that Phala Cloud generates with `generate_launch_token = true`. The token is stored in state as a sensitive value. Changing it rotates the token and updates each CVM's `requirements.launch_token_hash`; removing it removes the hash, then the token. ## 0.2.0-beta.3 (2026-05-03) ### Fixed * In-place updates to `phala_app.env` are now applied. The schema-level `Sensitive: true` flag on the `env` map attribute interacted with element-level marks coming from `sensitive = true` Terraform variables and caused Terraform Core to silently suppress the in-place diff, so changing an env value used to report "No changes." and never call the API. To redact env values in plan output, mark the source variable with `sensitive = true` — the marks propagate per-element and Terraform redacts them. Fixes [Phala-Network/phala-cloud#246](https://github.com/Phala-Network/phala-cloud/issues/246). *** ## 0.2.0-beta.2 (2026-03-13) ### Removed * **`phala_cvm` resource removed.** Use `phala_app` with `replicas = 1` instead. `phala_app` is now the sole lifecycle resource for managing CVMs on Phala Cloud. ### Changed * Stabilized data source IDs: `phala_account` uses a fixed `"current"` ID, and `phala_workspace` uses the immutable workspace ID. This prevents state churn on profile changes. * Delete polling now respects `wait_timeout_seconds` instead of a hardcoded 120s timeout. * Unified replica patch semantics: OS image and compose settings updates now use consistent 409-fallthrough across replicas. * Improved error messages for public key decoding and delete timeout failures. ### Fixed * API key is no longer leaked in error response headers. * `encrypted_env` is now validated as valid hex before sending to the API. * Typed API client logs a warning on initialization failure instead of silently degrading. *** ## 0.2.0-beta.1 (2026-03-08) ### Added * **New `phala_app` resource** with an app-first model: * Shared compose and environment at app scope. * Replica count management via `replicas`. * App-level outputs: `app_id`, `cvm_ids`, `endpoint`. * **New `phala_nodes` data source** for node placement discovery (`node_id`) with optional region and on-chain KMS filters. * **New `phala_attestation` data source** for read-only TEE attestation fetch by `cvm_id`. * Release packaging script for cross-platform provider artifacts. * CI workflow for provider tests and build checks. * Manual GitHub release workflow for versioned artifacts. * Feature maturity and release process documentation. ### Changed * `image` is now updatable in-place via `PATCH /cvms/{id}/os-image`. * Added create-time identity and placement inputs for `phala_app`: * `kms` (currently `phala` only; `ethereum`/`base` planned) * `custom_app_id` + `nonce` (PHALA deterministic identity flow) * `node_id` (maps to provision `teepod_id`) * Added compose-file runtime settings to `phala_app`: * `public_logs`, `public_sysinfo`, `public_tcbinfo`, `gateway_enabled`, `secure_time` * Updates use compose provision/apply flow and trigger restart/redeploy. * `storage_fs` (`zfs`/`ext4`) is now explicit and immutable (replacement required on change). * `disk_size` updates are constrained to grow-only (shrink rejected by provider validation). *** ## 0.1.0 (2026-03-07) ### Added * **Initial provider release** with: * `phala_app` resource * `phala_cvm_power` resource * `phala_ssh_key` resource * `phala_account` data source * `phala_workspace` data source * `phala_sizes` data source * `phala_regions` data source * `phala_images` data source * Workspace and account data sources with smoke-test example. * Env auto-encryption flow (`env` auto-derives `encrypted_env` + `env_keys`). *** ## Feature Maturity The provider is currently at **beta** maturity overall. Here is the per-component breakdown: | Component | Level | Notes | | - | - | - | | `phala_app` | beta | Full CRUD + replica scaling. Sole lifecycle resource. | | `phala_cvm_power` | beta | Running/stopped state management. Delete is state-only. | | `phala_ssh_key` | beta | Create/read/delete. Immutable fields. | | `phala_account` | beta | Read-only. Returns user/workspace linkage + credits. | | `phala_workspace` | beta | Read-only. Active workspace metadata. | | `phala_sizes` | beta | Read-only catalog. | | `phala_regions` | beta | Read-only catalog. | | `phala_images` | beta | Read-only catalog. | | `phala_nodes` | beta | Read-only. Node discovery with optional filters. | | `phala_attestation` | beta | Read-only. On-demand attestation fetch. | ### Criteria to Reach GA * Workspace isolation end-to-end tests in CI. * Stable documentation for upgrade semantics across minor versions. * Explicit import guidance and lifecycle caveats for all resources. * Release automation with reproducible artifacts and checksums. * Two consecutive releases with no breaking schema or state regressions. ## Roadmap * On-chain KMS create/update flows (BASE/ETHEREUM). * Richer filtering for data sources (`images`, `sizes`, `regions`). ## Related * [Provider Overview](/phala-cloud/references/terraform-provider/overview) * [phala\_app Resource](/phala-cloud/references/terraform-provider/app-resource) * [Examples](/phala-cloud/references/terraform-provider/examples) # phala_cvm_power Resource Source: https://docs.phala.com/phala-cloud/references/terraform-provider/cvm-power Reference for the phala_cvm_power resource — manage CVM power state (running/stopped) without recreating the parent app. `phala_cvm_power` lets you start or stop an existing CVM without recreating or modifying the parent `phala_app` resource. This is useful for cost management, maintenance windows, or controlled rollouts where you want to decouple power state from deployment lifecycle. ## Example Usage ```hcl theme={"system"} resource "phala_app" "web" { name = "power-demo" size = "tdx.medium" region = "US-WEST-1" image = "dstack-dev-0.5.7-9b6a5239" disk_size = 40 replicas = 1 docker_compose = <<-YAML services: web: image: nginx:stable ports: - "80:80" YAML } resource "phala_cvm_power" "web" { cvm_id = phala_app.web.primary_cvm_id state = "stopped" wait_for_state = true wait_timeout_seconds = 900 } ``` In this example, the app is created in a running state by default, then `phala_cvm_power` converges it to `stopped`. Changing `state` back to `"running"` on the next apply starts it again. ## Required Attributes | Attribute | Type | Description | | - | - | - | | `cvm_id` | String | The target CVM ID. Typically sourced from `phala_app..primary_cvm_id`. | | `state` | String | Desired power state: `"running"` or `"stopped"`. | ## Optional Attributes | Attribute | Type | Description | | - | - | - | | `wait_for_state` | Boolean | Wait until the CVM reaches the target state before Terraform returns. | | `wait_timeout_seconds` | Number | Timeout in seconds for the state wait. | > [!NOTE] > > Setting `wait_for_state = true` is recommended. Without it, Terraform marks the resource as converged immediately after issuing the start/stop API call, even if the CVM has not finished transitioning. ## Read-Only (Computed) Attributes | Attribute | Type | Description | | - | - | - | | `id` | String | Resource ID (same as `cvm_id`). | | `status` | String | Current CVM status as reported by the API. | ## Behavior ### Drift Detection On every `terraform plan`, the provider reads the current CVM status from the API. If the actual power state does not match the declared `state`, Terraform shows a diff and the next `apply` issues the appropriate start or stop call. ### Delete Semantics Destroying a `phala_cvm_power` resource only removes it from Terraform state. It does **not** stop or delete the CVM. The CVM continues running (or stays stopped) in whatever state it was last set to. To actually delete the CVM, destroy the parent `phala_app` resource. > [!WARNING] > > `phala_cvm_power` is a state-convergence resource, not a lifecycle resource. Removing it from your configuration leaves the CVM in its current state — it does not revert to any previous power state. ### API Backing The resource uses these Phala Cloud API endpoints: * `POST /cvms/{id}/start` — to transition to `running` * `POST /cvms/{id}/stop` — to transition to `stopped` * `GET /cvms/{id}` — for read and drift detection ## Related * [phala\_app Resource](/phala-cloud/references/terraform-provider/app-resource) — the parent lifecycle resource * [Examples](/phala-cloud/references/terraform-provider/examples) — power management patterns # Data Sources Source: https://docs.phala.com/phala-cloud/references/terraform-provider/data-sources Reference for all Phala Cloud Terraform data sources — discover account info, sizes, regions, images, nodes, and attestation data. The Phala Cloud provider includes seven read-only data sources. Use them to discover valid configuration values (sizes, regions, images, nodes) and to inspect account or attestation state. Data sources are refreshed on every `terraform plan` and `terraform apply`. ## phala\_account Returns current account info including user profile, Balance, and active workspace linkage. ```hcl theme={"system"} data "phala_account" "current" {} output "username" { value = data.phala_account.current.username } output "credit_balance" { value = data.phala_account.current.credit_balance } ``` ### Attributes | Attribute | Type | Description | | - | - | - | | `id` | String | Stable account identifier. | | `username` | String | Account username. | | `email` | String | Account email address. | | `email_verified` | Boolean | Whether the email is verified. | | `avatar` | String | Avatar URL. | | `role` | String | Account role. | | `has_password` | Boolean | Whether a password is set. | | `totp_enabled` | Boolean | Whether TOTP 2FA is enabled. | | `has_backup_codes` | Boolean | Whether backup codes exist. | | `credit_balance` | String | Current Balance. | | `credit_granted_balance` | String | Gifted credits balance. | | `credit_outstanding_amount` | String | Amount the workspace owes. | | `credit_is_post_paid` | Boolean | Whether the account is post-paid. | | `workspace_id` | String | Active workspace ID. | | `workspace_name` | String | Active workspace name. | | `workspace_slug` | String | Active workspace slug. | | `workspace_role` | String | Role in the active workspace. | | `workspace_tier` | String | Workspace tier (e.g. free, pro). | *** ## phala\_workspace Returns metadata about the active workspace for the current API key. ```hcl theme={"system"} data "phala_workspace" "current" {} output "workspace_name" { value = data.phala_workspace.current.name } output "workspace_tier" { value = data.phala_workspace.current.tier } ``` ### Attributes | Attribute | Type | Description | | - | - | - | | `id` | String | Workspace ID (immutable). | | `name` | String | Workspace display name. | | `slug` | String | Workspace slug. | | `role` | String | Current user's role in this workspace. | | `tier` | String | Workspace tier. | | `avatar` | String | Workspace avatar URL. | *** ## phala\_sizes Lists available CVM instance types. Use this to discover valid `size` slugs for `phala_app`. ```hcl theme={"system"} data "phala_sizes" "all" {} output "available_sizes" { value = data.phala_sizes.all.sizes[*].slug } ``` ### Input Attributes | Attribute | Type | Description | | - | - | - | | `family` | String | Optional filter by instance family (e.g. `cpu`, `gpu`, `tdx`). | ### Output: `sizes` List Each entry in `sizes` contains: | Attribute | Type | Description | | - | - | - | | `slug` | String | Instance type slug (use this as the `size` value in `phala_app`). | | `name` | String | Display name. | | `description` | String | Human-readable description. | | `family` | String | Instance family. | | `vcpu` | Number | Number of virtual CPUs. | | `memory_mb` | Number | Memory in megabytes. | | `default_disk_size_gb` | Number | Default disk size in GB. | | `hourly_rate` | String | Hourly cost. | | `requires_gpu` | Boolean | Whether this size requires GPU nodes. | *** ## phala\_regions Lists available deployment regions. ```hcl theme={"system"} data "phala_regions" "all" {} output "available_regions" { value = data.phala_regions.all.regions[*].slug } ``` ### Output: `regions` List Each entry in `regions` contains: | Attribute | Type | Description | | - | - | - | | `slug` | String | Region slug (use this as the `region` value in `phala_app`). | | `name` | String | Display name. | | `available` | Boolean | Whether the region currently accepts new deployments. | *** ## phala\_images Lists available OS images for CVMs. Always use the exact `slug` from this data source when setting the `image` attribute on `phala_app`. ```hcl theme={"system"} data "phala_images" "west" { region = "US-WEST-1" } output "image_slugs" { value = data.phala_images.west.images[*].slug } ``` > [!WARNING] > > Use the full image slug (e.g. `dstack-dev-0.5.7-9b6a5239`), not a shortened version like `dstack-dev` or `dstack-dev-0.5.7`. Shortened slugs are not accepted by the API. ### Input Attributes | Attribute | Type | Description | | - | - | - | | `region` | String | Optional region filter. Only returns images available in that region. | ### Output: `images` List Each entry in `images` contains: | Attribute | Type | Description | | - | - | - | | `slug` | String | Image slug (use this as the `image` value in `phala_app`). | | `name` | String | Image name. | | `version` | String | Image version. | | `os_image_hash` | String | Image content hash. | | `is_dev` | Boolean | Whether this is a development image. | | `regions` | List of String | Regions where this image is available. | *** ## phala\_nodes Lists available worker nodes for CVM placement. Use this when you need to pin a deployment to a specific node with `node` on `phala_app`. ```hcl theme={"system"} data "phala_nodes" "west" { region = "us-west" } output "node_names" { value = data.phala_nodes.west.nodes[*].node } ``` ### Input Attributes | Attribute | Type | Description | | - | - | - | | `region` | String | Optional region filter. | | `support_onchain_kms` | Boolean | Optional filter for nodes that support on-chain KMS. | ### Output: `nodes` List Each entry in `nodes` contains: | Attribute | Type | Description | | - | - | - | | `node` | String | Physical node name (use this as the `node` value in `phala_app`). | | `node_id` | Number | Numeric node ID. Not a placement input. | | `name` | String | Node display name. | | `region` | String | Node region. | | `device_id` | String | Hardware device identifier. | | `fmspc` | String | Intel FMSPC value for this node's TEE hardware. | | `listed` | Boolean | Whether the node is publicly listed. | | `support_onchain_kms` | Boolean | Whether the node supports on-chain KMS. | | `remaining_vcpu` | Number | Available vCPU capacity. | | `remaining_memory_mb` | Number | Available memory in MB. | | `remaining_cvm_slots` | Number | Available CVM slots. | | `resource_score` | Number | Computed resource availability score. | | `images` | List of String | Image slugs supported on this node. | *** ## phala\_attestation Fetches TEE attestation data for a specific CVM on demand. This is a read-only verification data source, not a lifecycle resource. ```hcl theme={"system"} data "phala_attestation" "web" { cvm_id = phala_app.web.primary_cvm_id } output "is_online" { value = data.phala_attestation.web.is_online } output "tcb_info" { value = data.phala_attestation.web.tcb_info_json } ``` ### Input Attributes | Attribute | Type | Description | | - | - | - | | `cvm_id` | String | The CVM or app identifier to fetch attestation for. | ### Output Attributes | Attribute | Type | Description | | - | - | - | | `id` | String | Stable state ID (same as `cvm_id`). | | `is_online` | Boolean | Whether the CVM is currently online. | | `is_public` | Boolean | Whether the CVM's attestation is publicly accessible. | | `error` | String | Error message if attestation fetch failed. | | `compose_file` | String | The compose file content from attestation. | | `tcb_info_json` | String | Raw TCB info object as JSON string. | | `app_certificates_json` | String | Raw app certificates array as JSON string. | | `raw_json` | String | Full attestation response as a JSON string. | > [!NOTE] > > Attestation data is fetched fresh on every plan/apply. The `raw_json` field contains the complete API response if you need fields beyond the top-level attributes. ## Related * [phala\_app Resource](/phala-cloud/references/terraform-provider/app-resource) — using data source outputs in deployments * [Examples](/phala-cloud/references/terraform-provider/examples) — discovery and deployment patterns # Examples Source: https://docs.phala.com/phala-cloud/references/terraform-provider/examples Common Terraform patterns for Phala Cloud — basic deployments, multi-replica, cross-app wiring, GPU, SSH access, and power management. This page collects practical Terraform examples for common Phala Cloud deployment scenarios. Each example is self-contained and can be adapted to your use case. ## Basic Deployment The simplest deployment: one app, one replica, public endpoint. ```hcl theme={"system"} terraform { required_providers { phala = { source = "phala-network/phala" version = "0.2.0-beta.1" } } } provider "phala" {} resource "phala_app" "hello" { name = "hello-phala" size = "tdx.medium" region = "US-WEST-1" image = "dstack-dev-0.5.7-9b6a5239" disk_size = 40 replicas = 1 docker_compose = <<-YAML services: web: image: nginx:stable ports: - "80:80" YAML wait_for_ready = true wait_timeout_seconds = 900 } output "app_id" { value = phala_app.hello.app_id } output "endpoint" { value = phala_app.hello.endpoint } ``` ## Dynamic Discovery Instead of hardcoding sizes, regions, and images, use data sources to discover valid values at plan time. ```hcl theme={"system"} data "phala_sizes" "all" {} data "phala_regions" "all" {} data "phala_images" "all" {} resource "phala_app" "web" { name = "dynamic-app" size = data.phala_sizes.all.sizes[0].slug region = data.phala_regions.all.regions[0].slug image = data.phala_images.all.images[0].slug disk_size = 40 replicas = 1 docker_compose = <<-YAML services: web: image: nginx:stable ports: - "80:80" YAML wait_for_ready = true wait_timeout_seconds = 900 } ``` ## Multi-Replica Deployment Scale an application horizontally by setting `replicas`. All replicas share the same compose file and environment. ```hcl theme={"system"} resource "phala_app" "api" { name = "api-service" size = "tdx.medium" region = "US-WEST-1" replicas = 3 env = { LOG_LEVEL = "info" } docker_compose = <<-YAML services: api: image: myregistry/api:latest ports: - "8080:8080" YAML wait_for_ready = true wait_timeout_seconds = 900 } output "all_cvm_ids" { value = phala_app.api.cvm_ids } ``` ## Cross-App Wiring Deploy one app and pass its outputs (app ID, endpoint) as environment variables to a second app. Terraform handles the dependency ordering automatically. ```hcl theme={"system"} data "phala_sizes" "all" {} data "phala_regions" "all" {} resource "phala_app" "api" { name = "api-app" size = data.phala_sizes.all.sizes[0].slug region = data.phala_regions.all.regions[0].slug replicas = 2 docker_compose = <<-YAML services: api: image: nginx:stable ports: - "80:80" YAML wait_for_ready = true wait_timeout_seconds = 900 } resource "phala_app" "consumer" { name = "consumer-app" size = data.phala_sizes.all.sizes[0].slug region = data.phala_regions.all.regions[0].slug replicas = 1 env = { UPSTREAM_APP_ID = phala_app.api.app_id UPSTREAM_ENDPOINT = phala_app.api.endpoint } docker_compose = <<-YAML services: app: image: nginx:stable ports: - "80:80" YAML wait_for_ready = true wait_timeout_seconds = 900 } ``` ## SSH Access Inject SSH keys at deploy time for direct access into CVM instances. You can also manage account-level SSH keys separately with `phala_ssh_key`. ```hcl theme={"system"} resource "phala_ssh_key" "laptop" { name = "laptop" public_key = file("~/.ssh/id_ed25519.pub") } resource "phala_app" "web" { name = "ssh-enabled-app" size = "tdx.medium" region = "US-WEST-1" replicas = 1 ssh_authorized_keys = [ file("~/.ssh/id_ed25519.pub"), ] env = { APP_SECRET = "replace-me" } docker_compose = <<-YAML services: web: image: nginx:stable ports: - "80:80" YAML wait_for_ready = true wait_timeout_seconds = 900 } ``` > [!NOTE] > > The `ssh_authorized_keys` attribute is force-new. Changing the key list after initial deployment requires recreating the app. For keys you want to manage independently, use `phala_ssh_key` at the account level. ## GPU Deployment For GPU workloads, use a size from the GPU family. Discover available GPU sizes with the `family` filter. ```hcl theme={"system"} data "phala_sizes" "gpu" { family = "gpu" } output "gpu_sizes" { value = data.phala_sizes.gpu.sizes[*].slug } resource "phala_app" "ml" { name = "ml-inference" size = data.phala_sizes.gpu.sizes[0].slug region = "US-WEST-1" replicas = 1 docker_compose = <<-YAML services: inference: image: myregistry/ml-model:latest ports: - "8000:8000" YAML wait_for_ready = true wait_timeout_seconds = 900 } ``` ## Node Pinning Pin a deployment to a specific worker node when you need deterministic hardware placement. ```hcl theme={"system"} data "phala_nodes" "west" { region = "us-west" } resource "phala_app" "pinned" { name = "pinned-app" size = "tdx.medium" node = data.phala_nodes.west.nodes[0].node docker_compose = <<-YAML services: web: image: nginx:stable ports: - "80:80" YAML wait_for_ready = true wait_timeout_seconds = 900 } ``` ## Power Management Use `phala_cvm_power` to stop and start CVMs independently of the app lifecycle. This is useful for cost control or scheduled maintenance. ```hcl theme={"system"} resource "phala_app" "web" { name = "power-managed-app" size = "tdx.medium" region = "US-WEST-1" disk_size = 40 replicas = 1 docker_compose = <<-YAML services: web: image: nginx:stable ports: - "80:80" YAML wait_for_ready = true wait_timeout_seconds = 900 } # Stop the CVM after deployment resource "phala_cvm_power" "web" { cvm_id = phala_app.web.primary_cvm_id state = "stopped" wait_for_state = true wait_timeout_seconds = 900 } ``` To restart, change `state` to `"running"` and run `terraform apply`. ## Attestation Verification After deployment, fetch TEE attestation data to verify the CVM's integrity. ```hcl theme={"system"} resource "phala_app" "secure" { name = "secure-app" size = "tdx.medium" region = "US-WEST-1" replicas = 1 docker_compose = <<-YAML services: web: image: nginx:stable ports: - "80:80" YAML wait_for_ready = true wait_timeout_seconds = 900 } data "phala_attestation" "secure" { cvm_id = phala_app.secure.primary_cvm_id } output "is_online" { value = data.phala_attestation.secure.is_online } output "tcb_info" { value = data.phala_attestation.secure.tcb_info_json } ``` ## Compose Runtime Settings Control visibility and behavior flags at the compose level. Changing these triggers a compose update and CVM restart. ```hcl theme={"system"} resource "phala_app" "monitored" { name = "monitored-app" size = "tdx.medium" region = "US-WEST-1" replicas = 1 public_logs = true public_sysinfo = true public_tcbinfo = true gateway_enabled = true secure_time = true docker_compose = <<-YAML services: web: image: nginx:stable ports: - "80:80" YAML wait_for_ready = true wait_timeout_seconds = 900 } ``` ## Related * [Provider Overview](/phala-cloud/references/terraform-provider/overview) — installation and configuration * [phala\_app Resource](/phala-cloud/references/terraform-provider/app-resource) — full attribute reference * [Data Sources](/phala-cloud/references/terraform-provider/data-sources) — discovery data sources # Terraform Provider Source: https://docs.phala.com/phala-cloud/references/terraform-provider/overview Deploy confidential apps on Phala Cloud with Terraform — install, configure, and deploy your first CVM in minutes. > [!NOTE] > > The Terraform Provider is currently in **beta**. The resource schema may change between releases. The Phala Cloud Terraform provider lets you manage confidential virtual machines (CVMs) using standard Terraform workflows. It follows an app-first model where `phala_app` is the primary resource, managing one application identity with shared Docker Compose configuration, shared environment variables, and one or more CVM replicas. If you have used providers like DigitalOcean or AWS, the patterns here will feel familiar: catalog data sources for discovery, declarative compute resources, explicit power control, and SSH key management. ## Installation The provider is published on the Terraform Registry under `phala-network/phala`. Add it to your `required_providers` block: ```hcl theme={"system"} terraform { required_version = ">= 1.5.0" required_providers { phala = { source = "phala-network/phala" version = "0.2.0-beta.1" } } } provider "phala" {} ``` Run `terraform init` to download the provider binary. Terraform handles the rest automatically. ## Authentication The provider authenticates with a Phala Cloud API key. You can get one from the dashboard: 1. Sign in at [cloud.phala.com](https://cloud.phala.com). 2. Go to **Settings** then **API Keys**. 3. Create a key and export it in your shell: ```bash theme={"system"} export PHALA_CLOUD_API_KEY="phak_xxx" ``` The provider reads `PHALA_CLOUD_API_KEY` automatically. You can also set it explicitly in the provider block, though environment variables are recommended for security. ## Provider Configuration | Attribute | Type | Description | | - | - | - | | `api_key` | String, Sensitive | Phala Cloud API key. Falls back to `PHALA_CLOUD_API_KEY` env var. | | `api_prefix` | String | API base URL. Falls back to `PHALA_CLOUD_API_PREFIX`. Most users do not need this. | | `api_version` | String | API version sent in `X-Phala-Version` header. | | `timeout_seconds` | Number | HTTP timeout in seconds. | ```hcl theme={"system"} # Explicit configuration (usually not needed) provider "phala" { api_key = var.phala_api_key timeout_seconds = 60 } ``` ## Quick Start This deploys a single nginx CVM and outputs the app ID and public endpoint. The values below (`tdx.medium`, `US-WEST-1`, 40 GB disk) are tested defaults that work out of the box. ```hcl theme={"system"} terraform { required_version = ">= 1.5.0" required_providers { phala = { source = "phala-network/phala" version = "0.2.0-beta.1" } } } provider "phala" {} resource "phala_app" "hello" { name = "hello-phala" size = "tdx.medium" region = "US-WEST-1" image = "dstack-dev-0.5.7-9b6a5239" disk_size = 40 replicas = 1 docker_compose = <<-YAML services: web: image: nginx:stable ports: - "80:80" YAML wait_for_ready = true wait_timeout_seconds = 900 } output "app_id" { value = phala_app.hello.app_id } output "endpoint" { value = phala_app.hello.endpoint } ``` Run the standard Terraform workflow: ```bash theme={"system"} terraform init terraform apply -auto-approve terraform output ``` When it completes, Terraform prints the `app_id` and a public `endpoint` URL. Your app also appears in the Phala Cloud dashboard in a running state. To tear down: ```bash theme={"system"} terraform destroy -auto-approve ``` ## What's in the Provider The provider includes three resources and seven data sources: **Resources:** * [`phala_app`](/phala-cloud/references/terraform-provider/app-resource) — the primary lifecycle resource for deploying apps with CVM replicas * [`phala_cvm_power`](/phala-cloud/references/terraform-provider/cvm-power) — start/stop power control for existing CVMs * [`phala_ssh_key`](/phala-cloud/references/terraform-provider/ssh-key) — manage account-level SSH keys **Data Sources:** * [`phala_account`](/phala-cloud/references/terraform-provider/data-sources) — current user and workspace info * [`phala_workspace`](/phala-cloud/references/terraform-provider/data-sources) — active workspace metadata * [`phala_sizes`](/phala-cloud/references/terraform-provider/data-sources) — available instance types * [`phala_regions`](/phala-cloud/references/terraform-provider/data-sources) — available deployment regions * [`phala_images`](/phala-cloud/references/terraform-provider/data-sources) — available OS images * [`phala_nodes`](/phala-cloud/references/terraform-provider/data-sources) — worker nodes for placement pinning * [`phala_attestation`](/phala-cloud/references/terraform-provider/data-sources) — TEE attestation data for a CVM ## Common Workflow A typical deployment follows this pattern: 1. Use data sources (`phala_sizes`, `phala_regions`, `phala_images`) to discover valid slugs. 2. Define a `phala_app` with your Docker Compose file and desired replica count. 3. Wait for readiness, then consume `app_id`, `cvm_ids`, and `endpoint` as outputs. 4. Optionally use `phala_cvm_power` for explicit start/stop control after deployment. ## Related * [App Resource Reference](/phala-cloud/references/terraform-provider/app-resource) * [Data Sources](/phala-cloud/references/terraform-provider/data-sources) * [Examples](/phala-cloud/references/terraform-provider/examples) * [Changelog](/phala-cloud/references/terraform-provider/changelog) # phala_ssh_key Resource Source: https://docs.phala.com/phala-cloud/references/terraform-provider/ssh-key Reference for the phala_ssh_key resource — manage account-level SSH keys on Phala Cloud. `phala_ssh_key` manages SSH public keys at the account level in Phala Cloud. These keys can be referenced or injected into CVM deployments for SSH access. ## Example Usage ```hcl theme={"system"} resource "phala_ssh_key" "laptop" { name = "laptop" public_key = file("~/.ssh/id_ed25519.pub") } ``` You can also inline the key directly: ```hcl theme={"system"} resource "phala_ssh_key" "ci" { name = "ci-deploy" public_key = "ssh-ed25519 AAAA... ci@example.com" } ``` ## Required Attributes | Attribute | Type | Description | | - | - | - | | `name` | String | Display name for the SSH key. **Immutable** — changing forces replacement. | | `public_key` | String | SSH public key content (e.g. the contents of `~/.ssh/id_ed25519.pub`). **Immutable** — changing forces replacement. | ## Read-Only (Computed) Attributes | Attribute | Type | Description | | - | - | - | | `id` | String | SSH key identifier assigned by the API. | | `fingerprint` | String | Computed key fingerprint. | | `key_type` | String | Key type (e.g. `ssh-ed25519`, `ssh-rsa`). | | `created_at` | String | Creation timestamp. | | `updated_at` | String | Last update timestamp. | | `source` | String | Key source metadata reported by the API. | ## Behavior ### Immutable Fields Both `name` and `public_key` are immutable. If you change either one, Terraform destroys the old key and creates a new one. This mirrors the DigitalOcean SSH key pattern where keys are treated as immutable identities. ### SSH Keys vs. ssh\_authorized\_keys There are two ways to get SSH access into a CVM: 1. **`phala_ssh_key` resource** — manages account-level keys in the Phala Cloud API. These persist across deployments. 2. **`ssh_authorized_keys` on `phala_app`** — injects keys directly into a specific deployment at launch time. These are per-deployment and force-new. You can use both approaches together. The `ssh_authorized_keys` attribute on `phala_app` accepts raw public key strings, not references to `phala_ssh_key` resources. ```hcl theme={"system"} resource "phala_ssh_key" "laptop" { name = "laptop" public_key = file("~/.ssh/id_ed25519.pub") } resource "phala_app" "web" { name = "web-app" size = "tdx.medium" # Inject the key at deploy time ssh_authorized_keys = [file("~/.ssh/id_ed25519.pub")] docker_compose = <<-YAML services: web: image: nginx:stable ports: - "80:80" YAML } ``` ### API Backing The resource uses these Phala Cloud API endpoints: * `POST /user/ssh-keys` — create * `GET /user/ssh-keys` — read * `DELETE /user/ssh-keys/{id}` — delete ## Related * [phala\_app Resource](/phala-cloud/references/terraform-provider/app-resource) — deploying apps with SSH access * [Examples](/phala-cloud/references/terraform-provider/examples) — SSH access patterns # Webhooks Source: https://docs.phala.com/phala-cloud/references/webhooks Receive real-time HTTP notifications for CVM lifecycle events Phala Cloud sends HTTP POST requests to your endpoint when events occur in your workspace — CVM deployments, updates, stops, deletes, and multisig approval requests. Each request includes an HMAC-SHA256 signature for verification. ## Supported Events | Event | When | | - | - | | `cvm.created` | CVM first deployment completed, now running | | `cvm.started` | Existing CVM started (after stop) | | `cvm.create_failed` | CVM deployment failed (boot error, timeout) | | `cvm.restarted` | CVM restart completed | | `cvm.updated` | CVM compose update completed, now running | | `cvm.stopped` | CVM stopped or shut down | | `cvm.deleted` | CVM deleted | | `cvm.update.pending_approval` | On-chain KMS update requires multisig approval | ## Payload Format ```json theme={"system"} { "id": "evt_a1b2c3d4e5f67890", "event": "cvm.created", "version": "1", "created_at": "2026-03-19T10:30:00Z", "workspace": { "id": "my-team-slug", "name": "My Team" }, "data": { "cvm_id": "1a09d706-2686-4e0a-8b1d-323ff0e3504b", "cvm_name": "my-app", "app_id": "0xabc...", "status": "running" } } ``` For failure events, `data` includes an `error` field: ```json theme={"system"} { "data": { "cvm_id": "...", "cvm_name": "my-app", "app_id": "0xabc...", "status": "error", "error": "CVM 82: Failed to request app keys: ..." } } ``` ## HTTP Headers | Header | Example | | - | - | | `Content-Type` | `application/json` | | `User-Agent` | `PhalaCloud-Webhook/1.0` | | `X-Webhook-Id` | `evt_a1b2c3d4e5f67890` | | `X-Webhook-Event` | `cvm.created` | | `X-Webhook-Timestamp` | `1679012345` | | `X-Webhook-Signature` | `sha256=a1b2c3...` | ## Verifying Signatures Each webhook has a signing secret (starts with `whsec_`). Use it to verify requests are authentic and untampered. The signature is: `sha256=HMAC-SHA256(secret, "{timestamp}.{raw_body}")` ### Using SDKs (Recommended) The Phala Cloud SDKs provide built-in verification with timestamp tolerance checks and constant-time comparison. ```typescript JavaScript / TypeScript theme={"system"} import { verifyWebhookSignature, parseWebhookEvent } from "@phala/cloud/webhook"; // Option 1: Verify signature manually const isValid = verifyWebhookSignature({ secret: "whsec_...", timestamp: req.headers["x-webhook-timestamp"], body: rawBody, signature: req.headers["x-webhook-signature"], }); // Option 2: Parse and verify in one step (throws on failure) try { const event = parseWebhookEvent({ headers: req.headers, body: rawBody, secret: "whsec_...", }); console.log(event.event, event.data); } catch (err) { // Invalid signature or expired timestamp res.status(401).send("Invalid signature"); } ``` ```python Python theme={"system"} from phala_cloud import verify_webhook_signature, parse_webhook_event # Option 1: Verify signature manually is_valid = verify_webhook_signature( secret="whsec_...", timestamp=request.headers["X-Webhook-Timestamp"], body=request.body.decode(), signature=request.headers["X-Webhook-Signature"], ) # Option 2: Parse and verify in one step (raises on failure) try: event = parse_webhook_event( headers=dict(request.headers), body=request.body.decode(), secret="whsec_...", ) print(event.event, event.data) except ValueError: # Invalid signature or expired timestamp return Response(status_code=401) ``` ```go Go theme={"system"} import phala "github.com/Phala-Network/phala-cloud-sdk-go" // Option 1: Verify signature ok := phala.VerifyWebhookSignature(secret, timestamp, string(body), signature) // Option 2: Parse and verify (returns error on failure) event, err := phala.ParseWebhookEvent(r.Header, body, secret) if err != nil { http.Error(w, "Invalid signature", http.StatusUnauthorized) return } fmt.Println(event.Event, string(event.Data)) ``` All three SDKs automatically reject timestamps older than 5 minutes (configurable via `toleranceSeconds`) and use constant-time comparison to prevent timing attacks. > [accordion] Manual Verification (Python / Node.js) > > ```python Python theme={"system"} > import hmac > import hashlib > > def verify_webhook(secret: str, timestamp: str, body: bytes, signature: str) -> bool: > message = f"{timestamp}.{body.decode('utf-8')}".encode("utf-8") > expected = "sha256=" + hmac.new( > secret.encode("utf-8"), message, hashlib.sha256 > ).hexdigest() > return hmac.compare_digest(expected, signature) > ``` > > ```javascript Node.js theme={"system"} > const crypto = require("crypto"); > > function verifyWebhook(secret, timestamp, body, signature) { > const message = `${timestamp}.${body}`; > const expected = "sha256=" + > crypto.createHmac("sha256", secret).update(message).digest("hex"); > const expectedBuf = Buffer.from(expected); > const actualBuf = Buffer.from(signature); > if (expectedBuf.length !== actualBuf.length) return false; > return crypto.timingSafeEqual(expectedBuf, actualBuf); > } > ``` > > **Replay protection:** reject events where `X-Webhook-Timestamp` is older than 5 minutes. ## Delivery Behavior | Aspect | Behavior | | - | - | | **Success** | HTTP `2xx` (`200`, `201`, `202`, etc.) | | **Failure** | Any non-`2xx` status, network error, or timeout | | **Redirects** | Not followed (`3xx` = failure) | | **Timeout** | 10 seconds | | **Retries** | Up to 3 retries: 1 min → 10 min → 1 hour | | **Total attempts** | 4 (1 initial + 3 retries) | | **Recording** | One delivery record per event (final result only) | ## Secret Management Webhook signing secrets follow a strict security model: * **Shown once at creation** — the full secret is returned only in the `POST /workspace/webhooks` response * **Masked afterward** — subsequent `GET`/`LIST` responses return a masked value (e.g. `whsec_****...xxxx`) * **Reveal requires 2FA** — to view the full secret again, your account must have two-factor authentication enabled and recently verified * **Rotation requires 2FA** — generating a new secret also requires 2FA verification ### Reveal Secret ``` POST /api/v1/workspace/webhooks/{id}/reveal-secret ``` Returns the full signing secret. Requires: * Account with 2FA enabled (returns `403` if not) * Recent 2FA step-up verification (returns `428` if not verified) ### Rotate Secret ``` POST /api/v1/workspace/webhooks/{id}/rotate-secret ``` Generates a new signing secret and invalidates the previous one. Same 2FA requirements as reveal. > [!WARNING] > > After rotation, update your webhook consumer with the new secret immediately. Events signed with the old secret will fail verification. ## URL Requirements Webhook URLs must meet the following requirements: * **HTTPS only** — HTTP URLs are rejected * **Public addresses only** — URLs resolving to private or reserved IP ranges are blocked: * `127.0.0.0/8`, `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16` (private) * `169.254.0.0/16` including `169.254.169.254` (cloud metadata) * `::1`, `fc00::/7`, `fe80::/10` (IPv6 private/loopback) * **No localhost** — `localhost` and `.local` domains are not allowed These restrictions apply both at webhook creation and at delivery time to prevent DNS rebinding attacks. ## Managing Webhooks ### Dashboard **Settings → Webhooks** in your workspace: * Create, edit, enable/disable, delete webhooks * Select subscribed events * Send test events * View delivery history with stats (success rate, response time) * Resend failed deliveries ### API ```bash theme={"system"} # Create POST /api/v1/workspace/webhooks {"url": "https://example.com/webhook", "events": ["cvm.created", "cvm.stopped"], "name": "My Hook"} # List GET /api/v1/workspace/webhooks # Update PUT /api/v1/workspace/webhooks/{id} {"enabled": false} # Delete DELETE /api/v1/workspace/webhooks/{id} # Test POST /api/v1/workspace/webhooks/{id}/test # Deliveries GET /api/v1/workspace/webhooks/{id}/deliveries # Stats GET /api/v1/workspace/webhooks/{id}/stats # Resend POST /api/v1/workspace/webhooks/{id}/deliveries/{event_id}/resend ``` ## Best Practices * **Verify signatures** — always check `X-Webhook-Signature` before processing * **Respond fast** — return `200` immediately, process asynchronously (10s timeout) * **Be idempotent** — use the `id` field to deduplicate retries * **Check timestamps** — reject events older than 5 minutes # Compliance & Certifications Source: https://docs.phala.com/phala-cloud/security-and-privacy/compliance Security compliance certifications, controls, and data processing practices for Phala Cloud # Compliance & Certifications This page documents Phala's compliance certifications, security controls, and data processing practices. > [!NOTE] > > For compliance reports, security documentation, or to schedule a security review, visit the [Trust Center](https://phala.com/trust) or contact [security@phala.network](mailto:security@phala.network). ## Compliance Reports Phala maintains the following compliance certifications: ### SOC 2 Type I > [card] [SOC 2 Type I Report](https://phala.com/phala_soc2_type1_report.pdf) > > Service Organization Control 2 Type I report validating our security, availability, and confidentiality controls at a specific point in time. The SOC 2 Type I report covers: * **Security**: Protection against unauthorized access * **Availability**: System availability for operation and use * **Confidentiality**: Protection of confidential information ### HIPAA Compliance > [card] HIPAA Compliance > > Health Insurance Portability and Accountability Act (HIPAA) compliance certification for protecting sensitive patient health information. **Coming Soon** Phala is working toward HIPAA compliance certification to support healthcare and life sciences customers with protected health information (PHI) requirements. ## Security Controls Framework Phala has implemented **120+ controls** across the following security domains. All controls are actively monitored. ### Control Categories > [accordion] Data & Customer Protection > > * Customer data handling policies approved by management > * Least-privileged access to sensitive data > * Encryption of web-based management interfaces > * Data classification and retention policies > [accordion] Access Control > > * Role-based access control (RBAC) > * Multi-factor authentication (MFA) required > * Periodic access reviews > * Unique user identities > * Access provisioning and deprovisioning procedures > * Root access restrictions > [accordion] Encryption > > * Data encrypted at rest using strong cryptographic algorithms > * Data encrypted in transit (TLS 1.2+) > * Key management procedures > * Removable media encryption > * Cryptography policies and standards > [accordion] Network Security > > * Network security controls limiting inbound/outbound traffic > * Web Application Firewall (WAF) > * Intrusion Detection/Prevention System (IDS/IPS) > * Remote server administration port restrictions > * Encrypted remote production access > [accordion] Incident Response > > * Documented incident response plan > * Incident response team with defined roles > * Security event tracking and evaluation > * Post-mortem reviews and lessons learned > * Breach notification procedures > * Annual incident response testing > [accordion] Business Continuity & Disaster Recovery > > * Documented disaster recovery plan > * Business continuity plan > * Business impact analysis > * High availability architecture > * Annual BCP/DR testing > [accordion] Vulnerability Management > > * Regular vulnerability scans > * Annual third-party penetration testing > * Vulnerability management policy > * Patch management procedures > [accordion] Logging & Monitoring > > * Centralized logging system > * Real-time alerting > * Database and server monitoring > * File integrity monitoring (FIM) > * Continuous control monitoring > [accordion] Personnel Security > > * Background checks for personnel > * Security awareness training > * Code of conduct > * Non-disclosure agreements > * Termination/offboarding procedures > [accordion] Vendor Management > > * Vendor risk assessments > * Compliance monitoring for critical vendors > * Data processing agreements > * Subprocessor management ## Subprocessors Phala works with trusted third-party service providers to deliver our services. Below is a list of our current subprocessors and their purposes. | Subprocessor | Purpose | Jurisdiction | | - | - | - | | Google Cloud | Infrastructure hosting | US, EU | | Stripe | Payment processing | US | | PostHog | Product analytics | US/EU | | Customer.io | Marketing & Email services | US | | Attio | CRM | UK | | LinkedIn | Marketing analytics | US | | Fingerprint | Security analytics | US | | GitHub | Code repository and software development | US | ### Data Processing Agreement Our commitment to protecting your data extends to our relationships with subprocessors: * All subprocessor agreements impose data protection obligations substantially similar to those in our main DPA * We notify customers of any intended additions or replacements to the subprocessor list * Phala remains liable for subprocessor performance in accordance with our DPA terms > [card] [Data Processing Agreement](https://phala.com/data-processing-agreement) > > View our full Data Processing Agreement for detailed information on data handling practices. ## Privacy Phala maintains comprehensive privacy practices: * **Privacy Policy**: Available at [phala.com/privacy](https://phala.com/privacy) * **Privacy by Design**: TEE technology ensures data remains encrypted even during processing * **Data Subject Rights**: Users can access, correct, and delete their personal information * **Privacy Compliance Review**: Quarterly executive review of privacy compliance * **HIPAA Privacy Rule**: Policies for allowable use and disclosure of PHI (for covered entities) ## Security Architecture Phala Cloud's security is built on Trusted Execution Environments (TEEs) that provide hardware-level isolation and cryptographic guarantees: > [card] [Trust Center Verification](/phala-cloud/attestation/trust-center-verification) > > Automated verification reports for every deployment > [card] [Security Architecture](/phala-cloud/security-and-privacy/security-architecture) > > Technical security architecture and design documents > [card] [Security Audit](/phala-cloud/security-and-privacy/security-audit) > > Independent third-party security audit by zkSecurity > [card] [Chain of Trust](/phala-cloud/attestation/chain-of-trust) > > Understand the cryptographic chain of trust ## Regulatory Compliance Phala Cloud helps customers meet various regulatory requirements: | Regulation | How Phala Helps | | - | - | | **GDPR** | Data encryption at rest and in transit, DPA available, subprocessor transparency | | **HIPAA** | TEE-based data isolation, access controls, audit logging (BAA available upon request) | | **SOC 2** | Certified Type I report, comprehensive security controls | | **PCI DSS** | Encryption, access controls, network segmentation | ## Contact For compliance inquiries, security documentation requests, or to schedule a security review: * **Email**: [security@phala.network](mailto:security@phala.network) * **Trust Center**: [phala.com/trust](https://phala.com/trust) ## Additional Resources * [Trust Center](https://phala.com/trust) - Compliance reports and security documentation * [Privacy Policy](https://phala.com/privacy) - Data handling practices * [Terms of Service](https://phala.com/terms) - Service agreement * [Data Processing Agreement](https://phala.com/data-processing-agreement) - DPA for data processors # Privacy Source: https://docs.phala.com/phala-cloud/security-and-privacy/privacy Phala Cloud privacy policy covering data collection, usage, and protection practices for TEE-powered confidential computing services. Welcome to Phala Cloud (cloud.phala.com) by Phala Network, a TEE cloud platform that offers secure, confidential computing solutions for various workloads ("Company," "we," "our," or "us"). We respect your privacy and are committed to protecting the personal information of our users ("User," "you," or "your"). This Privacy Policy describes how we collect, use, disclose, and protect your information when you use our services, including our website, platform, and associated products (collectively, the "Services"). By accessing or using our Services, you agree to this Privacy Policy and our Terms of Service. Learn about [private AI data processing](https://phala.com/solutions/private-ai-data) for GDPR and regulatory compliance. Details can be found at [https://cloud.phala.com/privacy](https://cloud.phala.com/privacy) # Security Architecture Source: https://docs.phala.com/phala-cloud/security-and-privacy/security-architecture Security features and remote attestation capabilities of Phala Cloud TEE. Phala Cloud's security relies on a decentralized root of trust, TEE-controlled TLS certificates, and a hardware-backed key management service. Each component is documented in detail below. > [card] > > Decentralized Root-of-Trust > > [Open](/dstack/design-documents/whitepaper) > [card] > > Zero Trust HTTPS (TLS) > > [Open](/dstack/design-documents/decentralized-root-of-trust) > [card] > > Key Management Service (KMS) > > [Open](/dstack/design-documents/key-management-protocol) # Security Audit Report Source: https://docs.phala.com/phala-cloud/security-and-privacy/security-audit Independent third-party security audit of Phala Cloud's underlying dstack infrastructure by zkSecurity # Security Audit Report **Phala Cloud's security has been independently validated by zkSecurity**, a leading blockchain security firm. In May 2025, zkSecurity conducted a comprehensive audit of dstack, the underlying infrastructure platform that powers Phala Cloud. ## Independent Security Validation dstack underwent a comprehensive security audit by zkSecurity in May 2025, covering: * **Low-level cryptographic implementations** (RATLS, attestation protocols) * **Production image security** and hardening measures * **TEE integration** and measurement integrity * **Attack surface analysis** and privilege escalation vectors > [card] [dstack Security Audit](/dstack/security-audit) > > View the complete security audit results, findings, and recommendations for the underlying dstack infrastructure. # Database Source: https://docs.phala.com/phala-cloud/storage/access-database Deploy confidential applications with Phala Cloud's managed TEE infrastructure. Phala Cloud supports running a database locally or connecting to an external database. There is no difference in how you access a database compared to a general server. To save your data to disk, **you need to** [**configure volumes**](https://docs.docker.com/reference/compose-file/volumes/) **in the Docker Compose file** and write data to the correct path, here is an example from Docker website. ```yaml theme={"system"} services: backend: image: example/database volumes: - db-data:/etc/data backup: image: backup-service volumes: - db-data:/var/lib/backup/data volumes: db-data: ``` # Get Support Source: https://docs.phala.com/phala-cloud/support Get your questions answered If you have any questions or need assistance, please contact us at: * Email: [support@phala.network](mailto:cloud@phala.network) * Contact the team: [Book a meeting](https://cloud.phala.com/contact) ## Resources * **Pricing**: View [transparent pricing](https://phala.com/pricing) for all compute resources * **Startup Program**: Apply for [startup credits](https://phala.com/startup-program) and free GPU TEE access * **Enterprise Support**: Need dedicated support? [Contact our sales team](https://phala.com/contact) ## Features Request You are more than welcome to create an issue on [Phala Cloud open source community](https://github.com/Phala-Network/phala-cloud/issues)! ## Join the Community * [Discord server](https://phala.com/discord) * [Telegram](https://t.me/+nbhjx1ADG9EyYmI9) * [Telegram (CN)](https://t.me/+4PcAE9qTZ1kzM2M9) # Debug Application Source: https://docs.phala.com/phala-cloud/troubleshooting/debug-your-application Access your CVM for debugging and troubleshooting. When deploying on Phala Cloud, you choose between two CVM base images: * **`dstack-`** (Production): No remote access. Use this for production deployments. * **`dstack-dev-`** (Development): Allows SSH access for debugging. > [!NOTE] > > Development images are not recommended for production environments. ## SSH Access The easiest way to debug your CVM is via SSH using the Phala CLI: ```bash theme={"system"} phala ssh my-cvm ``` Once connected, you can inspect containers, check logs, and debug networking: ```bash theme={"system"} docker ps -a docker logs htop ``` For setup instructions, see [Enable SSH Access](/phala-cloud/networking/enable-ssh-access). # Private Log Viewer Source: https://docs.phala.com/phala-cloud/troubleshooting/private-log-viewer Create and manage Confidential Virtual Machines (CVMs) on Phala Cloud. ## Securing Your Docker Logs For enhanced security, you may want to restrict log access to specific individuals. You can configure a private log viewer in your Docker Compose file using open-source tools like [Dozzle](https://github.com/amir20/dozzle). ### Implementation Steps 1. **Generate Authentication Credentials** On your local machine, generate a Dozzle user authority token using the following command: ```bash theme={"system"} docker run amir20/dozzle generate --name Admin --email me@email.net --password secret admin | base64 -w 1000 ``` This example creates a user with: * Username: "Admin" * Password: "secret" * Role: "admin" 2. **Configure Dozzle in Docker Compose** Add the following services to your Docker Compose file: ```yaml theme={"system"} services: # Setup service to initialize user data setup: image: busybox restart: "no" volumes: - dozzle-data:/dozzle-data/ command: > sh -c 'echo "use authority token" | base64 -d > /dozzle-data/users.yml || true' # Dozzle log viewer service dozzle: container_name: dozzle image: amir20/dozzle:latest depends_on: - setup environment: - DOZZLE_AUTH_PROVIDER=simple volumes: - /var/run/docker.sock:/var/run/docker.sock - dozzle-data:/data/ ports: - 8080:8080 ``` 3. **Access Protected Logs** Once deployed, you can access the logs through the container's public endpoint using the credentials you configured. Only authorized users with the correct username and password will be able to view the logs. # Troubleshooting Guide Source: https://docs.phala.com/phala-cloud/troubleshooting/troubleshooting Common issues and solutions for Phala Cloud deployments. Join our support groups: 🌍 [Global](https://t.me/+nbhjx1ADG9EyYmI9), 🇨🇳 [Chinese](https://t.me/+4PcAE9qTZ1kzM2M9) ## Deployment Errors ### No available nodes found This error indicates no available nodes for deployment. **Common causes:** * You've reached your tier's CVM limit * All nodes are currently at capacity **Solutions:** 1. Check your [account tier limits](https://cloud.phala.com/about/pricing) 2. Delete unused CVMs to free up capacity 3. Upgrade to a higher tier for more resources 4. Try again later if nodes are temporarily at capacity ![No available nodes found](https://mintcdn.com/phalanetwork-1606097b/57prl00-u-jQKn3n/images/error-no-available-nodes.png?fit=max\&auto=format\&n=57prl00-u-jQKn3n\&q=85\&s=15d7d1324bf873618c4a48fc18e5b145) No available nodes found error ### Can't deploy more CVMs - tier limit reached Each account tier has CVM limits: | Tier | Max CVMs | Max vCPUs | Max Memory | | - | - | - | - | | **Tier 1** | 8 | 16 | 32GB | | **Tier 2** | 16 | 32 | 64GB | | **Enterprise** | Unlimited | Unlimited | Unlimited | **Solutions:** * Delete unused CVMs * Contact [cloud@phala.network](mailto:cloud@phala.network) to upgrade your tier ### Deployment blocked - "violates terms & conditions" Some Docker images trigger anti-spam rules. **Known triggers:** * Certain base images that have been abused for spam * Images with suspicious patterns **Solutions:** 1. Use official base images (e.g., `python:3.11`, `node:20`) 2. Avoid deprecated or unmaintained base images 3. Contact support if you believe your image was incorrectly flagged ### CVM stuck, can't restart - "process already running" If your CVM is stuck and won't restart: **Solution:** Use the **"Power Off"** button in the Web UI for a force shutdown. This is different from "Stop" and will forcefully terminate the CVM. 1. Go to your CVM in the dashboard 2. Click **Power Off** (not Stop) 3. Wait for the CVM to fully shut down 4. Start the CVM again If this doesn't work, contact support for assistance. ## Container & Image Errors ### exec format error ```text theme={"system"} exec /usr/local/bin/docker-entrypoint.sh: exec format error ``` Your Docker image is not compatible with x86\_64 architecture. This happens when building on ARM (e.g., Apple Silicon Mac). **Solution:** Build your image with the correct platform: ```bash theme={"system"} docker build --platform linux/amd64 -t your-image:tag . ``` Or in docker-compose.yml: ```yaml theme={"system"} services: your-service: platform: linux/amd64 build: . ``` ### TEE socket error - "No such file or directory" for dstack.sock ```text theme={"system"} Error: /var/run/dstack.sock: No such file or directory ``` **Cause:** Incorrect volume configuration in docker-compose.yml. **Solution:** Only mount the socket file, NOT the lock file: ```yaml theme={"system"} # ✅ Correct volumes: - /var/run/dstack.sock:/var/run/dstack.sock # ❌ Wrong - remove this line # - /var/run/dstack.sock.lock:/var/run/dstack.sock.lock ``` ### \[FAILED] Failed to start Virtual Console Setup You can safely ignore this error. This is a [known issue](https://github.com/Dstack-TEE/dstack/issues/321) in OS image dstack v0.5.4 where the virtual console module was partially removed. ## Networking Issues ### Can't expose non-HTTPS ports By default, Phala Cloud only exposes **HTTPS/TLS ports** to the public internet. **For TCP services (SSH, databases, etc.):** * Use [TCP port forwarding](/phala-cloud/networking/expose-http-service) with TLS wrapping * See the [TCP services guide](/phala-cloud/networking/expose-tcp-service) **For DNS servers:** Running a DNS server on Phala Cloud is possible but requires workarounds since UDP port 53 cannot be directly exposed. Consider running DNS on a separate server and connecting to your TEE backend. ### SSH connection issues See the [SSH access guide](/phala-cloud/networking/enable-ssh-access) for detailed troubleshooting. **Common issues:** * Not using Development OS image (SSH is disabled on Production OS) * Missing `DSTACK_ROOT_PUBLIC_KEY` environment variable * Signing in with a root password. Since dstack 0.5.6, SSH rejects passwords. Use a public key. * Using LibreSSL instead of OpenSSL on macOS ## GPU TEE Issues ### "Resource matching failed: No teepod found" No GPU nodes are currently available matching your requirements. **Solutions:** 1. Try a different GPU configuration (fewer GPUs) 2. Try again later when resources become available 3. Contact [cloud@phala.network](mailto:cloud@phala.network) for dedicated capacity **For refunds on failed provisions:** Email [support@phala.network](mailto:support@phala.network) with: * Payment Order ID * Order reference ### GPU billing questions See [GPU TEE Billing](/phala-cloud/faqs#how-does-gpu-tee-billing-work) for details on: * Minimum rental period charges * When billing starts (only on launch) * Commitment pricing options ## API Error Codes If you encounter API errors with codes like `ERR-01-xxx` or `ERR-02-xxx`, see the [Error Codes Reference](/phala-cloud/references/error-codes) for a complete list of error codes and their meanings. ## Still Need Help? * Join our [Global Telegram](https://t.me/+nbhjx1ADG9EyYmI9) * Join our [Chinese Telegram](https://t.me/+4PcAE9qTZ1kzM2M9) * Email: [cloud@phala.network](mailto:cloud@phala.network) * [GitHub Issues](https://github.com/Phala-Network/phala-cloud/issues) # Scaling Source: https://docs.phala.com/phala-cloud/update/resize-resource Create and manage Confidential Virtual Machines (CVMs) on Phala Cloud. ## Prerequisites * A running CVM on Phala Cloud * Understanding of your application's resource requirements ## Dynamic Resource Allocation Phala Cloud provides flexible compute resource management, allowing you to scale your application's resources up or down based on your needs. ## How to Resize Your CVM 1. Navigate to your CVM dashboard 2. Locate the CVM you wish to modify 3. Click the **Resize** button on the CVM card 4. Adjust the CPU, memory, and storage allocations using the sliders 5. Review the new configuration and pricing 6. Confirm your changes ![resize-cvm](https://mintcdn.com/phalanetwork-1606097b/416gZMDMREnPDd33/images/cloud-resize-cvm.png?fit=max\&auto=format\&n=416gZMDMREnPDd33\&q=85\&s=04391ea3da85f5a96f97cffe1316c810) resize-cvm ## Important Considerations * **Restart Required**: The resize operation will trigger a restart of your CVM * **Downtime**: Your application will experience brief downtime during the resize process * **Data Persistence**: All data stored in persistent volumes will be preserved during resizing * **Billing Changes**: Resource adjustments will be reflected in your billing from the moment the resize completes ## Recommended Approach For production applications, consider: * Scheduling resize operations during low-traffic periods * Testing your application with the new resource configuration in a staging environment first * Monitoring application performance after resizing to ensure optimal resource allocation # Update CVM Configuration Source: https://docs.phala.com/phala-cloud/update/update-cvm-configuration Change a CVM's compose, environment, resources, OS image and gateway settings with one PATCH request, or stage several changes and apply them with one restart. You change an existing CVM with one request: `PATCH /cvms/{cvm_id}`. Send only the fields you want to change. Fields you leave out keep their current value. The examples use the API at `https://cloud-api.phala.com/api/v1` with your API key in the `X-API-Key` header. See [CVM Deployment via API](/phala-cloud/references/api-deployment-guide) for keys and SDKs. ## How do I update a CVM? Send the fields you want to change. This request turns on public logs and moves the CVM to a larger instance type: ```bash theme={"system"} curl -X PATCH "https://cloud-api.phala.com/api/v1/cvms/" \ -H "X-API-Key: $PHALA_CLOUD_API_KEY" \ -H "Content-Type: application/json" \ -d '{"public_logs": true, "instance_type": "tdx.medium"}' ``` The API answers `202 Accepted` and runs the update in the background: ```json theme={"system"} { "message": "CVM update initiated", "correlation_id": "...", "status": "in_progress" } ``` If you only sent compose settings and they match what the CVM already runs, nothing happens and the CVM does not restart: ```json theme={"system"} { "message": "Compose configuration unchanged", "correlation_id": "", "status": "no_change" } ``` `PATCH /cvms/{cvm_id}/docker-compose`, `PATCH /cvms/{cvm_id}/pre-launch-script`, `PATCH /cvms/{cvm_id}/envs`, redeploying a revision and the one-step full compose replacement (`POST /cvms/{cvm_id}/compose_file`) also answer `no_change` when nothing would change. In the two-step replacement, `POST /cvms/{cvm_id}/compose_file/provision` reports `compose_unchanged` instead; the second step, `PATCH /cvms/{cvm_id}/compose_file`, does not check again. Only one operation can run on a CVM at a time. If another one is still running, the request fails with `409`. Wait for it to finish, then send again. ## Which fields can I send? | Field | What it changes | | - | - | | `docker_compose_file` | The Docker Compose YAML | | `pre_launch_script` | The script that runs before your containers start | | `allowed_envs` | Names of the environment variables the CVM accepts | | `public_logs`, `public_sysinfo`, `public_tcbinfo` | What the public can see about the CVM | | `compose` | Other compose settings, as a patch. See [How does the compose patch work?](#how-does-the-compose-patch-work) | | `init_scripts` | Platform init scripts the CVM runs on every boot. See [Init scripts](/phala-cloud/cvm/advanced-settings#init-scripts) | | `confirm_data_wipe` | Set to `true` to confirm a change that erases data on every boot | | `encrypted_env` | Encrypted environment variables (hex) | | `vcpu`, `memory`, `disk_size`, `instance_type` | Compute and disk size. A disk cannot shrink. | | `image` | OS image name, from the CVM's available OS images | | `gpus` | GPU assignment: `{"gpus": [{"slot": "...", "product_id": "..."}], "attach_mode": "listed"}` | | `shutdown_timeout` | Seconds to wait for a clean shutdown (10 to 1200) | | `allow_force_stop` | Set to `true` to skip the clean shutdown and stop the CVM at once | The CVM's name and its Trust Center listing have their own endpoints, `PATCH /cvms/{cvm_id}/name` and `PATCH /cvms/{cvm_id}/listed`. Those only change records in Phala Cloud and never restart the CVM. The listing applies to every CVM of the app. ## How does the compose patch work? Every CVM runs an app compose: a JSON file that holds your Docker Compose YAML plus the settings the guest OS reads at boot. The `compose` field is a patch of that file. It follows [JSON Merge Patch](https://www.rfc-editor.org/rfc/rfc7396) rules: * A key you send sets that value. * A key you send as `null` removes it. * A key you leave out stays as it is. * An object such as `requirements` merges key by key, so you can change one requirement without sending the others. This request sets a 2 GB swap and requires a health check, and leaves every other setting alone: ```bash theme={"system"} curl -X PATCH "https://cloud-api.phala.com/api/v1/cvms/" \ -H "X-API-Key: $PHALA_CLOUD_API_KEY" \ -H "Content-Type: application/json" \ -d '{"compose": {"swap_size": "2G", "requirements": {"health_check": true}}}' ``` You can send these keys in `compose`: | Key | What it does | | - | - | | `gateway_enabled` | Route traffic to the CVM through the gateway. See [How do I turn the gateway on or off?](#how-do-i-turn-the-gateway-on-or-off) | | `port_policy` | Which ports the gateway forwards, and which get a PROXY protocol header | | `secure_time` | Wait for time to sync before the app gets its keys | | `swap_size` | Swap size, for example `"2G"` | | `storage_discard` | Return unused data-disk blocks to the host. Turn it off if the host must not learn when you allocate or delete files. | | `snapshotter` | `overlayfs` or `stargz`. Only for CVMs that use the `nerdctl-compose` runner. | | `event_log_version` | Event log format, `1` or `2`. Move to `2` only after every verifier that checks your app's attestation supports it. | | `bash_script` | The script a CVM with the `bash` runner runs. See [Other runners](/phala-cloud/cvm/advanced-settings#other-runners) | | `requirements.health_check`, `requirements.health_status_file` | Health check the guest runs | | `requirements.platforms` | Attestation platforms the app accepts | | `requirements.tdx_measure_acpi_tables` | Whether TDX measures the ACPI tables | | `requirements.ephemeral_data_disk` | Start every boot with an empty data disk. See [Ephemeral data disk](/phala-cloud/cvm/advanced-settings#ephemeral-data-disk) | | `requirements.launch_token_hash` | Launch token check. See [Launch Token](/phala-cloud/cvm/launch-token) | The top-level fields such as `docker_compose_file`, `pre_launch_script`, `allowed_envs` and `public_logs` also change the compose. Send them at the top level, not inside `compose`. `requirements.gpu_policy` cannot be changed with this request. A patch keeps the stored value, even if you remove `requirements`. ## Which settings cannot change after create? Some settings decide how the CVM's disk is encrypted and laid out, or what the guest runs. They are fixed when you create the CVM: * `kms_enabled`, `key_provider`, `key_provider_id`, `local_key_provider_enabled` * `storage_fs`, `verity_volumes` * `runner`, `manifest_version`, `no_instance_id` You can still send them. A value equal to the current one is accepted, so you can read the whole compose, edit it and send it back. A different value fails with `ERR-03-040`. `tproxy_enabled` and `features` are older names for the gateway setting. They move with `gateway_enabled`, and changing them on their own fails. ## Does an update restart my CVM? Yes, if it is running. The update stops the CVM, applies the change and starts it again. This happens even when only one field changes. A CVM that was stopped before the update stays stopped. It runs the new configuration when you next start it. These cases do not restart the CVM: * Compose settings that match what the CVM already runs. The API answers `no_change`. * Endpoints that only change records in Phala Cloud or on the host: the name, the Trust Center listing, the [KMS and gateway URLs](#can-i-change-the-kms-and-gateway-urls-a-cvm-uses) (unless you ask for a restart), the [app launch token](/phala-cloud/cvm/launch-token) and [annotations](/phala-cloud/cvm/advanced-settings#annotations). * [Staging a change](#how-do-i-stage-several-changes-and-restart-once). The CVM restarts once, when you apply the staged changes. To shorten the downtime, set `shutdown_timeout`. To stop at once without a clean shutdown, set `allow_force_stop` to `true`. ## How do I turn the gateway on or off? The gateway gives your CVM a public URL and forwards traffic to it. Turn it on or off with `compose.gateway_enabled`: ```json theme={"system"} { "compose": { "gateway_enabled": false } } ``` Turning it on needs a gateway that serves the CVM's node. The CVM must also have an instance ID, so it fails if the CVM was created with `no_instance_id`. Turning it off removes the CVM from the gateway once the update finishes, so its gateway URL stops working. The app ID does not change either way. `compose.port_policy` controls what the gateway forwards. With `restrict_mode` set to `true`, the gateway only forwards the ports in `ports` and refuses all others. Set `pp` to `true` on a port to have the gateway send a PROXY protocol header, so your app sees the client's address: ```json theme={"system"} { "compose": { "port_policy": { "restrict_mode": true, "ports": [{ "port": 443, "pp": true }, { "port": 8080 }] } } } ``` Port policy only covers the gateway. Ports mapped directly on the host are set with `PUT /cvms/{cvm_id}/ports`. ## Can I change the KMS and gateway URLs a CVM uses? Yes, with `PATCH /cvms/{cvm_id}/network-config`. Send `kms_urls`, `gateway_urls` or both. The CVM picks them up at its next boot. To restart it now, also send `"restart": true`. Changing `kms_urls` is available on request. Without it, a request that sends `kms_urls` fails with `403`. Phala Cloud keeps these URLs. Later updates send them instead of the URLs Phala Cloud would pick for the CVM's node. To go back to Phala Cloud's URLs, send an empty list for that field. Moving the CVM to another node removes both. `GET /cvms/{cvm_id}/network` shows the whole network setup in one answer: the gateway settings from the compose (`ingress`), the ports mapped on the host (`port_mappings`) and the KMS and gateway URLs (`endpoints`). In `endpoints`, `kms_urls_overridden` and `gateway_urls_overridden` say whether you set the URLs yourself. ## What changes for a CVM on Onchain KMS? With Onchain KMS, your app contract decides which composes may run. Any change to the compose gives it a new compose hash, and that hash must be added to the contract before the CVM can boot it. So the update takes two requests: 1. Send the `PATCH` as usual. If the new hash is not on the contract yet, the API answers HTTP `465` (`ERR-01-005`). The error's `details` list carries `compose_hash`, `app_id`, `device_id` and `kms_info`. 2. Call `addComposeHash` on your app contract with that hash. 3. Send the `PATCH` again with an empty body and two headers: `X-Compose-Hash` with the hash and `X-Transaction-Hash` with the transaction hash. The API checks the transaction and starts the update. If the hash is already on the contract, the first request starts the update right away. When someone else signs the transaction, such as a Safe or a timelock, add the header `X-Prepare-Only: true` to the first request. The `465` answer then also carries `commit_token`, `commit_url` and `api_commit_url`. Anyone with the token can finish the update with `POST /cvms/{cvm_id}/commit-update` after the hash is on the contract. [Multisig and Governance](/phala-cloud/key-management/multisig-governance) walks through this flow. The prepared update is kept for 14 days. After that, the second request fails with `ERR-01-006` and you start again. [Updating with Onchain KMS](/phala-cloud/key-management/updating-with-onchain-kms) covers the CLI path and the other error codes. ## How do I stage several changes and restart once? Each `PATCH /cvms/{cvm_id}` restarts a running CVM. To collect several changes, possibly from several people, and restart only once, stage them first and apply them together. 1. Stage a change with `PATCH /cvms/{cvm_id}/draft`. The body is the same as for `PATCH /cvms/{cvm_id}`. The CVM does not restart. Repeat for each change. Any workspace member who can update the CVM can add to the staged changes. 2. Check them with `GET /cvms/{cvm_id}/draft`. The answer lists each staged change with who sent it and when (`entries`), the one update that applying them sends (`patch`), and the compose hash the CVM will run afterwards (`preview_compose_hash`). 3. Apply them with `POST /cvms/{cvm_id}/draft/apply`. This sends one update, so a running CVM restarts once and a stopped CVM stays stopped. The answer is the same as for `PATCH /cvms/{cvm_id}`, including `no_change`. Compose changes are applied in the order you staged them. For other fields, such as `vcpu` or `encrypted_env`, the last staged value wins. Phala Cloud checks the compose that the staged changes produce each time you stage one, so a compose change the update would reject is refused right away. Once an apply starts the update, or answers `no_change`, the staged changes are cleared, but only if nobody changed them while the apply ran. If someone did, the apply still succeeds and all the staged changes stay, including the ones just applied. Review them before you apply again. If the CVM's compose hash has changed, the next apply fails with `ERR-03-053`: discard the staged changes, or apply them with the current hash. To throw them away instead, call `DELETE /cvms/{cvm_id}/draft`. Staged changes are kept for 14 days after the last change. A CVM with nothing staged answers `404` with `ERR-03-052`. ### What if the CVM changed after I staged? The first staged change records the CVM's compose hash (`base_compose_hash`). If the CVM's compose changes before you apply, for example through a direct `PATCH`, the apply fails with `409` and `ERR-03-053`, and nothing is applied. The error's `details` carry `base_compose_hash`, `current_compose_hash` and `changed_fields`, the compose fields that differ. Check the staged changes against the CVM as it is now. If you still want them, apply again with the current hash: ```json theme={"system"} { "base_compose_hash": "" } ``` If your stage or discard request conflicts with another write to the staged changes, it fails with `409` and `ERR-03-054`. Load the staged changes again and retry. ### How does apply work on Onchain KMS? Apply takes the same headers as `PATCH /cvms/{cvm_id}`: `X-Prepare-Only`, `X-Compose-Hash` and `X-Transaction-Hash`. See [What changes for a CVM on Onchain KMS?](#what-changes-for-a-cvm-on-onchain-kms) You can register `preview_compose_hash` on your app contract before you apply. The staged changes stay until the second step of the apply starts the update. If someone stages another change between the two steps, the second step fails with `ERR-03-054`. Apply again without the headers to get the new hash. If you finish a prepared apply with `POST /cvms/{cvm_id}/commit-update`, the staged changes are not cleared. The CVM now runs them, so the next apply fails with `ERR-03-053`. Discard them with `DELETE /cvms/{cvm_id}/draft`. ## Can I use the SDKs or the CLI? The [JavaScript](/phala-cloud/references/cloud-js-sdk/cvm-configuration#patchcvm), [Python](/phala-cloud/references/cloud-python-sdk/cvm-configuration#patch_cvm) and [Go](/phala-cloud/references/cloud-go-sdk/cvm-configuration#patchcvm) SDKs send this request, including `compose`, `init_scripts` and `confirm_data_wipe`, and handle the `465` answer for you. No SDK has methods for staged changes yet; call the API directly. The CLI updates a CVM with [`phala deploy --cvm-id`](/phala-cloud/phala-cloud-cli/deploy). Flags such as `--init-script`, `--clear-init-scripts`, `--launch-token-hash`, `--gateway`, `--ephemeral-data-disk`, `--event-log-version` and `--confirm-data-wipe` map to the fields on this page. Flags that set how a CVM is created, such as `--kms`, `--fs` or `--name`, fail on an update instead of being ignored. # Update Code Source: https://docs.phala.com/phala-cloud/update/upgrade-application Seamless code updates in TEE ## Prerequisites * A running CVM on Phala Cloud * New Docker image or updated configuration ready to deploy One of the key advantages of Phala Cloud is the ability to upgrade your application even while it's running inside a TEE. Thanks to the flexible architecture of the dstack SDK, your application isn't permanently bound to specific hardware configurations. ## Update Process 1. Navigate to your CVM dashboard 2. Locate the CVM running the application you wish to update 3. Click the **Code Update** button to open the update interface 4. In the update window, you can: * Update your Docker Compose configuration * Modify environment variables * Adjust application settings ## Important Considerations > [!NOTE] > > **NOTE** > > When restarting a Phala instance, it may not automatically pull the latest version of a **Docker image** if the **tag** has not changed. It's advisable to **increment Docker tags** for every new deployment to ensure the latest image is used. This behavior aligns with the need to update the Docker Compose file and execute an upgrade to pull the latest image > > The new environment variables will completely replace all existing variables. Be sure to include all required variables in your update, even those you don't intend to change. ## Completing the Update After configuring your update parameters: 1. Review all changes carefully 2. Click the **Save Changes** button to initiate the update 3. Monitor the update process through the CVM logs The platform will handle the secure transition to your updated application while maintaining the TEE security guarantees. ![Updating in Phala Cloud](https://mintcdn.com/phalanetwork-1606097b/416gZMDMREnPDd33/images/cloud-update-env.png?fit=max\&auto=format\&n=416gZMDMREnPDd33\&q=85\&s=56837264d69c46c44b60397a22b003fa) Updating in Phala Cloud ## Best Practices for Code Updates * Test your updates in a development environment before applying to production * Keep a backup of your current configuration before making changes * Schedule updates during periods of low user activity * Implement version tracking in your application to verify successful updates # What is Phala Cloud Source: https://docs.phala.com/phala-cloud/what-is/what-is-phala-cloud Phala Cloud provides secure TEE-powered infrastructure for running AI applications with hardware-level privacy and verifiable execution. Phala Cloud is a confidential computing platform for running AI applications with hardware-level privacy. Deploy any standard Docker application directly into a **TEE** — your AI models and data remain confidential and tamper-proof. ### Key Features for AI Developers * **Confidential AI computing**: Run LLMs and AI models in GPU TEE with hardware-level security * **Verifiable Results**: Cryptographic proof that your AI computations are genuine and unmodified * **Privacy Protection**: Complete confidentiality for your models, data, and algorithms * **Easy Deployment**: Deploy existing Docker applications with zero code changes * **Cost Effective**: Web2 pricing model, billed by the minute ## Getting Started New to Phala Cloud? You can start here: > [card] [Quick Start](/phala-cloud/getting-started/overview) > > Deploy your first secure application in minutes > [card] [Phala Cloud Platform](/phala-cloud/cvm/overview) > > Explore the complete cloud platform features > [card] [Private AI](/phala-cloud/confidential-ai/overview) > > Run LLMs in GPU TEE environments ## Core Concepts Understanding Phala Cloud's architecture: > [card] [Trusted Execution Environment](/phala-cloud/attestation/overview) > > Learn how TEE provides hardware-level security > [card] [Key Management](/dstack/design-documents/key-management-protocol) > > Secure cryptographic key generation and management > [card] [dstack SDK](/dstack/getting-started) > > Developer tools for building on Phala Cloud ## How Phala Cloud Compares Compare Phala Cloud to other confidential computing platforms: [Phala vs AWS Nitro](https://phala.com/compare/phala-vs-aws-nitro), [Phala vs Google Cloud](https://phala.com/compare/phala-vs-gcp), and [Phala vs Tinfoil](https://phala.com/compare/phala-vs-tinfoil). ## Support Need help? We're here to assist: * **Documentation Issues**: Report problems with our docs on [GitHub](https://github.com/Phala-Network/phala-docs) * **Technical Support**: Join our [Telegram community](https://t.me/+nbhjx1ADG9EyYmI9) for real-time help * **Enterprise**: [Contact us](https://cloud.phala.com/contact) for enterprise solutions and partnerships *** Ready to build secure AI? [Get started with Phala Cloud →](https://cloud.phala.com) # What is a Trusted Execution Environment (TEE)? Source: https://docs.phala.com/phala-cloud/what-is/what-is-tee Learn how Trusted Execution Environments provide hardware-level security for confidential computing, protecting your code and data from unauthorized access. A Trusted Execution Environment (TEE) is a secure area within your processor that protects code and data with hardware-level isolation. Even if someone has root access to your server, they cannot access what's running inside the TEE. Think of it like a vault built into your CPU. The processor encrypts everything inside this vault at the hardware level. The operating system, hypervisor, and even system administrators cannot peek inside or modify what's running there. ```mermaid theme={"system"} graph TB subgraph server["Physical Server"] subgraph untrusted["Untrusted Zone"] os["Operating System"] apps["Other Apps"] threat["Admins & Attackers"] end subgraph cpu["CPU with TEE"] subgraph tee["Protected Zone"] yourapp["Your App"] data["Your Data"] end end end os -.->|"❌ Blocked"| tee apps -.->|"❌ Blocked"| tee threat -.->|"❌ Blocked"| tee style tee fill:#2d5f2e,stroke:#4ade80,stroke-width:3px,color:#fff style untrusted fill:#5f2d2d,stroke:#f87171,stroke-width:2px,color:#fff style yourapp fill:#1e3a1e,color:#fff style data fill:#1e3a1e,color:#fff ``` ## How TEEs Protect Your Data TEEs use several hardware mechanisms to keep your applications secure. The CPU encrypts your application's memory automatically at the hardware level. Your code doesn't need to handle encryption, and the encryption keys never leave the processor. The TEE isolates your code from everything else on the system. Even if the operating system gets compromised, your application keeps running safely in its protected environment. This isolation extends to the physical world - cloud providers, datacenter staff, and hardware maintainers cannot extract your data, even with physical access to the machine. You can deploy standard Docker containers into a TEE without modifying your code. The TEE handles all security mechanisms transparently. ## Proving Security: Remote Attestation TEEs provide cryptographic proof that your code runs in a genuine hardware-protected environment. This proof is called remote attestation. When your application starts in a TEE, the hardware generates a signed report. This report includes measurements of your exact code, configuration, and the TEE's security state. Anyone can verify this report independently using the hardware manufacturer's public keys. ```mermaid theme={"system"} sequenceDiagram participant App as Your Application participant TEE as TEE Hardware participant Verifier as Verifier (Anyone) App->>TEE: Start in TEE TEE->>TEE: Measure code + data TEE->>TEE: Sign with hardware key TEE->>Verifier: Attestation Quote Note over Verifier: Contains:
- Code hash
- Configuration
- Hardware signature Verifier->>Verifier: Verify signature Verifier->>Verifier: Check measurements Verifier->>App: ✓ Verified! Note over Verifier: Trust established
without trusting
cloud provider ``` This means you can verify your code runs in a real TEE without trusting the cloud provider. The cryptographic signature comes from the CPU itself, not from any software that could be compromised. ## Why TEEs Matter for Your Applications TEEs enable confidential computing for applications that handle sensitive data or valuable intellectual property. **Confidential AI**: Run AI models where neither the cloud provider nor their staff can access your model weights or training data. This protects your AI intellectual property while still using cloud GPU acceleration. Learn more about [TEE with AI](/phala-cloud/cases/tee_with_ai). **Private Computation**: Process sensitive data like healthcare records or financial information in the cloud while keeping the data encrypted during computation. The TEE ensures that only your authorized code can access the data in its unencrypted form. **Secure Key Management**: Generate and store cryptographic keys inside a TEE where they cannot be extracted. Even administrators with full system access cannot steal the keys, because they exist only in the hardware-protected environment. **Verifiable Execution**: Prove to third parties that specific code processed their data, without revealing the data itself. The attestation report cryptographically binds your code to the TEE's security guarantees. ## Next Steps > [card] [Quick Start](/phala-cloud/getting-started/overview) > > Deploy your first TEE application in minutes > [card] [Understanding Attestation](/phala-cloud/attestation/overview) > > Deep dive into remote attestation and verification > [card] [Phala Cloud Platform](/phala-cloud/what-is/what-is-phala-cloud) > > Learn about Phala's TEE-powered cloud infrastructure > [card] [Private AI](/phala-cloud/confidential-ai/overview) > > Run AI models with hardware-guaranteed privacy