From ce85b09d62182d76ac3627996c6fb174c20fd913 Mon Sep 17 00:00:00 2001 From: Sanchit Rk <0xsanchit@gmail.com> Date: Thu, 19 Nov 2026 15:38:16 +0530 Subject: [PATCH] feat: bind every machine link to one identity key Each home now holds one Ed25519 identity key in machine.json, created inside the existing lock (also for homes connected before this change). At pairing, the identity key signs the new link key's thumbprint; the relay verifies the binding and stores the identity's thumbprint on the pairing and then the link. Links that share identityKeyId, in any workspace, are provably one machine, and the machine list exposes it. Per-link keys stay as they are: a leaked link key still exposes one workspace, and each link keeps its own relay. Co-Authored-By: Claude Opus 5.5 --- infra/relay/src/machines.ts | 32 ++++++-- infra/relay/src/migrations.ts | 5 +- infra/relay/test/__artifacts__/identity.json | 31 ++++++++ infra/relay/test/connect.test.ts | 81 ++++++++++++++++++++ packages/codework/src/machine/file.ts | 18 ++++- packages/codework/src/machine/relay.ts | 5 +- packages/schema/src/relay.ts | 15 ++++ 7 files changed, 177 insertions(+), 10 deletions(-) create mode 100644 infra/relay/test/__artifacts__/identity.json diff --git a/infra/relay/src/machines.ts b/infra/relay/src/machines.ts index 0f598e15..68fae23a 100644 --- a/infra/relay/src/machines.ts +++ b/infra/relay/src/machines.ts @@ -29,6 +29,7 @@ interface MachineRow { readonly ownerId: string; readonly key: Jws.PublicKey; readonly keyId: string; + readonly identityKeyId: string; readonly online: boolean; readonly lastSeenAt: Date | null; readonly revokedAt: Date | null; @@ -40,6 +41,7 @@ interface PairingRow { readonly machine: Relay.MachineInfo; readonly key: Jws.PublicKey; readonly keyId: string; + readonly identityKeyId: string; readonly status: "pending" | "approved" | "active" | "declined" | "superseded"; readonly approvedBy: string | null; readonly connected: Relay.Connected | null; @@ -57,6 +59,7 @@ const toMachine = (row: MachineRow) => arch: row.arch, version: row.version, keyId: row.keyId, + identityKeyId: row.identityKeyId, ownerId: row.ownerId, online: row.online, lastSeenAt: row.lastSeenAt?.toISOString() ?? null, @@ -138,7 +141,7 @@ export class Machines extends Context.Service< const machineColumns = sql` workspace_id, id, source, local_host_name, given_name, os, arch, version, owner_id, key, key_id, - last_seen_at, revoked_at, coalesce(last_seen_at > now() - make_interval(secs => ${leaseSeconds}), false) AS online + identity_key_id, last_seen_at, revoked_at, coalesce(last_seen_at > now() - make_interval(secs => ${leaseSeconds}), false) AS online `; // A machine request names its key by thumbprint; the key finds the one link it may act on. @@ -163,8 +166,22 @@ export class Machines extends Context.Service< return { row, claims: decoded }; }); + // The home's identity key vouches for a pairing's link key: it signs the link key's thumbprint, so + // a copied public key proves nothing and a binding made for one link can't serve another. + const identity = Effect.fn("Machines.identity")(function* (binding: string, keyId: string) { + const header = yield* Jws.peek(binding).pipe(Effect.mapError(() => invalid("Malformed identity"))); + if (header.jwk === undefined) return yield* invalid("An identity embeds its key"); + const claims = yield* Jws.verify(binding, header.jwk).pipe( + Effect.flatMap(Schema.decodeUnknownEffect(Relay.IdentityClaims)), + Effect.mapError(() => invalid("Invalid identity")), + ); + yield* fresh(claims.iat); + if (claims.keyId !== keyId) return yield* invalid("The identity vouches for another key"); + return yield* Jws.thumbprint(header.jwk).pipe(Effect.orDie); + }); + const pairingColumns = sql` - id, workspace_id, machine, key, key_id, approved_by, connected, expires_at < now() AS expired, + id, workspace_id, machine, key, key_id, identity_key_id, approved_by, connected, expires_at < now() AS expired, CASE WHEN status = 'active' AND NOT EXISTS ( SELECT 1 FROM machine m WHERE m.key_id = pairing.key_id AND m.revoked_at IS NULL ) THEN 'superseded' ELSE status END AS status @@ -188,16 +205,18 @@ export class Machines extends Context.Service< // Replacing a live link keeps its owner; a new or revoked one belongs to the approver. const [row] = yield* sql` INSERT INTO machine ( - workspace_id, id, source, local_host_name, given_name, os, arch, version, owner_id, key, key_id + workspace_id, id, source, local_host_name, given_name, os, arch, version, owner_id, key, key_id, + identity_key_id ) VALUES ( ${workspaceId}, ${info.id}, ${info.source}, ${info.localHostName}, ${info.givenName}, ${info.os}, ${info.arch}, ${info.version}, ${pairing.approvedBy}, - ${JSON.stringify(pairing.key)}::jsonb, ${pairing.keyId} + ${JSON.stringify(pairing.key)}::jsonb, ${pairing.keyId}, ${pairing.identityKeyId} ) ON CONFLICT (workspace_id, id) DO UPDATE SET source = excluded.source, local_host_name = excluded.local_host_name, given_name = excluded.given_name, os = excluded.os, arch = excluded.arch, version = excluded.version, key = excluded.key, key_id = excluded.key_id, + identity_key_id = excluded.identity_key_id, owner_id = CASE WHEN machine.revoked_at IS NULL THEN machine.owner_id ELSE excluded.owner_id END, last_seen_at = NULL, revoked_at = NULL RETURNING ${machineColumns} @@ -238,6 +257,7 @@ export class Machines extends Context.Service< ); yield* fresh(claims.iat); const keyId = yield* Jws.thumbprint(header.jwk).pipe(Effect.orDie); + const identityKeyId = yield* identity(claims.identity, keyId); // A key registers once: reused, it would answer for another connect or link. const taken = yield* sql` SELECT 1 FROM machine WHERE key_id = ${keyId} UNION ALL SELECT 1 FROM pairing WHERE key_id = ${keyId} @@ -251,10 +271,10 @@ export class Machines extends Context.Service< yield* sql`DELETE FROM pairing WHERE expires_at < now() - interval '1 day'`; const code = userCode(); yield* sql` - INSERT INTO pairing (user_code, workspace_id, machine, key, key_id, status, expires_at) + INSERT INTO pairing (user_code, workspace_id, machine, key, key_id, identity_key_id, status, expires_at) VALUES ( ${code}, ${claims.workspaceId}, ${JSON.stringify(claims.machine)}::jsonb, - ${JSON.stringify(header.jwk)}::jsonb, ${keyId}, 'pending', + ${JSON.stringify(header.jwk)}::jsonb, ${keyId}, ${identityKeyId}, 'pending', now() + make_interval(secs => ${pairingSeconds}) ) `; diff --git a/infra/relay/src/migrations.ts b/infra/relay/src/migrations.ts index 88d350d9..064f1a96 100644 --- a/infra/relay/src/migrations.ts +++ b/infra/relay/src/migrations.ts @@ -43,7 +43,8 @@ export const migrations = { const sql = yield* SqlClient.SqlClient; // A machine's link to one workspace. Each link has its own key, so one home connected to N - // workspaces is N rows, and the key's thumbprint (key_id) finds exactly one of them. + // workspaces is N rows, and the key's thumbprint (key_id) finds exactly one of them. The home's + // identity key vouched for that key at pairing: rows sharing identity_key_id are one machine. yield* sql` CREATE TABLE machine ( workspace_id uuid NOT NULL REFERENCES workspace(id) ON DELETE CASCADE, @@ -57,6 +58,7 @@ export const migrations = { owner_id uuid NOT NULL REFERENCES account(id), key jsonb NOT NULL, key_id text NOT NULL UNIQUE, + identity_key_id text NOT NULL, last_seen_at timestamptz, created_at timestamptz NOT NULL DEFAULT now(), revoked_at timestamptz, @@ -75,6 +77,7 @@ export const migrations = { machine jsonb NOT NULL, key jsonb NOT NULL, key_id text NOT NULL UNIQUE, + identity_key_id text NOT NULL, status text NOT NULL CHECK (status IN ('pending', 'approved', 'active', 'declined', 'superseded')), approved_by uuid REFERENCES account(id), connected jsonb, diff --git a/infra/relay/test/__artifacts__/identity.json b/infra/relay/test/__artifacts__/identity.json new file mode 100644 index 00000000..425ab070 --- /dev/null +++ b/infra/relay/test/__artifacts__/identity.json @@ -0,0 +1,31 @@ +{ + "machineFile": { + "identityKty": "OKP", + "identityCrv": "Ed25519", + "identityIsALinkKey": false + }, + "links": [ + { + "id": "e2e-box", + "workspace": "", + "identityIsHomeIdentity": true + }, + { + "id": "e2e-box", + "workspace": "", + "identityIsHomeIdentity": true + } + ], + "linkKeysDiffer": true, + "replayedBinding": { + "status": 401, + "tag": "Relay.Unauthorized", + "message": "The identity vouches for another key" + }, + "malformedBinding": { + "status": 401, + "tag": "Relay.Unauthorized", + "message": "Malformed identity" + }, + "forgedPairings": 0 +} diff --git a/infra/relay/test/connect.test.ts b/infra/relay/test/connect.test.ts index 5a1f60f7..3d41ac2d 100644 --- a/infra/relay/test/connect.test.ts +++ b/infra/relay/test/connect.test.ts @@ -399,4 +399,85 @@ describe.skipIf(secretKey === undefined)("codework connect", () => { gateway.closeAllConnections(); } }, 30_000); + + it("binds every link of a home to one identity, and refuses a binding made for another key", async () => { + const first = decodeMe(await (await asPerson("/v1/me")).json()).workspaces[0]!; + const created = await asPerson("/v1/workspaces", { method: "POST", body: JSON.stringify({ name: "Second" }) }); + const second = Schema.decodeUnknownSync(Relay.Workspace)(await created.json()); + const link = async (workspaceId: string) => { + const connect = codework(["connect", "--workspace", workspaceId]); + const done = finished(connect); + const userCode = await waitForLine(connect, (line) => /code ([A-Z]{4}-[A-Z]{4})/.exec(line)?.[1]); + const approve = await asPerson("/v1/pairings/approve", { + method: "POST", + body: JSON.stringify({ userCode, workspaceId }), + }); + expect(approve.status).toBe(200); + expect((await done).code).toBe(0); + }; + + // One home, two workspaces: two link keys, one identity behind both. + await link(first.id); + await link(second.id); + const file = machineFile(); + const [inFirst] = await machines(first.id); + const [inSecond] = await machines(second.id); + + // Even the home's real identity key can't vouch for a link key its binding doesn't name. + const forger: Relay.MachineInfo = { + id: "e2e-forger", + source: "flag", + localHostName: "forger", + givenName: null, + os: "linux", + arch: "arm64", + version: "0.0.0", + }; + const pair = async (identity: (keyId: string) => Promise) => { + const key = await Effect.runPromise(Jws.generate()); + const keyId = await Effect.runPromise(Jws.thumbprint(Jws.publicOf(key))); + const claims: Relay.PairingClaims = { + op: "pairing.create", + iat: Date.now(), + machine: forger, + workspaceId: first.id, + identity: await identity(keyId), + }; + const response = await fetch(`${relay.base}/v1/pairings`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ jws: await Effect.runPromise(Jws.sign(claims, key, { embed: true })) }), + }); + const body = Schema.decodeUnknownSync(Schema.Struct({ _tag: Schema.String, message: Schema.String }))( + await response.json(), + ); + return { status: response.status, tag: body._tag, message: body.message }; + }; + const bindingFor = (keyId: string) => + Effect.runPromise( + Jws.sign({ op: "identity.bind", iat: Date.now(), keyId }, file.identity.key, { embed: true }), + ); + const replayed = await pair(async () => bindingFor(inFirst!.keyId)); + const malformed = await pair(async () => "not-a-jws"); + + const artifact = { + machineFile: { + identityKty: file.identity.key.kty, + identityCrv: file.identity.key.crv, + identityIsALinkKey: Object.values<{ keyId: string }>(file.workspaces).some( + (entry) => entry.keyId === file.identity.keyId, + ), + }, + links: [inFirst!, inSecond!].map((machine) => ({ + id: machine.id, + workspace: machine.workspaceId === first.id ? "" : "", + identityIsHomeIdentity: machine.identityKeyId === file.identity.keyId, + })), + linkKeysDiffer: inFirst!.keyId !== inSecond!.keyId, + replayedBinding: replayed, + malformedBinding: malformed, + forgedPairings: Number(relay.psql("SELECT count(*) FROM pairing WHERE machine->>'id' = 'e2e-forger'")), + }; + await expect(`${JSON.stringify(artifact, null, "\t")}\n`).toMatchFileSnapshot("./__artifacts__/identity.json"); + }, 60_000); }); diff --git a/packages/codework/src/machine/file.ts b/packages/codework/src/machine/file.ts index 830d8092..970cc5ca 100644 --- a/packages/codework/src/machine/file.ts +++ b/packages/codework/src/machine/file.ts @@ -17,14 +17,22 @@ const Link = Schema.Struct({ keyId: Schema.String, }); +/** One key per home, vouching for each link key, so the relay knows every link of this home is one machine. */ +const Identity = Schema.Struct({ key: Jws.PrivateKey, keyId: Schema.String }); +type Identity = typeof Identity.Type; + export const Machine = Schema.Struct({ id: Schema.String, source: Relay.IdSource, /** The user's own name for the machine; shown in place of the OS host name when set. */ givenName: Schema.optional(Schema.String), + // Optional only for homes connected before identities existed; `update` gives every home one. + identity: Schema.optional(Identity), workspaces: Schema.Record(Schema.String, Link), }); export type Machine = typeof Machine.Type; +/** The machine as {@link update} hands it out: always with its identity. */ +type Identified = Machine & { readonly identity: Identity }; const json = Schema.fromJsonString(Machine); @@ -68,11 +76,16 @@ const write = Effect.fn("Machine.write")(function* (home: string, machine: Machi yield* fs.rename(temp, path); }); +const newIdentity = Effect.gen(function* () { + const key = yield* Jws.generate(); + return { key, keyId: yield* Jws.thumbprint(Jws.publicOf(key)) } satisfies Identity; +}); + /** Reads, changes and writes the machine under the lock, creating its identity on first use. */ export const update = ( home: string, options: { readonly machineId?: string | undefined }, - change: (machine: Machine) => Effect.Effect, + change: (machine: Identified) => Effect.Effect, ) => locked( home, @@ -89,7 +102,8 @@ export const update = ( }), ), }); - const next = yield* change(machine); + const identity = machine.identity ?? (yield* newIdentity); + const next = yield* change({ ...machine, identity }); yield* write(home, next); return next; }), diff --git a/packages/codework/src/machine/relay.ts b/packages/codework/src/machine/relay.ts index d8797c9d..0a0563c3 100644 --- a/packages/codework/src/machine/relay.ts +++ b/packages/codework/src/machine/relay.ts @@ -85,11 +85,14 @@ export const connect = Effect.fn("Machine.connect")(function* (options: { const machine = yield* File.update(options.home, { machineId: options.machineId }, Effect.succeed); const key = yield* Jws.generate(); const keyId = yield* Jws.thumbprint(Jws.publicOf(key)); + const iat = yield* Clock.currentTimeMillis; + const binding: Relay.IdentityClaims = { op: "identity.bind", iat, keyId }; const claims: Relay.PairingClaims = { op: "pairing.create", - iat: yield* Clock.currentTimeMillis, + iat, machine: yield* describe(machine), workspaceId: options.workspaceId ?? null, + identity: yield* Jws.sign(binding, machine.identity.key, { embed: true }), }; const pairing = yield* client.api.machine .pair({ payload: { jws: yield* Jws.sign(claims, key, { embed: true }) } }) diff --git a/packages/schema/src/relay.ts b/packages/schema/src/relay.ts index 75785f17..8594d0c5 100644 --- a/packages/schema/src/relay.ts +++ b/packages/schema/src/relay.ts @@ -49,6 +49,8 @@ export class Machine extends Schema.Class("Relay.Machine")({ workspaceId: WorkspaceId, /** The thumbprint of the key the link is live under; a home holds that key for this workspace. */ keyId: Schema.String, + /** The thumbprint of the home's identity key: links with the same one, in any workspace, are one machine. */ + identityKeyId: Schema.String, ownerId: Schema.String, online: Schema.Boolean, lastSeenAt: Schema.NullOr(Schema.String), @@ -65,9 +67,22 @@ export const PairingClaims = Schema.Struct({ machine: MachineInfo, /** The workspace the connect started from; the approver may pick another when it is null. */ workspaceId: Schema.NullOr(WorkspaceId), + /** An {@link IdentityClaims} JWS by the home's identity key, naming this request's key. */ + identity: Schema.String, }); export type PairingClaims = typeof PairingClaims.Type; +/** + * A home's identity key vouching for one of its link keys. It embeds the identity key and names the link + * key's thumbprint, so the binding can't be replayed for another link. + */ +export const IdentityClaims = Schema.Struct({ + op: Schema.Literal("identity.bind"), + iat: Schema.Number, + keyId: Schema.String, +}); +export type IdentityClaims = typeof IdentityClaims.Type; + /** A pairing's poll, signed with the key it registered: only that process learns the outcome. */ export const PollClaims = Schema.Struct({ op: Schema.Literal("pairing.poll"),