Skip to content

feat(kms/auth-eth): delegate app authorization while KMS policy stays on chain - #1648

Open
Leechael wants to merge 1 commit into
Dstack-TEE:nextfrom
Leechael:feat/auth-eth-app-auth-delegation
Open

Leechael wants to merge 1 commit into
Dstack-TEE:nextfrom
Leechael:feat/auth-eth-app-auth-delegation

Conversation

@Leechael

Copy link
Copy Markdown
Collaborator

Summary

KMS policy can stay on DstackKms while app authorization is decided by another service. Set APP_AUTH_URL to an absolute http(s) URL. Leave it unset and nothing changes.

  • POST /authorizeApp and GET /app/:appId are forwarded to ${APP_AUTH_URL} at the same path.
  • The /authorizeApp body is forwarded byte for byte. Fields this server does not interpret, including launchTicketHash and a future top-level userConfigHash, are not rewritten or dropped.
  • The delegate supplies authorized, rejectionReason, and currentAppEpoch. This server overwrites gatewayAppId and the current and latest root epoch fields 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. 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.
  • A delegate error, timeout (20s), non-2xx response, or invalid JSON is authorized: false with the chain root fields. The delegate body is not copied into rejectionReason. 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 /, and GET /sevSnpTcbRequirements stay on chain.
  • ETH_BLOCK_TAG still defaults to finalized. Deployments of this mode that accept reorg risk should set latest explicitly.

Why /bootAuth/app is not delegated

Only KMS builds before 0.6.4 call POST /bootAuth/app in 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 at APP_AUTH_URL would still have its app boots judged by DstackKms.

Test plan

  • bun run check in dstack/kms/auth-eth (oxlint + vitest, 80 tests)
  • APP_AUTH_URL unset keeps the chain path, including when the env is set after process start
  • forwarded /authorizeApp body is byte-equal, including unprefixed launchTicketHash and userConfigHash
  • root fields and gatewayAppId are overwritten from the pinned chain block, including a delegate denial
  • requestedRootEpoch newer than current is denied with no delegate call
  • delegate network error, timeout, HTTP error, invalid JSON, invalid shape, and oversized body fail closed with chain root fields and without echoing the delegate body
  • /authorizeKms, /bootAuth/app, and /sevSnpTcbRequirements stay on chain when APP_AUTH_URL is set
  • GET /app/:appId is forwarded; a delegate failure does not invent epoch 0

@Leechael
Leechael force-pushed the feat/auth-eth-app-auth-delegation branch from 6b401ec to 750b02d Compare November 26, 2026 23:20

@kvinwang kvinwang left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. The delegated path skips the OS image allowlist and the TEE variant policy. This one is blocking.
  2. A delegate failure is a 200 denial on /authorizeApp but a 503 on GET /app/:appId, and the KMS reads no root field from a denial.
  3. Cleanups in the new code: getAuthorizationRoots duplicates getRootEpoch, 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.
  4. Two tests that cannot fail on the behavior they name.
  5. Docs the new mode makes wrong, and the ETH_BLOCK_TAG=latest advice.

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) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) };

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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> {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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): {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 !== '') {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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'],

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread docs/app-key-epochs.md
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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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, keyProviderInfo included, to an external URL.
  • dstack/kms/README.md:340-343: "The Ethereum backends call the matching DstackKms method ... 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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
@Leechael
Leechael force-pushed the feat/auth-eth-app-auth-delegation branch from 750b02d to 6f64c65 Compare November 27, 2026 06:36

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants