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
18 changes: 17 additions & 1 deletion docs/CLI.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
Part of the user manual: every command the simlock CLI is expected to
implement. Results are JSON on **stdout**; progress/diagnostics are JSON
lines on **stderr** — this is the default output, not an opt-in, because
agents are the primary audience. `status`, `catalog`, `stats` and
agents are the primary audience. `status`, `catalog`, `stats`, `whoami`, and
`daemon <start|stop|status|logs>` are the exception: they default to a
human-oriented view for interactive/operator use and accept `--json` to
switch to the structured form. Every other command's output is already
Expand Down Expand Up @@ -1374,6 +1374,22 @@ under the pre-0.3.0 hand-written schemas (`leaseId`, `deviceId`,
`allowDownload`, `requesterId`, ...); those did not change shape, only their
schema's source of truth.

## `simlock whoami [--json]`

Prints who Simlock thinks you are, for this CLI's own session: the principal,
the name to show, the role and how you signed in. Like every command it
starts the daemon when none runs.

```
$ simlock whoami
Principal: claude-1
Name: claude-1
Role: admin
Via: socket
```

`--json` prints `{"principal","name","role","via"}` as one object.

## `simlock status`

In `status --json`, an enrolled physical device's entry carries `driverDeviceId`,
Expand Down
8 changes: 8 additions & 0 deletions docs/CLIENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,14 @@ Three limits worth knowing:
Paths in `args` resolve on the daemon's filesystem, not yours. Getting an
`.app` or an `.apk` there is out of scope for now.

## Who you are: `identity()`

`client.identity()` asks the daemon who it thinks this connection is and
resolves to `{ principal, name, role, via }`. `name` is the principal when
nothing else was declared, `role` is `"admin"` or `"agent"`, and `via` is
`"socket"` for a socket connection. Both `connectSimlock` and
`connectSimlockAdmin` clients have it.

## Picking a device: `getCatalog`

`getCatalog({ platform? })` returns what can be leased, per platform:
Expand Down
11 changes: 11 additions & 0 deletions docs/HTTP-API.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,17 @@ ignores every one of them keeps working against a gateway unchanged.

Unauthenticated liveness for tunnels/load balancers. → `200 {"ok":true}`.

### `GET /v1/identity`

