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
27 changes: 26 additions & 1 deletion docs/adr/0006-daemon-rpc-protocol-version.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ Accepted

## Rules at a glance

- Before remote JSON-RPC requests, compare the daemon's `rpcProtocolVersion` from `/health`.
- Before remote JSON-RPC requests, compare the daemon's `rpcProtocolVersion` from `/health`, or send them on the checked route, where the server makes that comparison.
- The checked route reaches its authentication verdict exactly as `/rpc` does, then refuses protocol skew before dispatch, with HTTP 409 and a typed `x-agent-device-refusal` header.
- Package `version` is diagnostic only and must not be used as a compatibility gate.
- Allow a missing `rpcProtocolVersion` unless a later security or protocol decision explicitly retires legacy compatibility.
- A persistent client may cache a successful probe if `/health` advertises an instance ID for the daemon endpoint and, for a proxy, for its upstream daemon.
Expand Down Expand Up @@ -70,13 +71,37 @@ Do not increment it for additive changes:
If a single command needs finer-grained compatibility in the future, prefer command-level feature or capability metadata to an increment of the whole RPC protocol.
This preference does not apply if the change also affects the shared transport contract.

### Checked RPC

`POST /rpc/checked` takes the same authentication, body, and answer as `/rpc`.
The client names its protocol in the mandatory `x-agent-device-rpc-protocol` header.
A missing header or another protocol gets HTTP 409, `x-agent-device-refusal: protocol-missing` or `protocol-mismatch`, and a JSON-RPC error with `dispatched: 'no'`.

The daemon runs a checked call through the `/rpc` flow: the same envelope, decoding, auth hook, tenant-trust and token gates, from the same inputs.
It answers the protocol refusal in place of any later answer, after those gates and before the instance precondition.
Only then do the error details name the refusing `service`, its `version`, and its `rpcProtocolVersion`.
A daemon checks the transport credential, from the headers or the JSON frame's `params.token`, before it compares the protocol or decodes the method, so a wrong credential always gets 401.
A checked call that fails before every auth gate passes, including a hook that throws, gets the ordinary `/rpc` rejection, never the protocol refusal; a refused call never reserves its request id.
A proxy authenticates, then checks the protocol, then the envelope; its default token check reads `params.token` from the body, and `authenticate` may receive a body that is not JSON.
Every refusal is built from local values: a bounded id (a short token or a safe integer, else `null`), the reason, and validated diagnostic values; a proxy never copies an upstream refusal's body or headers.
A proxy never follows a redirect on the checked route, and a custom upstream transport must not either.
A proxy admits `/rpc` and the checked route through one path: body limit, authentication, tenant method rules, credential rewriting, and public-only stamping.
It forwards a checked call to the daemon's checked route, which checks again, and marks a forwarded daemon protocol refusal as `upstream-protocol-mismatch`.
`/health` advertises `checked-rpc` on each link that serves the route.
A daemon that serves `checked-rpc` also serves `script-artifacts`, so the route needs no capability refusal.

The route, not a header, is what makes the check safe.
Released daemons and proxies answer an unknown route with 404 before dispatch, and they ignore unknown headers on `/rpc`.

## Alternatives Considered

