diff --git a/CHANGELOG.md b/CHANGELOG.md index d254f54c7..387d2a0ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 and the VMM web UI set them, and the VMM rejects malformed `int` and `float` specs at deployment. See [Environment value specs](docs/security/cvm-boundaries.md#environment-value-specs). +- **The KMS auth-eth server can require several RPC providers to agree.** + `ETH_RPC_URLS` with `ETH_RPC_QUORUM=n/m` answers a read only with what n of + the m endpoints return alike, and `ETH_MAX_BLOCK_AGE`, required with several + endpoints, rejects a stale block. + `dstack-app/deploy-to-vmm.sh` reads the endpoints from `rpc.json` and keeps + API keys out of the measured compose file. See [Multiple RPC providers](dstack/kms/auth-eth/README.md#multiple-rpc-providers). ### Security @@ -48,6 +54,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 in `allowed_envs`. An `allowed_envs` entry that contains a `:` must now be a valid `NAME: spec`; such an entry used to be a name no variable could have, and now stops the boot. +- **The KMS auth-eth server pins contract reads to a block hash.** Each + request reads the block it resolved by hash (EIP-1898) rather than by number, + so the RPC endpoint must accept a block hash in `eth_call`, which the server + checks at startup. HTTP redirects from the endpoint are refused. The server + no longer falls back to `http://localhost:8545`: it exits unless + `ETH_RPC_URL` or `ETH_RPC_URLS` is set. +- A failing `init_script` is reported to the VMM as a boot error. - **Go SDK module moves to `github.com/Dstack-TEE/dstack/sdk/go/dstack`.** `go get` now targets the module rooted at the `dstack` package, so pkg.go.dev lists it under its product name instead of "go". The `dstack` package import diff --git a/docs/tutorials/troubleshooting-kms-deployment.md b/docs/tutorials/troubleshooting-kms-deployment.md index 0e92efda1..24e9cde55 100644 --- a/docs/tutorials/troubleshooting-kms-deployment.md +++ b/docs/tutorials/troubleshooting-kms-deployment.md @@ -335,7 +335,7 @@ Then regenerate the app-compose.json and redeploy: {"error": "error decoding response body: missing field `status` at line 1 column ..."} ``` -**Root Cause:** auth-eth is reachable (port 9200 is correct), but it cannot read the contract. Without `ETH_RPC_URL` and `KMS_CONTRACT_ADDR`, auth-eth defaults to `http://localhost:8545` (nothing there) and the zero address, and returns `{status: 'error', ...}` instead of the expected `{status: 'ok', ...}` response. If the RPC is unreachable at startup, auth-eth exits instead, and GetMeta reports "Connection refused". +**Root Cause:** auth-eth is reachable (port 9200 is correct), but it cannot read the contract. Without `KMS_CONTRACT_ADDR`, auth-eth defaults to the zero address and returns `{status: 'error', ...}` instead of the expected `{status: 'ok', ...}` response. If `ETH_RPC_URL` is missing or the RPC is unreachable at startup, auth-eth exits instead, and GetMeta reports "Connection refused". **Solution:** Ensure your docker-compose.yaml includes both Ethereum configuration variables: diff --git a/dstack/kms/auth-eth/README.md b/dstack/kms/auth-eth/README.md index cb39d90c3..62f05d2eb 100644 --- a/dstack/kms/auth-eth/README.md +++ b/dstack/kms/auth-eth/README.md @@ -49,12 +49,63 @@ The Bun server sets `idleTimeout` to 255s (Bun's maximum). Bun's default of 10s ### Environment variables -- `ETH_RPC_URL` - ethereum RPC endpoint (default: http://localhost:8545) +- `ETH_RPC_URL` - ethereum RPC endpoint (required unless `ETH_RPC_URLS` is set) +- `ETH_RPC_URLS` - several RPC endpoints separated by whitespace, in place of `ETH_RPC_URL`. see [multiple RPC providers](#multiple-rpc-providers) +- `ETH_RPC_QUORUM` - `n/m`: every read must be answered alike by n of the m endpoints in `ETH_RPC_URLS`; m must be their count and n more than half of it (required with `ETH_RPC_URLS`) - `KMS_CONTRACT_ADDR` - KMS contract address (default: 0x0000000000000000000000000000000000000000) - `PORT` - server port (default: 3000) - `ETH_CHAIN_ID` - reject every decision if the RPC reports a different chain ID (default: unset, no check) -- `ETH_BLOCK_TAG` - block policy is read at: `latest`, `safe` or `finalized` (default: `finalized`). each request resolves the tag to one block and reads all state there, except `GET /app/:appId`, which serves only the env public key RPCs and reads the app epoch at `latest`. the server resolves the tag once at startup and refuses to start if the RPC cannot serve it. a later tag delays every policy change, including emergency revocations, until that block is reached (about 13 minutes for `finalized` on Ethereum mainnet). use `finalized` on L1. set `latest` explicitly for an OP-stack chain read through the Helios light client, which tracks only the sequencer-signed unsafe head and serves neither `safe` nor `finalized`, and for local development chains such as Anvil, which finalizes 64 blocks behind its head. see [reorgs and the block tag](#reorgs-and-the-block-tag) before using `latest` or `safe` +- `ETH_BLOCK_TAG` - block policy is read at: `latest`, `safe` or `finalized` (default: `finalized`). each request resolves the tag to one block and reads all state there, except `GET /app/:appId`, which serves only the env public key RPCs and reads the app epoch at `latest`, or `ETH_FINALITY_CONFIRMATIONS` blocks behind it (at least one) when the providers do not agree on the newest block. the server resolves the tag and reads at that block's hash once at startup, and refuses to start if the RPC cannot serve either. a later tag delays every policy change, including emergency revocations, until that block is reached (about 13 minutes for `finalized` on Ethereum mainnet). use `finalized` on L1. set `latest` explicitly for an OP-stack chain read through the Helios light client, which tracks only the sequencer-signed unsafe head and serves neither `safe` nor `finalized`, and for local development chains such as Anvil, which finalizes 64 blocks behind its head. see [reorgs and the block tag](#reorgs-and-the-block-tag) before using `latest` or `safe` - `ETH_FINALITY_CONFIRMATIONS` - read this many blocks further behind the block `ETH_BLOCK_TAG` resolves to (default: 0) +- `ETH_MAX_BLOCK_AGE` - reject every decision if the block read is older than this many seconds by the server clock (default: unset, no check; required with more than one RPC endpoint). it bounds how far providers that withhold new blocks can hold policy back; leave room for `ETH_BLOCK_TAG`, as `finalized` on Ethereum mainnet is already about 13 minutes old + +### Multiple RPC providers + +With one endpoint, whoever runs it decides what the KMS reads. `ETH_RPC_URLS` +and `ETH_RPC_QUORUM=n/m` make n providers have to agree instead: + +```yaml +environment: + ETH_RPC_URLS: | + https://eth-mainnet.g.alchemy.com/v2/${ALCHEMY_KEY} + https://mainnet.infura.io/v3/${INFURA_KEY} + https://ethereum-rpc.publicnode.com + ETH_RPC_QUORUM: 2/3 + ETH_MAX_BLOCK_AGE: 1800 +``` + +Each request resolves `ETH_BLOCK_TAG` to the highest block n providers have +reached, less `ETH_FINALITY_CONFIRMATIONS`, and takes that block's hash from n +providers that agree on it. Every contract read is then pinned to the hash and +answered only with a result n providers return alike. A provider that fails, +times out or reverts casts no vote, and without n votes the request fails +closed. `ETH_RPC_URL` alone is the same path with `1/1`. + +- **Choosing n/m.** Forging a read takes n colluding providers and stopping + the server takes m-n+1, so `2/3` or `3/5` tolerates one or two outages while + `n/n` stops on the first. n must be more than half of m, as otherwise two + groups of providers could each return a different answer. With `latest`, set `ETH_FINALITY_CONFIRMATIONS` to + 1 or 2 so that providers a block apart still agree. +- **Stale blocks.** The same m-n+1 providers, by lagging or by reporting an + old block, make the server read an earlier state of the chain, in which a + revoked policy is still in force. Only `ETH_MAX_BLOCK_AGE` bounds this, so + the server refuses to start with several endpoints and no such limit. The + bounds are proved in `formal/DstackFormal/Kms/RpcQuorum.lean`. +- **Choosing providers.** Use endpoints whose origin serves one chain and + nothing a customer controls. A provider that selects a chain or a + user-defined fork by path or by key lets whoever supplies the key decide what + that endpoint answers. Origins must be distinct, but two that resell the same + upstream are still one provider. +- **API keys.** The endpoint list and the quorum belong in the measured + compose file; the keys do not. `m` is stated apart from the list so that a + key cannot add an endpoint, and a key must not be able to leave its place in + the URL: in a dstack CVM, give it an `allowed_envs` spec such as + `ALCHEMY_KEY: /[A-Za-z0-9_-]{1,128}/` and deliver it through `.user-config`, + as `dstack-app/deploy-to-vmm.sh` does from the specs in its `rpc.json`. Only + the origin of an endpoint is ever logged or served by `GET /`. Redirects are + refused. +- **Cost.** Every request costs m times the RPC calls, and a provider that + hangs holds each request up for the 10-second RPC timeout. ### Reorgs and the block tag @@ -146,9 +197,12 @@ health check and system information `authApiInfo` is a JSON-encoded object the KMS forwards verbatim through its unauthenticated `GetMeta` RPC, so it carries public data only: -`kmsContractAddr`, `chainId`, `appImplementation`, `ethRpcUrl`, `blockTag` -(`ETH_BLOCK_TAG`), `finalityConfirmations` (`ETH_FINALITY_CONFIRMATIONS`) and -`policyBlockNumber` (the block the policy was read at). +`kmsContractAddr`, `chainId`, `appImplementation`, `ethRpcUrl` (the origins of +the endpoints, joined by commas), `ethRpcUrls` (the same origins as an array), +`rpcQuorum` (`ETH_RPC_QUORUM`), `blockTag` +(`ETH_BLOCK_TAG`), `finalityConfirmations` (`ETH_FINALITY_CONFIRMATIONS`), +`maxBlockAge` (`ETH_MAX_BLOCK_AGE`, when set) and `policyBlockNumber` (the +block the policy was read at). #### POST /bootAuth/app application boot authentication diff --git a/dstack/kms/auth-eth/index.test.ts b/dstack/kms/auth-eth/index.test.ts index 49d47c52f..e411b6db6 100644 --- a/dstack/kms/auth-eth/index.test.ts +++ b/dstack/kms/auth-eth/index.test.ts @@ -18,10 +18,15 @@ vi.mock('viem', async (importOriginal) => ({ getChainId: mockGetChainId, getBlock: mockGetBlock, })), - http: vi.fn(), + http: vi.fn(() => () => ({ request: vi.fn() })), getContract: vi.fn(), })); +// A chain whose tagged block is `tip` and whose block n has hash blockHash(n). +const blockHash = (n: bigint) => `0x${n.toString(16).padStart(64, '0')}`; +const chainAt = (tip: bigint, timestamp = 0n) => ({ blockTag, blockNumber }: { blockTag?: string; blockNumber?: bigint }) => + blockTag ? { number: tip } : { number: blockNumber, hash: blockHash(blockNumber!), timestamp }; + // Dynamic import after mocking let appFetch: any; @@ -42,7 +47,7 @@ beforeEach(() => { // Reset mocks before each test vi.clearAllMocks(); mockGetChainId.mockResolvedValue(1337); - mockGetBlock.mockResolvedValue({ number: 100n }); + mockGetBlock.mockImplementation(chainAt(100n)); }); describe('server runtime config', () => { @@ -117,6 +122,8 @@ describe('API Compatibility Tests', () => { chainId: 1337, appImplementation: '0x9876543210987654321098765432109876543210', ethRpcUrl: 'http://localhost:8545', + ethRpcUrls: ['http://localhost:8545'], + rpcQuorum: '1/1', blockTag: 'finalized', finalityConfirmations: 2, policyBlockNumber: 98, @@ -350,8 +357,8 @@ describe('API Compatibility Tests', () => { expect(calls.map(({ functionName }) => functionName)).toEqual(endpoint === 'app' ? ['rootEpochCount', 'currentRootEpoch'] : ['rootEpochCount', 'currentRootEpoch', 'rootEpoch']); - expect(calls.every(({ blockNumber }) => blockNumber === 98n)).toBe(true); - expect(mockGetBlock).toHaveBeenCalledTimes(1); + expect(calls.every((call) => call.blockHash === blockHash(98n) && call.requireCanonical)).toBe(true); + expect(mockGetBlock).toHaveBeenCalledTimes(2); }); describe.each(['rootEpochCount', 'currentRootEpoch'])('%s failures', (getter) => { @@ -684,9 +691,8 @@ describe('Ethereum finalized snapshot authorization', () => { })); it('reads the decision and gateway identity from one confirmation-depth snapshot', async () => { - mockGetBlock.mockResolvedValue({ number: 100n }); mockReadContract.mockImplementation((params) => { - expect(params.blockNumber).toBe(98n); + expect(params.blockHash).toBe(blockHash(98n)); if (params.functionName === 'rootEpochCount') return 0n; if (params.functionName === 'isAppAllowed') return [true, 'finalized allow']; if (params.functionName === 'gatewayAppId') return 'gateway-app'; @@ -695,25 +701,38 @@ describe('Ethereum finalized snapshot authorization', () => { const response = await authorize(); expect(await response.json()).toMatchObject({ isAllowed: true, reason: 'finalized allow' }); - expect(mockGetBlock).toHaveBeenCalledTimes(1); - expect(mockGetBlock).toHaveBeenCalledWith({ blockTag: 'finalized' }); + expect(mockGetBlock.mock.calls).toEqual([[{ blockTag: 'finalized' }], [{ blockNumber: 98n }]]); }); - it('probes the block tag at startup and names the fix when the RPC cannot serve it', async () => { + it('probes the block tag and a pinned read at startup and names what the RPC cannot serve', async () => { const { EthereumBackend } = await import('./index.ts'); - const getBlock = vi.fn().mockResolvedValue({ number: 5n }); - const client = { getChainId: async () => 1337, getBlock }; + const getBlock = vi.fn(chainAt(5n)); + const call = vi.fn(async (_: unknown) => ({})); + const client = { getChainId: async () => 1337, getBlock, call }; const backend = new EthereumBackend(client as never, '0x' + '11'.repeat(20), 1337, 'safe', 0n); - await expect(backend.probeBlockTag()).resolves.toBeUndefined(); + await expect(backend.probe()).resolves.toBeUndefined(); expect(getBlock).toHaveBeenCalledWith({ blockTag: 'safe' }); + expect(call.mock.calls[0][0]).toMatchObject({ blockHash: blockHash(5n), requireCanonical: true }); + call.mockRejectedValueOnce(new Error('invalid params')); + await expect(backend.probe()).rejects.toThrow(/^cannot read at a block hash, .+ \(invalid params\)$/); getBlock.mockRejectedValue(new Error('invalid block tag')); - await expect(backend.probeBlockTag()).rejects.toThrow( - /^ETH_BLOCK_TAG=safe is not supported by the RPC \(.+\); OP-stack via Helios requires latest$/, + await expect(backend.probe()).rejects.toThrow( + /^cannot resolve ETH_BLOCK_TAG=safe \(invalid block tag\); .+ requires latest$/, ); // Behind the confirmation depth counts as unavailable too. getBlock.mockResolvedValue({ number: 1n }); const deep = new EthereumBackend(client as never, '0x' + '11'.repeat(20), 1337, 'finalized', 2n); - await expect(deep.probeBlockTag()).rejects.toThrow(/ETH_BLOCK_TAG=finalized/); + await expect(deep.probe()).rejects.toThrow(/ETH_BLOCK_TAG=finalized/); + }); + + it('fails closed when the block is older than ETH_MAX_BLOCK_AGE', async () => { + const { EthereumBackend } = await import('./index.ts'); + const now = BigInt(Math.floor(Date.now() / 1000)); + const backend = (timestamp: bigint) => new EthereumBackend( + { getChainId: async () => 1337, getBlock: chainAt(5n, timestamp) } as never, '0x' + '11'.repeat(20), 1337, 'latest', 0n, 60, + ); + await expect(backend(now - 30n).resolveBlock()).resolves.toMatchObject({ number: 5n }); + await expect(backend(now - 90n).resolveBlock()).rejects.toThrow(/ETH_MAX_BLOCK_AGE/); }); it('accepts only the supported block tags, defaulting to finalized', async () => { @@ -726,13 +745,12 @@ describe('Ethereum finalized snapshot authorization', () => { }); it('re-evaluates the canonical finalized snapshot after a short reorg', async () => { - mockGetBlock.mockResolvedValueOnce({ number: 100n }).mockResolvedValueOnce({ number: 101n }); let decisions = 0; - const observedBlocks: bigint[] = []; + const observedBlocks: string[] = []; mockReadContract.mockImplementation((params) => { if (params.functionName === 'rootEpochCount') return 0n; if (params.functionName === 'isAppAllowed') { - observedBlocks.push(params.blockNumber); + observedBlocks.push(params.blockHash); decisions += 1; return decisions === 1 ? [true, 'old canonical allow'] : [false, 'new canonical deny']; } @@ -741,10 +759,11 @@ describe('Ethereum finalized snapshot authorization', () => { }); const before = await authorize(); + mockGetBlock.mockImplementation(chainAt(101n)); const after = await authorize(); expect(await before.json()).toMatchObject({ isAllowed: true }); expect(await after.json()).toMatchObject({ isAllowed: false, reason: 'new canonical deny' }); - expect(observedBlocks).toEqual([98n, 99n]); + expect(observedBlocks).toEqual([blockHash(98n), blockHash(99n)]); }); it.each([ @@ -762,7 +781,7 @@ describe('Ethereum finalized snapshot authorization', () => { }); mockGetChainId.mockResolvedValue(1337); - mockGetBlock.mockResolvedValue({ number: 102n }); + mockGetBlock.mockImplementation(chainAt(102n)); mockReadContract.mockImplementation((params) => { if (params.functionName === 'rootEpochCount') return 0n; if (params.functionName === 'isAppAllowed') return [true, 'recovered']; @@ -910,8 +929,13 @@ describe('GET /app/:appId', () => { const legacy = await appFetch(new Request(url)); expect(legacy.status).toBe(200); expect(await legacy.json()).toEqual({ currentAppEpoch: 0 }); - const { blockTag, blockNumber } = mockReadContract.mock.lastCall![0]; - expect([blockTag, blockNumber]).toEqual(['latest', undefined]); + expect(mockGetBlock).toHaveBeenCalledWith({ blockTag: 'latest' }); + expect(mockReadContract.mock.lastCall![0].blockHash).toBe(blockHash(100n)); + // Without agreement on the newest block, the read steps back by the confirmation depth. + mockGetBlock.mockImplementationOnce(chainAt(100n)).mockRejectedValueOnce(new Error('no quorum')); + mockReadContract.mockResolvedValueOnce(3n); + expect(await (await appFetch(new Request(url))).json()).toEqual({ currentAppEpoch: 3 }); + expect(mockReadContract.mock.lastCall![0].blockHash).toBe(blockHash(98n)); }); }); @@ -922,7 +946,7 @@ describe('GET /sevSnpTcbRequirements', () => { const response = await appFetch(new Request(url)); expect(await response.json()).toEqual({ requirements: '[]' }); expect(mockReadContract).toHaveBeenCalledWith( - expect.objectContaining({ functionName: 'sevSnpTcbRequirements', blockNumber: 98n }), + expect.objectContaining({ functionName: 'sevSnpTcbRequirements', blockHash: blockHash(98n) }), ); mockReadContract.mockRejectedValueOnce(new Error('execution reverted')); expect((await appFetch(new Request(url))).status).toBe(503); @@ -952,7 +976,7 @@ describe('POST /authorizeApp', () => { expect(await response.json()).toEqual({ ...result, currentRootEpoch: 2, currentAppEpoch: 0, latestRootEpoch: 3 }); expect(mockReadContract).toHaveBeenCalledTimes(1); expect(mockReadContract).toHaveBeenCalledWith(expect.objectContaining({ - functionName: 'authorizeApp', blockNumber: 98n, + functionName: 'authorizeApp', blockHash: blockHash(98n), args: [expect.objectContaining({ appInfo: expect.objectContaining({ appId: appInfo.appId }), requestedAppEpoch: { isSet: false, value: 0n }, requestedRootEpoch: { isSet: false, value: 0n }, teeVariant: appInfo.teeVariant })], })); }); @@ -1050,3 +1074,77 @@ describe('POST /authorizeApp', () => { expect(mockReadContract).toHaveBeenCalledTimes(1); }); }); + +describe('RPC quorum', () => { + const block = (number: number, fork = 'a') => ({ number: `0x${number.toString(16)}`, hash: `0x${fork}${number}`, timestamp: '0x1' }); + // Each answer is a value to return, or an Error to fail with. + const transport = async (threshold: number, answers: unknown[]) => { + const { quorumTransport } = await import('./index.ts'); + const providers = answers.map((answer, i) => ({ + origin: `https://rpc${i}.example`, + request: async () => { if (answer instanceof Error) throw answer; return answer; }, + })); + return quorumTransport(providers, threshold)({}); + }; + const call = { method: 'eth_call', params: [{}, 'latest'] }; + + it('answers only with what the threshold of providers agree on', async () => { + const request = async (threshold: number, answers: unknown[]) => (await transport(threshold, answers)).request(call); + await expect(request(2, ['0xAB', '0x01', '0xab'])).resolves.toBe('0xab'); + await expect(request(2, ['0x01', new Error('down'), '0x01'])).resolves.toBe('0x01'); + await expect(request(2, ['0x01', '0x02', '0x03'])).rejects.toThrow(/no 2 of 3 RPCs agree on eth_call/); + await expect(request(3, ['0x01', '0x01', new Error('execution reverted')])).rejects.toThrow( + 'https://rpc2.example: execution reverted', + ); + }); + + it('resolves a tag to the highest block the threshold has reached', async () => { + const tag = { method: 'eth_getBlockByNumber', params: ['finalized', false] }; + const request = async (answers: unknown[]) => (await transport(2, answers)).request(tag); + await expect(request([block(5), block(100), block(99)])).resolves.toEqual(block(99)); + await expect(request([block(1_000_000), block(100), block(100)])).resolves.toEqual(block(100)); + await expect(request([block(100), new Error('down'), block(98)])).resolves.toEqual(block(98)); + await expect(request([block(100), new Error('invalid block tag'), null])).rejects.toThrow( + /fewer than 2 RPCs serve block finalized \(https:\/\/rpc1\.example: invalid block tag/, + ); + }); + + it('agrees on a numbered block by hash and timestamp', async () => { + const numbered = { method: 'eth_getBlockByNumber', params: ['0x62', false] }; + const request = async (answers: unknown[]) => (await transport(2, answers)).request(numbered); + await expect(request([block(98), { ...block(98), extra: 1 }, block(98, 'b')])).resolves.toMatchObject(block(98)); + await expect(request([block(98), block(98, 'b'), null])).rejects.toThrow(/no 2 of 3 RPCs agree/); + await expect(request([block(98), { ...block(98), number: '0x1' }, null])).rejects.toThrow(/no 2 of 3 RPCs agree/); + }); + + it('refuses methods it has no agreement rule for', async () => { + const request = (await transport(1, ['0x1'])).request({ method: 'eth_getBalance', params: [] }); + await expect(request).rejects.toThrow(/eth_getBalance is not supported/); + }); + + it('pins the endpoint count and keeps URLs out of errors', async () => { + const { parseRpcConfig } = await import('./index.ts'); + const urls = 'https://a.example/v2/key1\n https://b.example/v3/key2\nhttps://c.example\n'; + expect(parseRpcConfig({ ETH_RPC_URLS: urls, ETH_RPC_QUORUM: '2/3', ETH_MAX_BLOCK_AGE: '1800' })).toMatchObject({ + origins: ['https://a.example', 'https://b.example', 'https://c.example'], threshold: 2, + }); + expect(parseRpcConfig({ ETH_RPC_URL: 'http://node:8545' })).toMatchObject({ quorum: '1/1', threshold: 1 }); + for (const [env, error] of [ + [{ ETH_RPC_URLS: urls }, /ETH_RPC_QUORUM must be n\/m/], + [{ ETH_RPC_URLS: urls, ETH_RPC_QUORUM: '4/3' }, /ETH_RPC_QUORUM must be n\/m/], + [{ ETH_RPC_URLS: urls, ETH_RPC_QUORUM: '2' }, /ETH_RPC_QUORUM must be n\/m/], + // One provider of three, or either half of four, could answer alone. + [{ ETH_RPC_URLS: urls, ETH_RPC_QUORUM: '1/3' }, /ETH_RPC_QUORUM must be n\/m/], + [{ ETH_RPC_URLS: urls + ' https://d.example', ETH_RPC_QUORUM: '2/4' }, /ETH_RPC_QUORUM must be n\/m/], + // A key that smuggles in an endpoint changes the count. + [{ ETH_RPC_URLS: urls + ' https://evil.example', ETH_RPC_QUORUM: '2/3' }, /expects 3 RPC URLs, got 4/], + [{ ETH_RPC_URLS: 'https://a.example/1 https://a.example/2', ETH_RPC_QUORUM: '2/2' }, /distinct origins/], + [{ ETH_RPC_URLS: 'https://a.example/key1 key2', ETH_RPC_QUORUM: '2/2' }, /^RPC URL 2 is invalid$/], + [{ ETH_RPC_URL: 'http://a', ETH_RPC_URLS: 'http://b', ETH_RPC_QUORUM: '1/1' }, /exactly one of/], + [{}, /exactly one of/], + [{ ETH_RPC_URLS: urls, ETH_RPC_QUORUM: '2/3' }, /ETH_MAX_BLOCK_AGE is required/], + ] as const) { + expect(() => parseRpcConfig(env)).toThrow(error); + } + }); +}); diff --git a/dstack/kms/auth-eth/index.ts b/dstack/kms/auth-eth/index.ts index 3b8447db5..3a7ef5953 100644 --- a/dstack/kms/auth-eth/index.ts +++ b/dstack/kms/auth-eth/index.ts @@ -8,7 +8,7 @@ import { secureHeaders } from 'hono/secure-headers'; import { HTTPException } from 'hono/http-exception'; import { zValidator } from '@hono/zod-validator'; import { z } from 'zod'; -import { createPublicClient, http, keccak256, toBytes, type Address, type Hex } from 'viem'; +import { BaseError, createPublicClient, custom, http, keccak256, toBytes, zeroAddress, type Address, type Hex } from 'viem'; // zod schemas for validation - compatible with original fastify implementation const boundedHex = (bytes: number, description: string) => @@ -220,12 +220,125 @@ export function parseBlockTag(value: string | undefined): BlockTag { return tag as BlockTag; } +export function parseRpcConfig(env: Record) { + const { ETH_RPC_URL: single, ETH_RPC_URLS: list } = env; + const given = list || single; + if (!given || (single && list)) throw new Error('set exactly one of ETH_RPC_URL and ETH_RPC_URLS'); + const urls = given.trim().split(/\s+/); + + // A single ETH_RPC_URL needs no ETH_RPC_QUORUM. + const quorum = env.ETH_RPC_QUORUM || (list ? '' : '1/1'); + const match = /^(\d+)\/(\d+)$/.exec(quorum); + const threshold = Number(match?.[1]); + const total = Number(match?.[2]); + // Two answers cannot both reach n only when n is more than half of m. + if (!match || threshold > total || threshold * 2 <= total) { + throw new Error('ETH_RPC_QUORUM must be n/m with m/2 < n <= m'); + } + // The count is pinned apart from the list, so a value interpolated into one + // URL cannot add an endpoint. + if (urls.length !== total) throw new Error(`ETH_RPC_QUORUM expects ${total} RPC URLs, got ${urls.length}`); + + // URLs carry API keys: never put one in an error. + const origins = urls.map((url, i) => { + if (!URL.canParse(url)) throw new Error(`RPC URL ${i + 1} is invalid`); + return new URL(url).origin; + }); + if (new Set(origins).size !== total) throw new Error('RPC URLs must have distinct origins'); + // Providers that lag or lie can hold the block back; only its age bounds that. + if (total > 1 && !env.ETH_MAX_BLOCK_AGE) throw new Error('ETH_MAX_BLOCK_AGE is required with several RPC URLs'); + + return { urls, origins, quorum, threshold }; +} + +// One RPC endpoint; the origin is the only part of its URL that is public. +type RpcProvider = { + origin: string; + request: (args: { method: string; params?: unknown }) => Promise; +}; +type RpcBlock = { hash: string; number: string; timestamp: string }; + +// viem puts a one-line summary without the request URL in shortMessage. +const errorSummary = (err: unknown): string => + (err as { shortMessage?: string }).shortMessage ?? (err instanceof Error ? err.message : String(err)); + +// Only a viem error has that summary; the text of any other error stays out of the log. +const logFailure = (what: string, err: unknown) => { + const reason = (err as { shortMessage?: string }).shortMessage; + console.error(reason ? `${what}: ${reason}` : what); +}; + +/// A transport that answers a request only with what `threshold` of the +/// providers answer alike. A provider that fails or reverts casts no vote. +export function quorumTransport(providers: RpcProvider[], threshold: number) { + const failure = (i: number, err: unknown) => `${providers[i].origin}: ${errorSummary(err)}`; + + // The first answer that `threshold` votes share under `key`. + const agree = (method: string, votes: Promise[], key: (answer: T) => string) => { + const counts = new Map(); + const failures: string[] = []; + // A vote fulfils only if it is the one that completes a quorum. + const quorum = votes.map(async (vote, i) => { + try { + const answer = await vote; + const answerKey = key(answer).toLowerCase(); + const count = (counts.get(answerKey) ?? 0) + 1; + counts.set(answerKey, count); + if (count >= threshold) return answer; + } catch (err) { + failures.push(failure(i, err)); + } + throw new BaseError('no quorum'); + }); + return Promise.any(quorum).catch(() => { + const detail = failures.length ? ` (${failures.join('; ')})` : ''; + throw new BaseError(`no ${threshold} of ${votes.length} RPCs agree on ${method}${detail}`); + }); + }; + + // The highest block `threshold` of the providers have reached, since they + // reach a tag at different times. Fewer than `threshold` providers cannot + // push it past a block one of the others has reached, but as few as + // m - threshold + 1 that lag or lie can hold it back: only + // ETH_MAX_BLOCK_AGE bounds that. + const reached = async (tag: unknown, votes: Promise[]) => { + const settled = await Promise.allSettled(votes.map(async (vote) => { + const tip = await vote; + return { tip, height: BigInt(tip.number) }; + })); + const tips = settled + .flatMap((vote) => (vote.status === 'fulfilled' ? [vote.value] : [])) + .sort((a, b) => Number(b.height - a.height)); + if (tips.length >= threshold) return tips[threshold - 1].tip; + const failures = settled.flatMap((vote, i) => (vote.status === 'rejected' ? [failure(i, vote.reason)] : [])); + throw new BaseError(`fewer than ${threshold} RPCs serve block ${tag} (${failures.join('; ')})`); + }; + + return custom({ + async request({ method, params }: { method: string; params?: unknown[] }) { + if (!['eth_chainId', 'eth_call', 'eth_getBlockByNumber'].includes(method)) { + throw new BaseError(`RPC method ${method} is not supported`); + } + const votes = providers.map((provider) => provider.request({ method, params })); + if (method !== 'eth_getBlockByNumber') return agree(method, votes as Promise[], (result) => result); + const blocks = votes as Promise[]; + const block = params?.[0]; + if (!String(block).startsWith('0x')) return reached(block, blocks); + return agree(method, blocks, ({ hash, number, timestamp }) => `${hash}:${number}:${timestamp}`); + }, + }, { retryCount: 0 }); +} + +// The block every read of a request is pinned to. +type Snapshot = { number: bigint; at: { blockHash: Hex; requireCanonical: true } }; + export class EthereumBackend { private client: ReturnType; private kmsContractAddr: Address; private expectedChainId?: number; readonly blockTag: BlockTag; readonly finalityConfirmations: bigint; + readonly maxBlockAge?: number; constructor( client: ReturnType, @@ -233,41 +346,47 @@ export class EthereumBackend { expectedChainId: number | undefined, blockTag: BlockTag, finalityConfirmations: bigint, + maxBlockAge?: number, ) { this.client = client; this.kmsContractAddr = kmsContractAddr as Address; this.expectedChainId = expectedChainId; this.blockTag = blockTag; this.finalityConfirmations = finalityConfirmations; + this.maxBlockAge = maxBlockAge; } - /// Resolve the configured tag, less the confirmation depth, to one block so - /// that every read of a request sees the same state. An RPC that does not - /// support the tag fails closed. - async resolveBlock(): Promise { + /// Resolve the tag, less the confirmation depth, to one block so that every + /// read of a request sees the same state. Reads are pinned to its hash, so + /// they fail rather than follow a reorg. An RPC that does not support the + /// tag fails closed. + async resolveBlock(tag: BlockTag = this.blockTag, confirmations = this.finalityConfirmations): Promise { const chainId = await this.client.getChainId(); if (this.expectedChainId !== undefined && chainId !== this.expectedChainId) { - throw new Error('authorization backend chain ID mismatch'); + throw new BaseError('authorization backend chain ID mismatch'); } - const { number } = await this.client.getBlock({ blockTag: this.blockTag }); - if (number === null || number < this.finalityConfirmations) { - throw new Error('authorization backend has not reached configured finality'); + const tip = await this.client.getBlock({ blockTag: tag }); + if (tip.number === null || tip.number < confirmations) { + throw new BaseError('authorization backend has not reached configured finality'); } - return number - this.finalityConfirmations; + const { hash, number, timestamp } = await this.client.getBlock({ blockNumber: tip.number - confirmations }); + if (hash === null || number === null) throw new BaseError('authorization backend block is pending'); + if (this.maxBlockAge !== undefined && Date.now() / 1000 - Number(timestamp) > this.maxBlockAge) { + throw new BaseError('authorization backend block is older than ETH_MAX_BLOCK_AGE'); + } + return { number, at: { blockHash: hash, requireCanonical: true } }; } - /// Resolve the tag once at startup, so an RPC that cannot serve it fails the - /// deployment instead of every later request. - async probeBlockTag(): Promise { - try { - await this.resolveBlock(); - } catch (err) { - // ethers and viem both put a one-line summary in shortMessage. - const detail = (err as { shortMessage?: string }).shortMessage ?? (err instanceof Error ? err.message : String(err)); - throw new Error( - `ETH_BLOCK_TAG=${this.blockTag} is not supported by the RPC (${detail}); OP-stack via Helios requires latest`, - ); - } + /// Resolve the tag and read at its block once at startup, so an RPC that + /// cannot serve either fails the deployment instead of every later request. + async probe(): Promise { + const block = await this.resolveBlock().catch((err) => { + const hint = this.blockTag === 'latest' ? '' : '; an RPC that cannot serve the tag, as OP-stack via Helios, requires latest'; + throw new Error(`cannot resolve ETH_BLOCK_TAG=${this.blockTag} (${errorSummary(err)})${hint}`); + }); + await this.client.call({ to: zeroAddress, ...block.at }).catch((err) => { + throw new Error(`cannot read at a block hash, which requires EIP-1898 of the RPC (${errorSummary(err)})`); + }); } private decodeHex(hex: string, sz: number = 32): Hex { @@ -296,7 +415,7 @@ export class EthereumBackend { } async checkAuthorization(appInfo: AuthorizationRequest, method: 'authorizeKms' | 'authorizeApp') { - const blockNumber = await this.resolveBlock(); + const block = await this.resolveBlock(); const result = await this.client.readContract({ address: this.kmsContractAddr, abi: DSTACK_KMS_ABI, @@ -309,7 +428,7 @@ export class EthereumBackend { teeVariant: appInfo.teeVariant, launchTicketHash: this.decodeHex(appInfo.launchTicketHash ?? '', 32), }], - blockNumber, + ...block.at, }); const currentRootEpoch = Number(result.currentRootEpoch); if (!Number.isSafeInteger(currentRootEpoch)) { @@ -324,7 +443,7 @@ export class EthereumBackend { async checkBoot(bootInfo: BootInfo, isKms: boolean): Promise { const bootInfoStruct = this.contractAppInfo(bootInfo); - const blockNumber = await this.resolveBlock(); + const block = await this.resolveBlock(); let response; if (isKms) { response = await this.client.readContract({ @@ -332,7 +451,7 @@ export class EthereumBackend { abi: DSTACK_KMS_ABI, functionName: 'isKmsAllowed', args: [bootInfoStruct], - blockNumber + ...block.at }); } else { response = await this.client.readContract({ @@ -340,7 +459,7 @@ export class EthereumBackend { abi: DSTACK_KMS_ABI, functionName: 'isAppAllowed', args: [bootInfoStruct], - blockNumber + ...block.at }); } @@ -349,11 +468,11 @@ export class EthereumBackend { address: this.kmsContractAddr, abi: DSTACK_KMS_ABI, functionName: 'gatewayAppId', - blockNumber + ...block.at }); const epochDenial = allowed - ? rootEpochDenial(bootInfo, await this.getRootEpoch(blockNumber)) + ? rootEpochDenial(bootInfo, await this.getRootEpoch(block)) : undefined; return { isAllowed: allowed && !epochDenial, @@ -363,39 +482,43 @@ export class EthereumBackend { } // The current root epoch and its chain hash; empty only when no epoch is registered. - async getRootEpoch(blockNumber?: bigint): Promise { - blockNumber ??= await this.resolveBlock(); + async getRootEpoch(block?: Snapshot): Promise { + block ??= await this.resolveBlock(); const count = await this.client.readContract({ address: this.kmsContractAddr, abi: DSTACK_KMS_ABI, functionName: 'rootEpochCount', - blockNumber + ...block.at }); if (count === 0n) return {}; const [epoch, chainHash] = await this.client.readContract({ address: this.kmsContractAddr, abi: DSTACK_KMS_ABI, functionName: 'currentRootEpoch', - blockNumber + ...block.at }); return { rootEpoch: Number(epoch), rootEpochHash: chainHash }; } // The root CA public key (P-256 SPKI DER) of the current root epoch, which // signs the RPC certificate of every KMS serving it. - async getRootCaPubkey(blockNumber: bigint, current: RootEpochInfo): Promise { + async getRootCaPubkey(block: Snapshot, current: RootEpochInfo): Promise { if (current.rootEpoch === undefined) return undefined; const [caPubkey] = await this.client.readContract({ address: this.kmsContractAddr, abi: DSTACK_KMS_ABI, functionName: 'rootEpoch', - args: [BigInt(current.rootEpoch)], blockNumber, + args: [BigInt(current.rootEpoch)], ...block.at, }); return caPubkey; } async getAppEpoch(appId: string): Promise { + // Providers a block apart share no newest block once one of them reports + // a head the others lack, so fall back to the depth they do agree at. + const block = await this.resolveBlock('latest', 0n) + .catch(() => this.resolveBlock('latest', this.finalityConfirmations || 1n)); const epoch = Number(await this.client.readContract({ address: this.kmsContractAddr, abi: DSTACK_KMS_ABI, functionName: 'currentAppEpoch', - args: [this.decodeHex(appId, 20)], blockTag: 'latest', + args: [this.decodeHex(appId, 20)], ...block.at, })); if (!Number.isSafeInteger(epoch)) throw new Error('app epoch exceeds the supported range'); return epoch; @@ -404,16 +527,16 @@ export class EthereumBackend { async getSevSnpTcbRequirements(): Promise { return await this.client.readContract({ address: this.kmsContractAddr, abi: DSTACK_KMS_ABI, functionName: 'sevSnpTcbRequirements', - blockNumber: await this.resolveBlock(), + ...(await this.resolveBlock()).at, }); } - async getGatewayAppId(blockNumber?: bigint): Promise { + async getGatewayAppId(block?: Snapshot): Promise { const result = await this.client.readContract({ address: this.kmsContractAddr, abi: DSTACK_KMS_ABI, functionName: 'gatewayAppId', - blockNumber: blockNumber ?? await this.resolveBlock(), + ...(block ?? await this.resolveBlock()).at, }); return result as string; } @@ -423,12 +546,12 @@ export class EthereumBackend { return Number(chainId); } - async getAppImplementation(blockNumber?: bigint): Promise { + async getAppImplementation(block?: Snapshot): Promise { const result = await this.client.readContract({ address: this.kmsContractAddr, abi: DSTACK_KMS_ABI, functionName: 'appImplementation', - blockNumber: blockNumber ?? await this.resolveBlock(), + ...(block ?? await this.resolveBlock()).at, }); return result as string; } @@ -438,7 +561,7 @@ export class EthereumBackend { const app = new Hono(); // initialize ethereum backend -const rpcUrl = process.env.ETH_RPC_URL || 'http://localhost:8545'; +const rpc = parseRpcConfig(process.env); const kmsContractAddr = process.env.KMS_CONTRACT_ADDR || '0x0000000000000000000000000000000000000000'; const parseNonNegativeInteger = (name: string, value: string | undefined): number | undefined => { if (value === undefined || value === '') return undefined; @@ -452,20 +575,22 @@ const finalityConfirmations = BigInt( parseNonNegativeInteger('ETH_FINALITY_CONFIRMATIONS', process.env.ETH_FINALITY_CONFIRMATIONS) ?? 0, ); const client = createPublicClient({ - transport: http(rpcUrl) + transport: quorumTransport(rpc.urls.map((url, i) => ({ + origin: rpc.origins[i], + // A redirect would take the request off the configured origin. With + // several providers the others stand in for a retry, which would only + // hold the decision up behind a dead one. + request: http(url, { + fetchOptions: { redirect: 'error' }, + retryCount: rpc.urls.length > 1 ? 0 : undefined, + })({}).request, + })), rpc.threshold), }); const ethereum = new EthereumBackend( client, kmsContractAddr, expectedChainId, parseBlockTag(process.env.ETH_BLOCK_TAG), finalityConfirmations, + parseNonNegativeInteger('ETH_MAX_BLOCK_AGE', process.env.ETH_MAX_BLOCK_AGE), ); - -const publicRpcEndpoint = (value: string): string => { - try { - const endpoint = new URL(value); - return `${endpoint.protocol}//${endpoint.host}`; - } catch { - return 'configured'; - } -}; +const ethRpcUrl = rpc.origins.join(','); const backendUnavailable = 'authorization backend unavailable'; const invalidRequest = { isAllowed: false, reason: 'invalid authorization request', gatewayAppId: '' }; @@ -508,7 +633,7 @@ app.get('/', async (c) => { return c.json({ status: 'ok', kmsContractAddr: kmsContractAddr, - ethRpcUrl: publicRpcEndpoint(rpcUrl), + ethRpcUrl, gatewayAppId: batch[0], chainId: batch[1], appAuthImplementation: batch[2], // NOTE: for backward compatibility @@ -518,16 +643,19 @@ app.get('/', async (c) => { kmsContractAddr, chainId: batch[1], appImplementation: batch[2], - ethRpcUrl: publicRpcEndpoint(rpcUrl), + ethRpcUrl, + ethRpcUrls: rpc.origins, + rpcQuorum: rpc.quorum, blockTag: ethereum.blockTag, finalityConfirmations: Number(ethereum.finalityConfirmations), - policyBlockNumber: Number(block), + maxBlockAge: ethereum.maxBlockAge, + policyBlockNumber: Number(block.number), }), ...batch[3], ...(rootCaPubkey && { rootCaPubkey }), }); - } catch { - console.error('authorization backend health check failed'); + } catch (err) { + logFailure('authorization backend health check failed', err); return c.json({ status: 'error', message: backendUnavailable @@ -577,8 +705,8 @@ for (const method of ['authorizeKms', 'authorizeApp'] as const) { async (c) => { try { return c.json(await ethereum.checkAuthorization(c.req.valid('json'), method)); - } catch { - console.error('authorization backend failed'); + } catch (err) { + logFailure('authorization backend failed', err); return c.json({ status: 'error', message: backendUnavailable }, 503); } } @@ -595,8 +723,8 @@ app.post('/bootAuth/app', const bootInfo = c.req.valid('json'); const result = await ethereum.checkBoot(bootInfo, false); return c.json(result); - } catch { - console.error('application authorization backend failed'); + } catch (err) { + logFailure('application authorization backend failed', err); return c.json({ isAllowed: false, gatewayAppId: '', @@ -619,7 +747,7 @@ app.post('/bootAuth/kms', } catch (error) { // don't log test backend errors if (!(error instanceof Error && "Test backend error" === error.message)) { - console.error('KMS authorization backend failed'); + logFailure('KMS authorization backend failed', error); } return c.json({ isAllowed: false, @@ -631,7 +759,7 @@ app.post('/bootAuth/kms', ); // start server -if (import.meta.main) await ethereum.probeBlockTag(); +if (import.meta.main) await ethereum.probe(); const port = parseInt(process.env.PORT || '3000'); console.log(`starting server on port ${port}`); diff --git a/dstack/kms/auth-eth/openapi.json b/dstack/kms/auth-eth/openapi.json index e08b773eb..55e427a55 100644 --- a/dstack/kms/auth-eth/openapi.json +++ b/dstack/kms/auth-eth/openapi.json @@ -334,7 +334,7 @@ }, "ethRpcUrl": { "type": "string", - "description": "Ethereum RPC URL" + "description": "Origins of the Ethereum RPC endpoints, joined by commas" }, "gatewayAppId": { "type": "string", @@ -354,7 +354,7 @@ }, "authApiInfo": { "type": "string", - "description": "JSON-encoded public metadata the KMS forwards verbatim through GetMeta: kmsContractAddr, chainId, appImplementation, ethRpcUrl, blockTag, finalityConfirmations, policyBlockNumber" + "description": "JSON-encoded public metadata the KMS forwards verbatim through GetMeta: kmsContractAddr, chainId, appImplementation, ethRpcUrl, ethRpcUrls, rpcQuorum, blockTag, finalityConfirmations, maxBlockAge, policyBlockNumber" }, "rootEpoch": { "type": "integer", diff --git a/dstack/kms/dstack-app/.gitignore b/dstack/kms/dstack-app/.gitignore index 09a73e562..6d376df96 100644 --- a/dstack/kms/dstack-app/.gitignore +++ b/dstack/kms/dstack-app/.gitignore @@ -1,3 +1,4 @@ .app-compose.json .env .GIT_REV +rpc.json diff --git a/dstack/kms/dstack-app/compose-dev.yaml b/dstack/kms/dstack-app/compose-dev.yaml index 70a10e1ed..e01154488 100644 --- a/dstack/kms/dstack-app/compose-dev.yaml +++ b/dstack/kms/dstack-app/compose-dev.yaml @@ -20,14 +20,22 @@ services: ENV NODE_ENV=production CMD ["bun", "index.ts"] environment: - - PORT=8000 - - ETH_RPC_URL=${ETH_RPC_URL} + PORT: 8000 + # One endpoint per line. Every read must be answered alike by n of the m + # endpoints, with ETH_RPC_QUORUM as n/m. A ${NAME} is an API key from + # env in the unmeasured .user-config; its allowed_envs spec keeps it + # to one path segment, so it cannot change an endpoint or add one. + ETH_RPC_URLS: | + ${ETH_RPC_URLS} + ETH_RPC_QUORUM: ${ETH_RPC_QUORUM} # finalized on L1; an OP-stack chain read through Helios requires latest. - - ETH_BLOCK_TAG=${ETH_BLOCK_TAG} - - ETH_FINALITY_CONFIRMATIONS=${ETH_FINALITY_CONFIRMATIONS} + ETH_BLOCK_TAG: ${ETH_BLOCK_TAG} + ETH_FINALITY_CONFIRMATIONS: ${ETH_FINALITY_CONFIRMATIONS} + # Empty disables the block age check. + ETH_MAX_BLOCK_AGE: "${ETH_MAX_BLOCK_AGE}" # Empty disables the chain ID check. - - ETH_CHAIN_ID=${ETH_CHAIN_ID} - - KMS_CONTRACT_ADDR=${KMS_CONTRACT_ADDR} + ETH_CHAIN_ID: "${ETH_CHAIN_ID}" + KMS_CONTRACT_ADDR: "${KMS_CONTRACT_ADDR}" restart: unless-stopped ports: - 8001:8000 diff --git a/dstack/kms/dstack-app/deploy-to-vmm.sh b/dstack/kms/dstack-app/deploy-to-vmm.sh index be598fb6f..e3618642b 100755 --- a/dstack/kms/dstack-app/deploy-to-vmm.sh +++ b/dstack/kms/dstack-app/deploy-to-vmm.sh @@ -5,6 +5,13 @@ # # SPDX-License-Identifier: Apache-2.0 +set -e + +# Write rpc.json with the given endpoint unless the file exists. +init_rpc_json() { + [ -f rpc.json ] || jq -n --arg url "$1" '{quorum: "1/1", endpoints: [$url], keys: {}}' >rpc.json +} + # Check if .env exists if [ -f ".env" ]; then # Load variables from .env @@ -42,8 +49,27 @@ else # The URL of the dstack app image download URL # IMAGE_DOWNLOAD_URL=https://download.dstack.org/os-images/mr_{OS_IMAGE_HASH}.tar.gz -# The URL of the Ethereum RPC service -ETH_RPC_URL=https://rpc.phala.network +# rpc.json lists the Ethereum RPC endpoints and how many of them must answer +# every read alike, as n/m. All of it is measured and public. Write an API key +# as \${NAME} in an endpoint, give NAME an allowed_envs spec under keys, and set +# its value here: values reach the CVM through its unmeasured user config and +# stay out of the measurement. For example: +# { +# "quorum": "2/3", +# "endpoints": [ +# "https://eth-mainnet.g.alchemy.com/v2/\${ALCHEMY_KEY}", +# "https://mainnet.infura.io/v3/\${INFURA_KEY}", +# "https://ethereum-rpc.publicnode.com" +# ], +# "keys": { +# "ALCHEMY_KEY": "/[A-Za-z0-9_-]{32}/", +# "INFURA_KEY": "/[0-9a-f]{32}/" +# } +# } +# A spec must keep its key to one URL path segment, so that the key cannot +# change an endpoint or add one. Keys need dstack OS 0.6.7 or later. +# ALCHEMY_KEY= +# INFURA_KEY= # The block the auth-api reads policy at: latest, safe or finalized (default). # Use finalized on L1; an OP-stack chain read through Helios requires latest. @@ -55,6 +81,11 @@ ETH_RPC_URL=https://rpc.phala.network # Read this many blocks behind the block ETH_BLOCK_TAG resolves to (default: 0). # ETH_FINALITY_CONFIRMATIONS=0 +# Reject decisions if the block read is older than this many seconds (empty: no +# check). Required when rpc.json lists more than one endpoint; leave room for +# ETH_BLOCK_TAG, as finalized on Ethereum mainnet is about 13 minutes old. +# ETH_MAX_BLOCK_AGE= + # The Git repository to deploy GIT_REPOSITORY=https://github.com/Dstack-TEE/dstack.git @@ -70,19 +101,40 @@ KMS_IMAGE=dstacktee/dstack-kms@sha256:11ac59f524a22462ccd2152219b0bec48a28ceb734 # The admin token for the KMS app ADMIN_TOKEN=$(tr -dc 'a-zA-Z0-9' < /dev/urandom | fold -w 32 | head -n 1) EOF + init_rpc_json https://rpc.phala.network echo "Please edit the .env file and set the required variables, then run this script again." exit 1 fi +# An .env that predates rpc.json names its one endpoint in ETH_RPC_URL. +init_rpc_json "${ETH_RPC_URL:-https://rpc.phala.network}" +if [ -n "${ETH_RPC_URL:-}" ] && ! jq -e --arg url "$ETH_RPC_URL" '.endpoints == [$url]' rpc.json >/dev/null; then + echo "Warning: ETH_RPC_URL in .env is ignored, as rpc.json names the RPC endpoints." +fi +if ! UNDECLARED=$(jq -r '[.endpoints[] | scan("\\$\\{(\\w+)\\}")[]] - (.keys | keys) | join(" ")' rpc.json); then + echo "Error: rpc.json is invalid." + exit 1 +fi +if [ -n "$UNDECLARED" ]; then + echo "Error: rpc.json gives no spec under keys for: $UNDECLARED" + exit 1 +fi +if [ -z "${ETH_MAX_BLOCK_AGE:-}" ] && jq -e '.endpoints | length > 1' rpc.json >/dev/null; then + echo "Error: set ETH_MAX_BLOCK_AGE in .env: the auth-api requires it with several RPC endpoints." + exit 1 +fi +mapfile -t RPC_KEYS < <(jq -r '.keys | keys[]' rpc.json) +mapfile -t ENV_SPECS < <(jq -r '.keys | to_entries[] | "--env-spec", "\(.key): \(.value)"' rpc.json) + required_env_vars=( "VMM_RPC" "KMS_RPC_ADDR" "AUTH_API_RPC_ADDR" "GUEST_AGENT_ADDR" "KMS_CONTRACT_ADDR" - "ETH_RPC_URL" "IMAGE_DOWNLOAD_URL" "GIT_REPOSITORY" + "${RPC_KEYS[@]}" ) for var in "${required_env_vars[@]}"; do @@ -111,10 +163,18 @@ subvar() { ETH_BLOCK_TAG=${ETH_BLOCK_TAG:-finalized} ETH_CHAIN_ID=${ETH_CHAIN_ID:-} ETH_FINALITY_CONFIRMATIONS=${ETH_FINALITY_CONFIRMATIONS:-0} -subvar ETH_RPC_URL +ETH_MAX_BLOCK_AGE=${ETH_MAX_BLOCK_AGE:-} +# One endpoint per line of the block scalar in compose-dev.yaml. +# shellcheck disable=SC2034 # consumed via `subvar` into compose-*.yaml +ETH_RPC_URLS=$(jq -r '.endpoints | join("\\n ")' rpc.json) +# shellcheck disable=SC2034 +ETH_RPC_QUORUM=$(jq -r .quorum rpc.json) +subvar ETH_RPC_URLS +subvar ETH_RPC_QUORUM subvar ETH_BLOCK_TAG subvar ETH_CHAIN_ID subvar ETH_FINALITY_CONFIRMATIONS +subvar ETH_MAX_BLOCK_AGE subvar KMS_CONTRACT_ADDR subvar GIT_REV subvar IMAGE_DOWNLOAD_URL @@ -144,11 +204,21 @@ $CLI compose \ --public-sysinfo \ --secure-time \ --no-instance-id \ + "${ENV_SPECS[@]}" \ + ${RPC_KEYS:+--init-script <(echo "dstack-util import-env ${RPC_KEYS[*]}")} \ --output .app-compose.json # Remove the temporary file as it is no longer needed rm "$COMPOSE_TMP" +# The user config holds the keys under env, apart from the fields dstack +# defines. The import-env init script copies them into the env file and refuses +# one that breaks its allowed_envs spec. mktemp keeps the keys readable by this +# user only. +USER_CONFIG=$(mktemp) +trap 'rm -f "$USER_CONFIG"' EXIT +jq '{env: .keys | with_entries(.value = env[.key])}' rpc.json >"$USER_CONFIG" + echo "Deploying KMS to dstack-vmm..." $CLI deploy \ @@ -159,6 +229,7 @@ $CLI deploy \ ${KMS_ADMIN_ADDR:+--port "tcp:$KMS_ADMIN_ADDR:8002"} \ --port tcp:"$AUTH_API_RPC_ADDR":8001 \ --port tcp:"$GUEST_AGENT_ADDR":8090 \ + ${RPC_KEYS:+--user-config "$USER_CONFIG"} \ --vcpu 8 \ --memory 8G \ --disk 50G diff --git a/formal/DstackFormal.lean b/formal/DstackFormal.lean index 5970e602a..4fe7246bb 100644 --- a/formal/DstackFormal.lean +++ b/formal/DstackFormal.lean @@ -22,6 +22,7 @@ import DstackFormal.Kms.KeyDerivation import DstackFormal.Kms.KeyRelease import DstackFormal.Kms.RaTlsEncoding import DstackFormal.Kms.RootEpoch +import DstackFormal.Kms.RpcQuorum import DstackFormal.Vmm.Lifecycle import DstackFormal.Vmm.Safety import DstackFormal.Vmm.Traces diff --git a/formal/DstackFormal/Kms/RpcQuorum.lean b/formal/DstackFormal/Kms/RpcQuorum.lean new file mode 100644 index 000000000..fef1cf509 --- /dev/null +++ b/formal/DstackFormal/Kms/RpcQuorum.lean @@ -0,0 +1,242 @@ +-- SPDX-FileCopyrightText: © 2026 Phala Network +-- +-- SPDX-License-Identifier: Apache-2.0 + +/-! +# RPC quorum: n of m providers + +Models `quorumTransport` in `dstack/kms/auth-eth/index.ts`: `agree`, which +answers `eth_chainId`, `eth_call` and a block read by number, and `reached`, +which resolves a block tag. + +Proven, for a threshold `n` and fewer than `n` faulty providers: +* `agree_honest`: an answer `agree` returns is the one the honest providers + give; `agree_complete`: `n` honest votes for it are enough to get it. +* `agree_unique`: with `2n > m` at most one answer can gather `n` votes, so + the result does not depend on the order the votes arrive in. +* `reached_le_honest`: the block a tag resolves to is no higher than one an + honest provider has reached. +* `reached_ge_honest`: it is no lower than one an honest provider has reached + when `n` honest providers answer, which takes at most `m - n` faulty or + silent ones. `reached_stale` shows the bound is tight: with `m/m`, one + provider holds the block back as far as it likes. + +Assumptions: an honest provider answers a read pinned to a block with the one +true answer or not at all, and reports a block it has reached. +Modeling gaps: answers are compared as the code's keys (the result, or +`hash:number:timestamp`); timeouts, the HTTP layer and `resolveBlock`, which +chains a tag, a block read and the calls, are not modeled. +-/ + +namespace DstackFormal.Kms.RpcQuorum + +theorem countP_le_add {β : Type} (p q r : β → Bool) (l : List β) + (h : ∀ x ∈ l, r x = true → p x = true ∨ q x = true) : + l.countP r ≤ l.countP p + l.countP q := by + induction l with + | nil => simp + | cons x xs ih => + have ih := ih fun y hy => h y (List.mem_cons_of_mem x hy) + have hx := h x List.mem_cons_self + simp only [List.countP_cons] + cases hr : r x <;> cases hp : p x <;> cases hq : q x <;> simp_all <;> omega + +/-! ## Agreement on one answer -/ + +section Agree +variable {α : Type} [DecidableEq α] + +/-- `agree`: the votes in the order they arrive, `none` for a provider that +fails; `seen` holds the answers counted so far. -/ +def agreeFrom (n : Nat) (seen : List α) : List (Option α) → Option α + | [] => none + | none :: rest => agreeFrom n seen rest + | some a :: rest => if n ≤ seen.count a + 1 then some a else agreeFrom n (a :: seen) rest + +def agree (n : Nat) (votes : List (Option α)) : Option α := agreeFrom n [] votes + +theorem agreeFrom_count {n : Nat} {v : α} (votes : List (Option α)) (seen : List α) + (h : agreeFrom n seen votes = some v) : n ≤ seen.count v + votes.count (some v) := by + induction votes generalizing seen with + | nil => simp [agreeFrom] at h + | cons vote rest ih => + cases vote with + | none => have := ih seen (by simpa [agreeFrom] using h); simpa using this + | some a => + simp only [agreeFrom] at h + split at h + · cases h; simp; omega + · have := ih (a :: seen) h + simp only [List.count_cons] at this ⊢ + by_cases hav : a = v <;> simp_all <;> omega + +/-- An answer `agree` returns has `n` votes. -/ +theorem agree_count {n : Nat} {v : α} {votes : List (Option α)} (h : agree n votes = some v) : + n ≤ votes.count (some v) := by + simpa using agreeFrom_count votes [] h + +theorem agreeFrom_isSome {n : Nat} {v : α} (votes : List (Option α)) (seen : List α) + (hseen : ∀ x, seen.count x < n) (h : n ≤ seen.count v + votes.count (some v)) : + (agreeFrom n seen votes).isSome := by + induction votes generalizing seen with + | nil => have := hseen v; simp at h; omega + | cons vote rest ih => + cases vote with + | none => simpa [agreeFrom] using ih seen hseen (by simpa using h) + | some a => + simp only [agreeFrom] + split + · rfl + · next hlt => + refine ih (a :: seen) (fun x => ?_) ?_ + · have := hseen x + simp only [List.count_cons] + by_cases hax : a = x <;> simp_all <;> omega + · simp only [List.count_cons] at h ⊢ + by_cases hav : a = v <;> simp_all <;> omega + +/-- One provider's vote. -/ +structure Vote (α : Type) where + honest : Bool + answer : Option α + +/-- With fewer than `n` faulty providers, `agree` returns only the answer of +the honest ones. -/ +theorem agree_honest {n : Nat} {t v : α} {votes : List (Vote α)} + (hfaulty : votes.countP (fun x => !x.honest) < n) + (hhonest : ∀ x ∈ votes, x.honest = true → x.answer = none ∨ x.answer = some t) + (h : agree n (votes.map (·.answer)) = some v) : v = t := by + refine Classical.byContradiction fun hne => ?_ + have hcount := agree_count h + rw [List.count_eq_countP, List.countP_map] at hcount + have := List.countP_mono_left (l := votes) (p := (· == some v) ∘ (·.answer)) + (q := fun x => !x.honest) fun x hx hv => by + cases hh : x.honest + · rfl + · rcases hhonest x hx hh with h0 | h0 <;> simp_all + omega + +/-- `n` honest votes for an answer are enough for `agree` to return it. -/ +theorem agree_complete {n : Nat} {t : α} {votes : List (Vote α)} (hn : 0 < n) + (hfaulty : votes.countP (fun x => !x.honest) < n) + (hhonest : ∀ x ∈ votes, x.honest = true → x.answer = none ∨ x.answer = some t) + (h : n ≤ votes.countP (fun x => x.honest && x.answer == some t)) : + agree n (votes.map (·.answer)) = some t := by + have hsome : (agree n (votes.map (·.answer))).isSome := by + refine agreeFrom_isSome (v := t) _ [] (fun _ => by simpa using hn) ?_ + rw [List.count_nil, Nat.zero_add, List.count_eq_countP, List.countP_map] + have := List.countP_mono_left (l := votes) (p := fun x => x.honest && x.answer == some t) + (q := (· == some t) ∘ (·.answer)) fun x _ hx => by simp_all + simp; omega + obtain ⟨v, hv⟩ := Option.isSome_iff_exists.mp hsome + rw [hv, agree_honest hfaulty hhonest hv] + +theorem count_add_le {v w : α} (hne : v ≠ w) (l : List (Option α)) : + l.count (some v) + l.count (some w) ≤ l.length := by + induction l with + | nil => simp + | cons x xs ih => + simp only [List.count_cons, List.length_cons] + by_cases h1 : x = some v <;> by_cases h2 : x = some w <;> simp_all <;> omega + +/-- With `2n > m`, two answers cannot both gather `n` votes. -/ +theorem agree_unique {n : Nat} {v w : α} {votes : List (Option α)} + (hmajority : votes.length < 2 * n) + (hv : n ≤ votes.count (some v)) (hw : n ≤ votes.count (some w)) : v = w := by + refine Classical.byContradiction fun hne => ?_ + have := count_add_le hne votes + omega + +end Agree + +/-! ## The block a tag resolves to -/ + +/-- `reached`: the `n`-th highest of the blocks the providers report. -/ +def reached (n : Nat) (heights : List Nat) : Option Nat := + (heights.mergeSort fun a b => decide (b ≤ a))[n - 1]? + +theorem sorted_nth (l : List Nat) (hp : l.Pairwise fun a b => b ≤ a) (i h : Nat) + (hi : l[i]? = some h) : + i + 1 ≤ l.countP (fun x => decide (h ≤ x)) ∧ l.countP (fun x => decide (h < x)) ≤ i := by + induction l generalizing i with + | nil => simp at hi + | cons x xs ih => + have ⟨hx, hxs⟩ := List.pairwise_cons.mp hp + cases i with + | zero => + simp at hi; subst hi + refine ⟨by simp, ?_⟩ + have : xs.countP (fun y => decide (x < y)) = 0 := by + rw [List.countP_eq_zero]; intro y hy; have := hx y hy; simp; omega + simp [this] + | succ k => + have hk : xs[k]? = some h := by simpa using hi + have ⟨h1, h2⟩ := ih hxs k hk + have hle : h ≤ x := hx h (List.mem_of_getElem? hk) + simp only [List.countP_cons] + refine ⟨by simp [hle]; omega, ?_⟩ + split <;> omega + +/-- `n` providers have reached the block, and fewer than `n` a higher one. -/ +theorem reached_spec {n h : Nat} {heights : List Nat} (hn : 0 < n) + (hr : reached n heights = some h) : + n ≤ heights.countP (fun x => decide (h ≤ x)) ∧ heights.countP (fun x => decide (h < x)) < n := by + have hsorted := List.pairwise_mergeSort (le := fun a b : Nat => decide (b ≤ a)) + (fun a b c hab hbc => by simp_all; omega) (fun a b => by simp; omega) heights + have hperm := List.mergeSort_perm heights fun a b => decide (b ≤ a) + have ⟨h1, h2⟩ := sorted_nth _ (hsorted.imp (by simp)) (n - 1) h hr + rw [hperm.countP_eq] at h1 h2 + omega + +/-- With fewer than `n` faulty providers, an honest one has reached the block: +it exists, and no earlier than they say. -/ +theorem reached_le_honest {n h : Nat} {reports : List (Bool × Nat)} (hn : 0 < n) + (hfaulty : reports.countP (fun r => !r.1) < n) + (hr : reached n (reports.map (·.2)) = some h) : + ∃ r ∈ reports, r.1 = true ∧ h ≤ r.2 := by + refine Classical.byContradiction fun hnone => ?_ + have ⟨h1, _⟩ := reached_spec hn hr + rw [List.countP_map] at h1 + have := List.countP_mono_left (l := reports) (p := (fun x => decide (h ≤ x)) ∘ (·.2)) + (q := fun r => !r.1) fun r hr hle => by + cases hh : r.1 + · rfl + · exact absurd ⟨r, hr, hh, by simpa using hle⟩ hnone + omega + +/-- When `n` honest providers answer, the block is no lower than one of them +has reached. `reports` holds the providers that answered, so the hypothesis +allows `m - n` faulty or silent ones. -/ +theorem reached_ge_honest {n h : Nat} {reports : List (Bool × Nat)} (hn : 0 < n) + (hhonest : reports.countP (fun r => !r.1) + n ≤ reports.length) + (hr : reached n (reports.map (·.2)) = some h) : + ∃ r ∈ reports, r.1 = true ∧ r.2 ≤ h := by + refine Classical.byContradiction fun hnone => ?_ + have ⟨_, h2⟩ := reached_spec hn hr + rw [List.countP_map] at h2 + have := countP_le_add (fun r => !r.1) ((fun x => decide (h < x)) ∘ (·.2)) (fun _ => true) reports + fun r hr _ => by + cases hh : r.1 + · simp + · refine Or.inr ?_ + have : ¬ r.2 ≤ h := fun hle => hnone ⟨r, hr, hh, hle⟩ + simp; omega + simp at this + omega + +/-- The bound of `reached_ge_honest` is tight: with `m/m`, the block is no +higher than any one provider reports, so one of them holds it back as far as it +likes. -/ +theorem reached_stale {n x : Nat} {heights : List Nat} (hn : 0 < n) + (hall : heights.length = n) (hx : x ∈ heights) : + ∃ h, reached n heights = some h ∧ h ≤ x := by + have hlt : n - 1 < (heights.mergeSort fun a b => decide (b ≤ a)).length := by + rw [List.length_mergeSort]; omega + generalize hh : (heights.mergeSort fun a b => decide (b ≤ a))[n - 1] = h + have hr : reached n heights = some h := by rw [← hh]; exact List.getElem?_eq_getElem hlt + have ⟨h1, _⟩ := reached_spec hn hr + have hle := List.countP_le_length (p := fun y => decide (h ≤ y)) (l := heights) + have hall' : heights.countP (fun y => decide (h ≤ y)) = heights.length := by omega + exact ⟨h, hr, by simpa using List.countP_eq_length.mp hall' x hx⟩ + +end DstackFormal.Kms.RpcQuorum diff --git a/formal/README.md b/formal/README.md index 9e439b0c2..3493be3c3 100644 --- a/formal/README.md +++ b/formal/README.md @@ -15,6 +15,7 @@ cd formal && lake build | `Kms.KeyDerivation` | `kms/src/crypto.rs`, key derivations in `main_service.rs` | HKDF inputs of distinct derivations never coincide; signed preimages are prefix-free | | `Kms.RaTlsEncoding` | `ra-tls/src/api_v1.rs` | length-prefixed encodings are injective; derivation info and claims never collide | | `Kms.KeyRelease` | `ensure_key_release_allowed`, `get_app_key`, `sign_cert`, handover | a released key implies every attestation, authorization, epoch and platform check passed; the self-authorization cache is per operation | +| `Kms.RpcQuorum` | `kms/auth-eth/index.ts: quorumTransport` (`agree`, `reached`) | with fewer than n faulty providers, an agreed answer is the honest one and n honest votes suffice; with 2n > m the answer is unique; a tag resolves to a block no higher than an honest provider has reached, and no lower when n honest providers answer; with m/m one provider can hold it back arbitrarily | | `Gateway.Import` | `kv/import.rs` (#1604) | accepted instances are injective on IP and WireGuard key, carry no gateway key, are order-independent, and partition the input; nodes agree once their own keys have replicated; key squatting: counterexample without proof of possession, key binding stable with it (#1615, modeled abstractly) | | `Gateway.IpAlloc` | `alloc_ip`, `valid_ip`, `release_ip` (#1605), `forget_instance`, reload, rebuild | allocation returns a free valid IP, none iff exhausted; a live instance's IP is never reissued, even when shared during a conflict loser's grace period; equal KV contents give equal accepted sets under `PoolsClear` (an assumption; #1606 only warns) | | `Gateway.CertLock` | `kv/mod.rs: try_acquire_lock`, `release_lock`, `lease_still_held` (#1599–#1601) | single-node ownership under any clock and force releases; single-node exclusion; cross-node, a release or lease-guarded commit never overrides a successor's lease (successor clock within the drift bound); limitations: replication gap, skew beyond the drift bound, cross-node force release | diff --git a/os/common/rootfs/dstack-prepare.sh b/os/common/rootfs/dstack-prepare.sh index b88cab4a2..133931bc4 100755 --- a/os/common/rootfs/dstack-prepare.sh +++ b/os/common/rootfs/dstack-prepare.sh @@ -357,11 +357,13 @@ if ((${#init_scripts[@]} > 5)); then fi if ((${#init_scripts[@]} > 0)); then dstack-util notify-host -e "boot.progress" -d "init-script" || true + trap '[ $? = 0 ] || dstack-util notify-host -e "boot.error" -d "init script [$i] failed" || true' EXIT for i in "${!init_scripts[@]}"; do log "Running init script [$i]" # shellcheck disable=SC1090 source <(printf '%s' "${init_scripts[$i]}" | base64 -d) done + trap - EXIT fi RUNNER=$(jq -r '.runner' app-compose.json)