Role: `agent`. Who Simlock thinks the caller is: `principal` (the token's id),
`name` (the token's label, or its id when it has none), `role` (`admin` for an
operator token, `agent` for an agent token) and `via` (`token`). A `worker`
token is refused with `403`, as on every route.

```json
{"principal":"tok_9f2c","name":"ci-runner","role":"agent","via":"token"}
```

### `GET /v1/status`

Role: `agent`. The same view `simlock status --json` reads: a `daemon` block,
Expand Down
95 changes: 95 additions & 0 deletions e2e/identity.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { describe, expect, it } from "vitest";

import { waitFor, withHttpDaemon, type TestEnv } from "./helpers/index.js";

interface HttpDaemon {
readonly env: TestEnv;
readonly baseUrl: string;
}

async function httpDaemon(mode: "worker" | "gateway"): Promise<HttpDaemon> {
const { env, port } = await withHttpDaemon((port) => {
const http = { enabled: true, host: "127.0.0.1", port };
return mode === "gateway"
? { agentId: "claude-1", configOverrides: { http, mode: "gateway" }, driver: "none" }
: { agentId: "claude-1", configOverrides: { http } };
});
const baseUrl = `http://127.0.0.1:${port}`;
await waitFor(
async () => {
try {
return (await fetch(`${baseUrl}/v1/healthz`)).ok;
} catch {
return false;
}
},
{ label: "HTTP listener accepting connections" },
);
return { baseUrl, env };
}

async function mint(
env: TestEnv,
role: string,
label?: string,
): Promise<{ readonly secret: string; readonly token: { readonly id: string } }> {
const minted = await env.cli([
"token",
"create",
"--role",
role,
...(label === undefined ? [] : ["--label", label]),
]);
expect(minted.code, minted.stderr).toBe(0);
return minted.json as { secret: string; token: { id: string } };
}

function getIdentity(daemon: HttpDaemon, secret: string): Promise<Response> {
return fetch(`${daemon.baseUrl}/v1/identity`, { headers: { authorization: `Bearer ${secret}` } });
}

describe("identity.get", () => {
it("simlock whoami prints the four labelled lines for the CLI's own session, and --json prints the same as one object, on a worker and on a gateway", async () => {
for (const mode of ["worker", "gateway"] as const) {
const { env } = await httpDaemon(mode);

const text = await env.cli(["whoami"]);
expect(text.code, `${mode}: ${text.stderr}`).toBe(0);
expect(text.stdout.trimEnd().split("\n"), mode).toEqual([
"Principal: claude-1",
"Name: claude-1",
"Role: admin",
"Via: socket",
]);

const json = await env.cli(["whoami", "--json"]);
expect(json.code, `${mode}: ${json.stderr}`).toBe(0);
expect(json.json, mode).toEqual({
name: "claude-1",
principal: "claude-1",
role: "admin",
via: "socket",
});
}
});

it("GET /v1/identity with a minted agent token answers that token's id, its label and role agent, and a worker token is refused with 403, on a worker and on a gateway", async () => {
for (const mode of ["worker", "gateway"] as const) {
const daemon = await httpDaemon(mode);
const agent = await mint(daemon.env, "agent", "ci-runner");
const worker = await mint(daemon.env, "worker", "join");

const answered = await getIdentity(daemon, agent.secret);
expect(answered.status, mode).toBe(200);
expect(await answered.json(), mode).toEqual({
name: "ci-runner",
principal: agent.token.id,
role: "agent",
via: "token",
});

const refused = await getIdentity(daemon, worker.secret);
expect(refused.status, mode).toBe(403);
}
});
});
8 changes: 7 additions & 1 deletion src/agent-device/edge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,18 @@ const scope = { clientId: "client-1", leaseProvider: "proxy", runId: "run-1" } a

const adminSession = {
manageEventSubscription: () => undefined,
via: "socket",
principal: "admin",
role: "admin",
} as const;

function sessionFor(principal: string) {
return { manageEventSubscription: () => undefined, principal, role: "agent" } as const;
return {
manageEventSubscription: () => undefined,
via: "socket",
principal,
role: "agent",
} as const;
}

interface Envelope {
Expand Down
8 changes: 7 additions & 1 deletion src/agent-device/gateway-front.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,18 @@ const endedMessage = "lease ended by simlock; run disconnect, then open";

const adminSession = {
manageEventSubscription: () => undefined,
via: "socket",
principal: "admin",
role: "admin",
} as const;

function sessionFor(principal: string) {
return { manageEventSubscription: () => undefined, principal, role: "agent" } as const;
return {
manageEventSubscription: () => undefined,
via: "socket",
principal,
role: "agent",
} as const;
}

interface Envelope {
Expand Down
10 changes: 10 additions & 0 deletions src/auth/strategies/conformance.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";

import { OPERATIONS } from "../../contract/index.js";
import { authStrategies } from "./index.js";
import { tokenFixture } from "./token/testing.js";

Expand Down Expand Up @@ -41,3 +42,12 @@ describe.each(authStrategies.map((definition) => ({ definition })))(
});
},
);

describe("the strategy registry and identity.get", () => {
it("every registered strategy's name is a value of identity.get's via enum", () => {
const via: readonly string[] = OPERATIONS["identity.get"].output.shape.via.options;

expect(authStrategies.length).toBeGreaterThan(0);
for (const definition of authStrategies) expect(via).toContain(definition.name);
});
});
32 changes: 32 additions & 0 deletions src/cli/commands/whoami.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { connectDaemonClient } from "../connect.js";
import { commandArgs, writeResult } from "../args.js";
import type { CommandContext } from "../tree.js";