- **Gate by package version.** This is simple, but it rejects compatible version differences.
It also makes proxy use brittle across frequent releases.
- **Do not check compatibility.** This maximizes compatibility.
However, it fails later, after the client has sent an RPC payload that a remote daemon may parse incorrectly.
- **Negotiate full schemas.** This is more precise, but it is too much machinery for the current JSON-RPC boundary.
- **Persist the `/health` answer in the client state directory (#5134).** It saves the probe across CLI processes, but it adds a local trust boundary and cache rules, and a rollback to a daemon that ignores instance headers would dispatch on a stale view.
- **Send the protocol as a header on `/rpc`.** Released daemons ignore unknown headers and dispatch anyway.

## Consequences

Expand Down
115 changes: 115 additions & 0 deletions packages/contracts/src/daemon-http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,121 @@ export const DAEMON_INSTANCE_REASONS = {
instanceMismatch: { reason: 'remote_instance_mismatch' },
} as const satisfies ReasonTable<'remote connection'>;

/**
* The checked RPC route (ADR 0006). It takes the same auth, body and answer as `/rpc`, and the
* server itself refuses a call on another RPC protocol before it dispatches anything. A server that
* predates the route answers 404 before dispatch.
*/
export const DAEMON_HTTP_CHECKED_RPC_ROUTE = '/rpc/checked';
/** The `/health` capability of a daemon or proxy that serves the checked route. */
export const DAEMON_HTTP_CHECKED_RPC_CAPABILITY = 'checked-rpc';
Comment thread
thymikee marked this conversation as resolved.
Resolved
/** The caller's `DAEMON_RPC_PROTOCOL_VERSION`. The checked route refuses a call without it. */
export const DAEMON_HTTP_RPC_PROTOCOL_HEADER = 'x-agent-device-rpc-protocol';
/** Which checked-route precondition refused a call. It comes only on a 409, before dispatch. */
export const DAEMON_HTTP_REFUSAL_HEADER = 'x-agent-device-refusal';
export const DAEMON_HTTP_REFUSALS = {
/** The call named no readable RPC protocol. */
protocolMissing: 'protocol-missing',
/** The daemon or proxy that answered speaks another RPC protocol. */
protocolMismatch: 'protocol-mismatch',
/** A proxy forwards the protocol refusal of the daemon behind it. */
upstreamProtocolMismatch: 'upstream-protocol-mismatch',
} as const;
/** The refusals a checked call's own protocol header can earn. */
export type CheckedRpcProtocolRefusal =
| typeof DAEMON_HTTP_REFUSALS.protocolMissing
| typeof DAEMON_HTTP_REFUSALS.protocolMismatch;

/** Why a checked RPC call failed. */
const DAEMON_CHECKED_RPC_REASONS = {
// The checked RPC call named no RPC protocol. An intermediary that strips request headers causes
// this.
protocolMissing: { reason: 'remote_rpc_protocol_missing' },
// The daemon or proxy speaks a different RPC protocol from the caller. After authentication,
// `details.service`, `details.version` and `details.rpcProtocolVersion` name the side that refused.
protocolMismatch: { reason: 'remote_rpc_protocol_mismatch' },
} as const satisfies ReasonTable<'remote connection'>;

/**
* The protocol refusal of a checked call on this build, or `undefined` when its protocol matches. A
* header that is absent or not a plain integer is `protocol-missing`.
*/
export function checkedRpcProtocolRefusal(
headerValue: unknown,
): CheckedRpcProtocolRefusal | undefined {
if (typeof headerValue !== 'string' || !/^[0-9]{1,9}$/.test(headerValue)) {
return DAEMON_HTTP_REFUSALS.protocolMissing;
}
return Number(headerValue) === DAEMON_RPC_PROTOCOL_VERSION
? undefined
: DAEMON_HTTP_REFUSALS.protocolMismatch;
}

/**
* The JSON-RPC id a checked-route refusal echoes: a bounded correlation token or a safe integer.
* Anything else, such as an object, a URL or a long string, is answered as `null`.
*/
export function checkedRpcRefusalId(id: unknown): string | number | null {
if (typeof id === 'number') return Number.isSafeInteger(id) ? id : null;
return typeof id === 'string' && /^[A-Za-z0-9._:-]{1,128}$/.test(id) ? id : null;
}

/** The refusing side of a protocol refusal, named in the `/health` vocabulary. */
export type CheckedRpcRefusalSide = Pick<
DaemonHealthPayload,
'service' | 'version' | 'rpcProtocolVersion'
>;

/** The refusing side a protocol refusal names, or `undefined` unless every value is bounded and valid. */
export function readCheckedRpcRefusalSide(details: unknown): CheckedRpcRefusalSide | undefined {
if (!details || typeof details !== 'object') return undefined;
const { service, version, rpcProtocolVersion } = details as Record<string, unknown>;
if (service !== 'agent-device-daemon' && service !== 'agent-device-proxy') return undefined;
// The whole string is capped first, at the length the `/health` reader allows a version.
if (
typeof version !== 'string' ||
version.length > 64 ||
!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]{1,48})?$/.test(version)
) {
return undefined;
}
if (typeof rpcProtocolVersion !== 'number' || !Number.isSafeInteger(rpcProtocolVersion)) {
return undefined;
}
return { service, version, rpcProtocolVersion };
}

/**
* The JSON-RPC body of a protocol refusal, built from local values only: the refusal's reason,
* `dispatched: 'no'`, a bounded id, and the refusing side when the caller passed authentication.
*/
export function buildCheckedRpcProtocolRefusal(
id: unknown,
refusal: CheckedRpcProtocolRefusal | typeof DAEMON_HTTP_REFUSALS.upstreamProtocolMismatch,
side?: CheckedRpcRefusalSide,
) {
const missing = refusal === DAEMON_HTTP_REFUSALS.protocolMissing;
const message = missing
? `Checked RPC requires the ${DAEMON_HTTP_RPC_PROTOCOL_HEADER} header`
: 'The remote speaks a different RPC protocol from the caller';
const reason = missing
? DAEMON_CHECKED_RPC_REASONS.protocolMissing.reason
: DAEMON_CHECKED_RPC_REASONS.protocolMismatch.reason;
return {
jsonrpc: '2.0' as const,
id: checkedRpcRefusalId(id),
error: {
code: -32001,
message,
data: {
code: 'COMMAND_FAILED',
message,
details: { reason, dispatched: 'no', ...side },
},
},
};
}

export function buildDaemonInstanceMismatchRpcResponse<Id>(
id: Id,
message: string,
Expand Down
4 changes: 3 additions & 1 deletion packages/daemon-contracts/src/daemon-resolution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,9 @@ export function resolveDaemonTransportPreference(
}

/** What a daemon can do beyond the base RPC contract, published in its `daemon.json`. */
export const DAEMON_CAPABILITIES = ['quiesce', 'script-artifacts'] as const;
// `checked-rpc`: the daemon's HTTP server serves the checked RPC route (ADR 0006). Every daemon that
// serves it also serves `script-artifacts`.
export const DAEMON_CAPABILITIES = ['quiesce', 'script-artifacts', 'checked-rpc'] as const;
export type DaemonCapability = (typeof DAEMON_CAPABILITIES)[number];

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ test('an idle daemon accepts a quiesce, drains and releases its state directory'
const published = JSON.parse(fs.readFileSync(paths.infoPath, 'utf8')) as {
capabilities?: unknown;
};
expect(published.capabilities).toEqual(['quiesce', 'script-artifacts']);
expect(published.capabilities).toEqual(['quiesce', 'script-artifacts', 'checked-rpc']);

expect(await daemon.quiesce()).toEqual({ ok: true, data: { outcome: 'draining' } });

Expand Down
Loading
Loading