diff --git a/.dependency-cruiser-known-violations.json b/.dependency-cruiser-known-violations.json index 96e13d3f4..6c591cc39 100644 --- a/.dependency-cruiser-known-violations.json +++ b/.dependency-cruiser-known-violations.json @@ -122,7 +122,7 @@ }, { "type": "dependency", - "from": "src/http/token-store.test.ts", + "from": "src/auth/token-store.test.ts", "to": "src/ports/token-secrets.ts", "unresolvedTo": "../ports/token-secrets.js", "dependencyTypes": ["local", "type-only", "import"], diff --git a/.dependency-cruiser.mjs b/.dependency-cruiser.mjs index b3c05f5e0..fbf9b2e6b 100644 --- a/.dependency-cruiser.mjs +++ b/.dependency-cruiser.mjs @@ -169,6 +169,13 @@ export default { pathNot: "^src/$1/definition\\.ts$", }, }, + { + name: "auth-imports-little", + comment: "src/auth imports only ports and contract", + severity: "error", + from: { path: "^src/auth/", pathNot: linkTestFile }, + to: { path: "^src/", pathNot: "^src/(auth|ports|contract)/" }, + }, { name: "modules-imports-little", comment: "src/modules imports only ports, contract and core, plus the bus for its types", diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index d55955301..586feb2c0 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -48,7 +48,8 @@ worker daemon ── uplink (WebSocket to /v1/uplink, worker dials) ──┘ | link | Byte channels over the uplink | [link](../../src/link/AGENTS.md) | | agent-device | Optional edge: the agent-device daemon beside a worker, its HTTP front | [agent-device](../../src/agent-device/AGENTS.md) | | stream | Optional edge: a leased device's live screen over HTTP, relayed by a gateway | [stream](../../src/stream/AGENTS.md) | -| http | HTTP frontend: routes, tokens, SSE | [http](../../src/http/AGENTS.md) | +| auth | Credential → identity: tokens, admin secret, `hello`, uplink join token, HTTP strategies | [auth](../../src/auth/AGENTS.md) | +| http | HTTP frontend: routes, SSE | [http](../../src/http/AGENTS.md) | | cli | Operator command surface | [cli](../../src/cli/AGENTS.md) | | mcp | stdio MCP server for one agent session | [mcp](../../src/mcp/AGENTS.md) | | simlock-client, client, admin | The typed programmatic client (`simlock/client`, `simlock/admin`) | [simlock-client](../../src/simlock-client/AGENTS.md) · [client](../../src/client/AGENTS.md) · [admin](../../src/admin/AGENTS.md) | @@ -74,6 +75,7 @@ Arrows point from the optional to the required (architecture rule 15). | `core-not-drivers` | Core and leasing reach a platform only through the `Driver` interface | | `no-fs-or-process` | Core, leasing, agent-device, host-load and stream use ports, never `fs` or `child_process` | | `definition-is-light` | A module's definition file imports its own module only for types or by dynamic import | +| `auth-imports-little` | `src/auth` imports only ports and contract | | `modules-imports-little`, `modules-imports-bus-types-only` | `src/modules` imports only ports, contract and core, and the bus for types | | `not-modules` | Core, leasing, drivers, gateway and contract import nothing from modules or module-registry | | `not-agent-device` | Core, leasing and drivers import nothing from agent-device | diff --git a/docs/internal/flows/startup.md b/docs/internal/flows/startup.md index 79b92a633..7186bdbe9 100644 --- a/docs/internal/flows/startup.md +++ b/docs/internal/flows/startup.md @@ -9,6 +9,7 @@ Entry: `src/daemon/main.ts` `startDaemon` → `DaemonServer.start` (`src/daemon/ 2. `Logger` → `daemon.log`. At `log.level: debug` the `ProcessRunner` is wrapped. 3. Host info read once (`sw_vers` on macOS); bounded, never throws. 4. `EventBus` → the event history is created (`createEventHistory`). It touches no file yet. + `createAuth` then builds the token store and the admin secret (hash in memory), once, for both modes. 5. `config.mode: gateway` → the gateway section. Otherwise go on. ## Worker: build (before the claim) @@ -23,8 +24,7 @@ Entry: `src/daemon/main.ts` `startDaemon` → `DaemonServer.start` (`src/daemon/ driver starts its adb server and reattaches running emulators here. 9. Host facts read in the background; host load sampler built. 10. `ComponentInstaller`, `createCore`, the optional-module host (`createModuleHost`; it loads each enabled module's worker half, agent-device's supervisor among them), `createLeasing`, - `core.connect(leasing.corePorts)`, `CleanupReaper`, `Nuke`, `TokenStore`, - `AdminSecretManager` (secret minted, hash in memory), `GatewayUplink` when + `core.connect(leasing.corePorts)`, `CleanupReaper`, `Nuke`, `GatewayUplink` when `gateway.url` and `gateway.token` are set, `DaemonServer`. ## Worker: claim and converge (`DaemonServer.start`) @@ -92,7 +92,7 @@ platform runs the deferred reclaim (step 21.2). ## Gateway 1. Instance identity — `instance.json`. -2. `TokenStore`, `AdminSecretManager`, `FleetLeaseIndex`, routing policy, +2. `FleetLeaseIndex`, routing policy, `GatewayService` (`workers.json`), `FleetLeaseCoordinator`, `DaemonServer` with `GatewayDispatcher`. No registry, drivers, reaper or health monitor. 3. `DaemonServer.start`: claim → host load → `admin.token` → converge starts → diff --git a/src/agent-device/AGENTS.md b/src/agent-device/AGENTS.md index 55e2b1f4f..dcfb048a4 100644 --- a/src/agent-device/AGENTS.md +++ b/src/agent-device/AGENTS.md @@ -2,7 +2,7 @@ Does: runs one agent-device daemon per worker and serves the agent-device CLI at `/v1/agent-device/*`, one simlock lease per agent-device lease. Entry: `index.ts` → `agentDeviceModule`. The front parts live in `front/edge-parts.ts` (`createGatewayAgentDeviceFrontParts`, `createAgentDeviceFront`, `disposeAgentDeviceEdge`, `cancelWaitingAllocates`). The gateway half is `gateway.ts` (`createGateway`, builds the `FleetPort` from the gateway context); the worker half is `worker.ts` (`createAgentDeviceEdgeParts`, builds `AgentDeviceSupervisor`). The module host loads both. -Uses: ports, http (session, errors, token identity), contract types, core and leasing types. Never imports: gateway, drivers, `fs`, `child_process`. +Uses: ports, auth (`Identity`), http (session, errors), contract types, core and leasing types. Never imports: gateway, drivers, `fs`, `child_process`. Imported by: the module registry (`index.ts` only); `daemon/main.ts` imports nothing from it (tests may use `testing.ts`). Pinned in `lint-rules.test.ts`. Off unless `capabilities.agent-device.enabled` (false). Off: nothing mounted, no daemon. diff --git a/src/agent-device/dispose.test.ts b/src/agent-device/dispose.test.ts index 986fb538e..3a7e48205 100644 --- a/src/agent-device/dispose.test.ts +++ b/src/agent-device/dispose.test.ts @@ -25,7 +25,7 @@ describe("disposeAgentDeviceEdge", () => { expect(linkDisposed).toBe(1); const context = { - map: { get: () => ({ endedAt: undefined, identity: { requesterId: "a" }, ttlMs: 30_000 }) }, + map: { get: () => ({ endedAt: undefined, identity: { principal: "a" }, ttlMs: 30_000 }) }, }; renewals.begin(context as never, "lease", "a", 60_000); expect(clock.pendingTimerCount).toBe(0); diff --git a/src/agent-device/front/allocate.test.ts b/src/agent-device/front/allocate.test.ts index 355238d4c..82d88e717 100644 --- a/src/agent-device/front/allocate.test.ts +++ b/src/agent-device/front/allocate.test.ts @@ -1,13 +1,14 @@ import { describe, expect, it, vi } from "vitest"; +import { tokenIdentity } from "../../auth/testing.js"; import type { HttpDispatch } from "../../http/dispatcher-session.js"; -import type { TokenIdentity } from "../../http/token-store.js"; +import type { Identity } from "../../auth/index.js"; import { FakeClock, NoopLogger } from "../../ports/index.js"; import { allocate } from "./allocate.js"; import type { FrontContext } from "./context.js"; import { FrontMap } from "./front-map.js"; -const agent: TokenIdentity = { requesterId: "tok_a", role: "agent" }; +const agent: Identity = tokenIdentity("tok_a"); const leaseId = "00000000000000000000000000000001"; interface AdmitSession { diff --git a/src/agent-device/front/allocate.ts b/src/agent-device/front/allocate.ts index a829fe51c..deec2d04c 100644 --- a/src/agent-device/front/allocate.ts +++ b/src/agent-device/front/allocate.ts @@ -3,7 +3,7 @@ import type { z } from "zod"; import type { OPERATIONS } from "../../contract/index.js"; import { buildHttpSession } from "../../http/dispatcher-session.js"; import { mapError } from "../../http/errors.js"; -import type { TokenIdentity } from "../../http/token-store.js"; +import type { Identity } from "../../auth/index.js"; import type { Clock } from "../../ports/index.js"; import { frontReply, @@ -135,7 +135,7 @@ type LeaseOutcome = // why: a request parked while the daemon starts cannot be called back, so wait on a read that parks at the same gate and give up if the CLI leaves, or a CLI that left would still be admitted. async function stillWaiting( context: FrontContext, - identity: TokenIdentity, + identity: Identity, signal: AbortSignal, ): Promise { if (signal.aborted) return false; @@ -156,7 +156,7 @@ function requiresOf(context: FrontContext): { readonly requires?: string[] } { async function requestLease( context: FrontContext, - identity: TokenIdentity, + identity: Identity, plan: Plan, signal: AbortSignal, ): Promise { @@ -254,13 +254,13 @@ function forwardedBody( export interface AllocateArguments { readonly request: Request; - readonly identity: TokenIdentity; + readonly identity: Identity; readonly call: RpcRead & { readonly kind: "request" }; } interface Granted { readonly request: Request; - readonly identity: TokenIdentity; + readonly identity: Identity; readonly call: RpcRead & { readonly kind: "request" }; readonly plan: Plan; readonly grant: Grant; diff --git a/src/agent-device/front/context.test.ts b/src/agent-device/front/context.test.ts index 8b128c179..41ce3f784 100644 --- a/src/agent-device/front/context.test.ts +++ b/src/agent-device/front/context.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import type { Logger } from "../../ports/index.js"; -import type { TokenIdentity } from "../../http/token-store.js"; +import type { Identity } from "../../auth/index.js"; import { exchange, type FrontContext } from "./context.js"; function rig(reply: () => Promise) { @@ -14,7 +14,7 @@ function rig(reply: () => Promise) { } const request = new Request("http://127.0.0.1/rpc", { method: "POST" }); -const identity = {} as TokenIdentity; +const identity = {} as Identity; describe("exchange", () => { it("a reply that is not JSON-RPC is logged with its status and the start of its body", async () => { diff --git a/src/agent-device/front/context.ts b/src/agent-device/front/context.ts index e5170d556..894217cf9 100644 --- a/src/agent-device/front/context.ts +++ b/src/agent-device/front/context.ts @@ -1,5 +1,5 @@ import type { HttpDispatch } from "../../http/dispatcher-session.js"; -import type { TokenIdentity } from "../../http/token-store.js"; +import type { Identity } from "../../auth/index.js"; import type { Clock, Logger } from "../../ports/index.js"; import { buildHttpSession } from "../../http/dispatcher-session.js"; import { mapError } from "../../http/errors.js"; @@ -34,7 +34,7 @@ export interface Exchange { export async function exchange( context: FrontContext, request: Request, - identity: TokenIdentity, + identity: Identity, call?: CallClass, leaseId?: string, ): Promise { @@ -106,7 +106,7 @@ export type SimlockRelease = export async function releaseSimlock( context: FrontContext, - identity: TokenIdentity, + identity: Identity, leaseId: string, ): Promise { try { @@ -144,7 +144,7 @@ export function scopeOf( export async function releaseAgentDevice( context: FrontContext, request: Request, - identity: TokenIdentity, + identity: Identity, leaseId: string, scope: Record, ) { @@ -160,7 +160,7 @@ export async function releaseAgentDevice( // why: a lease the token holds under another requester than its own id was made by something else (a gateway, for a worker's token of the same name), so this front has no claim to end it. export async function heldForAnother( context: FrontContext, - identity: TokenIdentity, + identity: Identity, leaseId: string, ): Promise { try { @@ -174,7 +174,7 @@ export async function heldForAnother( const LIST_TIMEOUT_MS = 5_000; -export async function listLeases(context: FrontContext, identity: TokenIdentity) { +export async function listLeases(context: FrontContext, identity: Identity) { let timer: ReturnType | undefined; const timeout = new Promise((_resolve, reject) => { timer = context.clock.setTimer(LIST_TIMEOUT_MS, () => diff --git a/src/agent-device/front/devices-filter.ts b/src/agent-device/front/devices-filter.ts index 440f1e898..23d6390ca 100644 --- a/src/agent-device/front/devices-filter.ts +++ b/src/agent-device/front/devices-filter.ts @@ -1,4 +1,4 @@ -import type { TokenIdentity } from "../../http/token-store.js"; +import type { Identity } from "../../auth/index.js"; import { failure, frontReply, workerUnreachable } from "../shared/replies.js"; import { readBounded, readReply } from "../shared/rpc.js"; import { asRecord } from "../shared/selectors.js"; @@ -15,7 +15,7 @@ function emptyList(rpc: { readonly id: unknown }): Response { export async function filterDevices( context: FrontContext, - identity: TokenIdentity, + identity: Identity, response: Response, rpc: { readonly id: unknown }, ): Promise { @@ -44,7 +44,7 @@ export async function filterDevices( // why: one lease the gateway cannot reach makes the whole list unknown, so `devices` answers it rather than a list missing that device. export async function anyUnreachable( context: FrontContext, - identity: TokenIdentity, + identity: Identity, leases: readonly { readonly leaseId: string }[], ): Promise { for (const lease of leases) { @@ -55,7 +55,7 @@ export async function anyUnreachable( interface GatewayDevices { readonly request: Request; - readonly identity: TokenIdentity; + readonly identity: Identity; readonly read: { readonly id: unknown; readonly text: string }; readonly forward: (request: Request, leaseId: string) => Promise; } diff --git a/src/agent-device/front/ended.ts b/src/agent-device/front/ended.ts index b56db990f..acf507265 100644 --- a/src/agent-device/front/ended.ts +++ b/src/agent-device/front/ended.ts @@ -1,4 +1,4 @@ -import type { TokenIdentity } from "../../http/token-store.js"; +import type { Identity } from "../../auth/index.js"; import { leaseIdOf } from "../shared/rpc.js"; import { asRecord } from "../shared/selectors.js"; import type { FrontContext } from "./context.js"; @@ -43,7 +43,7 @@ function endedLeaseIds(text: string): string[] { // why: the daemon no longer sends a release after it ends a lease, so the front ends the simlock lease from the command's reply; a copy is read so the CLI's reply goes out untouched. export function releaseEndedLeases( context: FrontContext, - identity: TokenIdentity, + identity: Identity, response: Response, ): void { if (!(response.headers.get("content-type") ?? "").includes("json")) return; diff --git a/src/agent-device/front/front-map.test.ts b/src/agent-device/front/front-map.test.ts index e06388851..b8ecf649c 100644 --- a/src/agent-device/front/front-map.test.ts +++ b/src/agent-device/front/front-map.test.ts @@ -1,10 +1,11 @@ import { describe, expect, it, vi } from "vitest"; -import type { TokenIdentity } from "../../http/token-store.js"; +import { tokenIdentity } from "../../auth/testing.js"; +import type { Identity } from "../../auth/index.js"; import { FakeClock } from "../../ports/index.js"; import { FrontMap } from "./front-map.js"; -const agent: TokenIdentity = { requesterId: "tok_a", role: "agent" }; +const agent: Identity = tokenIdentity("tok_a"); const ttlMs = 60_000; function entry(deadline: number) { @@ -80,14 +81,14 @@ describe("the front map", () => { const clock = new FakeClock(1_000); const map = new FrontMap(clock); for (let n = 0; n < 101; n += 1) { - const identity: TokenIdentity = { requesterId: `tok_${n}`, role: "agent" }; + const identity: Identity = tokenIdentity(`tok_${n}`); map.add(`lease-${n}`, { address: "a", deadline: 2_100 - n, identity, ttlMs }); } clock.advance(10_000); const asked: string[] = []; await map.refresh(async (who) => { - asked.push(who.requesterId); + asked.push(who.principal); return []; }); diff --git a/src/agent-device/front/front-map.ts b/src/agent-device/front/front-map.ts index 12db550c6..de0b86fa3 100644 --- a/src/agent-device/front/front-map.ts +++ b/src/agent-device/front/front-map.ts @@ -1,4 +1,4 @@ -import type { TokenIdentity } from "../../http/token-store.js"; +import type { Identity } from "../../auth/index.js"; import type { Clock } from "../../ports/index.js"; const MAX_PRINCIPALS_PER_REFRESH = 100; @@ -14,7 +14,7 @@ interface DeviceFacts { } export interface FrontMapEntry extends DeviceFacts { - readonly identity: TokenIdentity; + readonly identity: Identity; readonly address: string; readonly ttlMs: number; readonly deadline: number; @@ -23,7 +23,7 @@ export interface FrontMapEntry extends DeviceFacts { export type EndedBy = "agent" | "simlock"; export interface HeldView extends DeviceFacts { - readonly identity: TokenIdentity; + readonly identity: Identity; readonly address: string; readonly ttlMs: number; readonly endedAt?: number; @@ -37,7 +37,7 @@ export interface ListedLease { interface Held extends Omit { deviceKey?: string; - readonly identity: TokenIdentity; + readonly identity: Identity; readonly address: string; ttlMs: number; deadline: number; @@ -79,7 +79,7 @@ export class FrontMap { liveOf(requesterId: string): readonly (HeldView & { readonly leaseId: string })[] { this.#prune(); return [...this.#held] - .filter(([, held]) => held.identity.requesterId === requesterId && held.endedAt === undefined) + .filter(([, held]) => held.identity.principal === requesterId && held.endedAt === undefined) .map(([leaseId, held]) => ({ ...held, leaseId })); } @@ -112,18 +112,15 @@ export class FrontMap { held.releasing = false; } - async refresh(list: (identity: TokenIdentity) => Promise): Promise { + async refresh(list: (identity: Identity) => Promise): Promise { this.#prune(); const now = this.clock.now(); - const byPrincipal = new Map< - string, - { identity: TokenIdentity; oldest: number; ids: string[] } - >(); + const byPrincipal = new Map(); for (const [id, held] of this.#held) { if (held.endedAt !== undefined || held.deadline > now) continue; - const group = byPrincipal.get(held.identity.requesterId); + const group = byPrincipal.get(held.identity.principal); if (group === undefined) { - byPrincipal.set(held.identity.requesterId, { + byPrincipal.set(held.identity.principal, { identity: held.identity, ids: [id], oldest: held.deadline, diff --git a/src/agent-device/front/front.ts b/src/agent-device/front/front.ts index 455fe22b0..2592f4187 100644 --- a/src/agent-device/front/front.ts +++ b/src/agent-device/front/front.ts @@ -1,5 +1,5 @@ import type { HttpMount } from "../../http/app.js"; -import type { TokenIdentity } from "../../http/token-store.js"; +import type { Identity } from "../../auth/index.js"; import { FRONT_MOUNT, FRONT_PREFIX, LEASE_HEADER } from "../shared/paths.js"; import { failure, @@ -33,7 +33,7 @@ import { checkRequest } from "./request-rules.js"; type RpcRequest = RpcRead & { readonly kind: "request" }; interface Routed { - readonly identity: TokenIdentity; + readonly identity: Identity; readonly kind: CallClass; readonly leaseMaxTtlMs: number | undefined; readonly read: RpcRequest; @@ -82,7 +82,7 @@ const FAILED_BODY_LOG_CHARS = 500; // why: `devices` names no lease, so a gateway with no capable worker still answers "try again" when one of the token's own leases is only unreachable. async function notRunning( context: FrontContext, - identity: TokenIdentity, + identity: Identity, read: RpcRequest, status: Exclude, ): Promise { @@ -91,7 +91,7 @@ async function notRunning( !( isDevicesCall(read) && context.link.readsLeaseHeader && - (await anyUnreachable(context, identity, context.map.liveOf(identity.requesterId))) + (await anyUnreachable(context, identity, context.map.liveOf(identity.principal))) ) ) { return frontReply(notAvailable(status.reason), read); @@ -102,7 +102,7 @@ async function notRunning( async function handleRpc( context: FrontContext, request: Request, - identity: TokenIdentity, + identity: Identity, ): Promise { const read = await readRpcBody(request); if (read.kind === "too-large") { @@ -154,11 +154,11 @@ async function routeCall( async function runCommand( context: FrontContext, request: Request, - identity: TokenIdentity, + identity: Identity, read: RpcRequest, leaseId: string, ): Promise { - const end = context.renewals.begin(context, leaseId, identity.requesterId, context.maxRunMs); + const end = context.renewals.begin(context, leaseId, identity.principal, context.maxRunMs); request.signal.addEventListener("abort", end, { once: true }); let response: Response; try { @@ -215,7 +215,7 @@ function isDevicesCall(read: RpcRequest): boolean { async function forwardCommand( context: FrontContext, request: Request, - identity: TokenIdentity, + identity: Identity, read: RpcRequest, leaseId: string | undefined, ): Promise { @@ -261,7 +261,7 @@ async function readStart(response: Response, chars: number): Promise { async function passThrough( context: FrontContext, request: Request, - identity: TokenIdentity, + identity: Identity, rpc: { readonly id: unknown } | undefined, leaseId?: string, probe = false, @@ -315,7 +315,7 @@ function readLeaseHeader(request: Request): HeaderLease { async function routeByHeader( context: FrontContext, request: Request, - identity: TokenIdentity, + identity: Identity, ): Promise { const read = readLeaseHeader(request); if ("refused" in read) return read.refused; @@ -340,7 +340,7 @@ function namesLease(context: FrontContext, request: Request, probe: boolean): bo async function handlePlain( context: FrontContext, request: Request, - identity: TokenIdentity, + identity: Identity, ): Promise { const status = await context.link.status(); const path = new URL(request.url).pathname.slice(FRONT_PREFIX.length); @@ -359,7 +359,7 @@ async function handlePlain( } // why: after a gateway restart the map is empty, so the token's leases are rebuilt from what the gateway knows before any rule reads the map. -function adoptLeases(context: FrontContext, identity: TokenIdentity): void { +function adoptLeases(context: FrontContext, identity: Identity): void { for (const lease of context.link.adoptable?.(identity) ?? []) { if (context.map.get(lease.leaseId) !== undefined) continue; context.map.add(lease.leaseId, { diff --git a/src/agent-device/front/heartbeat.ts b/src/agent-device/front/heartbeat.ts index 7b5ef44e6..22ea37519 100644 --- a/src/agent-device/front/heartbeat.ts +++ b/src/agent-device/front/heartbeat.ts @@ -1,4 +1,4 @@ -import type { TokenIdentity } from "../../http/token-store.js"; +import type { Identity } from "../../auth/index.js"; import { failure, frontReply, leaseEndedByHost, refusal } from "../shared/replies.js"; import { leaseCallFields, @@ -40,7 +40,7 @@ function forwardedHeartbeat(request: Request, call: Call, ceiling: number | unde // why: simlock's own ownership check decides about a lease another token holds, so a refusal there is not a failure of the heartbeat. async function releaseOurs( context: FrontContext, - identity: TokenIdentity, + identity: Identity, leaseId: string, call: Call, held: boolean, @@ -56,7 +56,7 @@ async function releaseOurs( async function leaseStillThere( context: FrontContext, - { request, identity, call }: { request: Request; identity: TokenIdentity; call: Call }, + { request, identity, call }: { request: Request; identity: Identity; call: Call }, leaseId: string, ): Promise { const ended = await releaseAgentDevice( @@ -96,9 +96,9 @@ async function renewHeld( return relay(reply); } -function ownEntry(context: FrontContext, leaseId: string, identity: TokenIdentity) { +function ownEntry(context: FrontContext, leaseId: string, identity: Identity) { const entry = context.map.get(leaseId); - return entry?.identity.requesterId === identity.requesterId ? entry : undefined; + return entry?.identity.principal === identity.principal ? entry : undefined; } function badTtl(call: Call): boolean { @@ -114,7 +114,7 @@ export async function heartbeat( context: FrontContext, arguments_: { readonly request: Request; - readonly identity: TokenIdentity; + readonly identity: Identity; readonly call: Call; readonly leaseMaxTtlMs: number | undefined; }, diff --git a/src/agent-device/front/host-link.ts b/src/agent-device/front/host-link.ts index 436c6ab24..1fe4ad368 100644 --- a/src/agent-device/front/host-link.ts +++ b/src/agent-device/front/host-link.ts @@ -1,4 +1,4 @@ -import type { TokenIdentity } from "../../http/token-store.js"; +import type { Identity } from "../../auth/index.js"; import type { AgentDevicePlatform } from "../host/agent-device-supervisor.js"; import type { AgentDeviceHost } from "../host/host.js"; @@ -29,10 +29,10 @@ export interface HostLink { readonly readsLeaseHeader: boolean; // why: capabilities a lease request must require so it lands on a host that can serve agent-device; none means any worker. readonly leaseRequires?: readonly string[]; - status(leaseId?: string, identity?: TokenIdentity): Promise; - forward(request: Request, identity: TokenIdentity, leaseId?: string): Promise; + status(leaseId?: string, identity?: Identity): Promise; + forward(request: Request, identity: Identity, leaseId?: string): Promise; // why: only a link that serves many hosts adopts leases made before the front's map was empty; a worker's map is in memory and has no entry for a lease it made before a restart, but that lease is ended, not adopted. - adoptable?(identity: TokenIdentity): readonly AdoptableLease[]; + adoptable?(identity: Identity): readonly AdoptableLease[]; // why: a lease the front asked for in this process is its allocate's to keep or release, never to adopt. asked?(leaseId: string): void; dispose?(): void; @@ -47,7 +47,7 @@ export class InProcessHostLink implements HostLink { return this.host.status(); } - forward(request: Request, identity: TokenIdentity): Promise { + forward(request: Request, identity: Identity): Promise { return this.host.forward(request, identity); } } diff --git a/src/agent-device/front/relay-host-link.test.ts b/src/agent-device/front/relay-host-link.test.ts index 9accf3525..adbe53444 100644 --- a/src/agent-device/front/relay-host-link.test.ts +++ b/src/agent-device/front/relay-host-link.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it, vi } from "vitest"; -import type { TokenIdentity } from "../../http/token-store.js"; +import { tokenIdentity } from "../../auth/testing.js"; +import type { Identity } from "../../auth/index.js"; import { FakeClock } from "../../ports/index.js"; import { RelayHostLink, @@ -10,7 +11,7 @@ import { type PlacedLease, } from "./relay-host-link.js"; -const agent: TokenIdentity = { requesterId: "tok_a", role: "agent" }; +const agent: Identity = tokenIdentity("tok_a"); const worker: FleetWorker = { id: "w1", leaseMaxTtlMs: 1_000, platforms: ["ios"] }; const maxTtlMs = 120_000; @@ -78,7 +79,7 @@ describe("RelayHostLink", () => { const { index, link, relay } = setUp(); index.set("L", { ownerId: principal, workerId: "w1" }); - await link.forward(request(), { requesterId: principal, role: "agent" }, "L"); + await link.forward(request(), tokenIdentity(principal), "L"); expect(relay).toHaveBeenCalledTimes(1); expect(relay.mock.calls[0]?.[2]).toMatch(/^[A-Za-z0-9._-]{1,128}$/); @@ -90,7 +91,7 @@ describe("RelayHostLink", () => { const principals = ["a b", "a_b", "a.b", "a:b", "t".repeat(300), `${"t".repeat(299)}u`]; for (const principal of principals) { index.set("L", { ownerId: principal, workerId: "w1" }); - await link.forward(request(), { requesterId: principal, role: "agent" }, "L"); + await link.forward(request(), tokenIdentity(principal), "L"); } const tenants = relay.mock.calls.map((call) => call[2]); @@ -175,7 +176,7 @@ describe("RelayHostLink", () => { index.set("L", { ownerId: "tok_a", workerId: "w1" }); expect(await link.status("L", agent)).toMatchObject({ leaseMaxTtlMs: 86_400_000 }); - expect(await link.status("L", { ...agent, requesterId: "tok_b" })).not.toHaveProperty( + expect(await link.status("L", { ...agent, principal: "tok_b" })).not.toHaveProperty( "leaseMaxTtlMs", ); expect(await link.status()).not.toHaveProperty("leaseMaxTtlMs"); diff --git a/src/agent-device/front/relay-host-link.ts b/src/agent-device/front/relay-host-link.ts index 96bb7269f..7d0785da4 100644 --- a/src/agent-device/front/relay-host-link.ts +++ b/src/agent-device/front/relay-host-link.ts @@ -1,6 +1,6 @@ import { createHash } from "node:crypto"; -import type { TokenIdentity } from "../../http/token-store.js"; +import type { Identity } from "../../auth/index.js"; import type { Clock, TimerHandle } from "../../ports/index.js"; import type { AgentDevicePlatform } from "../host/agent-device-supervisor.js"; import { agentDeviceLeaseMaxTtlMs } from "../shared/daemon-environment.js"; @@ -128,19 +128,19 @@ export class RelayHostLink implements HostLink { }); } - status(leaseId?: string, identity?: TokenIdentity): Promise { + status(leaseId?: string, identity?: Identity): Promise { if (leaseId === undefined || identity === undefined) return Promise.resolve(this.#anyStatus()); const placed = this.#place(leaseId); if (placed === undefined && this.#inStartWindow()) return Promise.resolve(UNREACHABLE); - if (placed?.ownerId !== identity.requesterId) return Promise.resolve(this.#anyStatus()); + if (placed?.ownerId !== identity.principal) return Promise.resolve(this.#anyStatus()); return Promise.resolve(this.#holderStatus(placed)); } - async forward(request: Request, identity: TokenIdentity, leaseId?: string): Promise { - const tenant = relayTenant(this.options.fleet.instanceId, identity.requesterId); + async forward(request: Request, identity: Identity, leaseId?: string): Promise { + const tenant = relayTenant(this.options.fleet.instanceId, identity.principal); if (leaseId === undefined) return this.#forwardBare(request, tenant); const placed = this.#place(leaseId); - if (placed === undefined || placed.ownerId !== identity.requesterId) { + if (placed === undefined || placed.ownerId !== identity.principal) { return refuseRequest(request, notYours(leaseId), FORBIDDEN); } return this.#relay(placed.workerId, request, tenant, leaseId); @@ -150,8 +150,8 @@ export class RelayHostLink implements HostLink { this.#asked.add(leaseId); } - adoptable(identity: TokenIdentity): readonly AdoptableLease[] { - return this.options.fleet.leasesOf(identity.requesterId).flatMap((facts) => { + adoptable(identity: Identity): readonly AdoptableLease[] { + return this.options.fleet.leasesOf(identity.principal).flatMap((facts) => { const { listed } = facts; if ( facts.requesterId !== facts.leaseId || diff --git a/src/agent-device/front/release.ts b/src/agent-device/front/release.ts index e82f77588..c49f6089b 100644 --- a/src/agent-device/front/release.ts +++ b/src/agent-device/front/release.ts @@ -1,10 +1,10 @@ -import type { TokenIdentity } from "../../http/token-store.js"; +import type { Identity } from "../../auth/index.js"; import { leaseCallFields, leaseIdOf, type RpcRead } from "../shared/rpc.js"; import { exchange, relay, releaseSimlock, unreachableReply, type FrontContext } from "./context.js"; export async function release( context: FrontContext, - identity: TokenIdentity, + identity: Identity, call: RpcRead & { readonly kind: "request" }, forwarded: Request, ): Promise { @@ -20,11 +20,11 @@ export async function release( export async function endSimlockLease( context: FrontContext, - identity: TokenIdentity, + identity: Identity, leaseId: string, ): Promise { const entry = context.map.get(leaseId); - if (entry === undefined || entry.identity.requesterId !== identity.requesterId) { + if (entry === undefined || entry.identity.principal !== identity.principal) { // why: a lease the map does not hold for this token (as after a daemon restart) is freed by simlock's own ownership check, which refuses another token's lease. await releaseSimlock(context, identity, leaseId); } else if (entry.endedAt === undefined) { diff --git a/src/agent-device/front/renewals.test.ts b/src/agent-device/front/renewals.test.ts index 0f86d74d2..6874c1405 100644 --- a/src/agent-device/front/renewals.test.ts +++ b/src/agent-device/front/renewals.test.ts @@ -1,12 +1,13 @@ import { describe, expect, it } from "vitest"; -import type { TokenIdentity } from "../../http/token-store.js"; +import { tokenIdentity } from "../../auth/testing.js"; +import type { Identity } from "../../auth/index.js"; import { FakeClock } from "../../ports/index.js"; import type { FrontContext } from "./context.js"; import { FrontMap } from "./front-map.js"; import { Renewals } from "./renewals.js"; -const agent: TokenIdentity = { requesterId: "tok_a", role: "agent" }; +const agent: Identity = tokenIdentity("tok_a"); const longestTimerDelayMs = 2 ** 31 - 1; describe("the renewals", () => { @@ -23,7 +24,7 @@ describe("the renewals", () => { const renewals = new Renewals(clock); const context = { map } as unknown as FrontContext; - renewals.begin(context, "lease-a", agent.requesterId, 2 ** 40); + renewals.begin(context, "lease-a", agent.principal, 2 ** 40); expect(delays.length).toBeGreaterThanOrEqual(2); expect(Math.max(...delays)).toBeLessThanOrEqual(longestTimerDelayMs); @@ -36,7 +37,7 @@ describe("the renewals", () => { map.add("lease-a", { address: "addr", deadline: 9e12, identity: agent, ttlMs: 60_000 }); const renewals = new Renewals(clock); const context = { map } as unknown as FrontContext; - renewals.begin(context, "lease-a", agent.requesterId, 1_800_000); + renewals.begin(context, "lease-a", agent.principal, 1_800_000); expect(clock.pendingTimerCount).toBe(2); map.markEnded("lease-a"); diff --git a/src/agent-device/front/renewals.ts b/src/agent-device/front/renewals.ts index f64f2581e..de3830c98 100644 --- a/src/agent-device/front/renewals.ts +++ b/src/agent-device/front/renewals.ts @@ -50,7 +50,7 @@ export class Renewals { if ( this.#disposed || entry === undefined || - entry.identity.requesterId !== identityId || + entry.identity.principal !== identityId || entry.endedAt !== undefined ) { return () => undefined; diff --git a/src/agent-device/front/request-rules.ts b/src/agent-device/front/request-rules.ts index 971bc6f3a..db718fac8 100644 --- a/src/agent-device/front/request-rules.ts +++ b/src/agent-device/front/request-rules.ts @@ -1,6 +1,6 @@ import { findCatalogModel } from "../../core/index.js"; import { buildHttpSession } from "../../http/dispatcher-session.js"; -import type { TokenIdentity } from "../../http/token-store.js"; +import type { Identity } from "../../auth/index.js"; import { failure, refusal, type FrontReply } from "../shared/replies.js"; import { validDeviceKey } from "../shared/release-scope.js"; import { isKnownRpcMethod } from "../shared/routes.js"; @@ -48,7 +48,7 @@ interface Unit { interface Check { readonly context: FrontContext; - readonly identity: TokenIdentity; + readonly identity: Identity; readonly platforms: readonly string[]; readonly leaseId: string | undefined; readonly leased: TokenDevice | undefined; @@ -315,7 +315,7 @@ function unitFor(name: string, params: Fields): Unit | undefined { function buildCheck( context: FrontContext, - identity: TokenIdentity, + identity: Identity, platforms: readonly string[], params: Fields, kind: Unit["kind"], @@ -330,7 +330,7 @@ function buildCheck( identity, leaseId, leased: - leaseId !== undefined && held?.identity.requesterId === identity.requesterId + leaseId !== undefined && held?.identity.principal === identity.principal ? { ...held, leaseId } : undefined, meta, @@ -341,7 +341,7 @@ function buildCheck( export async function checkRequest( context: FrontContext, - identity: TokenIdentity, + identity: Identity, read: RpcRequest, platforms: readonly string[], ): Promise { @@ -363,7 +363,7 @@ function checkMeta(check: Check): void { async function run( context: FrontContext, - identity: TokenIdentity, + identity: Identity, read: RpcRequest, platforms: readonly string[], ): Promise { diff --git a/src/agent-device/front/token-devices.ts b/src/agent-device/front/token-devices.ts index 57703c043..5b306d184 100644 --- a/src/agent-device/front/token-devices.ts +++ b/src/agent-device/front/token-devices.ts @@ -1,4 +1,4 @@ -import type { TokenIdentity } from "../../http/token-store.js"; +import type { Identity } from "../../auth/index.js"; import { listLeases, type FrontContext } from "./context.js"; import type { HeldView } from "./front-map.js"; @@ -12,9 +12,9 @@ export class LeaseCheckFailed extends Error { export async function tokenDevices( context: FrontContext, - identity: TokenIdentity, + identity: Identity, ): Promise { - const held = context.map.liveOf(identity.requesterId); + const held = context.map.liveOf(identity.principal); if (held.length === 0) return held; let listed: Awaited>; try { @@ -25,5 +25,5 @@ export async function tokenDevices( for (const entry of held) { if (!listed.some((lease) => lease.id === entry.leaseId)) context.map.markEnded(entry.leaseId); } - return context.map.liveOf(identity.requesterId); + return context.map.liveOf(identity.principal); } diff --git a/src/agent-device/gateway.test.ts b/src/agent-device/gateway.test.ts index 3d98a8f1a..5fc6c526e 100644 --- a/src/agent-device/gateway.test.ts +++ b/src/agent-device/gateway.test.ts @@ -33,7 +33,7 @@ async function healthThroughGateway(served: readonly WorkerView[]) { const module = loaded?.createGateway(ctx); const handler = module?.mount?.({ dispatch: () => Promise.reject(new Error("unused")) }); const answer = await handler?.(new Request("http://gateway.test/v1/agent-device/health"), { - requesterId: "tok_one", + principal: "tok_one", role: "agent", }); return { body: await answer?.text(), relayed }; diff --git a/src/agent-device/gateway.ts b/src/agent-device/gateway.ts index 638ff86b8..5a8db08c2 100644 --- a/src/agent-device/gateway.ts +++ b/src/agent-device/gateway.ts @@ -1,5 +1,5 @@ import type { HttpDispatch } from "../http/dispatcher-session.js"; -import type { TokenIdentity } from "../http/token-store.js"; +import type { Identity } from "../auth/index.js"; import type { FleetLease, GatewayContext, GatewayModule, WorkerView } from "../modules/index.js"; import type { AgentDeviceModuleConfig } from "./definition.js"; import { @@ -149,7 +149,7 @@ export function createGateway(ctx: Context): GatewayModule { ? {} : { leaseTtlCapMs: ctx.config.leaseTtlCapMs }), }); - return (request, identity) => front.handle(request, identity as TokenIdentity); + return (request, identity) => front.handle(request, identity as Identity); }, }; } diff --git a/src/agent-device/host/download-cap.test.ts b/src/agent-device/host/download-cap.test.ts index ceaacca48..ae9a734b3 100644 --- a/src/agent-device/host/download-cap.test.ts +++ b/src/agent-device/host/download-cap.test.ts @@ -1,11 +1,12 @@ import { createHash } from "node:crypto"; import { describe, expect, it } from "vitest"; +import { tokenIdentity } from "../../auth/testing.js"; import { FakeAgentDevice } from "../testing.js"; import { AgentDeviceHost } from "./host.js"; const LIMIT = 2_147_483_648; -const identity = { requesterId: "tok_a", role: "agent" } as const; +const identity = tokenIdentity("tok_a"); function download(): Request { return new Request("http://simlock.test/v1/agent-device/artifacts/a1", { diff --git a/src/agent-device/host/host.ts b/src/agent-device/host/host.ts index 6a7f4b06d..0a2426b3f 100644 --- a/src/agent-device/host/host.ts +++ b/src/agent-device/host/host.ts @@ -1,6 +1,6 @@ import { randomUUID } from "node:crypto"; -import type { TokenIdentity } from "../../http/token-store.js"; +import type { Identity } from "../../auth/index.js"; import type { AgentDevicePlatform } from "./agent-device-supervisor.js"; import { FRONT_PREFIX, PROXY_BASE_PATH } from "../shared/paths.js"; import { frontReply, refusal } from "../shared/replies.js"; @@ -84,7 +84,7 @@ function capped(response: Response): Response { } export class AgentDeviceHost { - readonly #identities = new Map(); + readonly #identities = new Map(); #loading: Promise | undefined; #loadError: string | undefined; #proxy: { readonly generation: number; readonly proxy: DaemonProxy } | undefined; @@ -113,7 +113,7 @@ export class AgentDeviceHost { }; } - tag(request: Request, identity: TokenIdentity): string { + tag(request: Request, identity: Identity): string { const tag = randomUUID(); this.#identities.set(tag, identity); request.headers.set(TAG_HEADER, tag); @@ -123,10 +123,10 @@ export class AgentDeviceHost { authenticate(request: Request): { readonly tenantId: string } | null { const tag = request.headers.get(TAG_HEADER); const identity = tag === null ? undefined : this.#identities.get(tag); - return identity === undefined ? null : { tenantId: identity.requesterId }; + return identity === undefined ? null : { tenantId: identity.principal }; } - async forward(request: Request, identity: TokenIdentity): Promise { + async forward(request: Request, identity: Identity): Promise { const status = await this.status(); if (status.state === "unavailable") throw new Error(status.reason); const module = await this.#load(); diff --git a/src/agent-device/host/upstream.test.ts b/src/agent-device/host/upstream.test.ts index 119681d73..d98bd1099 100644 --- a/src/agent-device/host/upstream.test.ts +++ b/src/agent-device/host/upstream.test.ts @@ -10,6 +10,7 @@ import { ScriptedProcessRunner, type ScriptedProcessExpectation, } from "../../ports/index.js"; +import { tokenIdentity } from "../../auth/testing.js"; import { FakeAgentDeviceHealth } from "../testing.js"; import { agentDeviceLeaseMaxTtlMs } from "../shared/daemon-environment.js"; import { AgentDeviceSupervisor } from "./agent-device-supervisor.js"; @@ -146,7 +147,7 @@ describe("the agent-device host's authenticate", () => { it("returns the tagged identity's principal as the tenant, and null for a request the front did not tag", () => { const host = new AgentDeviceHost(upstream, ["ios"]); const tagged = new Request("http://worker/v1/agent-device/rpc"); - host.tag(tagged, { requesterId: "tok_agent", role: "agent" }); + host.tag(tagged, tokenIdentity("tok_agent")); expect(host.authenticate(tagged)).toEqual({ tenantId: "tok_agent" }); expect(host.authenticate(new Request("http://worker/v1/agent-device/rpc"))).toBeNull(); diff --git a/src/agent-device/worker.ts b/src/agent-device/worker.ts index 0be31dca2..c07870da6 100644 --- a/src/agent-device/worker.ts +++ b/src/agent-device/worker.ts @@ -1,5 +1,5 @@ import type { HttpDispatch } from "../http/dispatcher-session.js"; -import type { TokenIdentity } from "../http/token-store.js"; +import type { Identity } from "../auth/index.js"; import type { Clock } from "../ports/index.js"; import type { WorkerContext, WorkerModule } from "../modules/index.js"; import type { AgentDeviceModuleConfig } from "./definition.js"; @@ -47,7 +47,13 @@ function agentDeviceRelayTarget( if (status.state === "unavailable") { return frontReplyFor(request, notAvailable(status.reason)); } - return parts.link.forward(request, { requesterId: tenant, role: "agent" }); + return parts.link.forward(request, { + principal: tenant, + name: tenant, + role: "agent", + via: "relay", + ambient: false, + }); }; } @@ -132,7 +138,7 @@ export function createWorkerWith( ? {} : { leaseTtlCapMs: ctx.config.leaseTtlCapMs }), }); - return (request, identity) => front.handle(request, identity as TokenIdentity); + return (request, identity) => front.handle(request, identity as Identity); }, relayTarget: agentDeviceRelayTarget(parts), }; diff --git a/src/auth/AGENTS.md b/src/auth/AGENTS.md new file mode 100644 index 000000000..8a9e81269 --- /dev/null +++ b/src/auth/AGENTS.md @@ -0,0 +1,49 @@ +# Auth + +Does: turns a credential into an identity. The token store, the per-start admin secret, the socket `hello` check, the uplink join-token check and the HTTP request check live here and nowhere else. +Entry: `index.ts` → `createAuth(options)` → `Auth`; `testing.ts` (`createAuthWith`, `fakeAuth`, `tokenIdentity`). +Uses: ports, contract only (`auth-imports-little`). +Never imports: any other component. +Imported by: daemon (`src/daemon/main.ts`, `src/daemon/server.ts`, `src/daemon/dispatcher.ts`, `src/daemon/error-code.ts`), http, gateway (types), core (`src/core/config.ts` reads the strategy registry), agent-device (`Identity`). +Decision: [ADR 0033](../../docs/internal/adr/0033-a-sign-in-proxy-is-a-second-way-to-sign-in-and-auth-is-one-module.md). + +## Files + +| File | Role | +| -------------------------------- | --------------------------------------------------------------------------- | +| `index.ts` | `createAuth`, `Auth`, `AuthError`, `AdminAuthenticationFailedError` | +| `identity.ts` | `Identity`: principal, name, role, via, expiry, ambient, sign-out URL | +| `strategy.ts` | `AuthStrategyDefinition`, `AuthStrategy`, `StrategyAnswer`, `AuthConfig` | +| `strategies/index.ts` | The registry: ordered definitions (today `token`) | +| `strategies/token/index.ts` | The Simlock token strategy: `Authorization: Bearer slk_…` | +| `strategies/conformance.test.ts` | Every registered strategy: `not-mine` without its credential, `via` = name | +| `token-store.ts` | `TokenStore`: hashed tokens in `tokens.json`; re-reads the file per verify | +| `admin-secret.ts` | `AdminSecretManager`: per-start secret, `admin.token` | +| `hello.ts` | `SessionRoleResolver`, `resolveAgentRole`, `AdminAuthenticationFailedError` | +| `tokens.ts` | `TokenRole`, `TokenRecord`, `TokenOperations` | + +## Auth + +| Member | Does | +| --------------------- | -------------------------------------------------------------------------------------------------------- | +| `authenticateRequest` | Asks the enabled strategies in registry order; returns `Identity` or throws `AuthError` | +| `resolveHelloRole` | No credential → `agent`; operator token or admin secret → `admin`; else `AdminAuthenticationFailedError` | +| `authenticateUplink` | None or unknown → `unauthenticated`; not a `worker` token → `forbidden`; else accept with the token id | +| `tokens` | `create`, `list`, `revoke` (both dispatchers) | +| `adminSecret` | `persist`, `remove` (`DaemonServer`) | + +## Strategies + +A strategy answers `identified`, `not-mine` (its credential is absent; `sawCredential` when an +unclaimed bearer value was present), `rejected` (401) or `forbidden` (403). The first answer other +than `not-mine` ends the list, and the refusal's message and details come from the strategy. +When all answer `not-mine`: 401 "Unknown bearer token" if any saw a credential, else "Missing +bearer token". Adding one: a directory under `strategies/` with its `testing.ts` fixture, one line +in `strategies/index.ts`, and (if it owns a config key under `http`) the mirror in the contract's +`configSchema`; `src/core/config.ts` validates and defaults the key from the definition. + +## Facts + +- A worker join token is `forbidden` on HTTP and accepted only by `authenticateUplink`. +- `tokens.json` is re-read on every verify, so `token create`/`revoke` from another process takes effect at once. Writes are serialised in `TokenStore`. +- The admin secret's hash lives in memory from construction; the plaintext is written to `admin.token` (0600, atomic) only by `persist`, after the socket claim. diff --git a/src/auth/CLAUDE.md b/src/auth/CLAUDE.md new file mode 100644 index 000000000..43c994c2d --- /dev/null +++ b/src/auth/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/src/daemon/admin-secret.test.ts b/src/auth/admin-secret.test.ts similarity index 77% rename from src/daemon/admin-secret.test.ts rename to src/auth/admin-secret.test.ts index 1f1cd80b8..bd7714039 100644 --- a/src/daemon/admin-secret.test.ts +++ b/src/auth/admin-secret.test.ts @@ -3,12 +3,6 @@ import { describe, expect, it } from "vitest"; import { MemoryFilesystem, CryptoTokenSecrets, type Filesystem } from "../ports/index.js"; import { AdminSecretManager } from "./admin-secret.js"; -/** - * Regression coverage for review finding S1: `AdminSecretManager` (ADR 0003 §5's per-start - * admin secret) had zero test coverage of its own -- everything that exercises the daemon's - * credential handshake in `server.test.ts` goes through a stubbed `resolveRole`, so none of it - * ever calls `persist()` or `verify()` for real. - */ describe("AdminSecretManager", () => { function secrets(): CryptoTokenSecrets { return new CryptoTokenSecrets(); @@ -31,14 +25,7 @@ describe("AdminSecretManager", () => { expect(stat.mode).toBe(0o600); }); - // ADR §5: "owner-only permissions set at creation" -- not a later `chmod`. `Filesystem` (see - // `ports/filesystem.ts`) has no `chmod` method at all, only `writeFileAtomic(path, contents, - // {mode})`, so the interface itself rules out a two-step "write, then chmod" implementation -- - // this asserts `persist()` actually uses that option rather than, say, calling - // `writeFileAtomic` without `mode` and relying on the process umask to happen to land on - // 0600. Spying on the raw `Filesystem` call (rather than reading the mode back through - // `MemoryFilesystem#stat`, which the test above already does) proves the *call site* passes - // the option, not just that `MemoryFilesystem` happens to record whatever mode was implied. + // why: spying on the raw call proves the call site passes `mode`, not that MemoryFilesystem happens to record one. it("passes mode 0600 to writeFileAtomic itself, at the single call persist() makes", async () => { const calls: Array<{ readonly path: string; readonly mode: number | undefined }> = []; const filesystem: Filesystem = { @@ -102,12 +89,7 @@ describe("AdminSecretManager", () => { expect(manager.verify("")).toBe(false); }); - // ADR §5: "`verify()` never touches the filesystem or reconstructs the secret; it only ever - // compares hashes" -- and `session.ts`'s doc on the real credential handshake depends on this: - // "`hello` verifies against memory, so a credential can be checked before the file lands and - // before convergence." A `Filesystem` whose every method throws proves `verify()` truly never - // calls any of them, for a correct candidate, a wrong one, and before `persist()` has ever - // run. + // why: a Filesystem whose every method throws proves verify() never calls one, before persist() has run. it("verify() never touches the filesystem, even before persist() has ever run", () => { const throwingFilesystem: Filesystem = { readFile: () => { @@ -163,9 +145,7 @@ describe("AdminSecretManager", () => { }, }; const realSecrets = secrets(); - // Constructing `AdminSecretManager` calls `secrets.generateSecret()`/`secrets.hash(...)` - // once (see its constructor) -- capture the plaintext it generated to verify against, the - // only way to get a real candidate without ever calling `persist()`. + // why: the constructor generates the secret, so capturing it is the only way to get a real candidate without persist(). let generated = ""; const spySecrets: CryptoTokenSecrets = { ...realSecrets, @@ -181,8 +161,6 @@ describe("AdminSecretManager", () => { secrets: spySecrets, }); - // None of these touch `throwingFilesystem` -- if they did, the test would already have - // thrown before reaching these assertions. expect(manager.verify(generated)).toBe(true); expect(manager.verify("wrong")).toBe(false); }); @@ -242,9 +220,7 @@ describe("AdminSecretManager", () => { }, }; - // Constructing an `AdminSecretManager` -- e.g. a daemon that loses the start race and never - // calls `persist()` at all (ADR §5, `admin-secret.ts`'s class doc) -- must not touch the - // real file. Nothing here throws. + // why: a daemon that loses the start race constructs the manager and never persists, so construction must not touch the real file. expect( () => new AdminSecretManager({ diff --git a/src/auth/admin-secret.ts b/src/auth/admin-secret.ts new file mode 100644 index 000000000..6eda2c6bc --- /dev/null +++ b/src/auth/admin-secret.ts @@ -0,0 +1,43 @@ +import type { Filesystem, TokenSecrets } from "../ports/index.js"; + +// why: the real trust boundary is the same OS user, so owner-only (0600) protects against another user, not a hostile process running as this one. +const ADMIN_SECRET_FILE_MODE = 0o600; + +export interface AdminSecretManagerOptions { + readonly filesystem: Filesystem; + readonly secrets: TokenSecrets; + + readonly path: string; +} + +export class AdminSecretManager { + readonly #filesystem: Filesystem; + readonly #secrets: TokenSecrets; + readonly #path: string; + readonly #secret: string; + readonly #hash: string; + + constructor(options: AdminSecretManagerOptions) { + this.#filesystem = options.filesystem; + this.#secrets = options.secrets; + this.#path = options.path; + this.#secret = options.secrets.generateSecret(); + this.#hash = this.#secrets.hash(this.#secret); + } + + // why: call this only after the socket claim has succeeded, so a daemon that loses the start race never touches the winner's file. + async persist(): Promise { + await this.#filesystem.writeFileAtomic(this.#path, `${this.#secret}\n`, { + mode: ADMIN_SECRET_FILE_MODE, + }); + } + + async remove(): Promise { + await this.#filesystem.rm(this.#path); + } + + // why: both sides are fixed-length hex digests, so a plain `===` is no more timing-leaky than the hash comparison in `TokenStore#verify`. + verify(candidate: string): boolean { + return this.#secrets.hash(candidate) === this.#hash; + } +} diff --git a/src/auth/auth.test.ts b/src/auth/auth.test.ts new file mode 100644 index 000000000..3ea2dffcd --- /dev/null +++ b/src/auth/auth.test.ts @@ -0,0 +1,291 @@ +import { describe, expect, it } from "vitest"; + +import { OPERATIONS } from "../contract/index.js"; +import { FakeClock, MemoryFilesystem, NoopLogger, type TokenSecrets } from "../ports/index.js"; +import { AdminAuthenticationFailedError, AuthError, createAuth, type TokenRole } from "./index.js"; +import { TokenStoreError } from "./token-store.js"; +import { authStrategies } from "./strategies/index.js"; +import type { AuthConfig, AuthStrategyDefinition, StrategyAnswer } from "./strategy.js"; +import { createAuthWith } from "./testing.js"; + +const dataDirectory = "/home/agent/.simlock"; +const config: AuthConfig = { enabled: true, host: "127.0.0.1", port: 4700 }; + +class FakeTokenSecrets implements TokenSecrets { + #next = 0; + + generateSecret(): string { + this.#next += 1; + return `slk_generated-${this.#next}`; + } + + hash(secret: string): string { + return `hash:${secret}`; + } +} + +interface SeedToken { + readonly id: string; + readonly secret: string; + readonly role: TokenRole; + readonly label?: string; +} + +const seeds: readonly SeedToken[] = [ + { id: "tok_agent", secret: "slk_agent", role: "agent", label: "ci-runner" }, + { id: "tok_bare", secret: "slk_bare", role: "agent" }, + { id: "tok_operator", secret: "slk_operator", role: "operator", label: "ops" }, + { id: "tok_worker", secret: "slk_worker", role: "worker", label: "mac-mini" }, +]; + +async function options() { + const filesystem = new MemoryFilesystem(); + const secrets = new FakeTokenSecrets(); + await filesystem.mkdirp(dataDirectory); + await filesystem.writeFileAtomic( + `${dataDirectory}/tokens.json`, + JSON.stringify( + seeds.map(({ id, secret, role, label }) => ({ + id, + hash: secrets.hash(secret), + role, + ...(label === undefined ? {} : { label }), + createdAt: 1, + })), + ), + { mode: 0o600 }, + ); + return { + config, + dataDirectory, + filesystem, + secrets, + idGenerator: { generate: () => "id" }, + clock: new FakeClock(1_000), + logger: new NoopLogger(), + }; +} + +function headers(authorization?: string): Headers { + return new Headers(authorization === undefined ? {} : { authorization }); +} + +describe("authenticateRequest with the token strategy", () => { + it.each([ + { authorization: undefined, status: 401, message: "Missing bearer token" }, + { authorization: "Basic x", status: 401, message: "Missing bearer token" }, + { authorization: "Bearer ", status: 401, message: "Missing bearer token" }, + { authorization: "bearer slk_agent", status: 401, message: "Missing bearer token" }, + { authorization: "Bearer slk_unknown", status: 401, message: "Unknown bearer token" }, + { authorization: "Bearer abc", status: 401, message: "Unknown bearer token" }, + { + authorization: "Bearer slk_worker", + status: 403, + message: "A worker join token can only open an uplink, not call the HTTP API", + }, + ])("answers $status $message for Authorization $authorization", async (row) => { + const auth = createAuth(await options()); + + const refusal = await auth.authenticateRequest(headers(row.authorization)).then( + () => undefined, + (error: unknown) => error, + ); + + expect(refusal).toBeInstanceOf(AuthError); + expect(refusal).toMatchObject({ status: row.status, message: row.message }); + expect((refusal as AuthError).details).toBeUndefined(); + }); + + it("trims the bearer value before reading it, as the HTTP check does today", async () => { + const auth = createAuth(await options()); + + await expect(auth.authenticateRequest(headers("Bearer slk_agent "))).resolves.toMatchObject({ + principal: "tok_agent", + }); + await expect(auth.authenticateRequest(headers("Bearer "))).rejects.toMatchObject({ + message: "Missing bearer token", + }); + }); + + it("identifies a known slk_ token with its id as principal, its label as name, its role, via token, not ambient", async () => { + const auth = createAuth(await options()); + + await expect(auth.authenticateRequest(headers("Bearer slk_agent"))).resolves.toEqual({ + principal: "tok_agent", + name: "ci-runner", + role: "agent", + via: "token", + ambient: false, + }); + await expect(auth.authenticateRequest(headers("Bearer slk_bare"))).resolves.toMatchObject({ + principal: "tok_bare", + name: "tok_bare", + }); + await expect(auth.authenticateRequest(headers("Bearer slk_operator"))).resolves.toMatchObject({ + principal: "tok_operator", + role: "operator", + }); + }); +}); + +describe("authenticateRequest over several strategies", () => { + const identity = { + principal: "p", + name: "n", + role: "agent", + via: "second", + ambient: false, + } as const; + + function fake( + name: string, + answer: StrategyAnswer, + asked: string[], + enabled = true, + ): AuthStrategyDefinition { + return { + name, + enabled: () => enabled, + create: () => ({ + authenticate: async () => { + asked.push(name); + return answer; + }, + }), + }; + } + + it("lets the second strategy identify when the first answers not-mine", async () => { + const asked: string[] = []; + const auth = createAuthWith( + [ + fake("first", { kind: "not-mine", sawCredential: false }, asked), + fake("second", { kind: "identified", identity }, asked), + ], + await options(), + ); + + await expect(auth.authenticateRequest(headers("Bearer x"))).resolves.toEqual(identity); + expect(asked).toEqual(["first", "second"]); + }); + + it("stops at a rejected answer, never asks the second, and uses its message and details", async () => { + const asked: string[] = []; + const auth = createAuthWith( + [ + fake("first", { kind: "rejected", message: "Token expired", details: { at: 5 } }, asked), + fake("second", { kind: "identified", identity }, asked), + ], + await options(), + ); + + await expect(auth.authenticateRequest(headers("Bearer x"))).rejects.toMatchObject({ + status: 401, + message: "Token expired", + details: { at: 5 }, + }); + expect(asked).toEqual(["first"]); + }); + + it("stops at a forbidden answer, never asks the second, and uses its message", async () => { + const asked: string[] = []; + const auth = createAuthWith( + [ + fake("first", { kind: "forbidden", message: "No authority" }, asked), + fake("second", { kind: "identified", identity }, asked), + ], + await options(), + ); + + await expect(auth.authenticateRequest(headers("Bearer x"))).rejects.toMatchObject({ + status: 403, + message: "No authority", + }); + expect(asked).toEqual(["first"]); + }); + + it("never asks a definition whose enabled(config) is false", async () => { + const asked: string[] = []; + const auth = createAuthWith( + [ + fake( + "first", + { kind: "identified", identity: { ...identity, via: "first" } }, + asked, + false, + ), + fake("second", { kind: "identified", identity }, asked), + ], + await options(), + ); + + await expect(auth.authenticateRequest(headers("Bearer x"))).resolves.toEqual(identity); + expect(asked).toEqual(["second"]); + }); +}); + +describe("the registry", () => { + it("has a contract schema under configSchema.http for every definition that owns a config key", () => { + const contractHttp = OPERATIONS["config.get"].output.shape.http.shape as Record< + string, + { safeParse(value: unknown): { success: boolean; data?: unknown } } | undefined + >; + const owning = authStrategies.flatMap((definition) => + definition.config === undefined ? [] : [definition.config], + ); + + expect(authStrategies.map((definition) => definition.name)).toEqual(["token"]); + for (const { key, schema, defaults } of owning) { + const mirrored = contractHttp[key]; + expect(mirrored, key).toBeDefined(); + expect(mirrored?.safeParse(defaults)).toEqual(schema.safeParse(defaults)); + } + }); +}); + +describe("resolveHelloRole", () => { + it("resolves agent with no credential, admin for an operator token and for the admin secret, and refuses anything else", async () => { + const opts = await options(); + const auth = createAuth(opts); + await auth.adminSecret.persist(); + const adminSecret = (await opts.filesystem.readFile(`${dataDirectory}/admin.token`)).trim(); + + await expect(auth.resolveHelloRole({})).resolves.toBe("agent"); + await expect(auth.resolveHelloRole({ principal: "someone" })).resolves.toBe("agent"); + await expect(auth.resolveHelloRole({ credential: "slk_operator" })).resolves.toBe("admin"); + await expect(auth.resolveHelloRole({ credential: adminSecret })).resolves.toBe("admin"); + await expect(auth.resolveHelloRole({ credential: "slk_agent" })).rejects.toThrow( + AdminAuthenticationFailedError, + ); + await expect(auth.resolveHelloRole({ credential: "not-a-secret" })).rejects.toThrow( + AdminAuthenticationFailedError, + ); + }); + + it("checks the token store before the admin secret, so a corrupt store fails loudly even for the admin secret", async () => { + const opts = await options(); + const auth = createAuth(opts); + await auth.adminSecret.persist(); + const adminSecret = (await opts.filesystem.readFile(`${dataDirectory}/admin.token`)).trim(); + await opts.filesystem.writeFileAtomic(`${dataDirectory}/tokens.json`, "{ not valid json"); + + await expect(auth.resolveHelloRole({ credential: adminSecret })).rejects.toThrow( + TokenStoreError, + ); + }); +}); + +describe("authenticateUplink", () => { + it("answers unauthenticated for none and unknown, forbidden for a token that is not a worker's, accept with the token id for a worker token", async () => { + const auth = createAuth(await options()); + + await expect(auth.authenticateUplink(undefined)).resolves.toBe("unauthenticated"); + await expect(auth.authenticateUplink("slk_unknown")).resolves.toBe("unauthenticated"); + await expect(auth.authenticateUplink("slk_operator")).resolves.toBe("forbidden"); + await expect(auth.authenticateUplink("slk_agent")).resolves.toBe("forbidden"); + await expect(auth.authenticateUplink("slk_worker")).resolves.toEqual({ + outcome: "accept", + tokenId: "tok_worker", + }); + }); +}); diff --git a/src/auth/hello.test.ts b/src/auth/hello.test.ts new file mode 100644 index 000000000..3c0724d46 --- /dev/null +++ b/src/auth/hello.test.ts @@ -0,0 +1,12 @@ +import { describe, expect, it } from "vitest"; + +import { resolveAgentRole } from "./hello.js"; + +describe("resolveAgentRole", () => { + it("resolves agent unconditionally, regardless of what hello sends", () => { + expect(resolveAgentRole.resolve({})).toBe("agent"); + expect(resolveAgentRole.resolve({ credential: "anything", principal: "someone" })).toBe( + "agent", + ); + }); +}); diff --git a/src/auth/hello.ts b/src/auth/hello.ts new file mode 100644 index 000000000..2a026337b --- /dev/null +++ b/src/auth/hello.ts @@ -0,0 +1,19 @@ +import type { Role } from "../contract/index.js"; + +export interface SessionRoleResolver { + resolve(hello: { + readonly principal?: string; + readonly credential?: string; + }): Promise | Role; +} + +export const resolveAgentRole: SessionRoleResolver = { + resolve: () => "agent", +}; + +export class AdminAuthenticationFailedError extends Error { + constructor() { + super("Invalid admin credential"); + this.name = "AdminAuthenticationFailedError"; + } +} diff --git a/src/auth/identity.ts b/src/auth/identity.ts new file mode 100644 index 000000000..f3a685c3b --- /dev/null +++ b/src/auth/identity.ts @@ -0,0 +1,9 @@ +export interface Identity { + readonly principal: string; + readonly name: string; + readonly role: "operator" | "agent"; + readonly via: string; + readonly expiresAt?: number; + readonly ambient: boolean; + readonly signOutUrl?: string; +} diff --git a/src/auth/index.ts b/src/auth/index.ts new file mode 100644 index 000000000..856e9fe8e --- /dev/null +++ b/src/auth/index.ts @@ -0,0 +1,113 @@ +import { join } from "node:path"; + +import type { Clock, Filesystem, IdGenerator, Logger, TokenSecrets } from "../ports/index.js"; +import type { Role } from "../contract/index.js"; +import type { Identity } from "./identity.js"; +import { AuthError, type AuthConfig, type AuthStrategyDefinition } from "./strategy.js"; +import { authStrategies } from "./strategies/index.js"; +import { AdminSecretManager } from "./admin-secret.js"; +import { AdminAuthenticationFailedError } from "./hello.js"; +import { TokenStore } from "./token-store.js"; +import type { TokenOperations } from "./tokens.js"; + +export { AuthError } from "./strategy.js"; +export type { AuthConfig, AuthStrategyDefinition, StrategyAnswer } from "./strategy.js"; +export type { Identity } from "./identity.js"; +export type { TokenOperations, TokenRole } from "./tokens.js"; +export { authStrategies }; +export { AdminAuthenticationFailedError, resolveAgentRole } from "./hello.js"; +export type { SessionRoleResolver } from "./hello.js"; + +export interface AuthOptions { + readonly config: AuthConfig; + readonly dataDirectory: string; + readonly filesystem: Filesystem; + readonly secrets: TokenSecrets; + readonly idGenerator: IdGenerator; + readonly clock: Clock; + readonly logger: Logger; +} + +export type UplinkAnswer = + | "unauthenticated" + | "forbidden" + | { readonly outcome: "accept"; readonly tokenId: string }; + +export interface Auth { + authenticateRequest(headers: Headers): Promise; + resolveHelloRole(hello: { + readonly principal?: string; + readonly credential?: string; + }): Promise; + authenticateUplink(credential: string | undefined): Promise; + readonly tokens: TokenOperations; + readonly adminSecret: { persist(): Promise; remove(): Promise }; +} + +export function createAuthFrom( + definitions: readonly AuthStrategyDefinition[], + options: AuthOptions, +): Auth { + const store = new TokenStore({ + clock: options.clock, + filesystem: options.filesystem, + idGenerator: options.idGenerator, + path: join(options.dataDirectory, "tokens.json"), + secrets: options.secrets, + }); + const adminSecret = new AdminSecretManager({ + filesystem: options.filesystem, + secrets: options.secrets, + path: join(options.dataDirectory, "admin.token"), + }); + const strategies = definitions + .filter((definition) => definition.enabled(options.config)) + .map((definition) => + definition.create({ + config: options.config, + tokens: store, + clock: options.clock, + logger: options.logger, + }), + ); + + return { + authenticateRequest: async (headers) => { + let sawCredential = false; + for (const strategy of strategies) { + const answer = await strategy.authenticate({ headers }); + if (answer.kind === "identified") return answer.identity; + if (answer.kind === "rejected") throw new AuthError(401, answer.message, answer.details); + if (answer.kind === "forbidden") throw new AuthError(403, answer.message); + sawCredential ||= answer.sawCredential; + } + throw new AuthError(401, sawCredential ? "Unknown bearer token" : "Missing bearer token"); + }, + resolveHelloRole: async (hello) => { + if (hello.credential === undefined) return "agent"; + if ((await store.verify(hello.credential))?.role === "operator") return "admin"; + if (adminSecret.verify(hello.credential)) return "admin"; + throw new AdminAuthenticationFailedError(); + }, + authenticateUplink: async (credential) => { + if (credential === undefined) return "unauthenticated"; + const record = await store.verify(credential); + if (record === undefined) return "unauthenticated"; + if (record.role !== "worker") return "forbidden"; + return { outcome: "accept", tokenId: record.id }; + }, + tokens: { + create: (role, label) => store.create(role, label), + list: () => store.list(), + revoke: (id) => store.revoke(id), + }, + adminSecret: { + persist: () => adminSecret.persist(), + remove: () => adminSecret.remove(), + }, + }; +} + +export function createAuth(options: AuthOptions): Auth { + return createAuthFrom(authStrategies, options); +} diff --git a/src/auth/strategies/conformance.test.ts b/src/auth/strategies/conformance.test.ts new file mode 100644 index 000000000..4c4b395d1 --- /dev/null +++ b/src/auth/strategies/conformance.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it } from "vitest"; + +import { authStrategies } from "./index.js"; +import { tokenFixture } from "./token/testing.js"; + +interface Fixture { + readonly deps: typeof tokenFixture.deps; + readonly goodRequest: typeof tokenFixture.goodRequest; +} + +const fixtures: Record = { token: tokenFixture }; + +describe.each(authStrategies.map((definition) => ({ definition })))( + "the $definition.name strategy", + ({ definition }) => { + const fixture = fixtures[definition.name]; + + it("answers not-mine with no credential of its kind", async () => { + const strategy = definition.create(fixture!.deps()); + + for (const authorization of [undefined, "Basic x"]) { + const headers = new Headers(authorization === undefined ? {} : { authorization }); + await expect(strategy.authenticate({ headers })).resolves.toMatchObject({ + kind: "not-mine", + }); + } + }); + + it("identifies its good request with a principal, a name and via equal to its name", async () => { + const strategy = definition.create(fixture!.deps()); + + const answer = await strategy.authenticate(fixture!.goodRequest()); + + expect(answer.kind).toBe("identified"); + if (answer.kind !== "identified") return; + expect(answer.identity.principal).toEqual(expect.any(String)); + expect(answer.identity.principal).not.toBe(""); + expect(answer.identity.name).toEqual(expect.any(String)); + expect(answer.identity.name).not.toBe(""); + expect(answer.identity.via).toBe(definition.name); + }); + }, +); diff --git a/src/auth/strategies/index.ts b/src/auth/strategies/index.ts new file mode 100644 index 000000000..3c63bdcda --- /dev/null +++ b/src/auth/strategies/index.ts @@ -0,0 +1,4 @@ +import type { AuthStrategyDefinition } from "../strategy.js"; +import { tokenStrategy } from "./token/index.js"; + +export const authStrategies: readonly AuthStrategyDefinition[] = [tokenStrategy]; diff --git a/src/auth/strategies/token/index.ts b/src/auth/strategies/token/index.ts new file mode 100644 index 000000000..27c286247 --- /dev/null +++ b/src/auth/strategies/token/index.ts @@ -0,0 +1,40 @@ +import type { AuthStrategyDefinition } from "../../strategy.js"; + +const BEARER_PREFIX = "Bearer "; +const TOKEN_PREFIX = "slk_"; + +const WORKER_TOKEN_REFUSAL = "A worker join token can only open an uplink, not call the HTTP API"; + +function bearerValue(header: string | null): string { + if (header === null || !header.startsWith(BEARER_PREFIX)) return ""; + return header.slice(BEARER_PREFIX.length).trim(); +} + +export const tokenStrategy: AuthStrategyDefinition = { + name: "token", + enabled: () => true, + create: (deps) => ({ + authenticate: async ({ headers }) => { + const secret = bearerValue(headers.get("authorization")); + if (!secret.startsWith(TOKEN_PREFIX)) { + return { kind: "not-mine", sawCredential: secret !== "" }; + } + + const record = await deps.tokens.verify(secret); + if (record === undefined) return { kind: "rejected", message: "Unknown bearer token" }; + // why: 403, not 401 -- the token is real and recognized, it just has no authority here (ADR 0005 §25). + if (record.role === "worker") return { kind: "forbidden", message: WORKER_TOKEN_REFUSAL }; + + return { + kind: "identified", + identity: { + principal: record.id, + name: record.label ?? record.id, + role: record.role, + via: "token", + ambient: false, + }, + }; + }, + }), +}; diff --git a/src/auth/strategies/token/testing.ts b/src/auth/strategies/token/testing.ts new file mode 100644 index 000000000..913dbeefd --- /dev/null +++ b/src/auth/strategies/token/testing.ts @@ -0,0 +1,28 @@ +import { FakeClock, NoopLogger } from "../../../ports/index.js"; +import type { AuthConfig, AuthDeps } from "../../strategy.js"; +import type { TokenRecord } from "../../tokens.js"; + +const record: TokenRecord = { + id: "tok_good", + hash: "unused", + role: "agent", + label: "ci", + createdAt: 1, +}; + +const config: AuthConfig = { enabled: true, host: "127.0.0.1", port: 4700 }; + +export const tokenFixture = { + config, + deps(): AuthDeps { + return { + config, + tokens: { verify: async (secret) => (secret === "slk_good" ? record : undefined) }, + clock: new FakeClock(1_000), + logger: new NoopLogger(), + }; + }, + goodRequest(): { headers: Headers } { + return { headers: new Headers({ authorization: "Bearer slk_good" }) }; + }, +}; diff --git a/src/auth/strategy.ts b/src/auth/strategy.ts new file mode 100644 index 000000000..ec0bbc3cc --- /dev/null +++ b/src/auth/strategy.ts @@ -0,0 +1,51 @@ +import type { z } from "zod"; + +import type { OPERATIONS } from "../contract/index.js"; +import type { Clock, Logger } from "../ports/index.js"; +import type { Identity } from "./identity.js"; +import type { TokenRecord } from "./tokens.js"; + +export type AuthConfig = z.infer<(typeof OPERATIONS)["config.get"]["output"]>["http"]; + +export interface AuthRequest { + readonly headers: Headers; +} + +export type StrategyAnswer = + | { readonly kind: "identified"; readonly identity: Identity } + | { readonly kind: "not-mine"; readonly sawCredential: boolean } + | { readonly kind: "rejected"; readonly message: string; readonly details?: unknown } + | { readonly kind: "forbidden"; readonly message: string }; + +export interface AuthStrategy { + authenticate(request: AuthRequest): Promise; +} + +export interface AuthDeps { + readonly config: AuthConfig; + readonly tokens: { verify(secret: string): Promise }; + readonly clock: Clock; + readonly logger: Logger; +} + +export interface AuthStrategyDefinition { + readonly name: string; + readonly config?: { + readonly key: string; + readonly schema: z.ZodType; + readonly defaults: unknown; + }; + enabled(config: AuthConfig): boolean; + create(deps: AuthDeps): AuthStrategy; +} + +export class AuthError extends Error { + constructor( + readonly status: 401 | 403, + message: string, + readonly details?: unknown, + ) { + super(message); + this.name = "AuthError"; + } +} diff --git a/src/auth/testing.ts b/src/auth/testing.ts new file mode 100644 index 000000000..e578a86bf --- /dev/null +++ b/src/auth/testing.ts @@ -0,0 +1,34 @@ +import { type Auth, type AuthOptions, createAuthFrom } from "./index.js"; +import type { Identity } from "./identity.js"; +import { AuthError, type AuthStrategyDefinition } from "./strategy.js"; + +export function createAuthWith( + definitions: readonly AuthStrategyDefinition[], + options: AuthOptions, +): Auth { + return createAuthFrom(definitions, options); +} + +export function fakeAuth(identities: ReadonlyMap): Auth { + const unused = async (): Promise => { + throw new Error("fakeAuth only authenticates requests"); + }; + return { + authenticateRequest: async (headers) => { + const value = headers.get("authorization"); + const secret = value?.startsWith("Bearer ") ? value.slice(7).trim() : ""; + if (secret === "") throw new AuthError(401, "Missing bearer token"); + const identity = identities.get(secret); + if (identity === undefined) throw new AuthError(401, "Unknown bearer token"); + return identity; + }, + resolveHelloRole: unused, + authenticateUplink: unused, + tokens: { create: unused, list: unused, revoke: unused }, + adminSecret: { persist: unused, remove: unused }, + }; +} + +export function tokenIdentity(principal: string, role: Identity["role"] = "agent"): Identity { + return { principal, name: principal, role, via: "token", ambient: false }; +} diff --git a/src/http/token-store.test.ts b/src/auth/token-store.test.ts similarity index 94% rename from src/http/token-store.test.ts rename to src/auth/token-store.test.ts index 6c42b478b..8ef3fbbcf 100644 --- a/src/http/token-store.test.ts +++ b/src/auth/token-store.test.ts @@ -106,7 +106,7 @@ describe("TokenStore", () => { expect(persisted).toHaveLength(2); expect(persisted).toEqual(expect.arrayContaining(created.map(({ record }) => record))); await expect(Promise.all(created.map(({ secret }) => store.verify(secret)))).resolves.toEqual( - created.map(({ record }) => ({ requesterId: record.id, role: record.role })), + created.map(({ record }) => record), ); }); @@ -125,10 +125,7 @@ describe("TokenStore", () => { expect(revoked).toBe(true); expect(JSON.parse(await filesystem.readFile(tokensPath))).toEqual([created.record]); await expect(store.verify(existing.secret)).resolves.toBeUndefined(); - await expect(store.verify(created.secret)).resolves.toEqual({ - requesterId: created.record.id, - role: "operator", - }); + await expect(store.verify(created.secret)).resolves.toEqual(created.record); }, ); @@ -165,10 +162,7 @@ describe("TokenStore", () => { existing.record, created.record, ]); - await expect(store.verify(created.secret)).resolves.toEqual({ - requesterId: created.record.id, - role: "operator", - }); + await expect(store.verify(created.secret)).resolves.toEqual(created.record); }, ); @@ -176,10 +170,7 @@ describe("TokenStore", () => { const { store } = tokenStore(); const { record, secret } = await store.create("operator", "root"); - await expect(store.verify(secret)).resolves.toEqual({ - requesterId: record.id, - role: "operator", - }); + await expect(store.verify(secret)).resolves.toEqual(record); await expect(store.verify("slk_not-a-real-secret")).resolves.toBeUndefined(); }); @@ -192,8 +183,8 @@ describe("TokenStore", () => { await expect(reader.verify("slk_fake-secret-1")).resolves.toBeUndefined(); const { secret } = await writer.create("agent"); - await expect(reader.verify(secret)).resolves.toEqual({ - requesterId: "tok_writer-id", + await expect(reader.verify(secret)).resolves.toMatchObject({ + id: "tok_writer-id", role: "agent", }); }); diff --git a/src/http/token-store.ts b/src/auth/token-store.ts similarity index 64% rename from src/http/token-store.ts rename to src/auth/token-store.ts index ecfcf130d..1c50ebc7f 100644 --- a/src/http/token-store.ts +++ b/src/auth/token-store.ts @@ -1,36 +1,10 @@ import { dirname } from "node:path"; import type { Clock, Filesystem, IdGenerator, TokenSecrets } from "../ports/index.js"; +import type { TokenRecord, TokenRole } from "./tokens.js"; -/** - * ADR 0003 §5 (`agent`, `operator`) plus ADR 0005 §8/§25's `worker`: a *join token*, minted on - * a gateway with `simlock token create --role worker` and presented by a worker when it opens - * its uplink. It authorizes exactly one thing -- opening an uplink -- and nothing else: the - * HTTP bearer adapter answers `403` for a `worker` token on any `/v1` route (`auth.ts`), and - * it resolves to no daemon session role at all. Revoking it closes the uplink (ADR 0005 §8): - * `GatewayDispatcher#tokenRevoke` closes every link the revoked token authenticated - * (`GatewayService#closeLinksForToken`), so the effect is immediate rather than waiting on that - * worker's next reconnect. - */ -export type TokenRole = "agent" | "operator" | "worker"; - -/** The same three values as a list, for `isTokenRole`'s membership check -- one branch there - * instead of one per role. Module-private: `TokenRole` is the exported vocabulary. */ const TOKEN_ROLES: readonly TokenRole[] = ["agent", "operator", "worker"]; -export interface TokenRecord { - readonly id: string; - readonly hash: string; - readonly role: TokenRole; - readonly label?: string; - readonly createdAt: number; -} - -export interface TokenIdentity { - readonly requesterId: string; - readonly role: TokenRole; -} - export interface TokenStoreOptions { readonly filesystem: Filesystem; readonly clock: Clock; @@ -62,7 +36,6 @@ export class TokenStore { this.#path = options.path; } - // fallow-ignore-next-line unused-class-member -- called by `Dispatcher`'s `token.create` handler through `#requireTokens()`'s return value (src/daemon/dispatcher.ts); the audit does not follow a member access on a method's result. async create(role: TokenRole, label?: string): Promise<{ record: TokenRecord; secret: string }> { return this.#mutate(async () => { const secret = this.#secrets.generateSecret(); @@ -86,7 +59,6 @@ export class TokenStore { return this.#readAll(); } - // fallow-ignore-next-line unused-class-member -- same as `create` above: reached through `#requireTokens()`'s return value. async revoke(id: string): Promise { return this.#mutate(async () => { const records = await this.#readAll(); @@ -99,18 +71,10 @@ export class TokenStore { }); } - /** - * Re-reads tokens.json on every call instead of caching in memory, so a - * `simlock token create`/`revoke` run from another process takes effect - * immediately for a long-running process (the daemon) verifying bearer - * tokens -- there is no in-process invalidation path otherwise. - */ - async verify(secret: string): Promise { + // why: re-reading on every call is what lets a `token create`/`revoke` from another process take effect in the long-running daemon, which has no invalidation path. + async verify(secret: string): Promise { const hash = this.#secrets.hash(secret); - const record = (await this.#readAll()).find((candidate) => candidate.hash === hash); - if (record === undefined) return undefined; - - return { requesterId: record.id, role: record.role }; + return (await this.#readAll()).find((candidate) => candidate.hash === hash); } #mutate(operation: () => Promise): Promise { diff --git a/src/auth/tokens.ts b/src/auth/tokens.ts new file mode 100644 index 000000000..d8021569e --- /dev/null +++ b/src/auth/tokens.ts @@ -0,0 +1,15 @@ +export type TokenRole = "agent" | "operator" | "worker"; + +export interface TokenRecord { + readonly id: string; + readonly hash: string; + readonly role: TokenRole; + readonly label?: string; + readonly createdAt: number; +} + +export interface TokenOperations { + create(role: TokenRole, label?: string): Promise<{ record: TokenRecord; secret: string }>; + list(): Promise; + revoke(id: string): Promise; +} diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index ef0852d09..134d270b1 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1,7 +1,7 @@ import { EventEmitter } from "node:events"; import { mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; import { Readable } from "node:stream"; import { afterEach, describe, expect, it, vi } from "vitest"; @@ -20,15 +20,14 @@ import { MemoryIpcTransport, NodeFilesystem, NodeIpcTransport, + NoopLogger, type Filesystem, type IdGenerator, } from "../ports/index.js"; import { FakeSystemStats } from "../ports/index.js"; -import { TokenStore } from "../http/token-store.js"; +import { type Auth, createAuth } from "../auth/index.js"; import { DaemonEndpointHost } from "../daemon/connection-host.js"; import { DaemonServer } from "../daemon/server.js"; -import { AdminSecretManager } from "../daemon/admin-secret.js"; -import { createCredentialRoleResolver } from "../daemon/session.js"; import { fromWireError, SimlockError, @@ -6461,11 +6460,13 @@ async function startTestDaemon(): Promise<{ socketPath: string; daemon: DaemonSe filesystem, registry, }); - const tokens = new TokenStore({ + const auth = createAuth({ clock, + config: { enabled: false, host: "127.0.0.1", port: 4700 }, + dataDirectory: "/", filesystem, idGenerator: sequence(), - path: "/tokens.json", + logger: new NoopLogger(), secrets: new CryptoTokenSecrets(), }); const daemon = new DaemonServer({ @@ -6492,7 +6493,7 @@ async function startTestDaemon(): Promise<{ socketPath: string; daemon: DaemonSe reaper, registry, resolveRole: { resolve: () => "admin" }, - tokens, + tokens: auth.tokens, version: "test", }); runningDaemons.push(daemon); @@ -6522,7 +6523,7 @@ function realCliEnvironmentPorts( /** * why: A real `DaemonServer` wired against in-memory ports (`MemoryFilesystem` + `MemoryIpcTransport` * shared with the CLI environment under test), with the genuine credential handshake - * (`AdminSecretManager` + `createCredentialRoleResolver`) instead of `startTestDaemon`'s + * (`createAuth`) instead of `startTestDaemon`'s * `resolveRole: { resolve: () => "admin" }` shortcut -- B1 and B2 both hinge on that handshake * actually running. */ @@ -6531,7 +6532,7 @@ async function startInMemoryDaemon(options: { readonly ipcTransport: MemoryIpcTransport; readonly socketPath: string; readonly adminTokenPath: string; -}): Promise<{ daemon: DaemonServer; adminSecret: AdminSecretManager }> { +}): Promise<{ daemon: DaemonServer; adminSecret: Auth["adminSecret"] }> { const { adminTokenPath, filesystem, ipcTransport, socketPath } = options; const clock = new FakeClock(1_000); const eventBus = new EventBus(clock); @@ -6571,24 +6572,17 @@ async function startInMemoryDaemon(options: { filesystem, registry, }); - const tokens = new TokenStore({ + const auth = createAuth({ clock, + config: { enabled: false, host: "127.0.0.1", port: 4700 }, + dataDirectory: dirname(adminTokenPath), filesystem, idGenerator: sequence(), - path: "/tokens.json", + logger: new NoopLogger(), secrets: new CryptoTokenSecrets(), }); - const adminSecret = new AdminSecretManager({ - filesystem, - secrets: new CryptoTokenSecrets(), - path: adminTokenPath, - }); - const resolveRole = createCredentialRoleResolver({ - verifyOperatorToken: async (secret) => (await tokens.verify(secret))?.role === "operator", - verifyAdminSecret: (secret) => adminSecret.verify(secret), - }); const daemon = new DaemonServer({ - adminSecret, + adminSecret: auth.adminSecret, capacity: engine, warmPool: engine, deviceModes: engine, @@ -6611,13 +6605,13 @@ async function startInMemoryDaemon(options: { queue: engine, reaper, registry, - resolveRole, - tokens, + resolveRole: { resolve: (hello) => auth.resolveHelloRole(hello) }, + tokens: auth.tokens, version: "test", }); runningDaemons.push(daemon); await daemon.start(); - return { daemon, adminSecret }; + return { daemon, adminSecret: auth.adminSecret }; } function testConfig(): Config { diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index 0089a0dd3..fda39b2d9 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -1111,7 +1111,7 @@ export const configSchema = z.object({ // ---- tokens ----------------------------------------------------------------------------------- /** - * `TokenRole` (agent/operator/worker token store roles, src/http/token-store.ts) is a + * `TokenRole` (agent/operator/worker token store roles, src/auth/tokens.ts) is a * deliberately different vocabulary from the daemon session `Role` (agent/admin, see * `roles.ts`) -- a `token.create --role operator` mints a credential that *resolves to* the * admin session role at `hello` (ADR 0003 §5), it is not itself that role. Keeping the two diff --git a/src/core/AGENTS.md b/src/core/AGENTS.md index 7be861834..5bb6073bc 100644 --- a/src/core/AGENTS.md +++ b/src/core/AGENTS.md @@ -2,7 +2,7 @@ Does: device management on a worker — registry, state machine, device verbs, reclaim, quarantine, warm pool, capacity, cleanup, components, doctor. Entry: `index.ts` → `createCore(options)`, then `core.connect(ports)` once, before any request. -Uses: bus, ports, contract, history (`usage/` only). Never imports: leasing, drivers, daemon, gateway, agent-device. +Uses: auth (config strategies), bus, ports, contract, history (`usage/` only). Never imports: leasing, drivers, daemon, gateway, agent-device. Imported by: daemon, leasing, cli, http, agent-device, drivers (`Driver`, `ensureOwnedRoot`), gateway (catalog match, `fits`, `createUsageReader`). Flows: [startup](../../docs/internal/flows/startup.md), [device selection](../../docs/internal/flows/device-selection.md). See also: [leasing](../leasing/AGENTS.md) (lease flow, when reclaim runs), [warm pool](warm-pool/AGENTS.md), [capacity](capacity/AGENTS.md). diff --git a/src/core/config.test.ts b/src/core/config.test.ts index 54aef4cb2..1826787ef 100644 --- a/src/core/config.test.ts +++ b/src/core/config.test.ts @@ -1,5 +1,8 @@ import { describe, expect, it, vi } from "vitest"; +import { z } from "zod"; + +import type { AuthStrategyDefinition } from "../auth/index.js"; import { MemoryFilesystem, FakeSystemStats } from "../ports/index.js"; import type { ResourceStrategyOptions } from "./capacity/index.js"; import { configSchema } from "../contract/schemas.js"; @@ -2004,3 +2007,34 @@ describe("configSchema agrees with the config the daemon actually loads", () => ); }); }); + +describe("loadConfig over the auth strategies' config keys", () => { + const fake: AuthStrategyDefinition = { + name: "fake", + config: { + key: "fake", + schema: z.object({ limit: z.number().int().positive() }), + defaults: { limit: 5 }, + }, + enabled: () => true, + create: () => ({ authenticate: async () => ({ kind: "not-mine", sawCredential: false }) }), + }; + + async function load(http: unknown) { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/home/agent/.simlock"); + await filesystem.writeFileAtomic(configPath, JSON.stringify({ http })); + return loadConfig({ + authStrategies: [fake], + configPath, + filesystem, + systemStats: createStats(), + }); + } + + it("fills a registered strategy's defaults and validates the key it owns", async () => { + expect(dottedValue(await load({}), "http.fake.limit")).toBe(5); + expect(dottedValue(await load({ fake: { limit: 9 } }), "http.fake.limit")).toBe(9); + await expect(load({ fake: { limit: "many" } })).rejects.toThrow("http.fake"); + }); +}); diff --git a/src/core/config.ts b/src/core/config.ts index 67cda234e..cdb4420b0 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -1,4 +1,10 @@ +import type { ZodType } from "zod"; + import type { Filesystem, LogLevel, SystemStats } from "../ports/index.js"; +import { + authStrategies as registeredAuthStrategies, + type AuthStrategyDefinition, +} from "../auth/index.js"; import { capacityStrategyNames, capacityStrategyValidator, @@ -355,6 +361,7 @@ export interface ModuleConfigEntry { } export interface LoadConfigOptions { + readonly authStrategies?: readonly AuthStrategyDefinition[]; readonly modules?: readonly ModuleConfigEntry[]; readonly filesystem: Filesystem; readonly systemStats: SystemStats; @@ -366,6 +373,7 @@ export interface LoadConfigOptions { type Layer = Record; export async function loadConfig({ + authStrategies = registeredAuthStrategies, configPath = DEFAULT_CONFIG_PATH, filesystem, modules = [], @@ -384,7 +392,7 @@ export async function loadConfig({ // `http.enabled` defaults to, so it has to be known before anything is defaulted or warned // about. const mode = resolveMode([fromFile, fromOverrides]); - const validators = configValidators(strategy, modules); + const validators = configValidators(strategy, modules, authStrategies); const fileConfig = normalizeLayer( validateConfigLayer(fromFile, "", warn, validators), @@ -398,7 +406,7 @@ export async function loadConfig({ ); const mergedWithoutMetrics = mergeConfig( - mergeConfig(defaultConfig(systemStats, strategy, mode, modules), fileConfig), + mergeConfig(defaultConfig(systemStats, strategy, mode, modules, authStrategies), fileConfig), overrideConfig, ) as unknown as Omit & { readonly metrics?: Config["metrics"] }; const merged: Config = { @@ -711,6 +719,7 @@ function defaultConfig( strategy: CapacityStrategyName, mode: DaemonMode, modules: readonly ModuleConfigEntry[], + authStrategies: readonly AuthStrategyDefinition[], ): Omit { return { mode, @@ -763,7 +772,18 @@ function defaultConfig( // ADR 0005 §2: a gateway always listens on HTTP, so that is its default rather than // something every operator has to remember to switch on; a worker's HTTP gateway stays // opt-in exactly as before. - http: { enabled: mode === "gateway", host: "127.0.0.1", port: 4700 }, + http: { + enabled: mode === "gateway", + host: "127.0.0.1", + port: 4700, + ...Object.fromEntries( + authStrategies.flatMap((definition) => + definition.config === undefined + ? [] + : [[definition.config.key, definition.config.defaults]], + ), + ), + }, health: { enabled: true, probeIntervalMs: 30_000, @@ -853,6 +873,7 @@ const LEASE_IDENTITIES: readonly LeaseIdentity[] = ["reusable", "fresh"]; function configValidators( strategy: CapacityStrategyName, modules: readonly ModuleConfigEntry[], + authStrategies: readonly AuthStrategyDefinition[], ): Record { return { capabilities: capabilitiesValidator(modules), @@ -918,6 +939,13 @@ function configValidators( enabled: booleanValue, host: stringValue, port: integerInRange(1, 65535), + ...Object.fromEntries( + authStrategies.flatMap((definition) => + definition.config === undefined + ? [] + : [[definition.config.key, schemaValidator(definition.config.schema)]], + ), + ), }), health: objectValidator({ enabled: booleanValue, @@ -951,6 +979,18 @@ function configValidators( }; } +function schemaValidator(schema: ZodType): Validator { + return (value, path) => { + const result = schema.safeParse(value); + if (result.success) return result.data; + const issue = result.error.issues[0]; + throw invalidValue( + path, + issue === undefined ? "a valid value" : `a valid value (${issue.message})`, + ); + }; +} + function capabilitiesValidator(modules: readonly ModuleConfigEntry[]): Validator { return (value, path, warn) => { const result: Record = {}; diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 0528caecf..0cce45a08 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -2,7 +2,7 @@ Does: one process per data directory — composes a worker or a gateway and serves the contract on a unix socket. Entry: `main.ts` → `startDaemon(options)` → a started `DaemonServer`. -Uses: contract, daemon-protocol, ports, bus, history, link, core, leasing, drivers, http, host-load, modules, module-registry; gateway from `main.ts` only. +Uses: auth, contract, daemon-protocol, ports, bus, history, link, core, leasing, drivers, http, host-load, modules, module-registry; gateway from `main.ts` only. Never imports: gateway outside `main.ts`. `dispatch.ts` imports no core, drivers or http. Imported by: http (`dispatcher.ts`, `error-code.ts`, `owner-routed-facts.ts`); gateway (`dispatch.ts` only). Started by: cli and mcp spawn `main.ts` as a detached process. @@ -17,8 +17,6 @@ Flows: [startup](../../docs/internal/flows/startup.md), [device.exec](../../docs | `dispatch.ts` | `runDispatch` pipeline, `DispatchSession`, `DispatchError` | | `dispatcher.ts` | `Dispatcher`: the worker's handlers | | `connection-host.ts` | `DaemonEndpointHost`: socket claim, stale-socket recovery | -| `admin-secret.ts` | `AdminSecretManager`: per-start secret, `admin.token` | -| `session.ts` | `createCredentialRoleResolver`: credential → role | | `owner-routed-facts.ts` | `OwnerRoutedFactBus`: lease facts with their owner | | `gateway-uplink.ts` | `GatewayUplink`: a worker's dial to its gateway | | `relay.ts` | `RelayTargets`, `RelayConnection`: relays over the uplink | @@ -28,16 +26,16 @@ Flows: [startup](../../docs/internal/flows/startup.md), [device.exec](../../docs ## Composition (`main.ts`) -Both modes: config (`config.json`) → `Logger` → host info → `EventBus` → event history (`createEventHistory`, not yet started). +Both modes: config (`config.json`) → `Logger` → host info → `EventBus` → event history (`createEventHistory`, not yet started) → `createAuth` (`src/auth`, once). `config.mode` then picks one branch; a gateway builds none of the worker's parts. - **Worker** — `Registry` (`state.json`) → instance id (`instance.json`) → `discoverDrivers` (validates each root; a refused root costs that platform only) → `ComponentInstaller` → `createCore` → `createLeasing` → `core.connect` → - `CleanupReaper`, `Nuke`, `TokenStore`, `AdminSecretManager` → `GatewayUplink` + `CleanupReaper`, `Nuke` → `GatewayUplink` when `gateway.url` and `gateway.token` are both set → `DaemonServer` with `Dispatcher`. HTTP starts only when `http.enabled`. -- **Gateway** — instance id → `TokenStore`, `AdminSecretManager` → `FleetLeaseIndex` +- **Gateway** — instance id → `FleetLeaseIndex` (requester prefix `gw::`) → `GatewayService` (uplink listener, `workers.json`) → `FleetLeaseCoordinator` → `DaemonServer` with `GatewayDispatcher`. HTTP always starts; the uplink upgrades on the same listener. @@ -96,7 +94,7 @@ Health: `starting` → `running`, or `failed`. ## Identity and roles -Credential resolution (`createCredentialRoleResolver`), at `hello`: +Credential resolution (`Auth.resolveHelloRole`, `src/auth`), at `hello`: 1. No credential → `agent`. 2. An `operator` token in `tokens.json` → `admin`. diff --git a/src/daemon/admin-secret.ts b/src/daemon/admin-secret.ts deleted file mode 100644 index edb22dba7..000000000 --- a/src/daemon/admin-secret.ts +++ /dev/null @@ -1,74 +0,0 @@ -import type { Filesystem, TokenSecrets } from "../ports/index.js"; - -/** Owner-only: the daemon's OS user is the one who can ever read `admin.token`. Consistent - * with the rest of the daemon's local state (config.json, tokens.json, state.json) -- the real - * trust boundary is "same OS user" (ADR 0003 §5's socket-identity note applies here too: file - * permissions protect against another user on the box, not a hostile process running as this - * one). */ -const ADMIN_SECRET_FILE_MODE = 0o600; - -export interface AdminSecretManagerOptions { - readonly filesystem: Filesystem; - readonly secrets: TokenSecrets; - /** Path to `admin.token` under the daemon's data directory. */ - readonly path: string; -} - -/** - * The daemon's per-start admin secret (ADR 0003 §5, point 2). One instance per daemon process - * lifetime: `generate()` mints a fresh secret and keeps only its hash in memory the moment the - * instance is constructed -- `hello` can verify a credential against `#hash` immediately, long - * before `persist()` (called only after the socket claim succeeds, see `DaemonServer#start`) - * writes the plaintext secret to disk. `verify()` never touches the filesystem or reconstructs - * the secret; it only ever compares hashes, so the plaintext exists nowhere but this instance's - * private field and the file a caller reads to get it. - * - * A daemon that loses the start race never calls `persist()` at all (`DaemonServer#start` - * awaits `ConnectionHost#start()`, which throws `DaemonAlreadyRunningError` before this class's - * `persist()` is ever reached) -- so the file an already-running daemon wrote is never touched - * by the loser. This class enforces nothing about that ordering itself; it is a consequence of - * where its caller places the `persist()` call, called out here because it is easy to violate - * by moving that call earlier. - */ -export class AdminSecretManager { - readonly #filesystem: Filesystem; - readonly #secrets: TokenSecrets; - readonly #path: string; - readonly #secret: string; - readonly #hash: string; - - constructor(options: AdminSecretManagerOptions) { - this.#filesystem = options.filesystem; - this.#secrets = options.secrets; - this.#path = options.path; - this.#secret = options.secrets.generateSecret(); - this.#hash = this.#secrets.hash(this.#secret); - } - - /** - * Writes the plaintext secret to `admin.token`, atomically (temp file, rename -- see - * `Filesystem#writeFileAtomic`) and owner-only (mode set at creation, never a later - * `chmod`). Callers must only invoke this after the socket claim has succeeded -- see the - * class doc. - */ - async persist(): Promise { - await this.#filesystem.writeFileAtomic(this.#path, `${this.#secret}\n`, { - mode: ADMIN_SECRET_FILE_MODE, - }); - } - - /** Removes `admin.token` on graceful stop. A daemon that never called `persist()` (lost the - * start race) never calls this either -- both are gated by the same `DaemonServer#start` - * success. */ - async remove(): Promise { - await this.#filesystem.rm(this.#path); - } - - /** Constant-time-ish equality is not attempted here: `TokenSecrets#hash` output is a fixed - * 64-char hex digest either way, and `String.prototype ===` on two hex strings of equal - * length is not meaningfully more timing-leaky than the hash comparison every bearer-token - * verifier in this codebase already does (`TokenStore#verify`, same pattern). */ - verify(candidate: string): boolean { - return this.#secrets.hash(candidate) === this.#hash; - } -} diff --git a/src/daemon/dispatch.ts b/src/daemon/dispatch.ts index e6295bc99..0646d4e43 100644 --- a/src/daemon/dispatch.ts +++ b/src/daemon/dispatch.ts @@ -39,21 +39,6 @@ import { */ export type DispatchProgress = z.infer; -/** - * ADR 0003 §2's "session" argument to `dispatch`. Constructed fresh per call by the transport - * (`DaemonServer`, one per socket request; the HTTP app, one per HTTP request) from whatever - * longer-lived state it owns -- this type does not itself track anything across calls. - * - * `principal`/`role` are the ADR §4/§5 identity: fixed for the connection's lifetime once - * `hello` resolves them (see `session.ts`'s `SessionRoleResolver` seam). ADR 0004 removed the - * two connection-scoped fields that used to sit beside them (`heldLeaseIds`, - * `heartbeatCapability`): the daemon keeps no per-connection lease state at all any more. - * `onProgress` and `manageEventSubscription` are the two places a request-scoped or - * connection-scoped push actually reaches the wire -- `DaemonServer` supplies closures that - * write socket frames; an HTTP session can leave `onProgress` unset and no-op on - * `events.subscribe`, since HTTP has no open connection to push through even in principle - * (ADR §8's "the HTTP notice buffer stays"). - */ export interface DispatchSession { readonly principal: string; readonly role: Role; diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 144b714db..46cc4810c 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -49,10 +49,11 @@ import { FakeSystemStats, MemoryFilesystem, NodeProcessRunner, + NoopLogger, ScriptedProcessRunner, type ProcessRunner, } from "../ports/index.js"; -import { TokenStore } from "../http/token-store.js"; +import { createAuth } from "../auth/index.js"; import type { DispatcherOptions, DispatchSession } from "./dispatcher.js"; import { Dispatcher, DispatchError } from "./dispatcher.js"; import { classifyError } from "./error-code.js"; @@ -337,11 +338,13 @@ async function buildDispatcher( quarantine: engine.core.quarantine, registry, }); - const tokens = new TokenStore({ + const { tokens } = createAuth({ clock, + config: { enabled: false, host: "127.0.0.1", port: 4700 }, + dataDirectory: "/", filesystem, idGenerator: sequence(), - path: "/tokens.json", + logger: new NoopLogger(), secrets: new CryptoTokenSecrets(), }); const dispatcher = new Dispatcher({ diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 1e6cbffcf..85d3c8ae4 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -67,7 +67,7 @@ import { workerViewFields, withoutQuarantineMessages, } from "../contract/index.js"; -import type { TokenStore } from "../http/token-store.js"; +import type { TokenOperations } from "../auth/index.js"; import { DispatchError, runDispatch, @@ -182,17 +182,12 @@ export interface DispatcherOptions { * majority) don't need to fabricate one -- `#tokenCreate`/`#tokenList`/`#tokenRevoke` throw a * clear `DispatchError` when it is missing rather than crashing on `undefined.create(...)`. */ - readonly tokens?: TokenStore; + readonly tokens?: TokenOperations; /** Reports current daemon health for `status.get`. */ readonly health: () => "starting" | "running" | "failed"; /** `status.get`'s host block, from memory: answering never waits for a read (ADR 0008 §7). */ readonly hostFacts: () => HostFacts; readonly load?: () => StatusLoad | undefined; - /** - * ADR §2 step 4: every operation but `status.get` parks here before its handler runs. - * `hello` never reaches `dispatch()` at all -- it is answered before a `Session` exists, - * since the session's `role` is itself resolved from `hello`'s payload (see `session.ts`). - */ readonly awaitReady: () => Promise; /** This daemon's instance id (`instance.json`), the id it presents to a gateway. `worker.list` * answers with it as the one worker's id (ADR 0012 §1). */ @@ -1011,7 +1006,7 @@ export class Dispatcher { revoked: await this.#requireTokens().revoke(input.id), }); - #requireTokens(): TokenStore { + #requireTokens(): TokenOperations { if (this.options.tokens === undefined) { throw new DispatchError("INTERNAL", "Token store is unavailable"); } diff --git a/src/daemon/error-code.test.ts b/src/daemon/error-code.test.ts index 61a480104..9976a4214 100644 --- a/src/daemon/error-code.test.ts +++ b/src/daemon/error-code.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; +import { AdminAuthenticationFailedError } from "../auth/index.js"; import { ComponentInstallerClosedError, UnsupportedRequestOptionError } from "../core/index.js"; import { LeaseIdTakenError, @@ -66,3 +67,9 @@ describe("classifyError on a lease ID that is in use", () => { expect(classifyError(new LeaseIdTakenError("ad-7f3a"))).toBe("LEASE_ID_TAKEN"); }); }); + +describe("classifyError on a rejected admin credential", () => { + it("answers ADMIN_AUTHENTICATION_FAILED for the error src/auth throws", () => { + expect(classifyError(new AdminAuthenticationFailedError())).toBe("ADMIN_AUTHENTICATION_FAILED"); + }); +}); diff --git a/src/daemon/error-code.ts b/src/daemon/error-code.ts index 655aa2a98..3f5862a77 100644 --- a/src/daemon/error-code.ts +++ b/src/daemon/error-code.ts @@ -48,7 +48,7 @@ import { import { ExecOutputDeliveryStalledError } from "../ports/index.js"; import { ERROR_TABLE, type SimlockErrorCode } from "../contract/index.js"; import { DispatchError, DoctorUnavailableError, NukeUnavailableError } from "./dispatcher.js"; -import { AdminAuthenticationFailedError } from "./session.js"; +import { AdminAuthenticationFailedError } from "../auth/index.js"; /** * Thrown to a request parked on startup readiness (ADR §2 step 4's `awaitReady`) when diff --git a/src/daemon/main.ts b/src/daemon/main.ts index b37b67f78..7f0ac1961 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -51,10 +51,10 @@ import { type SlimmedFact, iosPrerequisites, } from "../drivers/ios/index.js"; +import { type Auth, createAuth } from "../auth/index.js"; import { createHttpApp } from "../http/app.js"; import type { HttpDispatch } from "../http/dispatcher-session.js"; import { HttpGateway } from "../http/server.js"; -import { TokenStore } from "../http/token-store.js"; import { CryptoIdGenerator, CryptoTokenSecrets, @@ -112,12 +112,10 @@ import { createModuleHost, type OptionalModuleDefinition } from "../modules/inde import { optionalModules } from "../module-registry/index.js"; import { DaemonServer } from "./server.js"; import { DaemonEndpointHost } from "./connection-host.js"; -import { AdminSecretManager } from "./admin-secret.js"; import { describeLeaseRequestFailure } from "./error-code.js"; import { wakingQueueAfter } from "./enrollment-wake.js"; import { GatewayUplink } from "./gateway-uplink.js"; import type { RelayTargets } from "./relay.js"; -import { createCredentialRoleResolver } from "./session.js"; export interface StartDaemonOptions { readonly clock?: Clock; @@ -208,12 +206,23 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise core.targetedDevices(), }); const nuke = new Nuke({ executor: core.nuke, registry }); - // Constructed unconditionally, not just when `config.http.enabled` -- ADR 0003 §5's operator - // token is a socket-hello credential too, so the daemon must be able to verify one against - // the token store regardless of whether the HTTP gateway is running. Previously this was - // only ever constructed inside the `config.http.enabled` block below; it is reused there now - // instead of being built twice. - const tokens = new TokenStore({ - clock, - filesystem, - idGenerator, - path: join(dataDirectory, "tokens.json"), - secrets: new CryptoTokenSecrets(), - }); - const adminSecret = new AdminSecretManager({ - filesystem, - secrets: new CryptoTokenSecrets(), - path: join(dataDirectory, "admin.token"), - }); - const resolveRole = createCredentialRoleResolver({ - verifyOperatorToken: async (secret) => (await tokens.verify(secret))?.role === "operator", - verifyAdminSecret: (secret) => adminSecret.verify(secret), - }); /** * ADR 0005 §3/§4: two config keys join a fleet. Undefined here means this worker has no * gateway, which is every worker today -- and the daemon is otherwise completely unchanged @@ -529,9 +517,9 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise auth.resolveHelloRole(hello) }, + adminSecret: auth.adminSecret, + tokens: auth.tokens, version: version, converge: convergeStartup, settle: async () => { @@ -630,7 +618,7 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise { - const { clock, config, dataDirectory, eventBus, eventHistory, filesystem, idGenerator, logger } = - options; + const { + auth, + clock, + config, + dataDirectory, + eventBus, + eventHistory, + filesystem, + idGenerator, + logger, + } = options; // The gateway's own identity, used to namespace the principal it announces to each worker // (ADR 0005 §27's shape) so a worker's logs attribute what the gateway did to the gateway. const instanceId = await loadInstanceId({ @@ -720,26 +718,6 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise (await tokens.verify(secret))?.role === "operator", - verifyAdminSecret: (secret) => adminSecret.verify(secret), - }); - // ADR 0005 §14/§27: stamped on every requester id this gateway forwards, and what // `FleetLeaseIndex` recognizes its own leases by when rebuilding from a worker's view. const gatewayRequesterPrefix = `gw:${instanceId}:`; @@ -756,13 +734,7 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise { - if (credential === undefined) return "unauthenticated"; - const identity = await tokens.verify(credential); - if (identity === undefined) return "unauthenticated"; - if (identity.role !== "worker") return "forbidden"; - return { outcome: "accept", tokenId: identity.requesterId }; - }, + authenticate: (credential) => auth.authenticateUplink(credential), clock, drainStore: new FileDrainStore({ filesystem, @@ -862,13 +834,13 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise fitHostLoad(hostLoad.current()) }), leaseIndex, logger: logger.child("gateway"), - tokens, + tokens: auth.tokens, workers: gatewayService.workers, historyPath: join(dataDirectory, HISTORY_DB_NAME), }); const daemon = new DaemonServer({ - adminSecret, + adminSecret: auth.adminSecret, clock, config, defaultRequesterId: process.env.SIMLOCK_AGENT_ID ?? String(process.pid), @@ -889,7 +861,7 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise ({ id: entry.gatewayLeaseId, ownerId: entry.ownerId })), logger: logger.child("server"), ownerRoutedFacts: gatewayOwnerRoutedFacts, - resolveRole, + resolveRole: { resolve: (hello) => auth.resolveHelloRole(hello) }, version: options.version, // A gateway's "convergence" is starting to accept uplinks and arming the refresh tick. // Running it here rather than before `start()` keeps one lifecycle: a listener that cannot @@ -959,7 +931,7 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise { expect(first.daemon.socketPath).toBe(socketPath); }); - // Review finding S1: `AdminSecretManager`'s own doc (`admin-secret.ts`) asserts "a daemon + // why: review finding S1: `AdminSecretManager`'s own doc (`src/auth`) asserts "a daemon // that loses the start race never calls `persist()` at all ... so the file an // already-running daemon wrote is never touched by the loser" -- untested anywhere before // this. Mirrors the "recovers a stale socket file" test above (two harnesses racing for the @@ -920,11 +925,7 @@ describe("DaemonServer", () => { // for `afterEach` to stop, and this test only needs the winner alive on `socketPath` (so // the loser's own `start()` below actually loses) plus its filesystem. await createHarness({ - adminSecret: new AdminSecretManager({ - filesystem: winnerFilesystem, - path: "/admin.token", - secrets, - }), + adminSecret: adminAuth(winnerFilesystem, secrets).adminSecret, socketPath, }); // The winner (the only one whose `start()` actually reached `host.start()`'s success path) @@ -933,11 +934,7 @@ describe("DaemonServer", () => { const loserFilesystem = new MemoryFilesystem(); const second = await createHarness({ - adminSecret: new AdminSecretManager({ - filesystem: loserFilesystem, - path: "/admin.token", - secrets, - }), + adminSecret: adminAuth(loserFilesystem, secrets).adminSecret, socketPath, start: false, }); @@ -964,14 +961,10 @@ describe("DaemonServer", () => { const socketPath = join(directory, "daemon.sock"); const filesystem = new MemoryFilesystem(); const secrets = new CryptoTokenSecrets(); - const oldSecret = new AdminSecretManager({ filesystem, path: "/admin.token", secrets }); - const replacementSecret = new AdminSecretManager({ - filesystem, - path: "/admin.token", - secrets, - }); + const oldSecret = adminAuth(filesystem, secrets); + const replacementSecret = adminAuth(filesystem, secrets); const replacement = await createHarness({ - adminSecret: replacementSecret, + adminSecret: replacementSecret.adminSecret, socketPath, start: false, }); @@ -983,7 +976,7 @@ describe("DaemonServer", () => { }); let replacementToken: string | undefined; const old = await createHarness({ - adminSecret: oldSecret, + adminSecret: oldSecret.adminSecret, host: { endpoint: socketPath, start: (accept) => host.start(accept), @@ -992,12 +985,18 @@ describe("DaemonServer", () => { // why: endpoint release lets a new process start before the old stop resumes. await replacement.daemon.start(); replacementToken = await filesystem.readFile("/admin.token"); - expect(replacementSecret.verify(replacementToken.trim())).toBe(true); + await expect( + replacementSecret.resolveHelloRole({ credential: replacementToken.trim() }), + ).resolves.toBe("admin"); }, }, socketPath, }); - expect(oldSecret.verify((await filesystem.readFile("/admin.token")).trim())).toBe(true); + await expect( + oldSecret.resolveHelloRole({ + credential: (await filesystem.readFile("/admin.token")).trim(), + }), + ).resolves.toBe("admin"); if (removalFails) { vi.spyOn(filesystem, "rm").mockRejectedValueOnce(new Error("EACCES")); @@ -3257,7 +3256,7 @@ async function createHarness( readonly beginStop?: () => void; readonly stateFilesystem?: MemoryFilesystem; readonly stopAuxiliary?: () => Promise; - readonly adminSecret?: AdminSecretManager; + readonly adminSecret?: Auth["adminSecret"]; readonly resolveRole?: SessionRoleResolver; readonly downloads?: Partial; readonly processRunner?: ProcessRunner; @@ -3736,3 +3735,15 @@ function testConfig( }, }; } + +function adminAuth(filesystem: MemoryFilesystem, secrets: CryptoTokenSecrets): Auth { + return createAuth({ + config: { enabled: false, host: "127.0.0.1", port: 4700 }, + dataDirectory: "/", + filesystem, + secrets, + idGenerator: { generate: () => "id" }, + clock: new FakeClock(1_000), + logger: new NoopLogger(), + }); +} diff --git a/src/daemon/server.ts b/src/daemon/server.ts index 27ff9b647..b92578e3c 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -49,7 +49,12 @@ import { } from "../contract/index.js"; import type { LinkChannel, LinkConnection } from "../link/index.js"; import type { ConnectionHost } from "./connection-host.js"; -import type { TokenStore } from "../http/token-store.js"; +import { + resolveAgentRole, + type Auth, + type SessionRoleResolver, + type TokenOperations, +} from "../auth/index.js"; import { Dispatcher, DispatchError, @@ -57,8 +62,6 @@ import { type DispatcherOptions, type DispatchSession, } from "./dispatcher.js"; -import { resolveAgentRole, type SessionRoleResolver } from "./session.js"; -import type { AdminSecretManager } from "./admin-secret.js"; import { OwnerRoutedFactBus, type OwnerRoutedFacts } from "./owner-routed-facts.js"; import { classifyError, StartupFailedError } from "./error-code.js"; import { RelayConnection, type RelayTargets } from "./relay.js"; @@ -162,7 +165,7 @@ export interface DaemonServerEngineOptions { readonly execEnv?: NodeJS.ProcessEnv; readonly registry: Registry; readonly stalls?: DispatcherOptions["stalls"]; - readonly tokens?: TokenStore; + readonly tokens?: TokenOperations; } export interface DaemonServerCommonOptions { @@ -186,7 +189,7 @@ export interface DaemonServerCommonOptions { * exercise the admin handshake at all -- `start()`/`#stop()` simply skip the persist/remove * calls below when it is absent, same style as `doctor`/`nuke`. */ - readonly adminSecret?: AdminSecretManager; + readonly adminSecret?: Auth["adminSecret"]; /** * why: Startup recovery work (doctor reconciliation, running-capacity convergence) run * *after* the socket is claimed, so reachability never depends on it. `hello` and @@ -230,7 +233,7 @@ export interface DaemonServerCommonOptions { * otherwise there is nothing for a request to park against, it just gets connection-refused * the way it always did. Called synchronously right after `#readyPromise` is assigned (so any * request `dispatch()` serves as a result of this callback already parks correctly) and after - * the socket claim and the admin-secret write, but *before* awaiting convergence -- an + * the socket claim and the admin secret write, but *before* awaiting convergence -- an * auxiliary frontend started from here must not itself assume convergence is done. A no-op * default leaves today's behaviour (no auxiliary frontend at all) unchanged. */ diff --git a/src/daemon/session.test.ts b/src/daemon/session.test.ts deleted file mode 100644 index 299d32fb6..000000000 --- a/src/daemon/session.test.ts +++ /dev/null @@ -1,144 +0,0 @@ -import { describe, expect, it, vi } from "vitest"; - -import { - AdminAuthenticationFailedError, - createCredentialRoleResolver, - resolveAgentRole, - type AdminCredentialVerifier, -} from "./session.js"; - -/** - * Regression coverage for review finding S1: `createCredentialRoleResolver` (ADR 0003 §5) was - * untested -- every role/ownership test in `server.test.ts` injects a *stubbed* `resolveRole`, - * so the real credential-checking logic (the resolver `main.ts` actually wires up against - * `TokenStore#verify` and `AdminSecretManager#verify`) had zero coverage. These tests exercise - * `createCredentialRoleResolver` directly against a scripted `AdminCredentialVerifier`, the - * narrow interface it depends on -- no real token store or admin secret needed. - */ -describe("createCredentialRoleResolver", () => { - function verifier(overrides: Partial = {}): AdminCredentialVerifier { - return { - verifyOperatorToken: vi.fn().mockResolvedValue(false), - verifyAdminSecret: vi.fn().mockReturnValue(false), - ...overrides, - }; - } - - it("resolves agent, unconditionally, when hello carries no credential", async () => { - const verify = verifier({ - // Neither should even be consulted with no credential to check -- see the "never calls - // either verifier" test below for the stronger assertion. - verifyOperatorToken: vi.fn().mockResolvedValue(true), - verifyAdminSecret: vi.fn().mockReturnValue(true), - }); - const resolver = createCredentialRoleResolver(verify); - - await expect(resolver.resolve({})).resolves.toBe("agent"); - await expect(resolver.resolve({ principal: "someone" })).resolves.toBe("agent"); - }); - - it("never calls either verifier when hello carries no credential", async () => { - const verifyOperatorToken = vi.fn().mockResolvedValue(false); - const verifyAdminSecret = vi.fn().mockReturnValue(false); - const resolver = createCredentialRoleResolver({ verifyOperatorToken, verifyAdminSecret }); - - await resolver.resolve({ principal: "someone" }); - - expect(verifyOperatorToken).not.toHaveBeenCalled(); - expect(verifyAdminSecret).not.toHaveBeenCalled(); - }); - - // ADR §5: "Two credentials are accepted, checked in this order: 1. An operator token ... - // 2. The per-start admin secret." Provable order, not just provable outcome: give both - // verifiers a way to record *when* they were called, and assert the operator check happened - // first. - it("checks the operator token store before the per-start admin secret", async () => { - const calls: string[] = []; - const resolver = createCredentialRoleResolver({ - verifyOperatorToken: async (secret) => { - calls.push(`operator:${secret}`); - return false; - }, - verifyAdminSecret: (secret) => { - calls.push(`admin-secret:${secret}`); - return true; - }, - }); - - await expect(resolver.resolve({ credential: "slk_whatever" })).resolves.toBe("admin"); - - expect(calls).toEqual(["operator:slk_whatever", "admin-secret:slk_whatever"]); - }); - - it("resolves admin when only the operator token store accepts the credential", async () => { - const verifyAdminSecret = vi.fn().mockReturnValue(false); - const resolver = createCredentialRoleResolver({ - verifyOperatorToken: async (secret) => secret === "slk_operator", - verifyAdminSecret, - }); - - await expect(resolver.resolve({ credential: "slk_operator" })).resolves.toBe("admin"); - // Short-circuits: the admin-secret check never runs once the operator token store already - // accepted the credential. - expect(verifyAdminSecret).not.toHaveBeenCalled(); - }); - - it("resolves admin when only the per-start admin secret accepts the credential", async () => { - const resolver = createCredentialRoleResolver({ - verifyOperatorToken: async () => false, - verifyAdminSecret: (secret) => secret === "the-admin-secret", - }); - - await expect(resolver.resolve({ credential: "the-admin-secret" })).resolves.toBe("admin"); - }); - - // The specific guarantee ADR §5/`session.ts`'s doc calls out: a bearer token that verifies - // but carries the "agent" role must never resolve to "admin" here -- `AdminCredentialVerifier` - // is deliberately typed so `verifyOperatorToken` can only ever answer "operator or not", never - // hand back a role, so this is really asserting the interface shape is honored by a verifier - // that mirrors what `TokenStore#verify` actually does (a token exists but isn't `operator`). - it("never resolves admin for a credential that verifies as a non-operator (agent-role) token", async () => { - const resolver = createCredentialRoleResolver({ - // Mirrors `main.ts`'s real wiring: `(await tokens.verify(secret))?.role === "operator"` -- - // a token that exists in the store but whose role isn't "operator" (an agent-role bearer - // token) answers false here, exactly like a credential with no matching token at all. - verifyOperatorToken: async () => false, - verifyAdminSecret: () => false, - }); - - await expect(resolver.resolve({ credential: "slk_agent_token" })).rejects.toThrow( - AdminAuthenticationFailedError, - ); - }); - - it("throws AdminAuthenticationFailedError for a credential neither verifier accepts", async () => { - const resolver = createCredentialRoleResolver(verifier()); - - await expect(resolver.resolve({ credential: "not-a-real-secret" })).rejects.toThrow( - AdminAuthenticationFailedError, - ); - }); - - it("never echoes the rejected credential in the thrown error's message", async () => { - const resolver = createCredentialRoleResolver(verifier()); - - await expect(resolver.resolve({ credential: "slk_super_secret_value" })).rejects.toThrow( - AdminAuthenticationFailedError, - ); - try { - await resolver.resolve({ credential: "slk_super_secret_value" }); - expect.unreachable("resolve should have thrown"); - } catch (error: unknown) { - expect(String(error)).not.toContain("slk_super_secret_value"); - } - }); -}); - -describe("resolveAgentRole", () => { - it("resolves agent unconditionally, regardless of what hello sends", () => { - expect(resolveAgentRole.resolve({})).toBe("agent"); - expect(resolveAgentRole.resolve({ credential: "anything", principal: "someone" })).toBe( - "agent", - ); - }); -}); diff --git a/src/daemon/session.ts b/src/daemon/session.ts deleted file mode 100644 index 657056059..000000000 --- a/src/daemon/session.ts +++ /dev/null @@ -1,76 +0,0 @@ -import type { Role } from "../contract/index.js"; - -/** - * The seam PR 2a's dispatcher work left for this PR's credential handshake (ADR 0003 §5). - * Everything else -- the dispatcher, `DaemonServer`'s connection state, every operation's role - * check -- consumes only the resulting `{ principal, role }`, so the credential handshake - * changes exactly one thing: what `resolve()` does. It does not change the dispatcher, the - * session shape, or any handler. - */ -export interface SessionRoleResolver { - /** - * Resolves the role a session gets for its lifetime. `hello`'s already-validated payload is - * the only input -- no socket-path or transport detail, so an HTTP session (this PR) can call - * the exact same resolver. Throws `AdminAuthenticationFailedError` (ADR §5) when a credential - * is present but matches neither the operator token store nor the per-start admin secret -- - * *before* the caller ever marks the session/connection as handshaken, so nothing runs on a - * rejected `hello`. - */ - resolve(hello: { - readonly principal?: string; - readonly credential?: string; - }): Promise | Role; -} - -/** Placeholder resolver kept for tests that don't care about roles: every session is "agent", - * unconditionally, regardless of what `hello` sent. */ -export const resolveAgentRole: SessionRoleResolver = { - resolve: () => "agent", -}; - -/** Thrown by `createCredentialRoleResolver`'s resolver for a present-but-wrong credential. - * Deliberately generic: the message never echoes the credential itself (ADR §5: "never - * logged... never returned by any operation"), and `DaemonServer#errorCode` maps this to the - * contract's `ADMIN_AUTHENTICATION_FAILED` the same way it maps every other typed rejection. */ -export class AdminAuthenticationFailedError extends Error { - constructor() { - super("Invalid admin credential"); - this.name = "AdminAuthenticationFailedError"; - } -} - -/** - * ADR 0003 §5: what a `hello.credential` is checked against, in order -- an operator token - * from the token store, then the daemon's own per-start admin secret. Kept as a narrow - * structural interface (not `TokenStore`/`AdminSecretManager` directly) so this module -- and - * anything testing it -- does not need to construct either of those, and so an HTTP session - * (this PR's part B) can share the exact same verifier its socket counterpart uses. - */ -export interface AdminCredentialVerifier { - /** Resolves `true` only for a credential that hashes to a token store record whose role is - * `"operator"` -- an `"agent"`-role bearer token never grants admin here. */ - verifyOperatorToken(secret: string): Promise; - verifyAdminSecret(secret: string): boolean; -} - -/** - * Builds the real `SessionRoleResolver` (ADR §5): no `credential` resolves `"agent"` - * (unconditionally -- a session that never asked for admin is never granted it); a `credential` - * that verifies against either source resolves `"admin"`; anything else throws - * `AdminAuthenticationFailedError`, which the caller must translate to a handshake failure - * *before* marking the connection/session as having received `hello` -- see - * `DaemonServer#handleHello` and the HTTP session adapter, both of which reject the credential - * ahead of any other request being served, per the ADR's explicit ordering. - */ -export function createCredentialRoleResolver( - verifier: AdminCredentialVerifier, -): SessionRoleResolver { - return { - resolve: async (hello) => { - if (hello.credential === undefined) return "agent"; - if (await verifier.verifyOperatorToken(hello.credential)) return "admin"; - if (verifier.verifyAdminSecret(hello.credential)) return "admin"; - throw new AdminAuthenticationFailedError(); - }, - }; -} diff --git a/src/gateway/AGENTS.md b/src/gateway/AGENTS.md index 89559c233..975fbc822 100644 --- a/src/gateway/AGENTS.md +++ b/src/gateway/AGENTS.md @@ -3,7 +3,7 @@ Does: a daemon in `mode: "gateway"`: owns no devices, fronts the workers that dial in. Entry: `index.ts`; `startGatewayDaemon` (`../daemon/main.ts`) wires `GatewayService`, `FleetLeaseCoordinator`, `GatewayDispatcher`, `GatewayRelay`, `GatewayOwnerRoutedFacts`. -Uses: bus, history (type), contract, ports, link, admin, simlock-client, `../daemon/dispatch.ts`, and from +Uses: auth (`TokenOperations`), bus, history (type), contract, ports, link, admin, simlock-client, `../daemon/dispatch.ts`, and from core and leasing only the names `.oxlintrc.json` allows (request book, in-memory store, wait queue). Never imports: drivers, the rest of daemon, core's registry, capacity or lifecycle. Imported by: `../daemon/main.ts`. This manual also covers the worker's end of the uplink. diff --git a/src/gateway/dispatcher.test.ts b/src/gateway/dispatcher.test.ts index 5887b085d..a79efa91e 100644 --- a/src/gateway/dispatcher.test.ts +++ b/src/gateway/dispatcher.test.ts @@ -16,7 +16,8 @@ import { import { OPERATIONS, type OperationName } from "../contract/index.js"; import { DispatchError, runDispatch, type DispatchSession } from "../daemon/dispatch.js"; import { FakeClock, JsonLinesLogger, MemoryLogSink } from "../ports/index.js"; -import { GatewayDispatcher, type GatewayTokenStore } from "./dispatcher.js"; +import type { TokenOperations } from "../auth/index.js"; +import { GatewayDispatcher } from "./dispatcher.js"; import { MemoryDrainStore } from "./drain-store.js"; import { FleetLeaseCoordinator } from "./fleet-coordinator.js"; import type { WorkerDirectory, WorkerDispatchTarget } from "./fleet-ports.js"; @@ -88,7 +89,7 @@ const gatewayConfig = { }, }; -class FakeTokens implements GatewayTokenStore { +class FakeTokens implements TokenOperations { constructor(private readonly records: readonly { id: string; label?: string }[] = []) {} readonly created: string[] = []; @@ -97,15 +98,26 @@ class FakeTokens implements GatewayTokenStore { async create(role: "agent" | "operator" | "worker", label?: string) { this.created.push(role); return { - record: { createdAt: 1, id: "tok_1", role, ...(label === undefined ? {} : { label }) }, + record: { + createdAt: 1, + hash: "unused", + id: "tok_1", + role, + ...(label === undefined ? {} : { label }), + }, secret: "slk_secret", }; } async list() { return [ - { createdAt: 1, id: "tok_1", role: "worker" as const }, - ...this.records.map((record) => ({ createdAt: 1, role: "agent" as const, ...record })), + { createdAt: 1, hash: "unused", id: "tok_1", role: "worker" as const }, + ...this.records.map((record) => ({ + createdAt: 1, + hash: "unused", + role: "agent" as const, + ...record, + })), ]; } diff --git a/src/gateway/dispatcher.ts b/src/gateway/dispatcher.ts index b0571800d..4922009e8 100644 --- a/src/gateway/dispatcher.ts +++ b/src/gateway/dispatcher.ts @@ -32,6 +32,7 @@ * the message say why. The table is typed total over the contract minus `daemon.stop`, so a * newly declared operation is a compile error here until someone decides where it belongs. */ +import type { TokenOperations } from "../auth/index.js"; import type { z } from "zod"; import { createUsageReader, type UsageReader } from "../core/index.js"; @@ -41,7 +42,6 @@ import { OPERATIONS, requestedDevice, type OperationName, - type tokenRecordSchema, withoutQuarantineMessages, } from "../contract/index.js"; import { @@ -65,8 +65,6 @@ type Handler = ( session: DispatchSession, ) => Promise | unknown; -type TokenRecord = z.infer; - type DeepReadonly = Value extends (infer Item)[] ? readonly DeepReadonly[] : Value extends object @@ -82,20 +80,6 @@ type DeepReadonly = Value extends (infer Item)[] */ export type GatewayConfig = DeepReadonly>; -/** - * The token store, structurally. Narrower than importing `TokenStore` itself (which lives under - * `src/http` for historical reasons): the gateway needs three methods, and depending on the - * shape rather than the class is what keeps `src/gateway` from importing a frontend. - */ -export interface GatewayTokenStore { - create( - role: "agent" | "operator" | "worker", - label?: string, - ): Promise<{ record: TokenRecord; secret: string }>; - list(): Promise; - revoke(id: string): Promise; -} - export interface GatewayDispatcherOptions { readonly historyPath?: string; /** The gateway's own config -- what `config.get` returns (ADR 0005 §34). */ @@ -105,7 +89,7 @@ export interface GatewayDispatcherOptions { /** Each worker's live link, for `worker.install-component` (ADR 0010 §7). `GatewayService` * satisfies it. */ readonly directory: WorkerDirectory; - readonly tokens?: GatewayTokenStore; + readonly tokens?: TokenOperations; /** * C-2, ADR 0005 §8: "revoking closes the uplink". Called after a successful `token.revoke` * with the revoked token's id, so any uplink that token authenticated is closed immediately @@ -559,7 +543,7 @@ export class GatewayDispatcher { } } - #requireTokens(): GatewayTokenStore { + #requireTokens(): TokenOperations { if (this.options.tokens === undefined) { throw new DispatchError("INTERNAL", "Token store is unavailable"); } diff --git a/src/gateway/index.ts b/src/gateway/index.ts index a9fc7656c..b5e3a2854 100644 --- a/src/gateway/index.ts +++ b/src/gateway/index.ts @@ -16,8 +16,6 @@ export { FileDrainStore } from "./drain-store.js"; // fallow-ignore-next-line unused-type -- public port shape for anyone supplying their own store. export type { DrainStore } from "./drain-store.js"; export { GatewayDispatcher } from "./dispatcher.js"; -// fallow-ignore-next-line unused-type -- public option shape for anyone composing a gateway; `main.ts` builds one inline. -export type { GatewayTokenStore } from "./dispatcher.js"; export { GatewayService, type GatewayServiceOptions } from "./service.js"; export type { FleetViews } from "./fleet-ports.js"; export type { WorkerRegistry } from "./worker-registry.js"; diff --git a/src/http/AGENTS.md b/src/http/AGENTS.md index 08961030e..22acc5576 100644 --- a/src/http/AGENTS.md +++ b/src/http/AGENTS.md @@ -2,8 +2,8 @@ Does: the network API — `/v1` routes, bearer token → session, SSE, lease-request resources, console files. Entry: no index. `src/daemon/main.ts` takes `createHttpApp` (`app.ts`), `HttpGateway` -(`server.ts`) and `TokenStore` (`token-store.ts`). -Uses: contract, daemon (`DispatchSession`, `classifyError`, `OwnerRoutedFacts`), leasing (errors), +(`server.ts`). +Uses: auth, contract, daemon (`DispatchSession`, `classifyError`, `OwnerRoutedFacts`), leasing (errors), bus, core (types), ports. Never imports: drivers, gateway. Surface: [HTTP-API.md](../../docs/HTTP-API.md), [CONSOLE.md](../../docs/CONSOLE.md). @@ -12,14 +12,13 @@ Surface: [HTTP-API.md](../../docs/HTTP-API.md), [CONSOLE.md](../../docs/CONSOLE. | File | Role | | ----------------------- | ---------------------------------------------------------------- | | `app.ts` | Every `/v1` route, error boundary, request log line | -| `auth.ts` | `requireAuth`: bearer token → `TokenIdentity` | +| `auth.ts` | `requireAuth`: asks `src/auth`, maps `AuthError` → 401/403 | | `dispatcher-session.ts` | `HttpDispatch`; `buildHttpSession`: identity → `DispatchSession` | | `tracker.ts` | `LeaseRequestTracker`: lease requests as resources | | `notices.ts` | `LeaseNoticeBuffer`: per-lease health facts between polls | | `output-relay.ts` | `OutputRelay`: `device.exec` chunks onto one SSE response | | `sse.ts` | `pipeSse`: ordered writes, keepalive | | `errors.ts` | `HttpApiError`, `mapError`: error → status and body | -| `token-store.ts` | `TokenStore`: hashed tokens in `tokens.json` | | `server.ts` | `HttpGateway` listener; `withConsole` serves the built `ui/` | | `test-fakes.ts` | Fakes for this module's tests | @@ -90,8 +89,8 @@ until `POST /v1/leases/{id}/renew` drains them into `notices`. `lease_lost` clea convergence. Early requests park in the dispatcher. On a gateway the worker uplink upgrades on the same listener (`onServerCreated`). - `tokens.json` (data directory): `{ id: "tok_…", hash, role, label?, createdAt }`, written - atomically, mode `0600`. The dispatcher's `token.*` handlers write it through the same `TokenStore`. - `verify` reads the file on every call. The secret is shown once, by `token.create`. + atomically, mode `0600`. `src/auth` owns it: the dispatcher's `token.*` handlers write it through `Auth.tokens`, + and every verify re-reads the file. The secret is shown once, by `token.create`. - `LeaseNoticeBuffer` is memory only. `HttpGateway.stop` closes the server and destroys every open socket. diff --git a/src/http/app.test.ts b/src/http/app.test.ts index d69c5dc6e..a8864373a 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -13,11 +13,12 @@ import { DispatchError } from "../daemon/dispatcher.js"; import { describeLeaseRequestFailure } from "../daemon/error-code.js"; import { OwnerRoutedFactBus } from "../daemon/owner-routed-facts.js"; import { FakeClock, JsonLinesLogger, MemoryFilesystem, MemoryLogSink } from "../ports/index.js"; +import type { Identity } from "../auth/index.js"; +import { fakeAuth, tokenIdentity } from "../auth/testing.js"; import { createHttpApp, type HttpGatewayDeps } from "./app.js"; import { FakeDispatcher, FakeRegistry, - FakeTokenVerifier, makeDevice, makeGrant, makeLease, @@ -40,10 +41,13 @@ function buildHarness( const dispatcher = new FakeDispatcher(clock); const registry = new FakeRegistry(); const ownerRoutedFacts = new OwnerRoutedFactBus(eventBus, registry); - const tokens = new FakeTokenVerifier(); - tokens.register("slk_agent", { requesterId: "tok_agent", role: "agent" }); - tokens.register("slk_other", { requesterId: "tok_other", role: "agent" }); - tokens.register("slk_operator", { requesterId: "tok_operator", role: "operator" }); + const auth = fakeAuth( + new Map([ + ["slk_agent", tokenIdentity("tok_agent", "agent")], + ["slk_other", tokenIdentity("tok_other", "agent")], + ["slk_operator", tokenIdentity("tok_operator", "operator")], + ]), + ); const logSink = new MemoryLogSink(); const logger = new JsonLinesLogger({ clock, sink: logSink }); const config = overrides.config ?? testConfig(); @@ -68,13 +72,13 @@ function buildHarness( logger, ownerRoutedFacts, registry: overrides.registry ?? registry, - tokens, + auth, ...(overrides.answerDownloadsEarly === undefined ? {} : { answerDownloadsEarly: overrides.answerDownloadsEarly }), }); - return { app, clock, config, dispatcher, eventBus, logSink, registry, tokens }; + return { app, clock, config, dispatcher, eventBus, logSink, registry }; } type App = ReturnType["app"]; diff --git a/src/http/app.ts b/src/http/app.ts index c25ed7425..6578e5f43 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -31,7 +31,7 @@ import { import { LeaseNoticeBuffer } from "./notices.js"; import { OutputRelay } from "./output-relay.js"; import { pipeSse } from "./sse.js"; -import type { TokenIdentity } from "./token-store.js"; +import type { Auth, Identity } from "../auth/index.js"; import { buildLeasePayload, type HttpLeaseDevice, @@ -78,7 +78,7 @@ export interface HttpGatewayDeps { readonly idGenerator: IdGenerator; readonly logger: Logger; readonly config: Config; - readonly tokens: { verify(secret: string): Promise }; + readonly auth: Pick; /** `false` on a gateway, which never downloads: `allowDownload` then does not answer the lease * request `POST` early. Default `true`. */ readonly answerDownloadsEarly?: boolean | undefined; @@ -87,7 +87,7 @@ export interface HttpGatewayDeps { export interface HttpMount { readonly prefix: string; - handle(request: Request, identity: TokenIdentity): Promise; + handle(request: Request, identity: Identity): Promise; } type Env = AuthEnv; @@ -195,7 +195,7 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa }); const notices = new LeaseNoticeBuffer(deps.ownerRoutedFacts); - const agentAuth = requireAuth(deps.tokens); + const agentAuth = requireAuth(deps.auth); // The one error boundary. Hono's `compose` catches a thrown error at the layer that threw // it and hands it to `app.onError` right there -- it never propagates up through an outer @@ -216,12 +216,12 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa // The one unauthenticated route is also the one a tunnel/load-balancer polls: logging it // would let an anonymous flood drive the synchronous log sink from the event loop. if (c.req.path === "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/v1/healthz") return; - const identity = c.get("identity") as TokenIdentity | undefined; + const identity = c.get("identity") as Identity | undefined; logger.info("request", { durationMs: deps.clock.now() - start, method: c.req.method, path: c.req.path, - requesterId: identity?.requesterId, + requesterId: identity?.principal, status: c.res.status, }); }); @@ -758,13 +758,9 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa }); } -/** Guard for the lease-request routes. The request is the daemon's stored record now, but there - * is still no dispatcher operation that reads one by id, so no `authorize` hook to reuse the way - * `lease.renew`/`lease.release`/`lease.cancel` do. Compared against the record's `ownerId` -- - * the principal the daemon saw send it -- never its `requesterId`, which is the caller's claim. - * A token's principal is its `requesterId` (`buildHttpSession`). */ -function requireOwnRequest(identity: TokenIdentity, ownerId: string): void { - if (identity.role === "operator" || identity.requesterId === ownerId) return; +// why: no dispatcher operation reads a stored lease request by id, so there is no `authorize` hook to reuse; compared against the record's `ownerId`, the principal the daemon saw send it, never its caller-claimed `requesterId`. +function requireOwnRequest(identity: Identity, ownerId: string): void { + if (identity.role === "operator" || identity.principal === ownerId) return; throw forbidden("Not permitted to access another requester's resource"); } diff --git a/src/http/auth.test.ts b/src/http/auth.test.ts index 5d2f40d35..be74710ee 100644 --- a/src/http/auth.test.ts +++ b/src/http/auth.test.ts @@ -1,32 +1,30 @@ import { Hono } from "hono"; import { describe, expect, it } from "vitest"; +import { + type Auth, + type Identity, + type AuthStrategyDefinition, + createAuth, + type StrategyAnswer, +} from "../auth/index.js"; +import { createAuthWith, fakeAuth, tokenIdentity } from "../auth/testing.js"; +import { CryptoTokenSecrets, FakeClock, MemoryFilesystem, NoopLogger } from "../ports/index.js"; import { type AuthEnv, requireAuth } from "./auth.js"; import { errorResponse } from "./errors.js"; -import type { TokenIdentity } from "./token-store.js"; -class FakeTokens { - readonly #identities = new Map(); - - register(secret: string, identity: TokenIdentity): void { - this.#identities.set(secret, identity); - } - - async verify(secret: string): Promise { - return this.#identities.get(secret); - } -} - -function appWithAuth(tokens: FakeTokens) { +function appWithAuth(identities: Map) { const app = new Hono(); app.onError((error, c) => errorResponse(c, error)); - app.get("/resource", requireAuth(tokens), (c) => c.json({ identity: c.get("identity") })); + app.get("/resource", requireAuth(fakeAuth(identities)), (c) => + c.json({ identity: c.get("identity") }), + ); return app; } describe("requireAuth", () => { it("401s with no Authorization header", async () => { - const response = await appWithAuth(new FakeTokens()).request("/resource"); + const response = await appWithAuth(new Map()).request("/resource"); expect(response.status).toBe(401); expect(await response.json()).toEqual({ error: { code: "UNAUTHENTICATED", message: expect.any(String) }, @@ -34,53 +32,105 @@ describe("requireAuth", () => { }); it("401s on a malformed Authorization header (no Bearer prefix)", async () => { - const response = await appWithAuth(new FakeTokens()).request("/resource", { + const response = await appWithAuth(new Map()).request("/resource", { headers: { authorization: "slk_secret" }, }); expect(response.status).toBe(401); }); it("401s on an unknown bearer token", async () => { - const response = await appWithAuth(new FakeTokens()).request("/resource", { + const response = await appWithAuth(new Map()).request("/resource", { headers: { authorization: "Bearer slk_unknown" }, }); expect(response.status).toBe(401); }); it("admits a known agent token and stores its identity", async () => { - const tokens = new FakeTokens(); - tokens.register("slk_agent", { requesterId: "tok_agent", role: "agent" }); - const response = await appWithAuth(tokens).request("/resource", { + const agent = tokenIdentity("tok_agent", "agent"); + const response = await appWithAuth(new Map([["slk_agent", agent]])).request("/resource", { headers: { authorization: "Bearer slk_agent" }, }); expect(response.status).toBe(200); - expect(await response.json()).toEqual({ - identity: { requesterId: "tok_agent", role: "agent" }, - }); + expect(await response.json()).toEqual({ identity: agent }); }); it("admits a known operator token too -- role gating is the shared dispatcher's job now, not this middleware's", async () => { - const tokens = new FakeTokens(); - tokens.register("slk_op", { requesterId: "tok_op", role: "operator" }); - const response = await appWithAuth(tokens).request("/resource", { + const operator = tokenIdentity("tok_op", "operator"); + const response = await appWithAuth(new Map([["slk_op", operator]])).request("/resource", { headers: { authorization: "Bearer slk_op" }, }); expect(response.status).toBe(200); - expect(await response.json()).toEqual({ - identity: { requesterId: "tok_op", role: "operator" }, + expect(await response.json()).toEqual({ identity: operator }); + }); +}); + +describe("requireAuth over src/auth", () => { + const options = { + config: { enabled: true, host: "127.0.0.1", port: 4700 }, + dataDirectory: "/home/agent/.simlock", + filesystem: new MemoryFilesystem(), + secrets: new CryptoTokenSecrets(), + idGenerator: { generate: () => "id" }, + clock: new FakeClock(1_000), + logger: new NoopLogger(), + }; + + function refusing(answer: StrategyAnswer): AuthStrategyDefinition { + return { + name: "fake", + enabled: () => true, + create: () => ({ authenticate: async () => answer }), + }; + } + + function appWithAuthFrom(auth: Auth) { + const app = new Hono(); + app.onError((error, c) => errorResponse(c, error)); + app.get("/resource", requireAuth(auth), (c) => c.json({ ok: true })); + return app; + } + + it("answers an AuthError 401 as UNAUTHENTICATED with its message and details, and a 403 as FORBIDDEN", async () => { + const rejected = await appWithAuthFrom( + createAuthWith( + [refusing({ kind: "rejected", message: "Token expired", details: { expiredAt: 5 } })], + options, + ), + ).request("/resource"); + expect(rejected.status).toBe(401); + expect(await rejected.json()).toEqual({ + error: { code: "UNAUTHENTICATED", message: "Token expired", details: { expiredAt: 5 } }, + }); + + const forbidden = await appWithAuthFrom( + createAuthWith([refusing({ kind: "forbidden", message: "No authority here" })], options), + ).request("/resource"); + expect(forbidden.status).toBe(403); + expect(await forbidden.json()).toEqual({ + error: { code: "FORBIDDEN", message: "No authority here" }, }); }); - it("403s a worker join token: it can open an uplink and nothing else (ADR 0005 §25)", async () => { - const tokens = new FakeTokens(); - tokens.register("slk_join", { requesterId: "tok_join", role: "worker" }); - const response = await appWithAuth(tokens).request("/resource", { - headers: { authorization: "Bearer slk_join" }, + it("answers a token's 401 with only code and message", async () => { + const response = await appWithAuthFrom(createAuth(options)).request("/resource", { + headers: { authorization: "Bearer slk_unknown" }, }); - // 403, not 401: the token is real and was recognized, it just has no authority here. - expect(response.status).toBe(403); + expect(response.status).toBe(401); expect(await response.json()).toEqual({ - error: { code: "FORBIDDEN", message: expect.any(String) }, + error: { code: "UNAUTHENTICATED", message: "Unknown bearer token" }, }); }); + + it("lets an error that is not an AuthError through as a 500, never a 401 or 403", async () => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp(options.dataDirectory); + await filesystem.writeFileAtomic(`${options.dataDirectory}/tokens.json`, "{ not valid json"); + + const response = await appWithAuthFrom(createAuth({ ...options, filesystem })).request( + "/resource", + { headers: { authorization: "Bearer slk_any" } }, + ); + + expect(response.status).toBe(500); + }); }); diff --git a/src/http/auth.ts b/src/http/auth.ts index b354cccd8..553781ba4 100644 --- a/src/http/auth.ts +++ b/src/http/auth.ts @@ -1,59 +1,27 @@ import type { Context, MiddlewareHandler, Next } from "hono"; -import { forbidden, unauthenticated } from "./errors.js"; -import type { TokenIdentity } from "./token-store.js"; +import { type Auth, AuthError, type Identity } from "../auth/index.js"; +import { HttpApiError } from "./errors.js"; export interface AuthEnv { readonly Variables: { - identity: TokenIdentity; + identity: Identity; }; } -export interface TokenVerifier { - verify(secret: string): Promise; -} - -const BEARER_PREFIX = "Bearer "; - -function extractSecret(header: string | undefined): string | undefined { - if (header === undefined || !header.startsWith(BEARER_PREFIX)) return undefined; - const secret = header.slice(BEARER_PREFIX.length).trim(); - return secret === "" ? undefined : secret; -} - -/** - * ADR 0003 §2: "The HTTP app becomes routing plus a bearer-token-to-session adapter". This is - * that adapter's authentication half -- it verifies the bearer token and stores its - * `TokenIdentity` on the context, nothing more. Role gating (what used to be this function's - * own `minRole` parameter, 403-ing an agent token before a handler ran) and per-resource - * ownership (what used to be the separate `requireOwnership` export) both moved to the shared - * `Dispatcher`'s role check and `authorize` hook (see `dispatcher-session.ts`) -- the same - * checks the socket path runs, not a second HTTP-only copy. A route still needs *an* identity - * to build the `DispatchSession` `dispatch()` takes, which is what this middleware supplies. - * - * The one role decision that *does* live here is ADR 0005 §25's: a `worker`-role join token is - * `403` on every `/v1` route. It is not a role gate of the kind that moved to the dispatcher -- - * those compare an operation's required role to a session's. This is narrower and belongs at - * the transport: a join token authorizes one transport (the uplink upgrade, see - * `src/ports/uplink.ts`) and no operation at all, so there is no session to build from it and - * nothing further down the stack could tell the difference between it and an agent token. - * Refusing it here, before a `DispatchSession` exists, is what makes "it can open an uplink and - * nothing else" true rather than aspirational. - */ -export function requireAuth(tokens: TokenVerifier): MiddlewareHandler { +export function requireAuth(auth: Pick): MiddlewareHandler { return async (c: Context, next: Next) => { - const secret = extractSecret(c.req.header("authorization")); - if (secret === undefined) throw unauthenticated("Missing bearer token"); - - const identity = await tokens.verify(secret); - if (identity === undefined) throw unauthenticated("Unknown bearer token"); - // 403, not 401: the token is real and was recognized -- it simply has no authority here - // (ADR 0005 §25). - if (identity.role === "worker") { - throw forbidden("A worker join token can only open an uplink, not call the HTTP API"); + try { + c.set("identity", await auth.authenticateRequest(c.req.raw.headers)); + } catch (error: unknown) { + if (!(error instanceof AuthError)) throw error; + throw new HttpApiError( + error.status, + error.status === 401 ? "UNAUTHENTICATED" : "FORBIDDEN", + error.message, + error.details === undefined ? undefined : { details: error.details }, + ); } - - c.set("identity", identity); await next(); }; } diff --git a/src/http/core-routes.test.ts b/src/http/core-routes.test.ts index e55a5d8d3..b00c9c678 100644 --- a/src/http/core-routes.test.ts +++ b/src/http/core-routes.test.ts @@ -4,14 +4,9 @@ import { EventBus } from "../bus/index.js"; import { CORE_ROUTE_SEGMENTS } from "../contract/index.js"; import { OwnerRoutedFactBus } from "../daemon/owner-routed-facts.js"; import { FakeClock, JsonLinesLogger, MemoryLogSink } from "../ports/index.js"; +import { fakeAuth } from "../auth/testing.js"; import { createHttpApp } from "./app.js"; -import { - FakeDispatcher, - FakeRegistry, - FakeTokenVerifier, - sequenceIdGenerator, - testConfig, -} from "./test-fakes.js"; +import { FakeDispatcher, FakeRegistry, sequenceIdGenerator, testConfig } from "./test-fakes.js"; describe("the routes createHttpApp registers", () => { it("every route createHttpApp registers starts with a name in CORE_ROUTE_SEGMENTS", () => { @@ -29,7 +24,7 @@ describe("the routes createHttpApp registers", () => { logger: new JsonLinesLogger({ clock, sink: new MemoryLogSink() }), ownerRoutedFacts: new OwnerRoutedFactBus(eventBus, registry), registry, - tokens: new FakeTokenVerifier(), + auth: fakeAuth(new Map()), }); const segments = app.routes diff --git a/src/http/dispatcher-session.ts b/src/http/dispatcher-session.ts index 51dcbe7f5..7063bd1b1 100644 --- a/src/http/dispatcher-session.ts +++ b/src/http/dispatcher-session.ts @@ -3,7 +3,7 @@ import type { z } from "zod"; import type { DispatchSession } from "../daemon/dispatcher.js"; import type { LeaseProgress } from "../core/index.js"; import type { ComponentProgress, OPERATIONS, OperationName, Role } from "../contract/index.js"; -import type { TokenIdentity, TokenRole } from "./token-store.js"; +import type { Identity } from "../auth/index.js"; /** * The one method `createHttpApp` needs from `DaemonServer` (ADR §2: "the HTTP app ... calls @@ -21,27 +21,14 @@ export type HttpDispatch = ( * `operator` token is what already grants HTTP's admin-only routes (`/v1/leases`, * `/v1/devices`, `/v1/events`...), so it resolves to the contract's `"admin"`; an `agent` * token resolves to `"agent"`. */ -function toRole(tokenRole: TokenRole): Role { - return tokenRole === "operator" ? "admin" : "agent"; +function toRole(identityRole: Identity["role"]): Role { + return identityRole === "operator" ? "admin" : "agent"; } -/** - * Builds the `DispatchSession` ADR §2's shared dispatcher needs, from one HTTP request's - * already-verified bearer-token identity. This is the "bearer-token-to-session adapter" ADR §2 - * assigns to the HTTP app: `principal` is the token's `requesterId` (ADR §4: "For HTTP the - * principal is the token's requester id"), `role` is `identity.role` translated per `toRole`. - * - * `onProgress`/`manageEventSubscription` are per-call, not part of the token identity -- - * callers that need either (the lease-request tracker's `onProgress`, the `/v1/events/stream` - * SSE route's `manageEventSubscription`) pass their own override via `extra`. Every other route - * gets an inert default: `onProgress` is simply never invoked by any operation but - * `lease.request`'s handler, and `manageEventSubscription` is only ever invoked by - * `events.subscribe`/`events.unsubscribe`'s handlers, neither of which any other route - * dispatches -- an HTTP request that doesn't wire either override never triggers this fallback - * in practice; it exists only to satisfy `DispatchSession`'s required fields. - */ +// why: `onProgress` and the like are per-call, not part of the identity, so the routes that need one pass an override in `extra`; every other route gets inert defaults that no operation it dispatches ever calls. + export function buildHttpSession( - identity: TokenIdentity, + identity: Identity, extra?: { readonly onProgress?: (progress: LeaseProgress) => void; /** The lease-request route's own override: the stored request's id, the moment the daemon @@ -73,7 +60,7 @@ export function buildHttpSession( ): DispatchSession { return { manageEventSubscription: extra?.manageEventSubscription ?? (() => undefined), - principal: identity.requesterId, + principal: identity.principal, role: toRole(identity.role), ...(extra?.onProgress === undefined ? {} : { onProgress: extra.onProgress }), ...(extra?.onRequestAdmitted === undefined diff --git a/src/http/server.test.ts b/src/http/server.test.ts index ae2b9de03..11e31945f 100644 --- a/src/http/server.test.ts +++ b/src/http/server.test.ts @@ -7,15 +7,11 @@ import { afterEach, describe, expect, it } from "vitest"; import { EventBus } from "../bus/index.js"; import { OwnerRoutedFactBus } from "../daemon/owner-routed-facts.js"; import { FakeClock, JsonLinesLogger, MemoryLogSink } from "../ports/index.js"; +import type { Identity } from "../auth/index.js"; +import { fakeAuth, tokenIdentity } from "../auth/testing.js"; import { createHttpApp } from "./app.js"; import { CONSOLE_CONTENT_SECURITY_POLICY, HttpGateway, withConsole } from "./server.js"; -import { - FakeDispatcher, - FakeRegistry, - FakeTokenVerifier, - sequenceIdGenerator, - testConfig, -} from "./test-fakes.js"; +import { FakeDispatcher, FakeRegistry, sequenceIdGenerator, testConfig } from "./test-fakes.js"; const PAGE = 'Simlock
'; const SCRIPT = "console.log('console');"; @@ -50,8 +46,9 @@ function harness(root: string) { const dispatcher = new FakeDispatcher(clock); dispatcher.handlers["status.get"] = () => ({ ok: true }); const registry = new FakeRegistry(); - const tokens = new FakeTokenVerifier(); - tokens.register("slk_operator", { requesterId: "tok_operator", role: "operator" }); + const auth = fakeAuth( + new Map([["slk_operator", tokenIdentity("tok_operator", "operator")]]), + ); const logSink = new MemoryLogSink(); const logger = new JsonLinesLogger({ clock, sink: logSink }); const app = createHttpApp({ @@ -64,7 +61,7 @@ function harness(root: string) { logger, ownerRoutedFacts: new OwnerRoutedFactBus(eventBus, registry), registry, - tokens, + auth, }); const site = withConsole(app, { logger, root }); const get = (path: string, init: RequestInit = {}) => diff --git a/src/http/test-fakes.ts b/src/http/test-fakes.ts index 7ab9f4bb8..6568fef7d 100644 --- a/src/http/test-fakes.ts +++ b/src/http/test-fakes.ts @@ -21,7 +21,6 @@ import { DispatchError } from "../daemon/dispatch.js"; import type { DispatchSession } from "../daemon/dispatcher.js"; import { describeLeaseRequestFailure } from "../daemon/error-code.js"; import { type Clock, FakeClock, type IdGenerator } from "../ports/index.js"; -import type { TokenIdentity } from "./token-store.js"; const gibibyte = 1024 * 1024 * 1024; @@ -318,16 +317,3 @@ export class FakeRegistry { }; } } - -export class FakeTokenVerifier { - readonly #identities = new Map(); - - register(secret: string, identity: TokenIdentity): void { - this.#identities.set(secret, identity); - } - - // fallow-ignore-next-line unused-class-member -- reached structurally through HttpGatewayDeps.tokens. - async verify(secret: string): Promise { - return this.#identities.get(secret); - } -} diff --git a/src/http/tracker.test.ts b/src/http/tracker.test.ts index c259081a3..e3ea0b5bb 100644 --- a/src/http/tracker.test.ts +++ b/src/http/tracker.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; +import { tokenIdentity } from "../auth/testing.js"; import { type VirtualDevice } from "../core/index.js"; import { NoCapacityError, @@ -21,7 +22,7 @@ function buildTracker() { return { clock, dispatcher, tracker }; } -const identity = { requesterId: "tok_agent", role: "agent" as const }; +const identity = tokenIdentity("tok_agent"); const body = { device: "iPhone 17 Pro", platform: "ios" as const }; async function createTracked( @@ -143,11 +144,7 @@ describe("LeaseRequestTracker.submit", () => { it("does not replay an Idempotency-Key across different requesters", async () => { const { dispatcher, tracker } = buildTracker(); await createTrackedWithKey(tracker, dispatcher, "key-1"); - const outcomePromise = tracker.submit( - { requesterId: "tok_other", role: "agent" }, - body, - "key-1", - ); + const outcomePromise = tracker.submit(tokenIdentity("tok_other"), body, "key-1"); const call = await waitForDispatch(dispatcher, "lease.request", 1); call.session.onProgress?.({ queuePosition: 1, stage: "queued" }); const outcome = await outcomePromise; diff --git a/src/http/tracker.ts b/src/http/tracker.ts index b829cdc41..ffdd76a09 100644 --- a/src/http/tracker.ts +++ b/src/http/tracker.ts @@ -4,7 +4,7 @@ import { type DeviceClass, leaseRequestRecordSchema } from "../contract/index.js import type { Clock } from "../ports/index.js"; import { buildHttpSession } from "./dispatcher-session.js"; import type { HttpDispatch } from "./dispatcher-session.js"; -import type { TokenIdentity } from "./token-store.js"; +import type { Identity } from "../auth/index.js"; export interface LeaseRequestInput { readonly platform: "ios" | "android"; @@ -190,7 +190,7 @@ export class LeaseRequestTracker { * the resource exists, and its state is the stored result. */ submit( - identity: TokenIdentity, + identity: Identity, body: LeaseRequestInput, idempotencyKey?: string, ): Promise< @@ -223,8 +223,8 @@ export class LeaseRequestTracker { const view = this.get(requestId) ?? { createdAt: new Date(this.options.clock.now()).toISOString(), id: requestId, - ownerId: identity.requesterId, - requesterId: identity.requesterId, + ownerId: identity.principal, + requesterId: identity.principal, state, }; resolve({ kind: "created", view: { ...view, state } }); @@ -323,7 +323,7 @@ export class LeaseRequestTracker { * from the moment it is rejected, before the record is written, so a `GET` right after the * `204` already reads `cancelled`. */ - async cancel(id: string, identity: TokenIdentity): Promise { + async cancel(id: string, identity: Identity): Promise { const before = this.get(id); if (before === undefined) return { kind: "not-found" }; if (before.state.stage === "granted") diff --git a/src/lint-rules.test.ts b/src/lint-rules.test.ts index edfb37f06..bfafd676d 100644 --- a/src/lint-rules.test.ts +++ b/src/lint-rules.test.ts @@ -633,6 +633,35 @@ describe("main.ts imports nothing from any module", () => { }); }); +describe("src/auth imports little", () => { + function authViolations(source: string): string[] { + const dir = join(scratch, `auth-little-${counter++}`); + const world: Record = { + "src/core/index.ts": "export const value = 1;\n", + "src/ports/index.ts": "export const port = 1;\n", + "src/auth/index.ts": source, + }; + for (const [path, contents] of Object.entries(world)) { + mkdirSync(dirname(join(dir, path)), { recursive: true }); + writeFileSync(join(dir, path), contents); + } + copyFileSync(join(repoRoot, ".dependency-cruiser.mjs"), join(dir, ".dependency-cruiser.mjs")); + copyFileSync(join(repoRoot, "tsconfig.json"), join(dir, "tsconfig.json")); + return cruise(dir, ["src"]) + .filter((v) => v.from === "src/auth/index.ts") + .map((v) => v.rule.name); + } + + it("dependency-cruiser fails a file in src/auth importing src/core/index.ts and passes one importing src/ports/index.ts", () => { + expect(authViolations('import { port } from "../ports/index.js";\nexport { port };\n')).toEqual( + [], + ); + expect( + authViolations('import { value } from "../core/index.js";\nexport { value };\n'), + ).toContain("auth-imports-little"); + }); +}); + describe("the cycle check between components", () => { function cycleWorld(files: Record): Violation[] { const dir = join(scratch, `cycles-${counter++}`); diff --git a/src/modules/types.ts b/src/modules/types.ts index 1664f27e7..69979dda7 100644 --- a/src/modules/types.ts +++ b/src/modules/types.ts @@ -76,7 +76,7 @@ export type ModuleDispatch = ( ) => Promise>; export interface ModuleIdentity { - readonly requesterId: string; + readonly principal: string; readonly role: "agent" | "operator" | "worker"; } diff --git a/src/stream/mounts.ts b/src/stream/mounts.ts index e27708eea..00e920cc6 100644 --- a/src/stream/mounts.ts +++ b/src/stream/mounts.ts @@ -6,7 +6,7 @@ import { handleStreamRequest, leaseIdOf, type StreamServiceOptions } from "./ser export interface StreamMount { handle( request: Request, - identity: { readonly requesterId: string; readonly role: string }, + identity: { readonly principal: string; readonly role: string }, ): Promise; } @@ -21,7 +21,7 @@ export function createStreamMount(options: StreamServiceOptions): StreamMount { options, request, { - principal: identity.requesterId, + principal: identity.principal, role: identity.role === "operator" ? "operator" : "agent", }, leaseIdOf(new URL(request.url).pathname),