Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 26 additions & 6 deletions infra/relay/src/machines.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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,
Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand All @@ -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<MachineRow>`
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}
Expand Down Expand Up @@ -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}
Expand All @@ -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})
)
`;
Expand Down
5 changes: 4 additions & 1 deletion infra/relay/src/migrations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -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,
Expand Down
31 changes: 31 additions & 0 deletions infra/relay/test/__artifacts__/identity.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"machineFile": {
"identityKty": "OKP",
"identityCrv": "Ed25519",
"identityIsALinkKey": false
},
"links": [
{
"id": "e2e-box",
"workspace": "<first>",
"identityIsHomeIdentity": true
},
{
"id": "e2e-box",
"workspace": "<second>",
"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
}
81 changes: 81 additions & 0 deletions infra/relay/test/connect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>) => {
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 ? "<first>" : "<second>",
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);
});
18 changes: 16 additions & 2 deletions packages/codework/src/machine/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down Expand Up @@ -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 = <E, R>(
home: string,
options: { readonly machineId?: string | undefined },
change: (machine: Machine) => Effect.Effect<Machine, E, R>,
change: (machine: Identified) => Effect.Effect<Identified, E, R>,
) =>
locked(
home,
Expand All @@ -89,7 +102,8 @@ export const update = <E, R>(
}),
),
});
const next = yield* change(machine);
const identity = machine.identity ?? (yield* newIdentity);
const next = yield* change({ ...machine, identity });
yield* write(home, next);
return next;
}),
Expand Down
5 changes: 4 additions & 1 deletion packages/codework/src/machine/relay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }) } })
Expand Down
15 changes: 15 additions & 0 deletions packages/schema/src/relay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ export class Machine extends Schema.Class<Machine>("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),
Expand All @@ -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"),
Expand Down