Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
sdk: resume a saved credential only while the control plane vouches for it
Antonio Ojea8b081a99308f
diff --git a/sdk/README.md b/sdk/README.mdindex ec438b83..d5ae0648 100644--- a/sdk/README.md+++ b/sdk/README.md@@ -198,6 +198,19 @@ directory with the other SDK and with an imported `sam-node`. Fields an SDKdoes not use (`receive_time`, `oidc_session`) are carried through on save,so a directory survives a round trip through any implementation.+`enroll` resumes the saved credential when it is for this control plane,+has more than five minutes left, and the control plane still serves a key+in `trusted_keys`: `/keys` is pulled and verified against the saved set+before the member is returned, and the keys it names are adopted. A member+off for longer than the key grace period holds a credential no current+key signed and a trusted set no current key is in, so neither verifies;+with a token given, `enroll` enrolls again as the saved identity, and+without one it raises `CredentialRetiredError`. A control plane that cannot+be reached leaves the saved credential in force; the pull before join tries+again. `TestKeyRotationWhileMembersOffline` and+`TestKeyRotationPastGraceWhileMembersOffline` in `tests/integration` run+both cases against real routers and a real control plane.+### Control plane (protobuf over HTTP)All requests and responses are `application/x-protobuf` bodies of the@@ -714,7 +727,7 @@ one follows is named so a change on one side can be carried to the others.| `identity.ts` | `identity.py` | ed25519 key pair, libp2p key encodings, peer ID || `controlplane.ts` | `controlplane.py` | `/info`, `/keys`, `/enroll`, `/enroll/status`, `/register`, `/refresh`, `/policies`, with the challenges of `api/network.go` || `credential.ts` | `credential.py` | what a member holds, `AuthFrame` encoding, `issuedUnderKeys` |-| `mesh.ts` | `mesh.py` | `AgentMesh`: enroll (resumes an unexpired credential in the state directory before spending a token), load, refresh, `syncControlPlane` as `SyncControlPlane` in `internal/node/controlplane_sync.go`; state directory (`identity.key`, `credential.json`, the same layout in both languages) |+| `mesh.ts` | `mesh.py` | `AgentMesh`: enroll (resumes a credential in the state directory before spending a token, while the control plane still serves a key it trusts), load, refresh, `syncControlPlane` as `SyncControlPlane` in `internal/node/controlplane_sync.go`; state directory (`identity.key`, `credential.json`, the same layout in both languages) || `biscuit.ts` | `biscuit.py` | verification of a peer's credential, as `internal/identity.verifyBiscuit` || `host.ts` | `host.py` | the libp2p host as `internal/node/node.go` configures it, plus gossipsub and the connection gater || `auth.ts` | `auth.py` | `/sam/auth/1.0.0` on both sides, as `HandleAuthHandshake` |diff --git a/sdk/js/src/controlplane.ts b/sdk/js/src/controlplane.tsindex cb711a83..1290ee56 100644--- a/sdk/js/src/controlplane.ts+++ b/sdk/js/src/controlplane.ts@@ -71,6 +71,18 @@ export class EnrollmentRejectedError extends Error {}}+/**+ * The /keys answer is signed by no key this member trusts: every key it+ * holds has left the control plane's set, so its credential cannot be+ * verified or refreshed either.+ */+export class KeysNotTrustedError extends Error {+ constructor() {+ super("keys response is not signed by any trusted control plane key");+ this.name = "KeysNotTrustedError";+ }+}+/** Plaintext http:// to a host that is not loopback; see api.ValidateControlPlaneTransport. */export class InsecureControlPlaneURLError extends Error {constructor(url: string) {@@ -192,7 +204,7 @@ export function verifyKeysResponse(resp: KeysResponse, trusted: Uint8Array[], no}});if (!verified) {- throw new Error("keys response is not signed by any trusted control plane key");+ throw new KeysNotTrustedError();}return keys;}diff --git a/sdk/js/src/index.ts b/sdk/js/src/index.tsindex 72290db4..c0870713 100644--- a/sdk/js/src/index.ts+++ b/sdk/js/src/index.ts@@ -12,13 +12,14 @@// See the License for the specific language governing permissions and// limitations under the License.-export { AgentMesh, type AgentMeshOptions, type ControlPlaneSync, type EnrollOptions } from "./mesh.ts";+export { AgentMesh, CredentialRetiredError, type AgentMeshOptions, type ControlPlaneSync, type EnrollOptions } from "./mesh.ts";export { Identity, canonicalPeerId, peerIdFromPublicKey, libp2pPublicKey, verifyEd25519 } from "./identity.ts";export {ControlPlaneClient,ControlPlaneError,EnrollmentRejectedError,InsecureControlPlaneURLError,+ KeysNotTrustedError,ROLE_NODE,validateControlPlaneURL,verifyKeysResponse,diff --git a/sdk/js/src/mesh.test.ts b/sdk/js/src/mesh.test.tsindex 53206dd6..18905302 100644--- a/sdk/js/src/mesh.test.ts+++ b/sdk/js/src/mesh.test.ts@@ -31,7 +31,7 @@ import {TokenRefreshResponseSchema,} from "./gen/sam_pb.ts";import { Identity } from "./identity.ts";-import { AgentMesh } from "./mesh.ts";+import { AgentMesh, CredentialRetiredError } from "./mesh.ts";const cpKey = Identity.generate();const text = (s: string) => new TextEncoder().encode(s);@@ -41,11 +41,14 @@ function proto(bytes: Uint8Array): Response {}/** A control plane that approves everything and hands out numbered biscuits. */-function fakeControlPlane(keysOk = true): { fetch: typeof fetch; issued: number } {- const state = { issued: 0 };+function fakeControlPlane(keysOk = true): { fetch: typeof fetch; issued: number; keys: Identity[]; keysOk: boolean } {+ // keys is what /keys serves and signs with; a test rotates by replacing it.+ const state = { issued: 0, keys: [cpKey], keysOk };+ const current = () => (state.keys[state.keys.length - 1] as Identity).publicKeyRaw;const signedKeys = () => {- const unsigned = create(KeysResponseSchema, { publicKeys: [cpKey.publicKeyRaw], signTime: timestampFromMs(Date.now()) });- return create(KeysResponseSchema, { ...unsigned, signatures: [cpKey.sign(toBinary(KeysResponseSchema, unsigned))] });+ const unsigned = create(KeysResponseSchema, { publicKeys: state.keys.map((k) => k.publicKeyRaw), signTime: timestampFromMs(Date.now()) });+ const payload = toBinary(KeysResponseSchema, unsigned);+ return create(KeysResponseSchema, { ...unsigned, signatures: state.keys.map((k) => k.sign(payload)) });};const fetch: typeof globalThis.fetch = (async (input: Parameters<typeof globalThis.fetch>[0], init?: RequestInit) => {const req = new Request(input, init);@@ -59,7 +62,7 @@ function fakeControlPlane(keysOk = true): { fetch: typeof fetch; issued: numbercreate(BootstrapEnrollResponseSchema, {status: EnrollmentStatus.APPROVED,biscuitToken: text(`biscuit-${state.issued}`),- controlPlanePublicKey: cpKey.publicKeyRaw,+ controlPlanePublicKey: current(),routerAddresses: ["/dns4/router.example/tcp/4001/p2p/12D3KooWP8iKhDf3iCMo2H3butNVfdTUtYwYWYQ75jTGnynXPFMp"],expireTime: timestampFromMs(Date.now() + 3600_000),}),@@ -77,7 +80,7 @@ function fakeControlPlane(keysOk = true): { fetch: typeof fetch; issued: numberEnrollResponseSchema,create(EnrollResponseSchema, {biscuitToken: text(`biscuit-for-${jwt}`),- controlPlanePublicKey: cpKey.publicKeyRaw,+ controlPlanePublicKey: current(),routerAddresses: ["/dns4/router.example/tcp/4001/p2p/12D3KooWP8iKhDf3iCMo2H3butNVfdTUtYwYWYQ75jTGnynXPFMp"],expireTime: timestampFromMs(Date.now() + 3600_000),}),@@ -85,7 +88,7 @@ function fakeControlPlane(keysOk = true): { fetch: typeof fetch; issued: number);}case "GET /keys":- return keysOk ? proto(toBinary(KeysResponseSchema, signedKeys())) : new Response("boom", { status: 500 });+ return state.keysOk ? proto(toBinary(KeysResponseSchema, signedKeys())) : new Response("boom", { status: 500 });default:return new Response(`no route for ${req.method} ${path}`, { status: 404 });}@@ -95,6 +98,18 @@ function fakeControlPlane(keysOk = true): { fetch: typeof fetch; issued: numberget issued() {return state.issued;},+ get keys() {+ return state.keys;+ },+ set keys(keys: Identity[]) {+ state.keys = keys;+ },+ get keysOk() {+ return state.keysOk;+ },+ set keysOk(ok: boolean) {+ state.keysOk = ok;+ },};}@@ -155,6 +170,49 @@ test("enroll persists identity and credential, load resumes them, refresh rotate}});+test("enroll resumes only a credential the control plane still vouches for", async () => {+ // A member off across a rotation comes back with a credential and a trust+ // set from before it. Within the grace period the retiring key still signs+ // /keys, so the credential is resumed and the new key adopted. Past it, the+ // control plane serves only keys the member never saw: the credential is+ // dead, and the member enrolls again with the token it has, or says so.+ const dir = await mkdtemp(join(tmpdir(), "sam-sdk-"));+ try {+ const cp = fakeControlPlane();+ const stateDir = join(dir, "state");+ const mesh = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", stateDir, bootstrapToken: "sbt_secret", fetch: cp.fetch });+ const issued = cp.issued;+ const hex = (keys: Uint8Array[]) => keys.map((k) => Buffer.from(k).toString("hex")).sort();++ // Within the grace period: resumed, both keys trusted, and persisted so.+ const rotated = Identity.generate();+ cp.keys = [cpKey, rotated];+ const within = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", stateDir, fetch: cp.fetch });+ assert.deepEqual(within.credential.biscuit, mesh.credential.biscuit);+ assert.equal(cp.issued, issued);+ assert.deepEqual(hex(within.credential.controlPlaneKeys), hex([cpKey.publicKeyRaw, rotated.publicKeyRaw]));+ const onDisk = JSON.parse(await readFile(join(stateDir, "credential.json"), "utf8")) as { trusted_keys: unknown[] };+ assert.equal(onDisk.trusted_keys.length, 2);++ // The control plane cannot be reached: resumed as saved; join tries again.+ cp.keysOk = false;+ assert.deepEqual((await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", stateDir, fetch: cp.fetch })).credential.biscuit, mesh.credential.biscuit);+ cp.keysOk = true;++ // Past the grace period, from the state as it was before the rotation.+ await writeFile(join(stateDir, "credential.json"), JSON.stringify({ ...onDisk, trusted_keys: [{ public_key: Buffer.from(cpKey.publicKeyRaw).toString("base64") }] }));+ cp.keys = [rotated];+ await assert.rejects(AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", stateDir, fetch: cp.fetch }), CredentialRetiredError);+ const again = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", stateDir, bootstrapToken: "sbt_secret", fetch: cp.fetch });+ assert.equal(again.peerId, mesh.peerId);+ assert.notDeepEqual(again.credential.biscuit, mesh.credential.biscuit);+ assert.equal(cp.issued, issued + 1);+ assert.deepEqual(hex(again.credential.controlPlaneKeys), hex([rotated.publicKeyRaw]));+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+});+test("load needs both the identity and the credential", async () => {const dir = await mkdtemp(join(tmpdir(), "sam-sdk-"));try {diff --git a/sdk/js/src/mesh.ts b/sdk/js/src/mesh.tsindex 5634f574..c191c237 100644--- a/sdk/js/src/mesh.ts+++ b/sdk/js/src/mesh.ts@@ -13,7 +13,7 @@// limitations under the License.import { toHex } from "./bytes.ts";-import { ControlPlaneClient, ROLE_NODE, type Enrollment } from "./controlplane.ts";+import { ControlPlaneClient, KeysNotTrustedError, ROLE_NODE, type Enrollment } from "./controlplane.ts";import { credentialFromJSON, credentialPredatesRotation, credentialTimeToLiveSeconds, credentialToJSON, encodeAuthFrame, type MeshCredential } from "./credential.ts";import { Identity } from "./identity.ts";import { openState, readTextFile } from "./platform/state.ts";@@ -25,6 +25,41 @@ const CREDENTIAL_FILE = "credential.json";/** A saved credential with less validity left than this is not worth resuming; enroll again instead. */const REUSE_MIN_TTL_SECONDS = 5 * 60;+/**+ * The saved credential was issued under a signing key the control plane no+ * longer serves, so nothing can verify or refresh it; the member must enroll+ * again with a token.+ */+export class CredentialRetiredError extends Error {+ constructor(stateDir: string) {+ super(+ `the credential in ${stateDir} was issued under a key the control plane no longer serves ` ++ "(the member was off for longer than the key grace period); enroll again with a token",+ );+ this.name = "CredentialRetiredError";+ }+}++/**+ * The saved credential with the control plane's current keys adopted, or+ * undefined when the control plane vouches for none of the keys it trusts. A+ * control plane that cannot be reached, or answers in a way that is not a+ * verdict on the keys, leaves the credential as it is: the pull before join+ * tries again.+ */+async function resumableCredential(controlPlane: ControlPlaneClient, credential: MeshCredential): Promise<MeshCredential | undefined> {+ let keys: Uint8Array[];+ try {+ keys = await controlPlane.keys(credential.controlPlaneKeys);+ } catch (err) {+ return err instanceof KeysNotTrustedError ? undefined : credential;+ }+ if (keys.length === 0 || sameKeySet(keys, credential.controlPlaneKeys)) {+ return credential;+ }+ return { ...credential, controlPlaneKeys: keys };+}+export interface AgentMeshOptions {/** Base URL of the control plane, e.g. https://mesh.example.com. */controlPlaneUrl: string;@@ -111,7 +146,11 @@ export class AgentMesh {* When stateDir already holds an unexpired credential from this control* plane for the saved identity, that member is returned and no token is* needed, so a program can call enroll on every start and read the token- * from its environment only on the first. Otherwise exactly one of+ * from its environment only on the first. A credential is resumed only+ * while the control plane still serves a key the member trusts: one issued+ * under a key that retired while the member was off cannot be verified or+ * refreshed, so the member enrolls again with the token given, or throws+ * CredentialRetiredError without one. Otherwise exactly one of* bootstrapToken, bootstrapTokenPath, jwt or jwtPath must be given. Delete* the state directory to enroll afresh, for instance with other labels.*/@@ -120,13 +159,23 @@ export class AgentMesh {const saved = await loadIdentity(state);const identity = options.identity ?? saved ?? Identity.generate();const controlPlane = newClient(options);+ const given = [options.bootstrapToken, options.bootstrapTokenPath, options.jwt, options.jwtPath].filter((v) => v !== undefined).length;if (state !== undefined && saved !== undefined && saved.peerId === identity.peerId) {const credential = await loadCredential(state);if (credential !== undefined && sameBaseUrl(credential.controlPlaneUrl, controlPlane.url) && credentialTimeToLiveSeconds(credential) > REUSE_MIN_TTL_SECONDS) {- return new AgentMesh(identity, controlPlane, credential, state);+ const resumed = await resumableCredential(controlPlane, credential);+ if (resumed !== undefined) {+ const mesh = new AgentMesh(identity, controlPlane, resumed, state);+ if (resumed !== credential) {+ await mesh.save();+ }+ return mesh;+ }+ if (given === 0) {+ throw new CredentialRetiredError(options.stateDir as string);+ }}}- const given = [options.bootstrapToken, options.bootstrapTokenPath, options.jwt, options.jwtPath].filter((v) => v !== undefined).length;if (given !== 1) {const where = options.stateDir !== undefined ? ` (no credential to resume in ${options.stateDir})` : "";throw new Error(`exactly one of bootstrapToken, bootstrapTokenPath, jwt or jwtPath is required${where}`);diff --git a/sdk/python/src/agent_mesh/__init__.py b/sdk/python/src/agent_mesh/__init__.pyindex df1ebe96..e7275b6d 100644--- a/sdk/python/src/agent_mesh/__init__.py+++ b/sdk/python/src/agent_mesh/__init__.py@@ -25,6 +25,7 @@ from .controlplane import (Enrollment,EnrollmentRejectedError,InsecureControlPlaneURLError,+ KeysNotTrustedError,RefreshResult,validate_control_plane_url,verify_keys_response,@@ -51,7 +52,7 @@ from .libp2p_http import (rewrite_agent_card,)from .mcp_client import LabelsNotSatisfiedError, ToolCallResult, ToolInfo, open_mcp_session, require_egress_labels, require_labels-from .mesh import AgentMesh, ControlPlaneSync+from .mesh import AgentMesh, ControlPlaneSync, CredentialRetiredErrorfrom .relay import dial_through_relay, reserve_relayfrom .session import AdmittedRouter, MeshSession, Peerfrom .sync import GOSSIP_EVENTS_TOPIC, BanSet, verify_mesh_event@@ -73,6 +74,7 @@ __all__ = ["ControlPlaneClient","ControlPlaneError","ControlPlaneSync",+ "CredentialRetiredError","DEFAULT_A2A_NAME","DHT_PROTOCOL","DiscoveredProvider",@@ -85,6 +87,7 @@ __all__ = ["HTTPResponse","Identity","InsecureControlPlaneURLError",+ "KeysNotTrustedError","LabelsNotSatisfiedError","MCP_PROTOCOL","MESH_PATH_PREFIX",diff --git a/sdk/python/src/agent_mesh/controlplane.py b/sdk/python/src/agent_mesh/controlplane.pyindex ce063dc0..b90d5b08 100644--- a/sdk/python/src/agent_mesh/controlplane.py+++ b/sdk/python/src/agent_mesh/controlplane.py@@ -65,6 +65,12 @@ class EnrollmentRejectedError(Exception):"""The control plane answered, and the answer is a refusal."""+class KeysNotTrustedError(ValueError):+ """The /keys answer is signed by no key this member trusts: every key it+ holds has left the control plane's set, so its credential cannot be+ verified or refreshed either."""++class InsecureControlPlaneURLError(Exception):"""Plaintext http:// to a host that is not loopback; see api.ValidateControlPlaneTransport."""@@ -141,7 +147,7 @@ def verify_keys_response(resp: pb.KeysResponse, trusted: Sequence[bytes], now_msif not verified and any(t == pub for t in trusted) and verify_ed25519(pub, payload, sig):verified = Trueif not verified:- raise ValueError("keys response is not signed by any trusted control plane key")+ raise KeysNotTrustedError("keys response is not signed by any trusted control plane key")return keysdiff --git a/sdk/python/src/agent_mesh/mesh.py b/sdk/python/src/agent_mesh/mesh.pyindex 2f29495c..d4f45ac5 100644--- a/sdk/python/src/agent_mesh/mesh.py+++ b/sdk/python/src/agent_mesh/mesh.py@@ -21,7 +21,7 @@ from dataclasses import dataclass, field, replacefrom pathlib import Pathfrom typing import Mapping, Optional-from .controlplane import ROLE_NODE, ControlPlaneClient, Enrollment, Transport+from .controlplane import ROLE_NODE, ControlPlaneClient, Enrollment, KeysNotTrustedError, Transportfrom .credential import MeshCredential, encode_auth_framefrom .identity import Identity@@ -31,6 +31,35 @@ _CREDENTIAL_FILE = "credential.json"_REUSE_MIN_TTL_SECONDS = 5 * 60+class CredentialRetiredError(Exception):+ """The saved credential was issued under a signing key the control plane+ no longer serves, so nothing can verify or refresh it; the member must+ enroll again with a token."""++ def __init__(self, state: Path):+ super().__init__(+ f"the credential in {state} was issued under a key the control plane no longer serves "+ "(the member was off for longer than the key grace period); enroll again with a token"+ )+++def _resumable_credential(control_plane: ControlPlaneClient, credential: MeshCredential) -> Optional[MeshCredential]:+ """The saved credential with the control plane's current keys adopted, or+ None when the control plane vouches for none of the keys it trusts. A+ control plane that cannot be reached, or answers in a way that is not a+ verdict on the keys, leaves the credential as it is: the pull before join+ tries again."""+ try:+ keys = control_plane.keys(credential.control_plane_keys)+ except KeysNotTrustedError:+ return None+ except Exception: # noqa: BLE001 - unreachable, or an answer that is not about the keys+ return credential+ if not keys or {bytes(k) for k in keys} == {bytes(k) for k in credential.control_plane_keys}:+ return credential+ return replace(credential, control_plane_keys=[bytes(k) for k in keys])++@dataclass(frozen=True)class ControlPlaneSync:"""What one pull from the control plane changed."""@@ -93,21 +122,32 @@ class AgentMesh:When state_dir already holds an unexpired credential from this controlplane for the saved identity, that member is returned and no token isneeded, so a program can call enroll on every start and read the token- from its environment only on the first. Otherwise exactly one of- bootstrap_token, bootstrap_token_path, jwt or jwt_path must be given; a- token is better read from a file than passed as a value, and jwt_path- also takes a platform's workload identity token, such as a Kubernetes- projected service account token. Delete the state directory to enroll- afresh, for instance with other labels."""+ from its environment only on the first. A credential is resumed only+ while the control plane still serves a key the member trusts: one+ issued under a key that retired while the member was off cannot be+ verified or refreshed, so the member enrolls again with the token+ given, or raises CredentialRetiredError without one. Otherwise exactly+ one of bootstrap_token, bootstrap_token_path, jwt or jwt_path must be+ given; a token is better read from a file than passed as a value, and+ jwt_path also takes a platform's workload identity token, such as a+ Kubernetes projected service account token. Delete the state directory+ to enroll afresh, for instance with other labels."""state = Path(state_dir).expanduser() if state_dir is not None else Nonesaved = _load_identity(state)identity = identity or saved or Identity.generate()control_plane = ControlPlaneClient(control_plane_url, allow_insecure=allow_insecure, transport=transport)+ given = sum(v is not None for v in (bootstrap_token, bootstrap_token_path, jwt, jwt_path))if state is not None and saved is not None and saved.peer_id == identity.peer_id:credential = _load_credential(state)if credential is not None and credential.control_plane_url.rstrip("/") == control_plane.url.rstrip("/") and credential.time_to_live_seconds() > _REUSE_MIN_TTL_SECONDS:- return cls(identity, control_plane, credential, state)- given = sum(v is not None for v in (bootstrap_token, bootstrap_token_path, jwt, jwt_path))+ resumed = _resumable_credential(control_plane, credential)+ if resumed is not None:+ mesh = cls(identity, control_plane, resumed, state)+ if resumed is not credential:+ mesh.save()+ return mesh+ if given == 0:+ raise CredentialRetiredError(state)if given != 1:where = f" (no credential to resume in {state})" if state is not None else ""raise ValueError(f"exactly one of bootstrap_token, bootstrap_token_path, jwt or jwt_path is required{where}")diff --git a/sdk/python/tests/test_mesh.py b/sdk/python/tests/test_mesh.pyindex a00a69c1..2c74050e 100644--- a/sdk/python/tests/test_mesh.py+++ b/sdk/python/tests/test_mesh.py@@ -25,7 +25,7 @@ import pytestfrom agent_mesh._proto import sam_pb2 as pbfrom agent_mesh.credential import decode_auth_responsefrom agent_mesh.identity import Identity-from agent_mesh.mesh import AgentMesh+from agent_mesh.mesh import AgentMesh, CredentialRetiredErrorfrom google.protobuf.timestamp_pb2 import Timestamp@@ -54,6 +54,8 @@ class FakeControlPlane:self.strict_refresh = strict_refreshself.refresh_delay = refresh_delayself.last_biscuit = b""+ # What /keys serves and signs with; a test rotates by replacing it.+ self.keys = [CP_KEY]self._lock = threading.Lock()def _issue(self, biscuit):@@ -63,8 +65,9 @@ class FakeControlPlane:def _signed_keys(self):ts = int(time.time() * 1000)- unsigned = pb.KeysResponse(public_keys=[CP_KEY.public_key_raw], sign_time=_ts_ms(ts))- return pb.KeysResponse(public_keys=[CP_KEY.public_key_raw], sign_time=_ts_ms(ts), signatures=[CP_KEY.sign(unsigned.SerializeToString(deterministic=True))])+ public = [k.public_key_raw for k in self.keys]+ payload = pb.KeysResponse(public_keys=public, sign_time=_ts_ms(ts)).SerializeToString(deterministic=True)+ return pb.KeysResponse(public_keys=public, sign_time=_ts_ms(ts), signatures=[k.sign(payload) for k in self.keys])def transport(self, method, url, headers, body):path = urllib.parse.urlsplit(url).path@@ -73,7 +76,7 @@ class FakeControlPlane:jwt = pb.EnrollRequest.FromString(body).jwtreturn 200, pb.EnrollResponse(biscuit_token=self._issue(f"biscuit-for-{jwt}".encode()),- control_plane_public_key=CP_KEY.public_key_raw,+ control_plane_public_key=self.keys[-1].public_key_raw,router_addresses=["/dns4/router.example/tcp/4001/p2p/12D3KooWP8iKhDf3iCMo2H3butNVfdTUtYwYWYQ75jTGnynXPFMp"],expire_time=_ts_s(int(time.time()) + 3600),).SerializeToString()@@ -81,7 +84,7 @@ class FakeControlPlane:return 200, pb.BootstrapEnrollResponse(status=pb.ENROLLMENT_STATUS_APPROVED,biscuit_token=self._issue(f"biscuit-{self.issued + 1}".encode()),- control_plane_public_key=CP_KEY.public_key_raw,+ control_plane_public_key=self.keys[-1].public_key_raw,router_addresses=["/dns4/router.example/tcp/4001/p2p/12D3KooWP8iKhDf3iCMo2H3butNVfdTUtYwYWYQ75jTGnynXPFMp"],expire_time=_ts_s(int(time.time()) + 3600),).SerializeToString()@@ -151,6 +154,41 @@ def test_enroll_persists_load_resumes_refresh_rotates(tmp_path):assert cp.issued == issued_before + 2+def test_enroll_resumes_only_a_credential_the_control_plane_still_vouches_for(tmp_path):+ """A member off across a rotation comes back with a credential and a trust+ set from before it. Within the grace period the retiring key still signs+ /keys, so the credential is resumed and the new key adopted. Past it, the+ control plane serves only keys the member never saw: the credential is+ dead, and the member enrolls again with the token it has, or says so."""+ cp = FakeControlPlane()+ state = tmp_path / "state"+ mesh = AgentMesh.enroll("http://127.0.0.1:1", bootstrap_token="sbt_secret", state_dir=state, transport=cp.transport)+ issued = cp.issued++ # Within the grace period: resumed, both keys trusted, and persisted so.+ rotated = Identity.generate()+ cp.keys = [CP_KEY, rotated]+ within = AgentMesh.enroll("http://127.0.0.1:1", state_dir=state, transport=cp.transport)+ assert within.credential.biscuit == mesh.credential.biscuit and cp.issued == issued+ assert {bytes(k) for k in within.credential.control_plane_keys} == {CP_KEY.public_key_raw, rotated.public_key_raw}+ assert len(json.loads((state / "credential.json").read_text())["trusted_keys"]) == 2++ # The control plane cannot be reached: resumed as saved; join tries again.+ cp.keys_ok = False+ assert AgentMesh.enroll("http://127.0.0.1:1", state_dir=state, transport=cp.transport).credential.biscuit == mesh.credential.biscuit+ cp.keys_ok = True++ # Past the grace period, from the state as it was before the rotation.+ (state / "credential.json").write_text(json.dumps({**json.loads((state / "credential.json").read_text()), "trusted_keys": [{"public_key": base64.b64encode(CP_KEY.public_key_raw).decode()}]}))+ cp.keys = [rotated]+ with pytest.raises(CredentialRetiredError, match="key the control plane no longer serves"):+ AgentMesh.enroll("http://127.0.0.1:1", state_dir=state, transport=cp.transport)+ again = AgentMesh.enroll("http://127.0.0.1:1", bootstrap_token="sbt_secret", state_dir=state, transport=cp.transport)+ assert again.peer_id == mesh.peer_id+ assert again.credential.biscuit != mesh.credential.biscuit and cp.issued == issued + 1+ assert [bytes(k) for k in again.credential.control_plane_keys] == [rotated.public_key_raw]++def test_state_dir_and_token_path_expand_home(tmp_path, monkeypatch):monkeypatch.setenv("HOME", str(tmp_path))(tmp_path / "bootstrap.token").write_text("sbt_secret\n")diff --git a/site/content/docs/guides/headless-enrollment.md b/site/content/docs/guides/headless-enrollment.mdindex bee424f0..1c5f62b9 100644--- a/site/content/docs/guides/headless-enrollment.md+++ b/site/content/docs/guides/headless-enrollment.md@@ -131,8 +131,10 @@ A node enrolled with a bootstrap token has no login to fall back on. Itscredential is refreshed automatically while it runs. But if the node is offfor longer than the control plane's key grace period (`--key-grace-period`,one hour by default), it comes back with a credential signed by a retired-key, and `/refresh` refuses it. There are three ways out, in order of-preference.+key, and `/refresh` refuses it. An SDK member in the same position enrolls+again on start when its `enroll` call is given a token, and otherwise+fails with `CredentialRetiredError` naming the state directory. There are+three ways out, in order of preference.**Enroll again.** Mint a new token and run `sam-node join` with it. Thecontrol plane already knows the peer ID, so it mints a new credentialdiff --git a/tests/integration/rotation_offline_test.go b/tests/integration/rotation_offline_test.goindex 78fe129c..24216e56 100644--- a/tests/integration/rotation_offline_test.go+++ b/tests/integration/rotation_offline_test.go@@ -19,6 +19,7 @@ import ("crypto/ed25519""encoding/base64""fmt"+ "net/http""os""path/filepath""sort"@@ -47,18 +48,120 @@ import (func TestKeyRotationWhileMembersOffline(t *testing.T) {mesh := startSDKMesh(t)ctx := context.Background()- nodeBin := buildBinary(t, "./cmd/sam-node")-- // The members, enrolled under the current key, then stopped. Each keeps- // its state directory; a token is read only to enroll, so the file can- // go once the member holds a credential.- type offlineSDKMember struct {- launcher sdkRunner- stateDir string- peerID string- biscuit string- }- var sdkMembers []offlineSDKMember+ members := enrollMembersThenStop(t, mesh)++ newPub := rotateSigningKey(t, ctx, mesh, time.Hour)++ // The Go node starts from its stored identity, with no token: it pulls+ // from the control plane before it starts and comes up under the new key.+ node := members.startNode(t, false)+ members.assertNodeBackUnderKey(t, node, mesh, newPub)++ // The SDK members start again from their state directories. The token+ // path names no file: the member resumes or fails, it cannot enroll.+ for _, s := range members.sdk {+ m := s.start(t, mesh, " resumed", "SAM_BOOTSTRAP_TOKEN_PATH="+filepath.Join(t.TempDir(), "no-token"))+ s.assertBackUnderKey(t, m, mesh, newPub, node)+ if res := m.sync(t); !res.OK {+ t.Fatalf("%s: pull after the resume failed: %s", m.name, res.Error)+ }+ m.quit(t)+ }+ node.kill()+}++// TestKeyRotationPastGraceWhileMembersOffline is the same outage with a+// longer absence: the member comes back after the key that signed its+// credential has left the control plane's set. Nothing can verify or+// refresh that credential, and the control plane's /keys answer is signed+// by no key the member trusts, so it cannot adopt the new one either. A+// member with a token at hand, as every canary has its projected service+// account token, must enroll again with the identity it keeps, rather than+// resume a dead credential and fail at every router until it expires. The+// default grace period is shorter than a credential's lifetime, so this is+// where any member off for a day lands.+func TestKeyRotationPastGraceWhileMembersOffline(t *testing.T) {+ mesh := startSDKMesh(t)+ ctx := context.Background()+ members := enrollMembersThenStop(t, mesh)++ newPub := rotateSigningKey(t, ctx, mesh, time.Second)+ waitForKeysRetired(t, mesh.cpPort, [][]byte{mesh.cpPub})++ // The node comes back with a fresh platform token on disk.+ if err := os.WriteFile(members.jwtPath, []byte(members.freshJWT()), 0o600); err != nil {+ t.Fatal(err)+ }+ node := members.startNode(t, true)+ members.assertNodeBackUnderKey(t, node, mesh, newPub)++ // Each SDK member comes back with a fresh token available and enrolls+ // again as the identity it persisted.+ for _, s := range members.sdk {+ m := s.start(t, mesh, " past grace")+ s.assertBackUnderKey(t, m, mesh, newPub, node)+ m.quit(t)+ }+ node.kill()+}++// offlineSDKMember is an SDK member that enrolled and stopped, keeping its+// state directory.+type offlineSDKMember struct {+ launcher sdkRunner+ stateDir string+ peerID string+ biscuit string+}++// start brings the member back from its state directory. launchSDKMember+// writes a fresh bootstrap token; env is appended and wins.+func (s *offlineSDKMember) start(t *testing.T, mesh *sdkMesh, suffix string, env ...string) *sdkMember {+ t.Helper()+ cmd, _ := s.launcher.cmd(mesh.root)+ return launchSDKMember(t, s.launcher.name+suffix, cmd, mesh.root, mesh.baseURL, mesh.adminToken, append([]string{"SAM_SDK_STATE_DIR=" + s.stateDir}, env...)...)+}++// assertBackUnderKey checks the member came back as the identity it kept,+// admitted by every router, holding a credential signed by pub alone, and+// able to reach the node that came back too, across the mesh.+func (s *offlineSDKMember) assertBackUnderKey(t *testing.T, m *sdkMember, mesh *sdkMesh, pub ed25519.PublicKey, node *backgroundNode) {+ t.Helper()+ if m.report.PeerID != s.peerID {+ t.Fatalf("%s came back as %s, want the identity it persisted, %s", m.name, m.report.PeerID, s.peerID)+ }+ assertAdmittedByEveryRouter(t, m, mesh.routerAddrs)+ if m.report.Biscuit == s.biscuit {+ t.Fatalf("%s still holds the credential minted before the rotation", m.name)+ }+ assertSignedOnlyBy(t, m.name, m.report.Biscuit, m.report.PeerID, pub, mesh.cpPub)+ if cred := m.auth(t, node.p2pAddr); cred.PeerID != node.peerID.String() {+ t.Fatalf("%s verified the node as %+v after coming back", m.name, cred)+ }+}++// offlineMembers is one member per SDK and a Go node, each enrolled under+// the key current at the time and then stopped.+type offlineMembers struct {+ sdk []offlineSDKMember++ nodeBin string+ nodeHome string+ nodeEnv []string+ nodeArgs []string+ jwtPath string+ freshJWT func() string+ socketClient *http.Client+ nodePeer peer.ID+ nodeBefore api.IdentityEvidenceResponse+}++func enrollMembersThenStop(t *testing.T, mesh *sdkMesh) *offlineMembers {+ t.Helper()+ members := &offlineMembers{nodeBin: buildBinary(t, "./cmd/sam-node")}++ // A token is read only to enroll, so the file can go once the member+ // holds a credential.for _, launcher := range sdkMemberLaunchers {cmd, skip := launcher.cmd(mesh.root)if skip != "" {@@ -67,105 +170,100 @@ func TestKeyRotationWhileMembersOffline(t *testing.T) {}stateDir := filepath.Join(t.TempDir(), "state")m := launchSDKMember(t, launcher.name, cmd, mesh.root, mesh.baseURL, mesh.adminToken, "SAM_SDK_STATE_DIR="+stateDir)- sdkMembers = append(sdkMembers, offlineSDKMember{launcher: launcher, stateDir: stateDir, peerID: m.report.PeerID, biscuit: m.report.Biscuit})+ members.sdk = append(members.sdk, offlineSDKMember{launcher: launcher, stateDir: stateDir, peerID: m.report.PeerID, biscuit: m.report.Biscuit})m.quit(t)}- // The Go node: enrolled through OIDC, its identity and mesh config in- // its data directory, its credential readable on the owner socket.- nodeHome := filepath.Join(t.TempDir(), "node")- if err := os.MkdirAll(nodeHome, 0o755); err != nil {+ // The Go node: enrolled through a platform token on disk, its identity+ // and mesh config in its data directory, its credential readable on the+ // owner socket.+ members.nodeHome = filepath.Join(t.TempDir(), "node")+ if err := os.MkdirAll(members.nodeHome, 0o755); err != nil {t.Fatal(err)}- nodeEnv := append(os.Environ(), "HOME="+nodeHome, "XDG_CONFIG_HOME="+filepath.Join(nodeHome, ".config"))+ members.nodeEnv = append(os.Environ(), "HOME="+members.nodeHome, "XDG_CONFIG_HOME="+filepath.Join(members.nodeHome, ".config"))socketDir, err := os.MkdirTemp("", "sam-rot-")if err != nil {t.Fatal(err)}t.Cleanup(func() { _ = os.RemoveAll(socketDir) })+ members.freshJWT = func() string {+ return mesh.mintToken(map[string]interface{}{"sub": "mock-user", "roles": []string{api.RoleNode}})+ }+ members.jwtPath = filepath.Join(t.TempDir(), "jwt")+ if err := os.WriteFile(members.jwtPath, []byte(members.freshJWT()), 0o600); err != nil {+ t.Fatal(err)+ }nodeSocket := filepath.Join(socketDir, "node.sock")- nodeArgs := []string{"run",+ members.nodeArgs = []string{"run","--control-plane", mesh.baseURL,"--allow-loopback","--api-token-path", tokenPath(t, "node-token"),"--socket-path", nodeSocket,"--log-level", "debug",}- node := launchNode(t, nodeBin, nodeEnv, nodeHome,- append(nodeArgs, "--jwt", mesh.mintToken(map[string]interface{}{"sub": "mock-user", "roles": []string{api.RoleNode}}))...)- node.waitForAPI(t)- socketClient := identityEvidenceSocketClient(nodeSocket)- waitForIdentityEvidenceSocket(t, socketClient)- var nodeBefore api.IdentityEvidenceResponse- getIdentityEvidenceJSON(t, socketClient, "/sam/identity", &nodeBefore)- nodePeer, err := peer.Decode(nodeBefore.PeerId)+ node := members.startNode(t, true)+ members.socketClient = identityEvidenceSocketClient(nodeSocket)+ waitForIdentityEvidenceSocket(t, members.socketClient)+ getIdentityEvidenceJSON(t, members.socketClient, "/sam/identity", &members.nodeBefore)+ members.nodePeer, err = peer.Decode(members.nodeBefore.PeerId)if err != nil {t.Fatal(err)}- if _, err := verifyBiscuitForApplication(nodeBefore.Biscuit, nodePeer, []ed25519.PublicKey{mesh.cpPub}); err != nil {+ if _, err := verifyBiscuitForApplication(members.nodeBefore.Biscuit, members.nodePeer, []ed25519.PublicKey{mesh.cpPub}); err != nil {t.Fatalf("node credential before the rotation does not verify under the current key: %v", err)}node.kill()+ return members+}++// startNode brings the node up from its data directory, with the platform+// token on disk offered or not.+func (o *offlineMembers) startNode(t *testing.T, withToken bool) *backgroundNode {+ t.Helper()+ args := o.nodeArgs+ if withToken {+ args = append(append([]string{}, args...), "--jwt-path", o.jwtPath)+ }+ node := launchNode(t, o.nodeBin, o.nodeEnv, o.nodeHome, args...)+ node.waitForAPI(t)+ return node+}++func (o *offlineMembers) assertNodeBackUnderKey(t *testing.T, node *backgroundNode, mesh *sdkMesh, pub ed25519.PublicKey) {+ t.Helper()+ waitForIdentityEvidenceSocket(t, o.socketClient)+ var after api.IdentityEvidenceResponse+ getIdentityEvidenceJSON(t, o.socketClient, "/sam/identity", &after)+ if after.PeerId != o.nodeBefore.PeerId {+ t.Fatalf("node came back as %s, want its stored identity %s", after.PeerId, o.nodeBefore.PeerId)+ }+ if _, err := verifyBiscuitForApplication(after.Biscuit, o.nodePeer, []ed25519.PublicKey{pub}); err != nil {+ t.Fatalf("node credential after coming back does not verify under the new key: %v\n--- node.log ---\n%s", err, node.log())+ }+ if _, err := verifyBiscuitForApplication(after.Biscuit, o.nodePeer, []ed25519.PublicKey{mesh.cpPub}); err == nil {+ t.Fatal("node credential after coming back still verifies under the retiring key: it was not refreshed")+ }+ waitForPeerOnRouter(t, mesh.cpPort, mesh.adminToken, o.nodeBefore.PeerId, 10*time.Second)+}- // The rotation, as the sam-control-plane binary makes it: a new current- // key, the old one retiring over a grace period, the event on the mesh.- // Every router refreshes its credential under the new key; a member- // that trusts only the old key can verify none of them any more.+// rotateSigningKey rotates as the sam-control-plane binary does: a new+// current key, the old one retiring over grace, the event on the mesh. It+// returns once every router presents a credential under the new key.+func rotateSigningKey(t *testing.T, ctx context.Context, mesh *sdkMesh, grace time.Duration) ed25519.PublicKey {+ t.Helper()newPub, newPriv, err := ed25519.GenerateKey(nil)if err != nil {t.Fatal(err)}- if err := mesh.store.RotateKeys(ctx, newPriv, newPub, time.Hour); err != nil {+ if err := mesh.store.RotateKeys(ctx, newPriv, newPub, grace); err != nil {t.Fatalf("RotateKeys: %v", err)}if err := mesh.publisher.PublishEvent(ctx, api.MeshEvent_KEY_ROTATION, "", newPub); err != nil {t.Fatalf("publish KEY_ROTATION: %v", err)}waitForRoutersUnderKey(t, ctx, mesh, newPub)-- // The SDK members start again from their state directories. The token- // path names no file: the member resumes or fails, it cannot enroll.- for _, s := range sdkMembers {- cmd, _ := s.launcher.cmd(mesh.root)- m := launchSDKMember(t, s.launcher.name+" resumed", cmd, mesh.root, mesh.baseURL, mesh.adminToken,- "SAM_SDK_STATE_DIR="+s.stateDir,- "SAM_BOOTSTRAP_TOKEN_PATH="+filepath.Join(t.TempDir(), "no-token"))- if m.report.PeerID != s.peerID {- t.Fatalf("%s came back as %s, want the identity it persisted, %s", m.name, m.report.PeerID, s.peerID)- }- assertAdmittedByEveryRouter(t, m, mesh.routerAddrs)- if m.report.Biscuit == s.biscuit {- t.Fatalf("%s still holds the credential minted before the rotation", m.name)- }- assertSignedOnlyBy(t, m.name, m.report.Biscuit, m.report.PeerID, newPub, mesh.cpPub)- if res := m.sync(t); !res.OK {- t.Fatalf("%s: pull after the resume failed: %s", m.name, res.Error)- }- // The node across the mesh admits the resumed member too.- if cred := m.auth(t, mesh.samNode.p2pAddr); cred.PeerID != mesh.samNode.peerID.String() {- t.Fatalf("%s verified the node as %+v after the resume", m.name, cred)- }- m.quit(t)- }-- // The Go node starts from its stored identity, with no token: it pulls- // from the control plane before it starts and comes up under the new key.- node = launchNode(t, nodeBin, nodeEnv, nodeHome, nodeArgs...)- node.waitForAPI(t)- waitForIdentityEvidenceSocket(t, socketClient)- var nodeAfter api.IdentityEvidenceResponse- getIdentityEvidenceJSON(t, socketClient, "/sam/identity", &nodeAfter)- if nodeAfter.PeerId != nodeBefore.PeerId {- t.Fatalf("node came back as %s, want its stored identity %s", nodeAfter.PeerId, nodeBefore.PeerId)- }- if _, err := verifyBiscuitForApplication(nodeAfter.Biscuit, nodePeer, []ed25519.PublicKey{newPub}); err != nil {- t.Fatalf("node credential after the resume does not verify under the new key: %v\n--- node.log ---\n%s", err, node.log())- }- if _, err := verifyBiscuitForApplication(nodeAfter.Biscuit, nodePeer, []ed25519.PublicKey{mesh.cpPub}); err == nil {- t.Fatal("node credential after the resume still verifies under the retiring key: it was not refreshed")- }- waitForPeerOnRouter(t, mesh.cpPort, mesh.adminToken, nodeBefore.PeerId, 10*time.Second)- node.kill()+ return newPub}// waitForRoutersUnderKey returns once every router presents a credential