Repository navigation
Conversation
6b401ec to
750b02d
Compare
kvinwang
left a comment
There was a problem hiding this comment.
Reviewed 750b02d (a rebase of 6b401ec; the patch is unchanged).
I deployed the contracts of this PR on a local anvil and ran auth-eth against them, once without APP_AUTH_URL and once with it pointing at a stub delegate that always answers authorized: true:
| Request | APP_AUTH_URL unset |
APP_AUTH_URL set |
|---|---|---|
OS image removed with removeOsImageHashAtEpochs |
OS image is not allowed |
authorized |
| OS image never added | OS image is not allowed |
authorized |
teeVariant outside setAllowedTeeVariants (SNP, GCP-TDX) |
TEE variant not allowed |
authorized |
Inline:
- The delegated path skips the OS image allowlist and the TEE variant policy. This one is blocking.
- A delegate failure is a 200 denial on
/authorizeAppbut a 503 onGET /app/:appId, and the KMS reads no root field from a denial. - Cleanups in the new code:
getAuthorizationRootsduplicatesgetRootEpoch, the delegate response is validated by hand twice next to zod, an unreachable branch, a response cap that bounds nothing, and an incomplete query/fragment check. - Two tests that cannot fail on the behavior they name.
- Docs the new mode makes wrong, and the
ETH_BLOCK_TAG=latestadvice.
Outside the diff: the example KMS deployment does not pass APP_AUTH_URL through. compose-dev.yaml and deploy-to-vmm.sh wire ETH_BLOCK_TAG, ETH_CHAIN_ID and ETH_FINALITY_CONFIRMATIONS, but not this one, so APP_AUTH_URL set in .env is dropped silently and auth-eth starts on the chain path, denying every non-DstackApp app with App not registered. Adding - APP_AUTH_URL=${APP_AUTH_URL} to the auth-api environment, and APP_AUTH_URL=${APP_AUTH_URL:-}, subvar APP_AUTH_URL and a commented .env line to deploy-to-vmm.sh would do. An empty value keeps the chain path.
Nit on callDelegate: the catch drops err, so a redirect (redirect: 'error'), a TLS failure and a refused connection all log as unavailable, and an invalid JSON or invalid shape answer is denied with no log line at all.
| if (!roots.registered) { | ||
| return { status: 200, body: appDenial(roots, 'Root epoch not registered') }; | ||
| } | ||
| if (request.requestedRootEpoch !== undefined && request.requestedRootEpoch > roots.currentRootEpoch) { |
There was a problem hiding this comment.
DstackKms._checkAppDeployment runs four checks before the app policy: registeredApps, allowedOsImagesAtEpoch(selectedRootEpoch, osImageHash), isContract and TeeVariantPolicy.admits. The first and the third are about the app identity, so leaving them to the delegate is the point of this mode. The OS image allowlist and the TEE variant policy are set by the DstackKms owner, and this path applies neither (table in the review summary).
Nothing else checks them. The KMS's verify_os_image_hash only checks that the measurement matches the reported hash, and the delegate gets neither the pinned block nor the selected root epoch, so it cannot do the check itself. With APP_AUTH_URL set, a revoked OS image or a disallowed platform gets app keys, which contradicts "KMS policy stays on chain".
This comes from copying _checkAppRequest into TypeScript: three of its checks were copied and two were missed. A public view on DstackKms running the KMS-owned part of _checkAppRequest (everything except registeredApps and isContract) would keep one copy of that logic, and auth-eth would call it once at the pinned block, replacing the three checks above. Without a contract change, reading allowedOsImagesAtEpoch and allowAnyTeeVariant / allowedTeeVariants at the pinned block works too, but keeps the logic in two places.
| 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) }; |
There was a problem hiding this comment.
The PR description says this is a 200 "so the KMS receives the result instead of treating a non-2xx as a transport failure". The KMS does not use that result: authorized_epoch in main_service.rs bails on !result.authorized before it reads current_root(), so the chain root fields of a denial are never read.
Both forms fail closed. The 200 makes a delegate outage look like a policy decision (the KMS logs Authorization denied: app authorization delegate unavailable), and alerting on auth-eth 5xx misses it. GET /app/:appId returns 503 for the same failure. Returning 503 here too would be consistent, and appDenial would then only serve the chain-side denials.
|
|
||
| // 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<AuthorizationRoots> { |
There was a problem hiding this comment.
This repeats getRootEpoch (rootEpochCount, then currentRootEpoch), and the rootEpoch(n) read is the one getRootCaPubkey makes. Building on getRootEpoch(blockNumber) plus one rootEpoch(count - 1) read keeps a single copy of the empty-registry handling.
The four reads after resolveBlock are sequential, but gatewayAppId / rootEpochCount do not depend on each other, nor do currentRootEpoch / rootEpoch(count - 1). Two Promise.all make it two round trips.
| return { authorized: false, rejectionReason, currentAppEpoch: 0, ...rootFields(roots) }; | ||
| } | ||
|
|
||
| function parseDelegatedAuthorization(body: string): { |
There was a problem hiding this comment.
The file already validates with zod. A schema replaces the hand-written checks here and in GET /app/:appId:
const AppEpochSchema = z.number().int().min(0).max(0xffffffff);
const DelegatedAuthorizationSchema = z.object({
authorized: z.boolean(),
rejectionReason: z.string(),
currentAppEpoch: AppEpochSchema,
});isAppEpoch and the 'invalid-json' | 'invalid-shape' union go away with it.
| if (request.requestedRootEpoch !== undefined && request.requestedRootEpoch > roots.currentRootEpoch) { | ||
| return { status: 200, body: appDenial(roots, 'Requested root epoch is not active') }; | ||
| } | ||
| if (!appAuthBase) { |
There was a problem hiding this comment.
delegatedAppAuthorization is only called when appAuthBase is set, so this branch cannot run. The try / catch around getAuthorizationRoots above also repeats the route's own; moving the delegated branch inside the route's try would let it share that catch.
| if (url.username !== '' || url.password !== '') { | ||
| throw new Error('APP_AUTH_URL must not include credentials'); | ||
| } | ||
| if (url.search !== '' || url.hash !== '') { |
There was a problem hiding this comment.
url.search and url.hash are '' for a bare ? or #, but toString() keeps the delimiter:
new URL('http://127.0.0.1:9/delegate?') -> search: '', href: 'http://127.0.0.1:9/delegate?'
Such a value starts, and /authorizeApp then lands in the query. With #, the path after it is dropped, so GET /app/:appId asks the delegate the same thing for every app. The README says the server refuses to start on these. Building the base from url.origin + url.pathname, or rejecting a raw ? / #, covers both.
| 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. |
There was a problem hiding this comment.
JSON.stringify(JSON.parse(rawBody)) === rawBody for this fixture, so the test still passes if the route forwards JSON.stringify(await c.req.json()): a parse and re-stringify keeps the unknown field and the key order, contrary to the comment. One space in the fixture ('{ ') makes that mutation fail.
|
|
||
| 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'], |
There was a problem hiding this comment.
The stub throws TimeoutError whatever signal it gets, and DelegateCall does not record signal, so removing signal: AbortSignal.timeout(APP_AUTH_TIMEOUT_MS) keeps this test green. The oversized case below only reaches the content-length precheck; it should follow whatever happens to the cap. Recording signal in the stub and asserting it would cover the timeout.
| 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 |
There was a problem hiding this comment.
With APP_AUTH_URL set, the key-release app epoch is the delegate's currentAppEpoch (epochs.app.unwrap_or(response.current_app_epoch) in the KMS), not a value read at the policy block, so "Key release still reads the policy block" holds only for the chain path.
The simple backend's "operators must preserve its monotonicity" also needs a counterpart for the delegate. auth-eth only range-checks its epoch, and a delegate that goes back an epoch (a restore, a bug) makes env public-key lookups and default boots use a retired epoch's keys.
Two places outside the diff that this mode makes wrong:
dstack/kms/auth-eth/README.md:199-200:/authorizeApp"always drop[s]keyProviderInfo". The delegated path forwards the raw body,keyProviderInfoincluded, to an external URL.dstack/kms/README.md:340-343: "The Ethereum backends call the matchingDstackKmsmethod ... the app method applies registered app policy".
| `/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 |
There was a problem hiding this comment.
This gives no reason specific to the delegated mode. The delegated app path reads no per-app chain state, so latest gains it nothing, while what stays on chain (/authorizeKms, the root epochs and, with the fix above, the OS image and TEE variant checks) takes on the reorg exposure described in "reorgs and the block tag". Unless there is a reason I am missing, I would drop this paragraph.
… on chain APP_AUTH_URL forwards POST /authorizeApp and GET /app/:appId to an external app-authorization service. The request body is forwarded unchanged, including fields this server does not interpret. Root epoch fields and gatewayAppId are overwritten from DstackKms at the request's pinned block. A future root epoch, a missing root registry, a KMS operation, or a delegate failure is a denial that still carries the chain root fields. /authorizeKms, GET /, and /sevSnpTcbRequirements stay on chain. Legacy /bootAuth/app stays on chain because only pre-0.6.4 KMS builds call it and its response has no root-epoch fields to reconcile. Signed-off-by: Leechael Yim <yanleech@gmail.com>
750b02d to
6f64c65
Compare
Summary
KMS policy can stay on
DstackKmswhile app authorization is decided by another service. SetAPP_AUTH_URLto an absolute http(s) URL. Leave it unset and nothing changes.POST /authorizeAppandGET /app/:appIdare forwarded to${APP_AUTH_URL}at the same path./authorizeAppbody is forwarded byte for byte. Fields this server does not interpret, includinglaunchTicketHashand a future top-leveluserConfigHash, are not rewritten or dropped.authorized,rejectionReason, andcurrentAppEpoch. This server overwritesgatewayAppIdand the current and latest root epoch fields with values read fromDstackKmsat the request's pinned block, the same blockGET /uses.requestedRootEpochnewer than the current root epoch is denied without calling the delegate. So is an app request while no root epoch is registered, and a KMS operation posted to/authorizeApp. Those denials use the contract's existing reasons and still return the chain root fields.authorized: falsewith the chain root fields. The delegate body is not copied intorejectionReason. HTTP 200 is used so the KMS receives the result instead of treating a non-2xx as a transport failure. If the chain itself cannot be read, the route returns 503 and does not call the delegate.POST /authorizeKms,GET /, andGET /sevSnpTcbRequirementsstay on chain.ETH_BLOCK_TAGstill defaults tofinalized. Deployments of this mode that accept reorg risk should setlatestexplicitly.Why
/bootAuth/appis not delegatedOnly KMS builds before 0.6.4 call
POST /bootAuth/appin production. Its response is{isAllowed, reason, gatewayAppId}and has no root-epoch fields to reconcile with a delegate. Leaving it on chain keeps the historical contract of that route. A delegated deployment must be used with a KMS that calls/authorizeApp. An older KMS pointed atAPP_AUTH_URLwould still have its app boots judged byDstackKms.Test plan
bun run checkindstack/kms/auth-eth(oxlint + vitest, 80 tests)APP_AUTH_URLunset keeps the chain path, including when the env is set after process start/authorizeAppbody is byte-equal, including unprefixedlaunchTicketHashanduserConfigHashgatewayAppIdare overwritten from the pinned chain block, including a delegate denialrequestedRootEpochnewer than current is denied with no delegate call/authorizeKms,/bootAuth/app, and/sevSnpTcbRequirementsstay on chain whenAPP_AUTH_URLis setGET /app/:appIdis forwarded; a delegate failure does not invent epoch 0