Files
multica/server/pkg/db/queries/daemon_token.sql
Jiayuan Zhang f52db9e96c feat(server): install_token mint+exchange + daemon_token revoke (MUL-2305)
Phase 1 of RFC MUL-2297 — DB and credential contract for the new runtime
install flow. CLI/daemon/UI plumbing lands in later phases.

Schema (migration 091):
- daemon_token.revoked_at — explicit revoke replaces TTL-based expiry; the
  exchange path now mints daemon_token rows with a ~100y expires_at so the
  cleanup query stays intact while the credential is effectively long-lived
  until revoked.
- install_token — short-lived (15m) single-use credential. used_at IS NULL
  is the atomic gate enforced inside the UPDATE so a concurrent second
  exchange returns zero rows.

API:
- POST /api/workspaces/{id}/install-tokens — admin-only mint, returns mit_
  once; only the hash is stored.
- POST /api/install-tokens/exchange — public (the mit_ is the credential);
  atomically consumes the install_token and returns a fresh mdt_.

Error contract for Phase 2 daemon installer:
- 401 invalid_install_token — unknown hash OR expired
- 401 install_token_already_used — hash exists but used_at IS NOT NULL

Co-authored-by: multica-agent <github@multica.ai>
2026-05-17 00:09:48 +08:00

43 lines
1.6 KiB
SQL

-- name: CreateDaemonToken :one
INSERT INTO daemon_token (token_hash, workspace_id, daemon_id, expires_at)
VALUES ($1, $2, $3, $4)
RETURNING *;
-- name: GetDaemonTokenByHash :one
-- revoked_at IS NULL filters out tokens explicitly revoked via the runtime
-- UX flow (RFC MUL-2297). expires_at > now() stays for defense in depth even
-- though Phase 1 mints tokens with a ~100-year expiry — the legacy short-TTL
-- behavior is still legal and the cleanup query depends on it.
SELECT * FROM daemon_token
WHERE token_hash = $1
AND revoked_at IS NULL
AND expires_at > now();
-- name: RevokeDaemonTokenByID :one
-- Marks a single daemon_token revoked. Returns token_hash so the caller can
-- invalidate auth.DaemonTokenCache before the 10-minute TTL would otherwise
-- let a revoked token keep authenticating on a cached lookup.
UPDATE daemon_token
SET revoked_at = now()
WHERE id = $1
AND workspace_id = $2
AND revoked_at IS NULL
RETURNING token_hash;
-- name: DeleteDaemonTokensByWorkspaceAndDaemons :many
-- Deletes every daemon_token row matching the (workspace_id, daemon_id)
-- pairs implied by `daemon_ids`. Used by the member-revocation flow to
-- nuke tokens for all runtimes a leaving member owned in one shot.
-- Returns token_hash so the caller can invalidate auth.DaemonTokenCache
-- before the 10-minute TTL expires — without that invalidate, a daemon
-- can keep using its stale token until cache eviction even though the
-- DB row is gone.
DELETE FROM daemon_token
WHERE workspace_id = @workspace_id
AND daemon_id = ANY(@daemon_ids::text[])
RETURNING token_hash;
-- name: DeleteExpiredDaemonTokens :exec
DELETE FROM daemon_token
WHERE expires_at <= now();