diff --git a/docs/app-key-epochs.md b/docs/app-key-epochs.md index 454d4c107..e07c198d0 100644 --- a/docs/app-key-epochs.md +++ b/docs/app-key-epochs.md @@ -38,10 +38,12 @@ without this capability remain at zero; failures of an advertised getter propaga The Ethereum auth backends query the policy through the KMS contract. The simple backend reads `apps[appId].currentAppEpoch` (default zero); operators must preserve its monotonicity. Public encryption-key lookup uses `GET /app/:appId` to read this -value. auth-eth reads it at the `latest` block, so a new app gets its key at -once and an advanced epoch never hands out the retired key; key release -still reads the policy block, so an environment sealed to a just-advanced epoch -boots only once the advance reaches that block. Legacy boot authorization and +value. With `APP_AUTH_URL` unset, auth-eth reads it at the `latest` block, so a +new app gets its key at once and an advanced epoch never hands out the retired +key. When `APP_AUTH_URL` is set, that service answers `GET /app/:appId` and owns +the epoch's freshness. Key release still reads the policy block, so an +environment sealed to a just-advanced epoch boots only once the advance reaches +that block. Legacy boot authorization and legacy environment public-key issuance are rejected once the app epoch is nonzero, preventing old clients from silently continuing with epoch-zero keys. diff --git a/docs/deployment.md b/docs/deployment.md index 7953e34e6..06872f0c6 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -199,6 +199,10 @@ previous epoch. `ETH_FINALITY_CONFIRMATIONS=N` hides reorgs shallower than N blocks but delays every policy change, emergency revocations included, by N blocks. See [reorgs and the block tag](../dstack/kms/auth-eth/README.md#reorgs-and-the-block-tag). +Optional `APP_AUTH_URL` leaves KMS policy on `DstackKms` and forwards +`/authorizeApp` and `GET /app/:appId` to another service. The default, leaving +it unset, is unchanged. See [delegated app authorization](../dstack/kms/auth-eth/README.md#delegated-app-authorization). + #### Getting OS Image Hash The OS image hash is in the `digest.txt` file inside the guest image tarball: diff --git a/dstack/kms/README.md b/dstack/kms/README.md index 3f2363a1e..07449bdb6 100644 --- a/dstack/kms/README.md +++ b/dstack/kms/README.md @@ -174,7 +174,7 @@ client can choose the `remote` that the logs and the key release audit record. - Chain interface for permission checks - Two-step validation: 1. KMS control contract check - 2. App control contract check + 2. App control contract check, or an external app-authorization service when `APP_AUTH_URL` is set ([delegated app authorization](auth-eth/README.md#delegated-app-authorization)) 3. **Authorization Contracts** ([`auth-eth`](auth-eth/)) - `DstackKms.sol` diff --git a/dstack/kms/auth-eth/README.md b/dstack/kms/auth-eth/README.md index cb39d90c3..a571cc78c 100644 --- a/dstack/kms/auth-eth/README.md +++ b/dstack/kms/auth-eth/README.md @@ -53,8 +53,9 @@ The Bun server sets `idleTimeout` to 255s (Bun's maximum). Bun's default of 10s - `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` when `APP_AUTH_URL` is unset, 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_FINALITY_CONFIRMATIONS` - read this many blocks further behind the block `ETH_BLOCK_TAG` resolves to (default: 0) +- `APP_AUTH_URL` - optional absolute http(s) URL of an app-authorization service (default: unset). when unset, `/authorizeApp` and `GET /app/:appId` are read from `DstackKms`. when set, those two routes are forwarded to this URL at the same path. the server refuses to start if the value is not an absolute http(s) URL without credentials, a query, or a fragment. a blank value is unset. see [delegated app authorization](#delegated-app-authorization) ### Reorgs and the block tag @@ -240,6 +241,50 @@ remain available. and subject semantics. Bootstrap alone may authorize before root registration; unknown operations are rejected. Legacy `/bootAuth/*` routes are unchanged. +#### Delegated app authorization + +Set `APP_AUTH_URL` to keep KMS policy on `DstackKms` and let another service +decide app policy. This is for app identities that are not `DstackApp` +contracts. Leave it unset to keep the chain path; the default is unchanged. + +When it is set: + +- `POST /authorizeApp` forwards the request body byte for byte, including + fields this server does not interpret. `launchTicketHash` passes through, and + so does a future top-level `userConfigHash` (lowercase hex, no `0x` prefix, + app operations only). The delegate returns `authorized`, `rejectionReason`, + and `currentAppEpoch`. This server overwrites `gatewayAppId`, + `currentRootEpoch`, `currentRootEpochHash`, `latestRootEpoch`, and + `latestRootEpochHash` with values read from `DstackKms` at the request's + pinned block, the same block `GET /` uses. +- A `requestedRootEpoch` newer than the current root epoch is denied without + calling the delegate (`Requested root epoch is not active`). So is an app + request while no root epoch is registered (`Root epoch not registered`), and + a KMS operation posted to `/authorizeApp` (`Invalid authorization operation`). +- A delegate error, timeout (20s, under the KMS webhook timeout of 60s), + non-2xx response, or invalid JSON is a denial (`authorized: false`) that + still carries the chain root fields. The delegate's body is not copied into + `rejectionReason`. If the chain itself cannot be read, the route returns 503 + and does not call the delegate. +- `GET /app/:appId` is forwarded to the same path. The app id is checked before + it is placed in the URL. A delegate failure is 503; this server does not + invent epoch 0. The chain's `latest` read for this route applies only when + `APP_AUTH_URL` is unset. +- `POST /authorizeKms`, `GET /`, and `GET /sevSnpTcbRequirements` stay on chain. + +`POST /bootAuth/app` also stays on chain. Only KMS builds before 0.6.4 call it +in production, and its response has no root-epoch fields to reconcile with a +delegate. A delegated deployment must be used with a KMS that calls +`/authorizeApp`. Do not point an older KMS at `APP_AUTH_URL`: its app boots +would still be judged by `DstackKms`. + +Deployments of this mode that accept reorg risk should set +`ETH_BLOCK_TAG=latest`. The default remains `finalized`. See +[reorgs and the block tag](#reorgs-and-the-block-tag). + +The delegate is not followed across redirects, and its responses are not +cached. + ## Contracts ### Prerequisites diff --git a/dstack/kms/auth-eth/index.test.ts b/dstack/kms/auth-eth/index.test.ts index 49d47c52f..f39604df4 100644 --- a/dstack/kms/auth-eth/index.test.ts +++ b/dstack/kms/auth-eth/index.test.ts @@ -1050,3 +1050,380 @@ describe('POST /authorizeApp', () => { expect(mockReadContract).toHaveBeenCalledTimes(1); }); }); + +describe('delegated app authorization', () => { + const CURRENT_HASH = '0x' + 'aa'.repeat(32); + const LATEST_HASH = '0x' + 'bb'.repeat(32); + const GATEWAY = 'chain-gateway'; + const ZERO_HASH = '0x' + '00'.repeat(32); + const launchTicketHash = 'ab'.repeat(32); + const userConfigHash = 'cd'.repeat(32); + const appId = '0x' + '11'.repeat(20); + // Key order and the uninterpreted userConfigHash must survive the forward. + // A re-serialized body would drop the unknown field and reorder the rest. + const rawBody = [ + '{', + `"userConfigHash":"${userConfigHash}",`, + `"launchTicketHash":"${launchTicketHash}",`, + '"operation":"app_get_key",', + '"teeVariant":"dstack-tdx",', + `"requestedRootEpoch":1,`, + `"appId":"${appId}",`, + `"composeHash":"${'22'.repeat(32)}",`, + '"instanceId":"",', + `"deviceId":"${'33'.repeat(32)}",`, + `"mrAggregated":"${'44'.repeat(32)}",`, + `"osImageHash":"${'66'.repeat(32)}"`, + '}', + ].join(''); + + type DelegateCall = { + url: string; + method: string; + body?: string; + redirect?: RequestRedirect; + cache?: RequestCache; + }; + let calls: DelegateCall[]; + + const chainRoots = { + gatewayAppId: GATEWAY, + currentRootEpoch: 2, + currentRootEpochHash: CURRENT_HASH, + latestRootEpoch: 3, + latestRootEpochHash: LATEST_HASH, + }; + + function mockChain({ count = 4n, fail = false }: { count?: bigint; fail?: boolean } = {}) { + mockReadContract.mockImplementation((params) => { + if (fail) return Promise.reject(new Error('rpc down')); + switch (params.functionName) { + case 'gatewayAppId': return GATEWAY; + case 'rootEpochCount': return count; + case 'currentRootEpoch': return [2n, CURRENT_HASH]; + case 'rootEpoch': return ['0x' + '11'.repeat(32), '0x' + '22'.repeat(32), 'evidence', LATEST_HASH]; + case 'appImplementation': return '0x' + '99'.repeat(20); + case 'sevSnpTcbRequirements': return '[]'; + case 'authorizeKms': return { + authorized: true, rejectionReason: '', gatewayAppId: GATEWAY, + currentAppEpoch: 0n, currentRootEpoch: 2n, currentRootEpochHash: CURRENT_HASH, + latestRootEpoch: 3n, latestRootEpochHash: LATEST_HASH, + }; + case 'isAppAllowed': return [true, 'on-chain']; + default: return Promise.reject(new Error(`unexpected contract call ${params.functionName}`)); + } + }); + } + + function stubDelegate(handler: (call: DelegateCall) => Response | Promise) { + calls = []; + vi.stubGlobal('fetch', async (url: string, init: RequestInit = {}) => { + const body = typeof init.body === 'string' || init.body == null + ? init.body ?? undefined + : await new Response(init.body).text(); + const call: DelegateCall = { + url: String(url), + method: init.method ?? 'GET', + body, + redirect: init.redirect, + cache: init.cache, + }; + calls.push(call); + return handler(call); + }); + } + + function delegateOk(extra: Record = {}) { + return new Response(JSON.stringify({ + authorized: true, + rejectionReason: '', + gatewayAppId: 'delegate-gateway', + currentRootEpoch: 9, + currentRootEpochHash: '0x' + 'ff'.repeat(32), + currentAppEpoch: 7, + latestRootEpoch: 9, + latestRootEpochHash: '0x' + 'ee'.repeat(32), + note: 'not-part-of-the-result', + ...extra, + }), { status: 200, headers: { 'content-type': 'application/json' } }); + } + + async function load(url?: string) { + if (url === undefined) delete process.env.APP_AUTH_URL; + else process.env.APP_AUTH_URL = url; + vi.resetModules(); + const mod = await import('./index.ts'); + return mod.default.fetch as (request: Request) => Promise; + } + + const postApp = (fetchApp: (request: Request) => Promise, body = rawBody) => fetchApp(new Request('http://localhost/authorizeApp', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, body, + })); + + beforeEach(() => { + calls = []; + vi.unstubAllGlobals(); + }); + + afterEach(() => { + delete process.env.APP_AUTH_URL; + vi.unstubAllGlobals(); + vi.resetModules(); + }); + + it('keeps the chain path when APP_AUTH_URL is unset, even if the env appears later', async () => { + const fetchSpy = vi.fn(); + vi.stubGlobal('fetch', fetchSpy); + process.env.APP_AUTH_URL = 'http://127.0.0.1:9'; + mockReadContract.mockResolvedValueOnce({ + authorized: false, rejectionReason: 'App not registered', gatewayAppId: 'gateway', + currentAppEpoch: 0n, currentRootEpoch: 2n, currentRootEpochHash: CURRENT_HASH, + latestRootEpoch: 2n, latestRootEpochHash: CURRENT_HASH, + }); + const response = await appFetch(new Request('http://localhost/authorizeApp', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + teeVariant: 'dstack-tdx', operation: 'app_get_key', appId, + composeHash: '0x' + '22'.repeat(32), instanceId: '', deviceId: '0x' + '33'.repeat(32), + mrAggregated: '0x' + '44'.repeat(32), osImageHash: '0x' + '66'.repeat(32), + }), + })); + expect(response.status).toBe(200); + expect((await response.json()).rejectionReason).toBe('App not registered'); + expect(fetchSpy).not.toHaveBeenCalled(); + expect(mockReadContract).toHaveBeenCalledWith(expect.objectContaining({ functionName: 'authorizeApp' })); + }); + + it('forwards the authorizeApp body byte for byte and overwrites root fields from the pinned chain block', async () => { + mockChain(); + stubDelegate(() => delegateOk()); + const fetchApp = await load('http://127.0.0.1:9/delegate/'); + const response = await postApp(fetchApp); + expect(response.status).toBe(200); + expect(calls).toEqual([{ + url: 'http://127.0.0.1:9/delegate/authorizeApp', + method: 'POST', + body: rawBody, + redirect: 'error', + cache: 'no-store', + }]); + expect(await response.json()).toEqual({ + authorized: true, + rejectionReason: '', + currentAppEpoch: 7, + ...chainRoots, + }); + expect(mockReadContract).not.toHaveBeenCalledWith(expect.objectContaining({ + functionName: 'authorizeApp', + })); + expect(mockReadContract).not.toHaveBeenCalledWith(expect.objectContaining({ + functionName: 'currentAppEpoch', + })); + for (const params of mockReadContract.mock.calls.map((call) => call[0])) { + expect(params.blockNumber).toBe(98n); + } + expect(mockReadContract).toHaveBeenCalledWith(expect.objectContaining({ + functionName: 'rootEpoch', args: [3n], blockNumber: 98n, + })); + + const info = await (await fetchApp(new Request('http://localhost/'))).json(); + expect(info.gatewayAppId).toBe(GATEWAY); + expect(info.rootEpoch).toBe(2); + expect(info.rootEpochHash).toBe(CURRENT_HASH); + expect(calls).toHaveLength(1); + }); + + it('keeps a delegate denial, including its app epoch, and still overwrites root fields', async () => { + mockChain(); + stubDelegate(() => delegateOk({ + authorized: false, rejectionReason: 'compose hash is not allowed', currentAppEpoch: 4, + })); + const fetchApp = await load('http://127.0.0.1:9'); + const response = await postApp(fetchApp); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ + authorized: false, + rejectionReason: 'compose hash is not allowed', + currentAppEpoch: 4, + ...chainRoots, + }); + }); + + it('denies a requested root epoch newer than the current one without calling the delegate', async () => { + mockChain(); + stubDelegate(() => delegateOk()); + const fetchApp = await load('http://127.0.0.1:9'); + const newer = rawBody.replace('"requestedRootEpoch":1', '"requestedRootEpoch":3'); + const denied = await postApp(fetchApp, newer); + expect(denied.status).toBe(200); + expect(await denied.json()).toEqual({ + authorized: false, + rejectionReason: 'Requested root epoch is not active', + currentAppEpoch: 0, + ...chainRoots, + }); + expect(calls).toEqual([]); + + const current = rawBody.replace('"requestedRootEpoch":1', '"requestedRootEpoch":2'); + expect((await postApp(fetchApp, current)).status).toBe(200); + expect(calls).toHaveLength(1); + expect(calls[0].body).toBe(current); + }); + + it('denies app authorization when no root epoch is registered, without calling the delegate', async () => { + mockChain({ count: 0n }); + stubDelegate(() => delegateOk()); + const fetchApp = await load('http://127.0.0.1:9'); + const response = await postApp(fetchApp); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ + authorized: false, + rejectionReason: 'Root epoch not registered', + gatewayAppId: GATEWAY, + currentRootEpoch: 0, + currentRootEpochHash: ZERO_HASH, + currentAppEpoch: 0, + latestRootEpoch: 0, + latestRootEpochHash: ZERO_HASH, + }); + expect(calls).toEqual([]); + expect(mockReadContract).not.toHaveBeenCalledWith(expect.objectContaining({ functionName: 'currentRootEpoch' })); + expect(mockReadContract).not.toHaveBeenCalledWith(expect.objectContaining({ functionName: 'rootEpoch' })); + }); + + it('denies a KMS operation on /authorizeApp without calling the delegate', async () => { + mockChain(); + stubDelegate(() => delegateOk()); + const fetchApp = await load('http://127.0.0.1:9'); + const response = await postApp(fetchApp, rawBody.replace('app_get_key', 'kms_serve')); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ + authorized: false, + rejectionReason: 'Invalid authorization operation', + currentAppEpoch: 0, + ...chainRoots, + }); + expect(calls).toEqual([]); + }); + + it.each([ + ['network', () => { throw new TypeError('connect ECONNREFUSED'); }, 'app authorization delegate unavailable'], + ['timeout', () => { throw new DOMException('The operation was timed out', 'TimeoutError'); }, 'app authorization delegate timed out'], + ['HTTP error', () => new Response('super-secret-policy', { status: 502 }), 'app authorization delegate returned HTTP 502'], + ['invalid JSON', () => new Response('not-json', { status: 200 }), 'app authorization delegate returned invalid JSON'], + ['invalid shape', () => new Response('{"authorized":true}', { status: 200 }), 'app authorization delegate returned an invalid response'], + ['oversized', () => new Response('{}', { status: 200, headers: { 'content-length': String(128 * 1024) } }), 'app authorization delegate response is too large'], + ])('fails closed when the delegate returns %s', async (_label, respond, reason) => { + mockChain(); + stubDelegate(respond); + const fetchApp = await load('http://127.0.0.1:9'); + const response = await postApp(fetchApp); + expect(response.status).toBe(200); + const data = await response.json(); + expect(data).toEqual({ + authorized: false, + rejectionReason: reason, + currentAppEpoch: 0, + ...chainRoots, + }); + expect(JSON.stringify(data)).not.toContain('super-secret-policy'); + }); + + it('does not call the delegate when the chain cannot supply root fields', async () => { + mockChain({ fail: true }); + stubDelegate(() => delegateOk()); + const fetchApp = await load('http://127.0.0.1:9'); + const response = await postApp(fetchApp); + expect(response.status).toBe(503); + expect(calls).toEqual([]); + }); + + it('rejects an invalid authorizeApp body before calling the delegate', async () => { + mockChain(); + stubDelegate(() => delegateOk()); + const fetchApp = await load('http://127.0.0.1:9'); + const response = await postApp(fetchApp, '{"operation":"app_get_key"}'); + expect(response.status).toBe(400); + expect(calls).toEqual([]); + expect(mockReadContract).not.toHaveBeenCalled(); + }); + + it('leaves KMS authorization, boot, and TCB requirements on chain', async () => { + mockChain(); + stubDelegate(() => delegateOk()); + const fetchApp = await load('http://127.0.0.1:9'); + const kms = await fetchApp(new Request('http://localhost/authorizeKms', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: rawBody.replace('app_get_key', 'kms_serve'), + })); + expect(kms.status).toBe(200); + expect(mockReadContract).toHaveBeenCalledWith(expect.objectContaining({ functionName: 'authorizeKms' })); + + mockReadContract.mockClear(); + mockChain(); + const boot = await fetchApp(new Request('http://localhost/bootAuth/app', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + appId, composeHash: '0x' + '22'.repeat(32), instanceId: '0x' + '33'.repeat(20), + deviceId: '0x' + '44'.repeat(32), mrAggregated: '0x' + '55'.repeat(32), + osImageHash: '0x' + '66'.repeat(32), + rootEpoch: 2, rootEpochHash: CURRENT_HASH, + }), + })); + expect(boot.status).toBe(200); + expect(await boot.json()).toMatchObject({ isAllowed: true, reason: 'on-chain' }); + expect(mockReadContract).toHaveBeenCalledWith(expect.objectContaining({ functionName: 'isAppAllowed' })); + + const tcb = await fetchApp(new Request('http://localhost/sevSnpTcbRequirements')); + expect(await tcb.json()).toEqual({ requirements: '[]' }); + expect(calls).toEqual([]); + }); + + it('forwards GET /app/:appId and fails closed instead of inventing an epoch', async () => { + stubDelegate((call) => { + if (call.url.endsWith('/app/' + '0xAb' + 'cd'.repeat(19))) { + return new Response(JSON.stringify({ currentAppEpoch: 5, extra: true }), { status: 200 }); + } + return new Response('nope', { status: 500 }); + }); + const fetchApp = await load('http://127.0.0.1:9/delegate'); + const appIdPath = '0xAb' + 'cd'.repeat(19); + const ok = await fetchApp(new Request(`http://localhost/app/${appIdPath}`)); + expect(ok.status).toBe(200); + expect(await ok.json()).toEqual({ currentAppEpoch: 5 }); + expect(calls[0]).toMatchObject({ url: `http://127.0.0.1:9/delegate/app/${appIdPath}`, method: 'GET' }); + expect(mockReadContract).not.toHaveBeenCalled(); + + const failed = await fetchApp(new Request(`http://localhost/app/0x${'12'.repeat(20)}`)); + expect(failed.status).toBe(503); + expect(await failed.json()).not.toHaveProperty('currentAppEpoch'); + + const invalid = await fetchApp(new Request('http://localhost/app/not-an-id')); + expect(invalid.status).toBe(400); + expect(calls).toHaveLength(2); + }); + + it('refuses to start when APP_AUTH_URL is not an absolute http(s) URL', async () => { + process.env.APP_AUTH_URL = 'file:///tmp/auth'; + vi.resetModules(); + await expect(import('./index.ts')).rejects.toThrow(/APP_AUTH_URL/); + }); + + it('treats a blank APP_AUTH_URL as unset and rejects credentials in the URL', async () => { + delete process.env.APP_AUTH_URL; + vi.resetModules(); + const { parseAppAuthUrl } = await import('./index.ts'); + expect(parseAppAuthUrl(undefined)).toBeUndefined(); + expect(parseAppAuthUrl(' ')).toBeUndefined(); + expect(parseAppAuthUrl('http://127.0.0.1:9/delegate/')).toBe('http://127.0.0.1:9/delegate'); + expect(() => parseAppAuthUrl('http://user:pass@127.0.0.1:9')).toThrow(/credentials/); + }); + + it('returns a delegate failure before the KMS webhook timeout', async () => { + delete process.env.APP_AUTH_URL; + vi.resetModules(); + const { APP_AUTH_TIMEOUT_MS } = await import('./index.ts'); + expect(APP_AUTH_TIMEOUT_MS).toBeGreaterThan(0); + expect(APP_AUTH_TIMEOUT_MS).toBeLessThan(60_000); + }); +}); diff --git a/dstack/kms/auth-eth/index.ts b/dstack/kms/auth-eth/index.ts index 3b8447db5..e1fe36086 100644 --- a/dstack/kms/auth-eth/index.ts +++ b/dstack/kms/auth-eth/index.ts @@ -57,6 +57,17 @@ const BootResponseSchema = z.object({ // keys of epochs 0..=rootEpoch; both absent when none is registered. type RootEpochInfo = { rootEpoch?: number; rootEpochHash?: Hex }; +const ZERO_ROOT_HASH = `0x${'00'.repeat(32)}` as Hex; + +type AuthorizationRoots = { + gatewayAppId: string; + currentRootEpoch: number; + currentRootEpochHash: Hex; + latestRootEpoch: number; + latestRootEpochHash: Hex; + registered: boolean; +}; + type BootInfo = z.infer; type BootResponse = z.infer; @@ -432,6 +443,56 @@ export class EthereumBackend { }); return result as string; } + + // Root fields of an AuthorizationResult, from the same pinned block GET / uses. + // Empty registry: zero epochs and hashes, and no call to currentRootEpoch, which reverts then. + async getAuthorizationRoots(): Promise { + const blockNumber = await this.resolveBlock(); + const gatewayAppId = await this.getGatewayAppId(blockNumber); + const count = await this.client.readContract({ + address: this.kmsContractAddr, + abi: DSTACK_KMS_ABI, + functionName: 'rootEpochCount', + blockNumber, + }); + if (count === 0n) { + return { + gatewayAppId, + currentRootEpoch: 0, + currentRootEpochHash: ZERO_ROOT_HASH, + latestRootEpoch: 0, + latestRootEpochHash: ZERO_ROOT_HASH, + registered: false, + }; + } + const [epoch, chainHash] = await this.client.readContract({ + address: this.kmsContractAddr, + abi: DSTACK_KMS_ABI, + functionName: 'currentRootEpoch', + blockNumber, + }); + const latest = count - 1n; + const latestRoot = await this.client.readContract({ + address: this.kmsContractAddr, + abi: DSTACK_KMS_ABI, + functionName: 'rootEpoch', + args: [latest], + blockNumber, + }); + const currentRootEpoch = Number(epoch); + const latestRootEpoch = Number(latest); + if (!Number.isSafeInteger(currentRootEpoch) || !Number.isSafeInteger(latestRootEpoch)) { + throw new Error('root epoch exceeds the supported range'); + } + return { + gatewayAppId, + currentRootEpoch, + currentRootEpochHash: chainHash, + latestRootEpoch, + latestRootEpochHash: latestRoot[3], + registered: true, + }; + } } // initialize app @@ -458,6 +519,159 @@ const ethereum = new EthereumBackend( client, kmsContractAddr, expectedChainId, parseBlockTag(process.env.ETH_BLOCK_TAG), finalityConfirmations, ); +// Stay under the KMS webhook timeout (60s) so a delegate failure still returns +// the chain root fields before the KMS gives up on the call. +export const APP_AUTH_TIMEOUT_MS = 20_000; +const MAX_DELEGATE_RESPONSE_BYTES = 64 * 1024; +const APP_OPERATIONS = new Set(['app_get_key', 'app_get_cert']); + +export function parseAppAuthUrl(value: string | undefined): string | undefined { + if (value === undefined) return undefined; + const trimmed = value.trim(); + if (trimmed === '') return undefined; + let url: URL; + try { + url = new URL(trimmed); + } catch { + throw new Error('APP_AUTH_URL must be an absolute http(s) URL'); + } + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + throw new Error('APP_AUTH_URL must be an absolute http(s) URL'); + } + if (url.username !== '' || url.password !== '') { + throw new Error('APP_AUTH_URL must not include credentials'); + } + if (url.search !== '' || url.hash !== '') { + throw new Error('APP_AUTH_URL must not include a query or fragment'); + } + return url.toString().replace(/\/$/, ''); +} + +const appAuthBase = parseAppAuthUrl(process.env.APP_AUTH_URL); +const backendUnavailable = 'authorization backend unavailable'; + +type DelegateCall = { ok: true; body: string } | { ok: false; reason: string }; + +function delegateTimedOut(err: unknown): boolean { + return err instanceof DOMException && (err.name === 'TimeoutError' || err.name === 'AbortError'); +} + +async function callDelegate(url: string, init: { method: string; body?: string }): Promise { + try { + const response = await fetch(url, { + method: init.method, + body: init.body, + headers: init.body === undefined ? undefined : { 'content-type': 'application/json' }, + redirect: 'error', + cache: 'no-store', + signal: AbortSignal.timeout(APP_AUTH_TIMEOUT_MS), + }); + const length = response.headers.get('content-length'); + if (length !== null && /^(?:0|[1-9][0-9]*)$/.test(length) && Number(length) > MAX_DELEGATE_RESPONSE_BYTES) { + await response.body?.cancel(); + return failedDelegate('app authorization delegate response is too large'); + } + const body = await response.text(); + if (body.length > MAX_DELEGATE_RESPONSE_BYTES) { + return failedDelegate('app authorization delegate response is too large'); + } + if (!response.ok) { + return failedDelegate(`app authorization delegate returned HTTP ${response.status}`); + } + return { ok: true, body }; + } catch (err) { + if (delegateTimedOut(err)) return failedDelegate('app authorization delegate timed out'); + return failedDelegate('app authorization delegate unavailable'); + } +} + +function failedDelegate(reason: string): DelegateCall { + console.error(`app authorization delegate failed: ${reason}`); + return { ok: false, reason }; +} + +function isAppEpoch(value: unknown): value is number { + return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 && value <= 0xffffffff; +} + +function rootFields(roots: AuthorizationRoots) { + return { + gatewayAppId: roots.gatewayAppId, + currentRootEpoch: roots.currentRootEpoch, + currentRootEpochHash: roots.currentRootEpochHash, + latestRootEpoch: roots.latestRootEpoch, + latestRootEpochHash: roots.latestRootEpochHash, + }; +} + +function appDenial(roots: AuthorizationRoots, rejectionReason: string) { + return { authorized: false, rejectionReason, currentAppEpoch: 0, ...rootFields(roots) }; +} + +function parseDelegatedAuthorization(body: string): { + authorized: boolean; + rejectionReason: string; + currentAppEpoch: number; +} | 'invalid-json' | 'invalid-shape' { + let parsed: unknown; + try { + parsed = JSON.parse(body); + } catch { + return 'invalid-json'; + } + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return 'invalid-shape'; + const record = parsed as Record; + if (typeof record.authorized !== 'boolean' || typeof record.rejectionReason !== 'string' || !isAppEpoch(record.currentAppEpoch)) { + return 'invalid-shape'; + } + return { + authorized: record.authorized, + rejectionReason: record.rejectionReason, + currentAppEpoch: record.currentAppEpoch, + }; +} + +async function delegatedAppAuthorization(request: AuthorizationRequest, rawBody: string): Promise<{ status: 200 | 503; body: unknown }> { + let roots: AuthorizationRoots; + try { + roots = await ethereum.getAuthorizationRoots(); + } catch { + console.error('authorization backend failed'); + return { status: 503, body: { status: 'error', message: backendUnavailable } }; + } + if (!APP_OPERATIONS.has(request.operation)) { + return { status: 200, body: appDenial(roots, 'Invalid authorization operation') }; + } + if (!roots.registered) { + return { status: 200, body: appDenial(roots, 'Root epoch not registered') }; + } + if (request.requestedRootEpoch !== undefined && request.requestedRootEpoch > roots.currentRootEpoch) { + return { status: 200, body: appDenial(roots, 'Requested root epoch is not active') }; + } + if (!appAuthBase) { + console.error('app authorization delegate is not configured'); + return { status: 503, body: { status: 'error', message: backendUnavailable } }; + } + const delegated = await callDelegate(`${appAuthBase}/authorizeApp`, { method: 'POST', body: rawBody }); + if (!delegated.ok) return { status: 200, body: appDenial(roots, delegated.reason) }; + const parsed = parseDelegatedAuthorization(delegated.body); + if (parsed === 'invalid-json') { + return { status: 200, body: appDenial(roots, 'app authorization delegate returned invalid JSON') }; + } + if (parsed === 'invalid-shape') { + return { status: 200, body: appDenial(roots, 'app authorization delegate returned an invalid response') }; + } + return { + status: 200, + body: { + authorized: parsed.authorized, + rejectionReason: parsed.rejectionReason, + currentAppEpoch: parsed.currentAppEpoch, + ...rootFields(roots), + }, + }; +} + const publicRpcEndpoint = (value: string): string => { try { const endpoint = new URL(value); @@ -467,7 +681,6 @@ const publicRpcEndpoint = (value: string): string => { } }; -const backendUnavailable = 'authorization backend unavailable'; const invalidRequest = { isAllowed: false, reason: 'invalid authorization request', gatewayAppId: '' }; const invalidAuthorization = { authorized: false, @@ -538,6 +751,21 @@ app.get('/', async (c) => { app.get('/app/:appId', async (c) => { const appId = c.req.param('appId'); if (!/^0x[0-9a-fA-F]{40}$/.test(appId)) return c.json({ error: 'invalid app ID' }, 400); + if (appAuthBase) { + const delegated = await callDelegate(`${appAuthBase}/app/${appId}`, { method: 'GET' }); + if (!delegated.ok) return c.json({ error: delegated.reason }, 503); + let parsed: unknown; + try { + parsed = JSON.parse(delegated.body); + } catch { + return c.json({ error: 'app authorization delegate returned invalid JSON' }, 503); + } + const epoch = parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) + ? (parsed as Record).currentAppEpoch + : undefined; + if (!isAppEpoch(epoch)) return c.json({ error: 'app authorization delegate returned an invalid response' }, 503); + return c.json({ currentAppEpoch: epoch }); + } try { return c.json({ currentAppEpoch: await ethereum.getAppEpoch(appId) }); } catch { @@ -575,6 +803,12 @@ for (const method of ['authorizeKms', 'authorizeApp'] as const) { if (!result.success) return c.json(invalidAuthorization, 400); }), async (c) => { + if (method === 'authorizeApp' && appAuthBase) { + // The validator already consumed the body as JSON; text() is that same + // cached string, so fields this server does not interpret are unchanged. + const result = await delegatedAppAuthorization(c.req.valid('json'), await c.req.text()); + return c.json(result.body, result.status); + } try { return c.json(await ethereum.checkAuthorization(c.req.valid('json'), method)); } catch { @@ -585,7 +819,9 @@ for (const method of ['authorizeKms', 'authorizeApp'] as const) { ); } -// app boot authentication +// Legacy app boot. Left on chain when APP_AUTH_URL is set: KMS builds since +// 0.6.4 do not call it, and the response has no root-epoch fields to reconcile +// with a delegate. Do not point a pre-0.6.4 KMS at a delegated deployment. app.post('/bootAuth/app', zValidator('json', BootInfoSchema, (result, c) => { if (!result.success) return c.json(invalidRequest, 400); diff --git a/dstack/kms/auth-eth/openapi.json b/dstack/kms/auth-eth/openapi.json index e08b773eb..cca5bb5dd 100644 --- a/dstack/kms/auth-eth/openapi.json +++ b/dstack/kms/auth-eth/openapi.json @@ -133,6 +133,7 @@ "/authorizeApp": { "post": { "summary": "Authorize a App identity and return the current root epoch", + "description": "When APP_AUTH_URL is unset, the decision is read from DstackKms. When it is set, the raw request body is forwarded to that service at the same path, including fields not in this schema. authorized, rejectionReason, and currentAppEpoch come from the delegate. gatewayAppId and the current and latest root epoch fields are overwritten from DstackKms at this request's pinned block. A requestedRootEpoch newer than the current root epoch is denied without calling the delegate. A delegate failure is HTTP 200 with authorized false and the chain root fields; it is not a 503.", "operationId": "authorizeApp", "requestBody": { "required": true, @@ -164,6 +165,7 @@ "/app/{appId}": { "get": { "summary": "Read the current application key epoch", + "description": "When APP_AUTH_URL is unset, the epoch is read from DstackKms at latest. When it is set, the request is forwarded to that service at the same path. A delegate failure is 503 and does not fall back to the chain or to epoch 0.", "parameters": [ { "name": "appId",