async function run(
argv: readonly string[],
{ environment, token }: CommandContext,
): Promise<number> {
const values = commandArgs(argv, {
help: { type: "boolean", short: "h" },
json: { type: "boolean" },
});
if (values.help) {
environment.stdout.write("Usage: simlock whoami [--json]\n");
return 0;
}
const client = await connectDaemonClient(environment, token);
try {
const identity = await client.identity();
if (values.json) writeResult((value) => environment.stdout.write(value), identity);
else {
environment.stdout.write(
`Principal: ${identity.principal}\nName: ${identity.name}\nRole: ${identity.role}\nVia: ${identity.via}\n`,
);
}
return 0;
} finally {
await client.close();
}
}

export { run };
7 changes: 7 additions & 0 deletions src/cli/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6292,6 +6292,13 @@ function fakeClient(overrides: Partial<SimlockAdminClient> = {}): SimlockAdminCl
daemonVersion: "test",
getCatalog: () => Promise.resolve(emptyCatalog),
getStatus: () => Promise.resolve(EMPTY_STATUS),
identity: () =>
Promise.resolve({
name: "test-requester",
principal: "test-requester",
role: "admin",
via: "socket",
}),
listComponents: () => Promise.resolve({ components: [] }),
requestLease: (_input, _options) => Promise.resolve(grant),
resolvePassthrough: () => Promise.resolve({ args: [], command: "adb", env: {} }),
Expand Down
2 changes: 1 addition & 1 deletion src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const USAGE = `Usage: simlock <command> [options]

Commands:
lease, release, status, list, catalog, cleanup, doctor, nuke, events, stats,
daemon, config, token
daemon, config, token, whoami
worker <list|drain|undrain|remove>
Inspect and manage the workers of a gateway; on a
single host, list shows the host itself
Expand Down
1 change: 1 addition & 0 deletions src/cli/tree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ export const COMMANDS: readonly CommandNode[] = [
{ name: "set", load: configModule },
],
},
{ name: "whoami", load: () => import("./commands/whoami.js") },
{
name: "token",
load: tokenModule,
Expand Down
1 change: 1 addition & 0 deletions src/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export type {
DoctorReport,
DoctorRunInput,
DriverPassthroughInput,
IdentityOutput,
LeaseCancelInput,
LeaseCancelOutput,
LeaseGrant,
Expand Down
4 changes: 2 additions & 2 deletions src/contract/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ park on readiness (all but `status.get`) → handler → parse output.
`src/daemon/dispatcher.ts` and `src/gateway/dispatcher.ts` each hold a handler for
every operation but `daemon.stop`, which `DaemonServer` answers.

- `agent`: `catalog.get`, `status.get`, `component.list`, `lease.request`, `lease.cancel`,
- `agent`: `identity.get`, `catalog.get`, `status.get`, `component.list`, `lease.request`, `lease.cancel`,
`lease.renew`, `lease.release`, `lease.list`, `driver.passthrough`, `device.exec`,
`doctor.run` without `fix` or `purgeOrphans`.
- `admin`: every other operation (`list.get`, `config.get`, `daemon.stop`, `events.*`,
Expand All @@ -55,7 +55,7 @@ Three identities:

## Protocol version

- Now `{ min: 46, max: 46 }`. `DAEMON_PROTOCOL_VERSION` (`src/daemon-protocol/`) is its `max`.
- Now `{ min: 47, max: 47 }`. `DAEMON_PROTOCOL_VERSION` (`src/daemon-protocol/`) is its `max`.
- Every change to a contract shape bumps it by one in the same PR. Move `min` too, unless
a compatibility path stays side by side.
- `hello` picks the highest overlap. None → `PROTOCOL_VERSION_UNSUPPORTED` with both ranges.
Expand Down
2 changes: 2 additions & 0 deletions src/contract/operations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ const ROLE_MATRIX: ReadonlyArray<{
input: { args: ["devices"], leaseId: "lease_1", tool: "adb" },
role: "agent",
},
{ name: "identity.get", input: {}, role: "agent" },
{ name: "token.list", input: {}, role: "admin" },
{ name: "token.revoke", input: { id: "tok_1" }, role: "admin" },
{ name: "worker.list", input: {}, role: "admin" },
Expand Down Expand Up @@ -135,6 +136,7 @@ const EFFECT_MATRIX: ReadonlyArray<{
input: { args: ["devices"], leaseId: "lease_1", tool: "adb" },
effect: "write",
},
{ name: "identity.get", input: {}, effect: "read" },
{ name: "token.list", input: {}, effect: "read" },
{ name: "token.revoke", input: { id: "tok_1" }, effect: "write" },
{ name: "worker.list", input: {}, effect: "read" },
Expand Down
15 changes: 15 additions & 0 deletions src/contract/operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1028,7 +1028,22 @@ export const relayCancel = defineOperation({
output: z.object({}),
});

const identityGet = defineOperation({
name: "identity.get",
role: "agent",
effect: "read",
input: z.object({}),
output: z.object({
principal: z.string(),
name: z.string(),
role: z.enum(["admin", "agent"]),
via: z.enum(["token", "proxy", "socket", "uplink"]),
signOutUrl: z.string().optional(),
}),
});

export const OPERATIONS = {
"identity.get": identityGet,
"catalog.get": catalogGet,
"status.get": statusGet,
"lease.request": leaseRequest,
Expand Down
4 changes: 2 additions & 2 deletions src/contract/protocol.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ describe("helloRequestSchema", () => {
});

describe("PROTOCOL_VERSION_RANGE", () => {
it("is 46, for usage.get and its ledger", () => {
expect(PROTOCOL_VERSION_RANGE).toEqual({ max: 46, min: 46 });
it("is one above the base branch's, for identity.get", () => {
expect(PROTOCOL_VERSION_RANGE).toEqual({ max: 47, min: 47 });
});
});
3 changes: 2 additions & 1 deletion src/contract/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export interface ProtocolRange {
const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() });

/** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */
export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 46, max: 46 };
export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 47, max: 47 };

const LEGACY_DAEMON_PROTOCOL_VERSION = 2;

Expand Down Expand Up @@ -85,6 +85,7 @@ export const CORE_ROUTE_SEGMENTS: readonly string[] = [
"devices",
"events",
"healthz",
"identity",
"lease-requests",
"leases",
"stats",
Expand Down
2 changes: 1 addition & 1 deletion src/daemon-protocol/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {

describe("daemon protocol", () => {
it("keeps the current protocol version and newline framing", () => {
expect(DAEMON_PROTOCOL_VERSION).toBe(46);
expect(DAEMON_PROTOCOL_VERSION).toBe(47);
expect(serializeFrame({ id: 1, type: "hello" })).toBe('{"id":1,"type":"hello"}\n');
});

Expand Down
2 changes: 1 addition & 1 deletion src/daemon/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ An HTTP bind failure after a good start stops the daemon (`http-start-failed`).
Principal: `hello.principal`, else `SIMLOCK_AGENT_ID`, else the daemon's pid.
Both are fixed for the connection's life.
3. **Version** — ranges overlap → highest common version. `PROTOCOL_VERSION_RANGE`
is `{ min: 46, max: 46 }` (`src/contract/protocol.ts`). No overlap → the
is `{ min: 47, max: 47 }` (`src/contract/protocol.ts`). No overlap → the
connection stays open, and every request but `daemon.stop` gets
`PROTOCOL_VERSION_UNSUPPORTED`.
4. **Request** — one frame → one `dispatch()` call. While stopping: `DAEMON_STOPPING`.
Expand Down
Loading
Loading