Skip to content

Agent Mesh

api: what a member persists is a message; one layout in every implementation

Antonio Ojead8f58b47a0fd
diff --git a/AGENTS.md b/AGENTS.md
index 16f900bb..8d8db18e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -5,7 +5,8 @@ You are an expert software engineering assistant helping to develop, maintain, a
## 1. Architecture & Component Independence
* **Decoupled Architecture:** The `sam-control-plane`, `sam-router` and `sam-node` components are strictly independent. They must not share internal state or tightly couple their logic.
* **API Communication:** All data communication between `sam-control-plane`, `sam-router` and `sam-node` must happen exclusively via the common API defined in `api/sam.proto`.
-* **One schema, two encodings:** every request and response on any SAM surface is a message in `api/sam.proto`. The *mesh protocol* — anything a mesh component speaks (node, router, `sam-box`, the agent connector, the SDKs under `sdk/`): enrollment, refresh, keys, leases, auth streams, policy sync — is binary protobuf (`application/x-protobuf`). The *operator plane* — what humans, the web console and admin CLIs call (`/admin/*`, `/users/*`, `POST /policies`) — is protojson of the same messages, with `UseProtoNames` and unknown fields rejected. Never define a wire shape as a Go struct with `json` tags, an anonymous struct or `map[string]any`, and never serialize an `internal/storage` (or any other internal) type onto either surface. Use `google.protobuf.Timestamp` for instants so protojson renders them as RFC 3339. Clients in `cmd/`, `internal/console` and `sdk/` import `api/` or its generated bindings only.
+* **One schema, two encodings:** every request and response on any SAM surface is a message in `api/sam.proto`. The *mesh protocol* — anything a mesh component speaks (node, router, `sam-box`, the agent connector, the SDKs under `sdk/`): enrollment, refresh, keys, leases, auth streams, policy sync — is binary protobuf (`application/x-protobuf`). The *operator plane* — what humans, the web console and admin CLIs call (`/admin/*`, `/users/*`, `POST /policies`) — is protojson of the same messages, with `UseProtoNames` and unknown fields rejected. Never define a wire shape as a Go struct with `json` tags, an anonymous struct or `map[string]any`, and never serialize an `internal/storage` (or any other internal) type onto either surface. Clients in `cmd/`, `internal/console` and `sdk/` import `api/` or its generated bindings only.
+* **Instants are `google.protobuf.Timestamp`, named `*_time`** (`expire_time`, `receive_time`), never `int64` seconds or milliseconds. `Timestamp` has fixed units, an explicit unset, renders as RFC 3339 in protojson (an `int64` renders as a quoted decimal string), and has a first-class conversion in Go, JavaScript, Python and Dart. The `int64` instants still in `api/sam.proto` predate this rule; converting them is a coordinated protocol change, not something to do one field at a time. What a member persists between runs is also a message here (`MemberCredential`), so a state directory written by one implementation loads in another.
* **Datalog text is the policy contract:** the control plane renders the mesh policy as Datalog rules (`PolicyConfigGetResponse.datalog_rules`); every member, in any language, adds that text to its authorizer and none derives rules from roles and bindings itself. Datalog must stay in the form every Biscuit implementation parses: a predicate carries at least one term (presence-only facts are `name(true)`, see `api.MarkerFact`).
* **Secrets never travel as flag values:** binaries read credentials from a file (`--*-path`) or the environment, never from a command-line argument that would sit in `ps` output and shell history. Banners and logs name the source of an operator-supplied secret instead of echoing it.
* **Sandbox Dataplane:** `sam-box` (one per sandbox) is the single egress policy enforcement point. It holds no libp2p host, no enrollment and no mesh identity, and reaches the mesh exclusively as a client of the local `sam-node` sidecar socket. `nano-init` (PID 1 inside the guest, its own Go module) owns the guest side; its datapath is the `tun2connect` library. The sandbox boundary is a Unix socket speaking named HTTP tunnels: CONNECT (TCP) and connect-udp (UDP) out, `CONNECT <port>` back in. The authoritative design is `site/content/docs/preview/agent-architecture.md`; do not contradict it.
diff --git a/api/sam.pb.go b/api/sam.pb.go
index f0cd4e4d..9b44a6c3 100644
--- a/api/sam.pb.go
+++ b/api/sam.pb.go
@@ -23,6 +23,7 @@ package api
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
+ timestamppb "google.golang.org/protobuf/types/known/timestamppb"
reflect "reflect"
sync "sync"
unsafe "unsafe"
@@ -3023,11 +3024,237 @@ func (x *PeerEvidenceResponse) GetCheckedAt() int64 {
return 0
}
+type MemberCredential struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // Base URL of the control plane that minted the biscuit.
+ ControlPlaneUrl string `protobuf:"bytes,1,opt,name=control_plane_url,json=controlPlaneUrl,proto3" json:"control_plane_url,omitempty"`
+ // The member's biscuit.
+ Biscuit []byte `protobuf:"bytes,2,opt,name=biscuit,proto3" json:"biscuit,omitempty"`
+ // When the biscuit expires.
+ ExpireTime *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=expire_time,json=expireTime,proto3" json:"expire_time,omitempty"`
+ // Control plane signing keys trusted now; a rotation keeps several valid.
+ TrustedKeys []*TrustedSigningKey `protobuf:"bytes,4,rep,name=trusted_keys,json=trustedKeys,proto3" json:"trusted_keys,omitempty"`
+ // The keys trusted when the biscuit was issued. A key trusted now that is
+ // absent here means a rotation happened since: the biscuit is signed by a
+ // retiring key and must be refreshed before that key leaves its grace
+ // period.
+ IssuedUnderKeys [][]byte `protobuf:"bytes,5,rep,name=issued_under_keys,json=issuedUnderKeys,proto3" json:"issued_under_keys,omitempty"`
+ // Router multiaddrs, `/p2p/<peer id>` suffixed.
+ RouterAddresses []string `protobuf:"bytes,6,rep,name=router_addresses,json=routerAddresses,proto3" json:"router_addresses,omitempty"`
+ // The session that renews an identity enrolled through the mesh's
+ // identity provider. Unset for a member enrolled with a bootstrap token.
+ OidcSession *OIDCSession `protobuf:"bytes,7,opt,name=oidc_session,json=oidcSession,proto3" json:"oidc_session,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *MemberCredential) Reset() {
+ *x = MemberCredential{}
+ mi := &file_api_sam_proto_msgTypes[42]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *MemberCredential) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*MemberCredential) ProtoMessage() {}
+
+func (x *MemberCredential) ProtoReflect() protoreflect.Message {
+ mi := &file_api_sam_proto_msgTypes[42]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use MemberCredential.ProtoReflect.Descriptor instead.
+func (*MemberCredential) Descriptor() ([]byte, []int) {
+ return file_api_sam_proto_rawDescGZIP(), []int{42}
+}
+
+func (x *MemberCredential) GetControlPlaneUrl() string {
+ if x != nil {
+ return x.ControlPlaneUrl
+ }
+ return ""
+}
+
+func (x *MemberCredential) GetBiscuit() []byte {
+ if x != nil {
+ return x.Biscuit
+ }
+ return nil
+}
+
+func (x *MemberCredential) GetExpireTime() *timestamppb.Timestamp {
+ if x != nil {
+ return x.ExpireTime
+ }
+ return nil
+}
+
+func (x *MemberCredential) GetTrustedKeys() []*TrustedSigningKey {
+ if x != nil {
+ return x.TrustedKeys
+ }
+ return nil
+}
+
+func (x *MemberCredential) GetIssuedUnderKeys() [][]byte {
+ if x != nil {
+ return x.IssuedUnderKeys
+ }
+ return nil
+}
+
+func (x *MemberCredential) GetRouterAddresses() []string {
+ if x != nil {
+ return x.RouterAddresses
+ }
+ return nil
+}
+
+func (x *MemberCredential) GetOidcSession() *OIDCSession {
+ if x != nil {
+ return x.OidcSession
+ }
+ return nil
+}
+
+type TrustedSigningKey struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // Raw ed25519 public key.
+ PublicKey []byte `protobuf:"bytes,1,opt,name=public_key,json=publicKey,proto3" json:"public_key,omitempty"`
+ // When the member first learned the key. A key rotated out is dropped a
+ // grace period after this; unset means unknown and is read as now.
+ ReceiveTime *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=receive_time,json=receiveTime,proto3" json:"receive_time,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *TrustedSigningKey) Reset() {
+ *x = TrustedSigningKey{}
+ mi := &file_api_sam_proto_msgTypes[43]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *TrustedSigningKey) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*TrustedSigningKey) ProtoMessage() {}
+
+func (x *TrustedSigningKey) ProtoReflect() protoreflect.Message {
+ mi := &file_api_sam_proto_msgTypes[43]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use TrustedSigningKey.ProtoReflect.Descriptor instead.
+func (*TrustedSigningKey) Descriptor() ([]byte, []int) {
+ return file_api_sam_proto_rawDescGZIP(), []int{43}
+}
+
+func (x *TrustedSigningKey) GetPublicKey() []byte {
+ if x != nil {
+ return x.PublicKey
+ }
+ return nil
+}
+
+func (x *TrustedSigningKey) GetReceiveTime() *timestamppb.Timestamp {
+ if x != nil {
+ return x.ReceiveTime
+ }
+ return nil
+}
+
+type OIDCSession struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Issuer string `protobuf:"bytes,1,opt,name=issuer,proto3" json:"issuer,omitempty"`
+ ClientId string `protobuf:"bytes,2,opt,name=client_id,json=clientId,proto3" json:"client_id,omitempty"`
+ Audience string `protobuf:"bytes,3,opt,name=audience,proto3" json:"audience,omitempty"`
+ RefreshToken string `protobuf:"bytes,4,opt,name=refresh_token,json=refreshToken,proto3" json:"refresh_token,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *OIDCSession) Reset() {
+ *x = OIDCSession{}
+ mi := &file_api_sam_proto_msgTypes[44]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *OIDCSession) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*OIDCSession) ProtoMessage() {}
+
+func (x *OIDCSession) ProtoReflect() protoreflect.Message {
+ mi := &file_api_sam_proto_msgTypes[44]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use OIDCSession.ProtoReflect.Descriptor instead.
+func (*OIDCSession) Descriptor() ([]byte, []int) {
+ return file_api_sam_proto_rawDescGZIP(), []int{44}
+}
+
+func (x *OIDCSession) GetIssuer() string {
+ if x != nil {
+ return x.Issuer
+ }
+ return ""
+}
+
+func (x *OIDCSession) GetClientId() string {
+ if x != nil {
+ return x.ClientId
+ }
+ return ""
+}
+
+func (x *OIDCSession) GetAudience() string {
+ if x != nil {
+ return x.Audience
+ }
+ return ""
+}
+
+func (x *OIDCSession) GetRefreshToken() string {
+ if x != nil {
+ return x.RefreshToken
+ }
+ return ""
+}
+
var File_api_sam_proto protoreflect.FileDescriptor
const file_api_sam_proto_rawDesc = "" +
"\n" +
- "\rapi/sam.proto\x12\x06sam.v1\"b\n" +
+ "\rapi/sam.proto\x12\x06sam.v1\x1a\x1fgoogle/protobuf/timestamp.proto\"b\n" +
"\tAuthFrame\x12\x18\n" +
"\abiscuit\x18\x01 \x01(\fR\abiscuit\x12%\n" +
"\x0etarget_service\x18\x02 \x01(\tR\rtargetService\x12\x14\n" +
@@ -3259,7 +3486,25 @@ const file_api_sam_proto_rawDesc = "" +
"checked_at\x18\b \x01(\x03R\tcheckedAt\x1a9\n" +
"\vLabelsEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
- "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01*\x94\x01\n" +
+ "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\xe2\x02\n" +
+ "\x10MemberCredential\x12*\n" +
+ "\x11control_plane_url\x18\x01 \x01(\tR\x0fcontrolPlaneUrl\x12\x18\n" +
+ "\abiscuit\x18\x02 \x01(\fR\abiscuit\x12;\n" +
+ "\vexpire_time\x18\x03 \x01(\v2\x1a.google.protobuf.TimestampR\n" +
+ "expireTime\x12<\n" +
+ "\ftrusted_keys\x18\x04 \x03(\v2\x19.sam.v1.TrustedSigningKeyR\vtrustedKeys\x12*\n" +
+ "\x11issued_under_keys\x18\x05 \x03(\fR\x0fissuedUnderKeys\x12)\n" +
+ "\x10router_addresses\x18\x06 \x03(\tR\x0frouterAddresses\x126\n" +
+ "\foidc_session\x18\a \x01(\v2\x13.sam.v1.OIDCSessionR\voidcSession\"q\n" +
+ "\x11TrustedSigningKey\x12\x1d\n" +
+ "\n" +
+ "public_key\x18\x01 \x01(\fR\tpublicKey\x12=\n" +
+ "\freceive_time\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\vreceiveTime\"\x83\x01\n" +
+ "\vOIDCSession\x12\x16\n" +
+ "\x06issuer\x18\x01 \x01(\tR\x06issuer\x12\x1b\n" +
+ "\tclient_id\x18\x02 \x01(\tR\bclientId\x12\x1a\n" +
+ "\baudience\x18\x03 \x01(\tR\baudience\x12#\n" +
+ "\rrefresh_token\x18\x04 \x01(\tR\frefreshToken*\x94\x01\n" +
"\x10EnrollmentStatus\x12!\n" +
"\x1dENROLLMENT_STATUS_UNSPECIFIED\x10\x00\x12\x1d\n" +
"\x19ENROLLMENT_STATUS_PENDING\x10\x01\x12\x1e\n" +
@@ -3284,7 +3529,7 @@ func file_api_sam_proto_rawDescGZIP() []byte {
}
var file_api_sam_proto_enumTypes = make([]protoimpl.EnumInfo, 3)
-var file_api_sam_proto_msgTypes = make([]protoimpl.MessageInfo, 47)
+var file_api_sam_proto_msgTypes = make([]protoimpl.MessageInfo, 50)
var file_api_sam_proto_goTypes = []any{
(EnrollmentStatus)(0), // 0: sam.v1.EnrollmentStatus
(ServiceType)(0), // 1: sam.v1.ServiceType
@@ -3331,23 +3576,27 @@ var file_api_sam_proto_goTypes = []any{
(*AgentStatusResponse)(nil), // 42: sam.v1.AgentStatusResponse
(*IdentityEvidenceResponse)(nil), // 43: sam.v1.IdentityEvidenceResponse
(*PeerEvidenceResponse)(nil), // 44: sam.v1.PeerEvidenceResponse
- nil, // 45: sam.v1.EnrollRequest.LabelsEntry
- nil, // 46: sam.v1.BootstrapEnrollRequest.LabelsEntry
- nil, // 47: sam.v1.CommandBackend.EnvEntry
- nil, // 48: sam.v1.ServiceAnnounce.LabelsEntry
- nil, // 49: sam.v1.PeerEvidenceResponse.LabelsEntry
+ (*MemberCredential)(nil), // 45: sam.v1.MemberCredential
+ (*TrustedSigningKey)(nil), // 46: sam.v1.TrustedSigningKey
+ (*OIDCSession)(nil), // 47: sam.v1.OIDCSession
+ nil, // 48: sam.v1.EnrollRequest.LabelsEntry
+ nil, // 49: sam.v1.BootstrapEnrollRequest.LabelsEntry
+ nil, // 50: sam.v1.CommandBackend.EnvEntry
+ nil, // 51: sam.v1.ServiceAnnounce.LabelsEntry
+ nil, // 52: sam.v1.PeerEvidenceResponse.LabelsEntry
+ (*timestamppb.Timestamp)(nil), // 53: google.protobuf.Timestamp
}
var file_api_sam_proto_depIdxs = []int32{
2, // 0: sam.v1.MeshEvent.type:type_name -> sam.v1.MeshEvent.Type
- 45, // 1: sam.v1.EnrollRequest.labels:type_name -> sam.v1.EnrollRequest.LabelsEntry
- 46, // 2: sam.v1.BootstrapEnrollRequest.labels:type_name -> sam.v1.BootstrapEnrollRequest.LabelsEntry
+ 48, // 1: sam.v1.EnrollRequest.labels:type_name -> sam.v1.EnrollRequest.LabelsEntry
+ 49, // 2: sam.v1.BootstrapEnrollRequest.labels:type_name -> sam.v1.BootstrapEnrollRequest.LabelsEntry
0, // 3: sam.v1.BootstrapEnrollResponse.status:type_name -> sam.v1.EnrollmentStatus
1, // 4: sam.v1.ServiceInfo.type:type_name -> sam.v1.ServiceType
- 47, // 5: sam.v1.CommandBackend.env:type_name -> sam.v1.CommandBackend.EnvEntry
+ 50, // 5: sam.v1.CommandBackend.env:type_name -> sam.v1.CommandBackend.EnvEntry
10, // 6: sam.v1.RegisterServiceRequest.service:type_name -> sam.v1.ServiceInfo
11, // 7: sam.v1.RegisterServiceRequest.command:type_name -> sam.v1.CommandBackend
1, // 8: sam.v1.ServiceAnnounce.type:type_name -> sam.v1.ServiceType
- 48, // 9: sam.v1.ServiceAnnounce.labels:type_name -> sam.v1.ServiceAnnounce.LabelsEntry
+ 51, // 9: sam.v1.ServiceAnnounce.labels:type_name -> sam.v1.ServiceAnnounce.LabelsEntry
18, // 10: sam.v1.PolicyConfig.roles:type_name -> sam.v1.PolicyRole
19, // 11: sam.v1.PolicyConfig.bindings:type_name -> sam.v1.PolicyBinding
10, // 12: sam.v1.NodeCatalogReport.services:type_name -> sam.v1.ServiceInfo
@@ -3358,12 +3607,16 @@ var file_api_sam_proto_depIdxs = []int32{
33, // 17: sam.v1.AgentAttachRequest.bundle:type_name -> sam.v1.AgentBundle
32, // 18: sam.v1.AgentStatus.ingress:type_name -> sam.v1.AgentIngress
41, // 19: sam.v1.AgentStatusResponse.agents:type_name -> sam.v1.AgentStatus
- 49, // 20: sam.v1.PeerEvidenceResponse.labels:type_name -> sam.v1.PeerEvidenceResponse.LabelsEntry
- 21, // [21:21] is the sub-list for method output_type
- 21, // [21:21] is the sub-list for method input_type
- 21, // [21:21] is the sub-list for extension type_name
- 21, // [21:21] is the sub-list for extension extendee
- 0, // [0:21] is the sub-list for field type_name
+ 52, // 20: sam.v1.PeerEvidenceResponse.labels:type_name -> sam.v1.PeerEvidenceResponse.LabelsEntry
+ 53, // 21: sam.v1.MemberCredential.expire_time:type_name -> google.protobuf.Timestamp
+ 46, // 22: sam.v1.MemberCredential.trusted_keys:type_name -> sam.v1.TrustedSigningKey
+ 47, // 23: sam.v1.MemberCredential.oidc_session:type_name -> sam.v1.OIDCSession
+ 53, // 24: sam.v1.TrustedSigningKey.receive_time:type_name -> google.protobuf.Timestamp
+ 25, // [25:25] is the sub-list for method output_type
+ 25, // [25:25] is the sub-list for method input_type
+ 25, // [25:25] is the sub-list for extension type_name
+ 25, // [25:25] is the sub-list for extension extendee
+ 0, // [0:25] is the sub-list for field type_name
}
func init() { file_api_sam_proto_init() }
@@ -3381,7 +3634,7 @@ func file_api_sam_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_api_sam_proto_rawDesc), len(file_api_sam_proto_rawDesc)),
NumEnums: 3,
- NumMessages: 47,
+ NumMessages: 50,
NumExtensions: 0,
NumServices: 0,
},
diff --git a/api/sam.proto b/api/sam.proto
index 6610b10b..91e2fe0a 100644
--- a/api/sam.proto
+++ b/api/sam.proto
@@ -16,6 +16,8 @@ syntax = "proto3";
package sam.v1;
option go_package = "github.com/google/sam/api";
+import "google/protobuf/timestamp.proto";
+
message AuthFrame {
@@ -461,5 +463,54 @@ message PeerEvidenceResponse {
int64 checked_at = 8;
}
+// ============================================================================
+// Member state
+// ============================================================================
+//
+// What a member keeps between runs besides its private key, in one message
+// every implementation persists. The private key is the libp2p crypto.proto
+// PrivateKey encoding. The SDKs keep both in a state directory as
+// `identity.key` and `credential.json` (protojson of MemberCredential with
+// proto field names, unknown fields rejected); sam-node keeps both in its
+// database. `sam-node state export` and `sam-node state import` move a
+// member between the two, so an identity enrolled by one implementation
+// runs under another.
+
+message MemberCredential {
+ // Base URL of the control plane that minted the biscuit.
+ string control_plane_url = 1;
+ // The member's biscuit.
+ bytes biscuit = 2;
+ // When the biscuit expires.
+ google.protobuf.Timestamp expire_time = 3;
+ // Control plane signing keys trusted now; a rotation keeps several valid.
+ repeated TrustedSigningKey trusted_keys = 4;
+ // The keys trusted when the biscuit was issued. A key trusted now that is
+ // absent here means a rotation happened since: the biscuit is signed by a
+ // retiring key and must be refreshed before that key leaves its grace
+ // period.
+ repeated bytes issued_under_keys = 5;
+ // Router multiaddrs, `/p2p/<peer id>` suffixed.
+ repeated string router_addresses = 6;
+ // The session that renews an identity enrolled through the mesh's
+ // identity provider. Unset for a member enrolled with a bootstrap token.
+ OIDCSession oidc_session = 7;
+}
+
+message TrustedSigningKey {
+ // Raw ed25519 public key.
+ bytes public_key = 1;
+ // When the member first learned the key. A key rotated out is dropped a
+ // grace period after this; unset means unknown and is read as now.
+ google.protobuf.Timestamp receive_time = 2;
+}
+
+message OIDCSession {
+ string issuer = 1;
+ string client_id = 2;
+ string audience = 3;
+ string refresh_token = 4;
+}
+
diff --git a/cmd/sam-node/main.go b/cmd/sam-node/main.go
index 24b9a15f..aa4adc72 100644
--- a/cmd/sam-node/main.go
+++ b/cmd/sam-node/main.go
@@ -912,6 +912,7 @@ func main() {
rootCmd.AddCommand(runCmd)
rootCmd.AddCommand(joinCmd)
rootCmd.AddCommand(resetCmd)
+ rootCmd.AddCommand(newStateCmd())
rootCmd.AddCommand(newSkillCmd())
rootCmd.AddCommand(newDebugCmd())
diff --git a/cmd/sam-node/state.go b/cmd/sam-node/state.go
new file mode 100644
index 00000000..40600e67
--- /dev/null
+++ b/cmd/sam-node/state.go
@@ -0,0 +1,141 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package main
+
+import (
+ "errors"
+ "fmt"
+
+ "github.com/google/sam/internal/node"
+ "github.com/libp2p/go-libp2p/core/crypto"
+ "github.com/libp2p/go-libp2p/core/peer"
+ "github.com/spf13/cobra"
+)
+
+// newStateCmd moves a member between this node's database and a state
+// directory, the layout the native SDKs use, so an identity enrolled by one
+// runs under the other. Both directions need the node stopped: the database
+// lock refuses a running node's data directory.
+func newStateCmd() *cobra.Command {
+ stateCmd := &cobra.Command{
+ Use: "state",
+ Short: "Export or import this node's identity and credential as an SDK state directory",
+ Long: "Export or import this node's identity and credential as a state directory.\n\n" +
+ "A state directory is how the native SDKs keep a member: identity.key (the\n" +
+ "libp2p private key) and credential.json (the MemberCredential message of\n" +
+ "api/sam.proto as JSON). Exporting hands this node's identity to a program\n" +
+ "written with an SDK; importing runs an SDK-enrolled identity as a sam-node.\n" +
+ "Stop the node first; a running node holds its data directory.",
+ }
+
+ exportCmd := &cobra.Command{
+ Use: "export <dir>",
+ Short: "Write this node's identity and credential to a state directory",
+ Args: cobra.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ store, err := openStoreForState()
+ if err != nil {
+ return err
+ }
+ defer func() { _ = store.Close() }()
+ privKey, err := store.LoadKey()
+ if err != nil {
+ return err
+ }
+ if len(privKey) == 0 {
+ return errors.New("this node has no identity yet; run it once or enroll first")
+ }
+ credential, err := store.Credential()
+ if err != nil {
+ return err
+ }
+ if len(credential.Biscuit) == 0 {
+ return errors.New("this node has not enrolled; nothing to export beyond the key")
+ }
+ if err := node.WriteStateDir(args[0], privKey, credential); err != nil {
+ return err
+ }
+ id, err := peerIDOf(privKey)
+ if err != nil {
+ return err
+ }
+ fmt.Printf("Exported %s to %s\nThe files hold the node's private key and credential; whoever reads them is this member.\n", id, args[0])
+ return nil
+ },
+ }
+
+ importCmd := &cobra.Command{
+ Use: "import <dir>",
+ Short: "Replace this node's identity and credential with a state directory's",
+ Args: cobra.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ privKey, credential, err := node.ReadStateDir(args[0])
+ if err != nil {
+ return err
+ }
+ id, err := peerIDOf(privKey)
+ if err != nil {
+ return err
+ }
+ store, err := openStoreForState()
+ if err != nil {
+ return err
+ }
+ defer func() { _ = store.Close() }()
+ if existing, _ := store.LoadKey(); len(existing) > 0 && !assumeYesFlag {
+ existingID, err := peerIDOf(existing)
+ if err != nil {
+ existingID = "an identity"
+ }
+ return fmt.Errorf("%s already holds %s; pass --yes to replace it with %s", resolveDataDir(), existingID, id)
+ }
+ if err := store.SaveKey(privKey); err != nil {
+ return err
+ }
+ if err := store.SetCredential(credential); err != nil {
+ return err
+ }
+ fmt.Printf("Imported %s from %s into %s\nStart the node with 'sam-node run'; it resumes as that member.\n", id, args[0], resolveDataDir())
+ return nil
+ },
+ }
+ importCmd.Flags().BoolVar(&assumeYesFlag, "yes", false, "Replace an identity already in the data directory")
+
+ stateCmd.AddCommand(exportCmd, importCmd)
+ return stateCmd
+}
+
+func openStoreForState() (*node.Store, error) {
+ store, err := node.NewStore(resolveDataDir())
+ if errors.Is(err, node.ErrStoreLocked) {
+ return nil, fmt.Errorf("%w; stop it first", err)
+ }
+ if err != nil {
+ return nil, fmt.Errorf("opening %s: %w", resolveDataDir(), err)
+ }
+ return store, nil
+}
+
+func peerIDOf(privKey []byte) (string, error) {
+ priv, err := crypto.UnmarshalPrivateKey(privKey)
+ if err != nil {
+ return "", err
+ }
+ id, err := peer.IDFromPrivateKey(priv)
+ if err != nil {
+ return "", err
+ }
+ return id.String(), nil
+}
diff --git a/internal/node/statedir.go b/internal/node/statedir.go
new file mode 100644
index 00000000..b465e6d7
--- /dev/null
+++ b/internal/node/statedir.go
@@ -0,0 +1,91 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package node
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+
+ "github.com/google/sam/api"
+ "github.com/libp2p/go-libp2p/core/crypto"
+ "google.golang.org/protobuf/encoding/protojson"
+)
+
+// The state directory is the layout the native SDKs keep a member in, and
+// what `sam-node state export` writes and `sam-node state import` reads:
+// the private key in the libp2p PrivateKey encoding and the
+// api.MemberCredential as protojson with proto field names. Files are
+// owner-only; unknown fields in the credential are an error, as on every
+// SAM surface.
+const (
+ StateDirIdentityFile = "identity.key"
+ StateDirCredentialFile = "credential.json"
+)
+
+var stateDirMarshal = protojson.MarshalOptions{UseProtoNames: true, Multiline: true, Indent: " "}
+
+// WriteStateDir writes a member to dir, creating it owner-only.
+func WriteStateDir(dir string, privKey []byte, c *api.MemberCredential) error {
+ if _, err := crypto.UnmarshalPrivateKey(privKey); err != nil {
+ return fmt.Errorf("private key is not a libp2p key: %w", err)
+ }
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ return err
+ }
+ credential, err := stateDirMarshal.Marshal(c)
+ if err != nil {
+ return err
+ }
+ if err := writeOwnerOnly(filepath.Join(dir, StateDirIdentityFile), privKey); err != nil {
+ return err
+ }
+ return writeOwnerOnly(filepath.Join(dir, StateDirCredentialFile), append(credential, '\n'))
+}
+
+// ReadStateDir reads a member from dir.
+func ReadStateDir(dir string) (privKey []byte, c *api.MemberCredential, err error) {
+ privKey, err = os.ReadFile(filepath.Join(dir, StateDirIdentityFile))
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return nil, nil, fmt.Errorf("no identity in %s: %w", dir, err)
+ }
+ return nil, nil, err
+ }
+ if _, err := crypto.UnmarshalPrivateKey(privKey); err != nil {
+ return nil, nil, fmt.Errorf("%s: not a libp2p private key: %w", filepath.Join(dir, StateDirIdentityFile), err)
+ }
+ raw, err := os.ReadFile(filepath.Join(dir, StateDirCredentialFile))
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return nil, nil, fmt.Errorf("no credential in %s: %w", dir, err)
+ }
+ return nil, nil, err
+ }
+ c = &api.MemberCredential{}
+ if err := protojson.Unmarshal(raw, c); err != nil {
+ return nil, nil, fmt.Errorf("%s: %w", filepath.Join(dir, StateDirCredentialFile), err)
+ }
+ return privKey, c, nil
+}
+
+func writeOwnerOnly(path string, data []byte) error {
+ tmp := path + ".tmp"
+ if err := os.WriteFile(tmp, data, 0o600); err != nil {
+ return err
+ }
+ return os.Rename(tmp, path)
+}
diff --git a/internal/node/statedir_test.go b/internal/node/statedir_test.go
new file mode 100644
index 00000000..02427980
--- /dev/null
+++ b/internal/node/statedir_test.go
@@ -0,0 +1,115 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package node
+
+import (
+ "bytes"
+ "crypto/ed25519"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/google/sam/api"
+ "github.com/libp2p/go-libp2p/core/crypto"
+ "google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/types/known/timestamppb"
+)
+
+func TestStateDirRoundTrip(t *testing.T) {
+ priv, _, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ privKey, _ := crypto.MarshalPrivateKey(priv)
+ want := &api.MemberCredential{
+ ControlPlaneUrl: "https://cp.example",
+ Biscuit: []byte("biscuit"),
+ ExpireTime: timestamppb.New(time.Unix(1790000000, 0)),
+ TrustedKeys: []*api.TrustedSigningKey{{PublicKey: bytes.Repeat([]byte{3}, ed25519.PublicKeySize)}},
+ IssuedUnderKeys: [][]byte{bytes.Repeat([]byte{3}, ed25519.PublicKeySize)},
+ RouterAddresses: []string{"/dns4/router.example/tcp/4001/p2p/12D3KooWP8iKhDf3iCMo2H3butNVfdTUtYwYWYQ75jTGnynXPFMp"},
+ OidcSession: &api.OIDCSession{Issuer: "https://issuer.example", RefreshToken: "secret"},
+ }
+ dir := filepath.Join(t.TempDir(), "state")
+ if err := WriteStateDir(dir, privKey, want); err != nil {
+ t.Fatal(err)
+ }
+ for _, f := range []string{StateDirIdentityFile, StateDirCredentialFile} {
+ info, err := os.Stat(filepath.Join(dir, f))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if info.Mode().Perm() != 0o600 {
+ t.Errorf("%s mode %o, want 0600", f, info.Mode().Perm())
+ }
+ }
+
+ // The file is protojson with proto field names and RFC 3339 instants,
+ // what the SDKs read and write.
+ raw, _ := os.ReadFile(filepath.Join(dir, StateDirCredentialFile))
+ var fields map[string]any
+ if err := json.Unmarshal(raw, &fields); err != nil {
+ t.Fatal(err)
+ }
+ for _, k := range []string{"control_plane_url", "biscuit", "expire_time", "trusted_keys", "issued_under_keys", "router_addresses", "oidc_session"} {
+ if _, ok := fields[k]; !ok {
+ t.Errorf("credential.json lacks %q: %s", k, raw)
+ }
+ }
+ if exp, _ := fields["expire_time"].(string); !strings.HasSuffix(exp, "Z") {
+ t.Errorf("expire_time = %v, want RFC 3339", fields["expire_time"])
+ }
+
+ gotKey, got, err := ReadStateDir(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(gotKey, privKey) || !proto.Equal(got, want) {
+ t.Fatalf("round trip differs:\n got %v\nwant %v", got, want)
+ }
+}
+
+func TestStateDirRejectsUnknownFieldsAndForeignKeys(t *testing.T) {
+ dir := t.TempDir()
+ if _, _, err := ReadStateDir(dir); err == nil || !strings.Contains(err.Error(), "no identity") {
+ t.Fatalf("empty dir: %v", err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, StateDirIdentityFile), []byte("not a key"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := ReadStateDir(dir); err == nil || !strings.Contains(err.Error(), "not a libp2p private key") {
+ t.Fatalf("garbage key: %v", err)
+ }
+ priv, _, _ := crypto.GenerateKeyPair(crypto.Ed25519, -1)
+ privKey, _ := crypto.MarshalPrivateKey(priv)
+ if err := os.WriteFile(filepath.Join(dir, StateDirIdentityFile), privKey, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := ReadStateDir(dir); err == nil || !strings.Contains(err.Error(), "no credential") {
+ t.Fatalf("missing credential: %v", err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, StateDirCredentialFile), []byte(`{"control_plane_url": "https://cp.example", "surprise": 1}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := ReadStateDir(dir); err == nil || !strings.Contains(err.Error(), "surprise") {
+ t.Fatalf("unknown field: %v", err)
+ }
+ if err := WriteStateDir(dir, []byte("not a key"), &api.MemberCredential{}); err == nil {
+ t.Fatal("WriteStateDir accepted a private key that is not a libp2p key")
+ }
+}
diff --git a/internal/node/store.go b/internal/node/store.go
index 12a9b158..dca4ebf9 100644
--- a/internal/node/store.go
+++ b/internal/node/store.go
@@ -21,28 +21,49 @@ import (
"fmt"
"os"
"path/filepath"
+ "strconv"
"time"
+ "github.com/google/sam/api"
"go.etcd.io/bbolt"
bbolterrors "go.etcd.io/bbolt/errors"
+ "google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/types/known/timestamppb"
)
const (
// StoreFile is the node database inside the data directory.
StoreFile = "agent.db"
- bucketIdentity = "identity"
- keyBiscuit = "identity_biscuit"
- keyPrivKey = "node_private_key"
- keyIdentityExp = "identity_expiration"
- keyRefreshToken = "refresh_token"
- keyOidcIssuer = "oidc_issuer"
- keyOidcClientID = "oidc_client_id"
- keyOidcAudience = "oidc_audience"
- keyTrustedKeys = "trusted_keys"
- keyIdentityKeys = "identity_key_set"
+ bucketIdentity = "identity"
+ // keyPrivKey holds the libp2p PrivateKey encoding, as identity.key in a
+ // state directory does.
+ keyPrivKey = "node_private_key"
+ // keyCredential holds the binary api.MemberCredential, the same message a
+ // state directory keeps as credential.json.
+ keyCredential = "member_credential"
)
+// legacyKeys are the per-field entries the database held before the
+// credential became one message. A store that still has them is migrated on
+// open and they are removed.
+var legacyKeys = []string{
+ "identity_biscuit",
+ "identity_expiration",
+ "refresh_token",
+ "oidc_issuer",
+ "oidc_client_id",
+ "oidc_audience",
+ "trusted_keys",
+ "identity_key_set",
+ "control_plane_public_key",
+ "router_addresses",
+ "control_plane_url",
+}
+
+// Store is the node's persistent state: its private key and its
+// api.MemberCredential, in a bbolt database whose file lock also tells a
+// second sam-node that this data directory is in use.
type Store struct {
db *bbolt.DB
}
@@ -77,33 +98,168 @@ func NewStore(dir string) (*Store, error) {
}
err = db.Update(func(tx *bbolt.Tx) error {
- if _, err := tx.CreateBucketIfNotExists([]byte(bucketIdentity)); err != nil {
+ b, err := tx.CreateBucketIfNotExists([]byte(bucketIdentity))
+ if err != nil {
return err
}
- return nil
+ return migrateLegacyCredential(b)
})
+ if err != nil {
+ _ = db.Close()
+ return nil, err
+ }
+ return &Store{db: db}, nil
+}
- return &Store{db: db}, err
+// migrateLegacyCredential folds the per-field entries of an older database
+// into one MemberCredential. The enrollment key seeds both key sets when the
+// old database recorded neither, which is what the code reading them assumed.
+func migrateLegacyCredential(b *bbolt.Bucket) error {
+ if b.Get([]byte(keyCredential)) != nil {
+ return nil
+ }
+ present := false
+ for _, k := range legacyKeys {
+ if b.Get([]byte(k)) != nil {
+ present = true
+ break
+ }
+ }
+ if !present {
+ return nil
+ }
+ c := &api.MemberCredential{
+ ControlPlaneUrl: string(b.Get([]byte("control_plane_url"))),
+ Biscuit: append([]byte(nil), b.Get([]byte("identity_biscuit"))...),
+ }
+ if raw := b.Get([]byte("identity_expiration")); len(raw) > 0 {
+ if exp, err := strconv.ParseInt(string(raw), 10, 64); err == nil {
+ c.ExpireTime = timestamppb.New(time.Unix(exp, 0))
+ }
+ }
+ if raw := b.Get([]byte("router_addresses")); len(raw) > 0 {
+ if err := json.Unmarshal(raw, &c.RouterAddresses); err != nil {
+ return fmt.Errorf("migrating router_addresses: %w", err)
+ }
+ }
+ if raw := b.Get([]byte("trusted_keys")); len(raw) > 0 {
+ var keys []TrustedKey
+ if err := json.Unmarshal(raw, &keys); err != nil {
+ return fmt.Errorf("migrating trusted_keys: %w", err)
+ }
+ c.TrustedKeys = trustedKeysToProto(keys)
+ }
+ if raw := b.Get([]byte("identity_key_set")); len(raw) > 0 {
+ var keys []ed25519.PublicKey
+ if err := json.Unmarshal(raw, &keys); err != nil {
+ return fmt.Errorf("migrating identity_key_set: %w", err)
+ }
+ for _, k := range keys {
+ c.IssuedUnderKeys = append(c.IssuedUnderKeys, []byte(k))
+ }
+ }
+ if enrollmentKey := b.Get([]byte("control_plane_public_key")); len(enrollmentKey) == ed25519.PublicKeySize {
+ if !containsKeyBytes(trustedKeyBytes(c.TrustedKeys), enrollmentKey) {
+ c.TrustedKeys = append(c.TrustedKeys, &api.TrustedSigningKey{PublicKey: append([]byte(nil), enrollmentKey...), ReceiveTime: timestamppb.Now()})
+ }
+ if len(c.IssuedUnderKeys) == 0 {
+ c.IssuedUnderKeys = [][]byte{append([]byte(nil), enrollmentKey...)}
+ }
+ }
+ issuer, clientID, audience := string(b.Get([]byte("oidc_issuer"))), string(b.Get([]byte("oidc_client_id"))), string(b.Get([]byte("oidc_audience")))
+ refresh := string(b.Get([]byte("refresh_token")))
+ if issuer != "" || clientID != "" || audience != "" || refresh != "" {
+ c.OidcSession = &api.OIDCSession{Issuer: issuer, ClientId: clientID, Audience: audience, RefreshToken: refresh}
+ }
+ if err := putCredential(b, c); err != nil {
+ return err
+ }
+ for _, k := range legacyKeys {
+ if err := b.Delete([]byte(k)); err != nil {
+ return err
+ }
+ }
+ return nil
}
-func (s *Store) SaveIdentity(biscuit []byte) error {
+func putCredential(b *bbolt.Bucket, c *api.MemberCredential) error {
+ data, err := proto.Marshal(c)
+ if err != nil {
+ return err
+ }
+ return b.Put([]byte(keyCredential), data)
+}
+
+func getCredential(b *bbolt.Bucket) (*api.MemberCredential, error) {
+ c := &api.MemberCredential{}
+ if raw := b.Get([]byte(keyCredential)); len(raw) > 0 {
+ if err := proto.Unmarshal(raw, c); err != nil {
+ return nil, fmt.Errorf("corrupt member credential in store: %w", err)
+ }
+ }
+ return c, nil
+}
+
+// view reads the credential; an empty message stands for a node that has not enrolled.
+func (s *Store) view(fn func(c *api.MemberCredential) error) error {
+ return s.db.View(func(tx *bbolt.Tx) error {
+ c, err := getCredential(tx.Bucket([]byte(bucketIdentity)))
+ if err != nil {
+ return err
+ }
+ return fn(c)
+ })
+}
+
+// update applies fn to the credential and writes it back in one transaction.
+func (s *Store) update(fn func(c *api.MemberCredential) error) error {
return s.db.Update(func(tx *bbolt.Tx) error {
b := tx.Bucket([]byte(bucketIdentity))
- return b.Put([]byte(keyBiscuit), biscuit)
+ c, err := getCredential(b)
+ if err != nil {
+ return err
+ }
+ if err := fn(c); err != nil {
+ return err
+ }
+ return putCredential(b, c)
+ })
+}
+
+// Credential returns a copy of everything the node persists besides its
+// private key. A node that has not enrolled holds an empty message.
+func (s *Store) Credential() (*api.MemberCredential, error) {
+ var out *api.MemberCredential
+ err := s.view(func(c *api.MemberCredential) error {
+ out = proto.Clone(c).(*api.MemberCredential)
+ return nil
+ })
+ return out, err
+}
+
+// SetCredential replaces everything the node persists besides its private
+// key; `sam-node state import` uses it.
+func (s *Store) SetCredential(c *api.MemberCredential) error {
+ return s.db.Update(func(tx *bbolt.Tx) error {
+ return putCredential(tx.Bucket([]byte(bucketIdentity)), c)
+ })
+}
+
+func (s *Store) SaveIdentity(biscuit []byte) error {
+ return s.update(func(c *api.MemberCredential) error {
+ c.Biscuit = append([]byte(nil), biscuit...)
+ return nil
})
}
func (s *Store) LoadIdentity() ([]byte, error) {
var val []byte
- _ = s.db.View(func(tx *bbolt.Tx) error {
- b := tx.Bucket([]byte(bucketIdentity))
- dbVal := b.Get([]byte(keyBiscuit))
- if len(dbVal) > 0 {
- val = make([]byte, len(dbVal))
- copy(val, dbVal)
- }
+ if err := s.view(func(c *api.MemberCredential) error {
+ val = append([]byte(nil), c.Biscuit...)
return nil
- })
+ }); err != nil {
+ return nil, err
+ }
if len(val) == 0 {
return nil, fmt.Errorf("no identity found")
}
@@ -111,156 +267,143 @@ func (s *Store) LoadIdentity() ([]byte, error) {
}
func (s *Store) SaveIdentityExpiration(exp int64) error {
- return s.db.Update(func(tx *bbolt.Tx) error {
- b := tx.Bucket([]byte(bucketIdentity))
- return b.Put([]byte(keyIdentityExp), []byte(fmt.Sprintf("%d", exp)))
+ return s.update(func(c *api.MemberCredential) error {
+ c.ExpireTime = timestamppb.New(time.Unix(exp, 0))
+ return nil
})
}
func (s *Store) LoadIdentityExpiration() (int64, error) {
- var val []byte
- _ = s.db.View(func(tx *bbolt.Tx) error {
- b := tx.Bucket([]byte(bucketIdentity))
- val = b.Get([]byte(keyIdentityExp))
+ var exp *timestamppb.Timestamp
+ if err := s.view(func(c *api.MemberCredential) error {
+ exp = c.ExpireTime
return nil
- })
- if len(val) == 0 {
- return 0, fmt.Errorf("no identity expiration found")
- }
- var exp int64
- _, err := fmt.Sscanf(string(val), "%d", &exp)
- if err != nil {
+ }); err != nil {
return 0, err
}
- return exp, nil
+ if exp == nil {
+ return 0, fmt.Errorf("no identity expiration found")
+ }
+ return exp.AsTime().Unix(), nil
}
func (s *Store) SaveRefreshToken(token string) error {
- return s.db.Update(func(tx *bbolt.Tx) error {
- b := tx.Bucket([]byte(bucketIdentity))
- return b.Put([]byte(keyRefreshToken), []byte(token))
+ return s.update(func(c *api.MemberCredential) error {
+ if c.OidcSession == nil {
+ c.OidcSession = &api.OIDCSession{}
+ }
+ c.OidcSession.RefreshToken = token
+ return nil
})
}
func (s *Store) LoadRefreshToken() (string, error) {
- var val []byte
- _ = s.db.View(func(tx *bbolt.Tx) error {
- b := tx.Bucket([]byte(bucketIdentity))
- val = b.Get([]byte(keyRefreshToken))
+ var token string
+ if err := s.view(func(c *api.MemberCredential) error {
+ token = c.GetOidcSession().GetRefreshToken()
return nil
- })
- if len(val) == 0 {
+ }); err != nil {
+ return "", err
+ }
+ if token == "" {
return "", fmt.Errorf("no refresh token found")
}
- return string(val), nil
+ return token, nil
}
func (s *Store) SaveOIDCConfig(issuer, clientID, audience string) error {
- return s.db.Update(func(tx *bbolt.Tx) error {
- b := tx.Bucket([]byte(bucketIdentity))
- if err := b.Put([]byte(keyOidcIssuer), []byte(issuer)); err != nil {
- return err
+ return s.update(func(c *api.MemberCredential) error {
+ if c.OidcSession == nil {
+ c.OidcSession = &api.OIDCSession{}
}
- if err := b.Put([]byte(keyOidcClientID), []byte(clientID)); err != nil {
- return err
- }
- return b.Put([]byte(keyOidcAudience), []byte(audience))
+ c.OidcSession.Issuer, c.OidcSession.ClientId, c.OidcSession.Audience = issuer, clientID, audience
+ return nil
})
}
func (s *Store) LoadOIDCConfig() (string, string, string, error) {
- var issuer, clientID, audience []byte
- err := s.db.View(func(tx *bbolt.Tx) error {
- b := tx.Bucket([]byte(bucketIdentity))
- issuer = b.Get([]byte(keyOidcIssuer))
- clientID = b.Get([]byte(keyOidcClientID))
- audience = b.Get([]byte(keyOidcAudience))
+ var issuer, clientID, audience string
+ err := s.view(func(c *api.MemberCredential) error {
+ issuer, clientID, audience = c.GetOidcSession().GetIssuer(), c.GetOidcSession().GetClientId(), c.GetOidcSession().GetAudience()
return nil
})
- return string(issuer), string(clientID), string(audience), err
+ return issuer, clientID, audience, err
}
func (s *Store) SaveKey(key []byte) error {
return s.db.Update(func(tx *bbolt.Tx) error {
- b := tx.Bucket([]byte(bucketIdentity))
- return b.Put([]byte(keyPrivKey), key)
+ return tx.Bucket([]byte(bucketIdentity)).Put([]byte(keyPrivKey), key)
})
}
func (s *Store) LoadKey() ([]byte, error) {
var val []byte
_ = s.db.View(func(tx *bbolt.Tx) error {
- b := tx.Bucket([]byte(bucketIdentity))
- dbVal := b.Get([]byte(keyPrivKey))
- if len(dbVal) > 0 {
- val = make([]byte, len(dbVal))
- copy(val, dbVal)
- }
+ val = append([]byte(nil), tx.Bucket([]byte(bucketIdentity)).Get([]byte(keyPrivKey))...)
return nil
})
return val, nil
}
+// SaveMeshConfig records what enrollment handed out: the control plane key
+// that signed the biscuit and the routers to join through. The key enters
+// the trusted set, and seeds the issuance set when nothing recorded it yet.
+// Later calls, from the sync that follows router changes, pass the key
+// LoadMeshConfig returned and only move the addresses.
func (s *Store) SaveMeshConfig(pubKey []byte, addrs []string) error {
- return s.db.Update(func(tx *bbolt.Tx) error {
- b := tx.Bucket([]byte(bucketIdentity))
- if err := b.Put([]byte("control_plane_public_key"), pubKey); err != nil {
- return err
+ return s.update(func(c *api.MemberCredential) error {
+ c.RouterAddresses = append([]string(nil), addrs...)
+ if len(pubKey) != ed25519.PublicKeySize {
+ return nil
}
- data, _ := json.Marshal(addrs)
- return b.Put([]byte("router_addresses"), data)
+ if !containsKeyBytes(trustedKeyBytes(c.TrustedKeys), pubKey) {
+ c.TrustedKeys = append(c.TrustedKeys, &api.TrustedSigningKey{PublicKey: append([]byte(nil), pubKey...), ReceiveTime: timestamppb.Now()})
+ }
+ if len(c.IssuedUnderKeys) == 0 {
+ c.IssuedUnderKeys = [][]byte{append([]byte(nil), pubKey...)}
+ }
+ return nil
})
}
+// LoadMeshConfig returns the first trusted control plane key, which is the
+// one enrollment handed out until a rotation retires it, and the router
+// addresses.
func (s *Store) LoadMeshConfig() ([]byte, []string, error) {
var pubKey []byte
var addrs []string
- err := s.db.View(func(tx *bbolt.Tx) error {
- b := tx.Bucket([]byte(bucketIdentity))
- dbVal := b.Get([]byte("control_plane_public_key"))
- if len(dbVal) > 0 {
- pubKey = make([]byte, len(dbVal))
- copy(pubKey, dbVal)
- }
- addrsBytes := b.Get([]byte("router_addresses"))
- if len(addrsBytes) > 0 {
- return json.Unmarshal(addrsBytes, &addrs)
+ err := s.view(func(c *api.MemberCredential) error {
+ if len(c.TrustedKeys) > 0 {
+ pubKey = append([]byte(nil), c.TrustedKeys[0].PublicKey...)
}
+ addrs = append([]string(nil), c.RouterAddresses...)
return nil
})
return pubKey, addrs, err
}
func (s *Store) SaveControlPlaneURL(url string) error {
- return s.db.Update(func(tx *bbolt.Tx) error {
- b := tx.Bucket([]byte(bucketIdentity))
- return b.Put([]byte("control_plane_url"), []byte(url))
+ return s.update(func(c *api.MemberCredential) error {
+ c.ControlPlaneUrl = url
+ return nil
})
}
// SaveTrustedKeys persists the full set of control plane public keys the
// node currently trusts, so keys learned from rotation events or /keys
-// survive restarts (the singular mesh-config key only tracks enrollment).
+// survive restarts.
func (s *Store) SaveTrustedKeys(keys []TrustedKey) error {
- data, err := json.Marshal(keys)
- if err != nil {
- return err
- }
- return s.db.Update(func(tx *bbolt.Tx) error {
- b := tx.Bucket([]byte(bucketIdentity))
- return b.Put([]byte(keyTrustedKeys), data)
+ return s.update(func(c *api.MemberCredential) error {
+ c.TrustedKeys = trustedKeysToProto(keys)
+ return nil
})
}
func (s *Store) LoadTrustedKeys() ([]TrustedKey, error) {
var keys []TrustedKey
- err := s.db.View(func(tx *bbolt.Tx) error {
- b := tx.Bucket([]byte(bucketIdentity))
- data := b.Get([]byte(keyTrustedKeys))
- if len(data) == 0 {
- return nil
- }
- return json.Unmarshal(data, &keys)
+ err := s.view(func(c *api.MemberCredential) error {
+ keys = trustedKeysFromProto(c.TrustedKeys)
+ return nil
})
return keys, err
}
@@ -269,39 +412,35 @@ func (s *Store) LoadTrustedKeys() ([]TrustedKey, error) {
// stored identity was issued. A key that later appears outside this set is
// a rotation the identity predates, which is why it survives restarts.
func (s *Store) SaveIdentityKeySet(keys []ed25519.PublicKey) error {
- data, err := json.Marshal(keys)
- if err != nil {
- return err
- }
- return s.db.Update(func(tx *bbolt.Tx) error {
- b := tx.Bucket([]byte(bucketIdentity))
- return b.Put([]byte(keyIdentityKeys), data)
+ return s.update(func(c *api.MemberCredential) error {
+ c.IssuedUnderKeys = c.IssuedUnderKeys[:0]
+ for _, k := range keys {
+ c.IssuedUnderKeys = append(c.IssuedUnderKeys, append([]byte(nil), k...))
+ }
+ return nil
})
}
// LoadIdentityKeySet returns the set saved by SaveIdentityKeySet, or nil when
-// the identity was issued by a build that did not record it.
+// nothing recorded it.
func (s *Store) LoadIdentityKeySet() ([]ed25519.PublicKey, error) {
var keys []ed25519.PublicKey
- err := s.db.View(func(tx *bbolt.Tx) error {
- b := tx.Bucket([]byte(bucketIdentity))
- data := b.Get([]byte(keyIdentityKeys))
- if len(data) == 0 {
- return nil
+ err := s.view(func(c *api.MemberCredential) error {
+ for _, k := range c.IssuedUnderKeys {
+ keys = append(keys, ed25519.PublicKey(append([]byte(nil), k...)))
}
- return json.Unmarshal(data, &keys)
+ return nil
})
return keys, err
}
func (s *Store) LoadControlPlaneURL() (string, error) {
- var val []byte
- err := s.db.View(func(tx *bbolt.Tx) error {
- b := tx.Bucket([]byte(bucketIdentity))
- val = b.Get([]byte("control_plane_url"))
+ var url string
+ err := s.view(func(c *api.MemberCredential) error {
+ url = c.ControlPlaneUrl
return nil
})
- return string(val), err
+ return url, err
}
// ResetMeshIdentity clears everything about a node's mesh membership (its
@@ -310,26 +449,55 @@ func (s *Store) LoadControlPlaneURL() (string, error) {
// the node's PeerID survives the switch.
func (s *Store) ResetMeshIdentity() error {
return s.db.Update(func(tx *bbolt.Tx) error {
- b := tx.Bucket([]byte(bucketIdentity))
- for _, key := range []string{
- keyBiscuit,
- keyIdentityExp,
- keyRefreshToken,
- keyOidcIssuer,
- keyOidcClientID,
- keyOidcAudience,
- keyTrustedKeys,
- keyIdentityKeys,
- "control_plane_public_key",
- "router_addresses",
- "control_plane_url",
- } {
- if err := b.Delete([]byte(key)); err != nil {
- return err
- }
+ return tx.Bucket([]byte(bucketIdentity)).Delete([]byte(keyCredential))
+ })
+}
+
+func trustedKeysToProto(keys []TrustedKey) []*api.TrustedSigningKey {
+ out := make([]*api.TrustedSigningKey, 0, len(keys))
+ for _, k := range keys {
+ tk := &api.TrustedSigningKey{PublicKey: append([]byte(nil), k.Key...)}
+ if !k.ReceivedAt.IsZero() {
+ tk.ReceiveTime = timestamppb.New(k.ReceivedAt)
}
+ out = append(out, tk)
+ }
+ return out
+}
+
+// trustedKeysFromProto reads a key learned at an unknown time as learned now,
+// so it is the newest and survives the grace period like a fresh rotation.
+func trustedKeysFromProto(keys []*api.TrustedSigningKey) []TrustedKey {
+ if len(keys) == 0 {
return nil
- })
+ }
+ now := time.Now()
+ out := make([]TrustedKey, 0, len(keys))
+ for _, k := range keys {
+ tk := TrustedKey{Key: ed25519.PublicKey(append([]byte(nil), k.PublicKey...)), ReceivedAt: now}
+ if k.ReceiveTime != nil {
+ tk.ReceivedAt = k.ReceiveTime.AsTime()
+ }
+ out = append(out, tk)
+ }
+ return out
+}
+
+func trustedKeyBytes(keys []*api.TrustedSigningKey) [][]byte {
+ out := make([][]byte, 0, len(keys))
+ for _, k := range keys {
+ out = append(out, k.PublicKey)
+ }
+ return out
+}
+
+func containsKeyBytes(keys [][]byte, want []byte) bool {
+ for _, k := range keys {
+ if string(k) == string(want) {
+ return true
+ }
+ }
+ return false
}
func (s *Store) Close() error {
diff --git a/internal/node/store_test.go b/internal/node/store_test.go
index 0546fac7..e83ff4d8 100644
--- a/internal/node/store_test.go
+++ b/internal/node/store_test.go
@@ -17,12 +17,18 @@ package node
import (
"bytes"
"crypto/ed25519"
+ "encoding/json"
"errors"
"os"
"path/filepath"
"reflect"
"testing"
"time"
+
+ "github.com/google/sam/api"
+ "go.etcd.io/bbolt"
+ "google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/types/known/timestamppb"
)
func TestStore_NewStore_And_Close(t *testing.T) {
@@ -283,7 +289,7 @@ func TestStore_MeshConfig(t *testing.T) {
t.Errorf("Expected empty mesh config, got pubKey=%v, addrs=%v", pubKey, addrs)
}
- controlPlanePubKey := []byte("control-plane-public-key-bytes")
+ controlPlanePubKey := bytes.Repeat([]byte{7}, ed25519.PublicKeySize)
routerAddrs := []string{"/ip4/127.0.0.1/tcp/5001", "/dns4/cp.example.com/tcp/5001"}
if err := store.SaveMeshConfig(controlPlanePubKey, routerAddrs); err != nil {
@@ -301,6 +307,147 @@ func TestStore_MeshConfig(t *testing.T) {
if !reflect.DeepEqual(loadedAddrs, routerAddrs) {
t.Errorf("Expected loaded router addrs %v, got %v", routerAddrs, loadedAddrs)
}
+
+ // Enrollment's key is trusted and is what the identity was issued under.
+ trusted, err := store.LoadTrustedKeys()
+ if err != nil || len(trusted) != 1 || !bytes.Equal(trusted[0].Key, controlPlanePubKey) {
+ t.Fatalf("trusted keys after enrollment = %v, %v; want the enrollment key", trusted, err)
+ }
+ issuance, err := store.LoadIdentityKeySet()
+ if err != nil || len(issuance) != 1 || !bytes.Equal(issuance[0], controlPlanePubKey) {
+ t.Fatalf("identity key set after enrollment = %v, %v; want the enrollment key", issuance, err)
+ }
+}
+
+// TestStore_MigratesLegacyLayout opens a database written by a build that
+// kept one entry per field and finds the same state as one MemberCredential.
+func TestStore_MigratesLegacyLayout(t *testing.T) {
+ dir := t.TempDir()
+ enrollmentKey := bytes.Repeat([]byte{1}, ed25519.PublicKeySize)
+ rotatedKey := bytes.Repeat([]byte{2}, ed25519.PublicKeySize)
+ received := time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)
+ trustedJSON, _ := json.Marshal([]TrustedKey{{Key: rotatedKey, ReceivedAt: received}})
+ addrsJSON, _ := json.Marshal([]string{"/dns4/router.example/tcp/4001/p2p/12D3KooWP8iKhDf3iCMo2H3butNVfdTUtYwYWYQ75jTGnynXPFMp"})
+ db, err := bbolt.Open(filepath.Join(dir, StoreFile), 0600, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := db.Update(func(tx *bbolt.Tx) error {
+ b, err := tx.CreateBucketIfNotExists([]byte(bucketIdentity))
+ if err != nil {
+ return err
+ }
+ for k, v := range map[string][]byte{
+ keyPrivKey: []byte("private-key-bytes"),
+ "identity_biscuit": []byte("biscuit-bytes"),
+ "identity_expiration": []byte("1790000000"),
+ "refresh_token": []byte("refresh-secret"),
+ "oidc_issuer": []byte("https://issuer.example"),
+ "oidc_client_id": []byte("client"),
+ "oidc_audience": []byte("aud"),
+ "trusted_keys": trustedJSON,
+ "control_plane_public_key": enrollmentKey,
+ "router_addresses": addrsJSON,
+ "control_plane_url": []byte("https://cp.example"),
+ } {
+ if err := b.Put([]byte(k), v); err != nil {
+ return err
+ }
+ }
+ return nil
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if err := db.Close(); err != nil {
+ t.Fatal(err)
+ }
+
+ store, err := NewStore(dir)
+ if err != nil {
+ t.Fatalf("NewStore on a legacy database: %v", err)
+ }
+ defer func() { _ = store.Close() }()
+
+ if key, _ := store.LoadKey(); string(key) != "private-key-bytes" {
+ t.Errorf("private key = %q, want it untouched", key)
+ }
+ if biscuit, err := store.LoadIdentity(); err != nil || string(biscuit) != "biscuit-bytes" {
+ t.Errorf("biscuit = %q, %v", biscuit, err)
+ }
+ if exp, err := store.LoadIdentityExpiration(); err != nil || exp != 1790000000 {
+ t.Errorf("expiration = %d, %v", exp, err)
+ }
+ if tok, err := store.LoadRefreshToken(); err != nil || tok != "refresh-secret" {
+ t.Errorf("refresh token = %q, %v", tok, err)
+ }
+ if iss, cid, aud, err := store.LoadOIDCConfig(); err != nil || iss != "https://issuer.example" || cid != "client" || aud != "aud" {
+ t.Errorf("oidc = %q %q %q, %v", iss, cid, aud, err)
+ }
+ if url, _ := store.LoadControlPlaneURL(); url != "https://cp.example" {
+ t.Errorf("control plane url = %q", url)
+ }
+ pubKey, addrs, _ := store.LoadMeshConfig()
+ if len(addrs) != 1 || !bytes.Equal(pubKey, rotatedKey) {
+ t.Errorf("mesh config = %x, %v; want the first trusted key and one router", pubKey, addrs)
+ }
+ // The rotated key keeps its timestamp; the enrollment key joins the
+ // trusted set and, since the old build recorded no issuance set, stands
+ // for it.
+ trusted, _ := store.LoadTrustedKeys()
+ if len(trusted) != 2 || !bytes.Equal(trusted[0].Key, rotatedKey) || !trusted[0].ReceivedAt.Equal(received) || !bytes.Equal(trusted[1].Key, enrollmentKey) {
+ t.Errorf("trusted keys = %+v", trusted)
+ }
+ if issuance, _ := store.LoadIdentityKeySet(); len(issuance) != 1 || !bytes.Equal(issuance[0], enrollmentKey) {
+ t.Errorf("identity key set = %x, want the enrollment key", issuance)
+ }
+
+ // The legacy entries are gone; only the key and the credential remain.
+ if err := store.db.View(func(tx *bbolt.Tx) error {
+ b := tx.Bucket([]byte(bucketIdentity))
+ for _, k := range legacyKeys {
+ if b.Get([]byte(k)) != nil {
+ t.Errorf("legacy entry %q survived the migration", k)
+ }
+ }
+ return nil
+ }); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// TestStore_CredentialRoundTrip is what `sam-node state export | import`
+// relies on: the message out is the message in.
+func TestStore_CredentialRoundTrip(t *testing.T) {
+ store, err := NewStore(t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = store.Close() }()
+
+ want := &api.MemberCredential{
+ ControlPlaneUrl: "https://cp.example",
+ Biscuit: []byte("biscuit"),
+ ExpireTime: timestamppb.New(time.Unix(1790000000, 0)),
+ TrustedKeys: []*api.TrustedSigningKey{{PublicKey: bytes.Repeat([]byte{3}, ed25519.PublicKeySize), ReceiveTime: timestamppb.New(time.Unix(1780000000, 0))}},
+ IssuedUnderKeys: [][]byte{bytes.Repeat([]byte{3}, ed25519.PublicKeySize)},
+ RouterAddresses: []string{"/dns4/router.example/tcp/4001/p2p/12D3KooWP8iKhDf3iCMo2H3butNVfdTUtYwYWYQ75jTGnynXPFMp"},
+ }
+ if err := store.SetCredential(want); err != nil {
+ t.Fatal(err)
+ }
+ got, err := store.Credential()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !proto.Equal(want, got) {
+ t.Fatalf("credential round trip:\n got %v\nwant %v", got, want)
+ }
+ if err := store.ResetMeshIdentity(); err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := store.Credential(); !proto.Equal(got, &api.MemberCredential{}) {
+ t.Fatalf("credential after reset = %v, want empty", got)
+ }
}
func TestStore_ControlPlaneURL(t *testing.T) {
diff --git a/sdk/README.md b/sdk/README.md
index e177547e..6e89f18c 100644
--- a/sdk/README.md
+++ b/sdk/README.md
@@ -129,6 +129,23 @@ alters one of these, the SDKs change with it.
`peer_id` is not derived from `public_key`
(`internal/controlplane/server.go`, `pID.MatchesPublicKey`).
+### State directory
+
+What a member keeps between runs is `api.MemberCredential` plus its private
+key, and every implementation persists the same two things. The SDKs keep
+them in a directory: `identity.key` is the libp2p `PrivateKey` encoding
+above; `credential.json` is `MemberCredential` as protojson with proto field
+names (`control_plane_url`, `biscuit`, `expire_time` as RFC 3339,
+`trusted_keys[].public_key`, `issued_under_keys`, `router_addresses`,
+`oidc_session`), written with mode `0600` in a directory of mode `0700`.
+An unknown field is an error. `control_plane_url` has no trailing slash.
+`sam-node` keeps the same message in `agent.db`, and `sam-node state
+export|import <dir>` moves a member between the two
+(`internal/node/statedir.go`). `TestNativeSDKExamples` resumes each SDK's
+directory with the other SDK and with an imported `sam-node`. Fields an SDK
+does not use (`receive_time`, `oidc_session`) are carried through on save,
+so a directory survives a round trip through any implementation.
+
### Control plane (protobuf over HTTP)
All requests and responses are `application/x-protobuf` bodies of the
diff --git a/sdk/js/src/credential.ts b/sdk/js/src/credential.ts
index edecd7cb..e4490170 100644
--- a/sdk/js/src/credential.ts
+++ b/sdk/js/src/credential.ts
@@ -12,8 +12,9 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-import { create, fromBinary, toBinary } from "@bufbuild/protobuf";
-import { AuthFrameSchema, AuthResponseSchema, type AuthResponse } from "./gen/sam_pb.ts";
+import { create, fromBinary, fromJson, toBinary, toJson } from "@bufbuild/protobuf";
+import { timestampDate, timestampFromDate, type Timestamp } from "@bufbuild/protobuf/wkt";
+import { AuthFrameSchema, AuthResponseSchema, MemberCredentialSchema, type AuthResponse, type OIDCSession } from "./gen/sam_pb.ts";
/** What a member holds after enrolling: its biscuit and what it trusts. */
export interface MeshCredential {
@@ -33,6 +34,12 @@ export interface MeshCredential {
issuedUnderKeys: Uint8Array[];
/** Router multiaddrs, `/p2p/<peer id>` suffixed, as handed out at enrollment. */
routerAddresses: string[];
+ /**
+ * What other implementations persist in the same file and this SDK does
+ * not use: key receipt times and sam-node's OIDC session. Carried through
+ * so a state directory survives a round trip untouched.
+ */
+ extra?: { receiveTime: Map<string, Timestamp>; oidcSession?: OIDCSession };
}
/** Whether a key trusted now was unknown when the credential was issued. */
@@ -60,40 +67,47 @@ export function decodeAuthResponse(bytes: Uint8Array): AuthResponse {
return fromBinary(AuthResponseSchema, bytes);
}
-interface CredentialJSON {
- control_plane_url: string;
- biscuit: string;
- expiration: number;
- control_plane_keys: string[];
- issued_under_keys?: string[];
- router_addresses: string[];
-}
-
+/**
+ * credential.json is the api.MemberCredential message as protojson with
+ * proto field names, the layout `sam-node state export` writes and every
+ * SDK reads. An unknown field is an error, as on every SAM surface.
+ */
export function credentialToJSON(c: MeshCredential): string {
- const out: CredentialJSON = {
- control_plane_url: c.controlPlaneUrl,
- biscuit: Buffer.from(c.biscuit).toString("base64"),
- expiration: c.expiration,
- control_plane_keys: c.controlPlaneKeys.map((k) => Buffer.from(k).toString("base64")),
- issued_under_keys: c.issuedUnderKeys.map((k) => Buffer.from(k).toString("base64")),
- router_addresses: c.routerAddresses,
- };
- return JSON.stringify(out, null, 2) + "\n";
+ const message = create(MemberCredentialSchema, {
+ controlPlaneUrl: c.controlPlaneUrl,
+ biscuit: c.biscuit,
+ expireTime: timestampFromDate(new Date(c.expiration * 1000)),
+ trustedKeys: c.controlPlaneKeys.map((k) => {
+ const receiveTime = c.extra?.receiveTime.get(Buffer.from(k).toString("hex"));
+ return receiveTime !== undefined ? { publicKey: k, receiveTime } : { publicKey: k };
+ }),
+ issuedUnderKeys: c.issuedUnderKeys,
+ routerAddresses: c.routerAddresses,
+ ...(c.extra?.oidcSession !== undefined ? { oidcSession: c.extra.oidcSession } : {}),
+ });
+ return JSON.stringify(toJson(MemberCredentialSchema, message, { useProtoFieldName: true }), null, 2) + "\n";
}
export function credentialFromJSON(text: string): MeshCredential {
- const raw = JSON.parse(text) as Partial<CredentialJSON>;
- if (typeof raw.control_plane_url !== "string" || typeof raw.biscuit !== "string" || typeof raw.expiration !== "number") {
- throw new Error("malformed credential file");
+ const message = fromJson(MemberCredentialSchema, JSON.parse(text));
+ if (message.controlPlaneUrl === "" || message.biscuit.length === 0 || message.expireTime === undefined) {
+ throw new Error("malformed credential file: control_plane_url, biscuit and expire_time are required");
+ }
+ const controlPlaneKeys = message.trustedKeys.map((k) => k.publicKey);
+ const receiveTime = new Map<string, Timestamp>();
+ for (const k of message.trustedKeys) {
+ if (k.receiveTime !== undefined) {
+ receiveTime.set(Buffer.from(k.publicKey).toString("hex"), k.receiveTime);
+ }
}
- const controlPlaneKeys = (raw.control_plane_keys ?? []).map((k) => new Uint8Array(Buffer.from(k, "base64")));
return {
- controlPlaneUrl: raw.control_plane_url,
- biscuit: new Uint8Array(Buffer.from(raw.biscuit, "base64")),
- expiration: raw.expiration,
+ controlPlaneUrl: message.controlPlaneUrl,
+ biscuit: message.biscuit,
+ expiration: Math.floor(timestampDate(message.expireTime).getTime() / 1000),
controlPlaneKeys,
- // A file from before this field: the set known then is the best answer.
- issuedUnderKeys: raw.issued_under_keys !== undefined ? raw.issued_under_keys.map((k) => new Uint8Array(Buffer.from(k, "base64"))) : controlPlaneKeys,
- routerAddresses: raw.router_addresses ?? [],
+ // A file that recorded no issuance set: the keys trusted then are the best answer.
+ issuedUnderKeys: message.issuedUnderKeys.length > 0 ? message.issuedUnderKeys : controlPlaneKeys,
+ routerAddresses: message.routerAddresses,
+ extra: { receiveTime, ...(message.oidcSession !== undefined ? { oidcSession: message.oidcSession } : {}) },
};
}
diff --git a/sdk/js/src/gen/sam_pb.ts b/sdk/js/src/gen/sam_pb.ts
index d7b4bd9c..17bbd358 100644
--- a/sdk/js/src/gen/sam_pb.ts
+++ b/sdk/js/src/gen/sam_pb.ts
@@ -18,13 +18,15 @@
import type { GenEnum, GenFile, GenMessage } from "@bufbuild/protobuf/codegenv2";
import { enumDesc, fileDesc, messageDesc } from "@bufbuild/protobuf/codegenv2";
+import type { Timestamp } from "@bufbuild/protobuf/wkt";
+import { file_google_protobuf_timestamp } from "@bufbuild/protobuf/wkt";
import type { Message } from "@bufbuild/protobuf";
/**
* Describes the file sam.proto.
*/
export const file_sam: GenFile = /*@__PURE__*/
- fileDesc("CglzYW0ucHJvdG8SBnNhbS52MSJDCglBdXRoRnJhbWUSDwoHYmlzY3VpdBgBIAEoDBIWCg50YXJnZXRfc2VydmljZRgCIAEoCRINC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2xfcGxhbmVfdXJsGAEgASgJEg8KB2Jpc2N1aXQYAiABKAwSLwoLZXhwaXJlX3RpbWUYAyABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wEi8KDHRydXN0ZWRfa2V5cxgEIAMoCzIZLnNhbS52MS5UcnVzdGVkU2lnbmluZ0tleRIZChFpc3N1ZWRfdW5kZXJfa2V5cxgFIAMoDBIYChByb3V0ZXJfYWRkcmVzc2VzGAYgAygJEikKDG9pZGNfc2Vzc2lvbhgHIAEoCzITLnNhbS52MS5PSURDU2Vzc2lvbiJZChFUcnVzdGVkU2lnbmluZ0tleRISCgpwdWJsaWNfa2V5GAEgASgMEjAKDHJlY2VpdmVfdGltZRgCIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXAiWQoLT0lEQ1Nlc3Npb24SDgoGaXNzdWVyGAEgASgJEhEKCWNsaWVudF9pZBgCIAEoCRIQCghhdWRpZW5jZRgDIAEoCRIVCg1yZWZyZXNoX3Rva2VuGAQgASgJKpQBChBFbnJvbGxtZW50U3RhdHVzEiEKHUVOUk9MTE1FTlRfU1RBVFVTX1VOU1BFQ0lGSUVEEAASHQoZRU5ST0xMTUVOVF9TVEFUVVNfUEVORElORxABEh4KGkVOUk9MTE1FTlRfU1RBVFVTX0FQUFJPVkVEEAISHgoaRU5ST0xMTUVOVF9TVEFUVVNfUkVKRUNURUQQAypzCgtTZXJ2aWNlVHlwZRIcChhTRVJWSUNFX1RZUEVfVU5TUEVDSUZJRUQQABIUChBTRVJWSUNFX1RZUEVfTUNQEAESGgoWU0VSVklDRV9UWVBFX0lORkVSRU5DRRACEhQKEFNFUlZJQ0VfVFlQRV9BMkEQA0IbWhlnaXRodWIuY29tL2dvb2dsZS9zYW0vYXBpYgZwcm90bzM", [file_google_protobuf_timestamp]);
/**
* @generated from message sam.v1.AuthFrame
@@ -1477,6 +1479,130 @@ export type PeerEvidenceResponse = Message<"sam.v1.PeerEvidenceResponse"> & {
export const PeerEvidenceResponseSchema: GenMessage<PeerEvidenceResponse> = /*@__PURE__*/
messageDesc(file_sam, 41);
+/**
+ * @generated from message sam.v1.MemberCredential
+ */
+export type MemberCredential = Message<"sam.v1.MemberCredential"> & {
+ /**
+ * Base URL of the control plane that minted the biscuit.
+ *
+ * @generated from field: string control_plane_url = 1;
+ */
+ controlPlaneUrl: string;
+
+ /**
+ * The member's biscuit.
+ *
+ * @generated from field: bytes biscuit = 2;
+ */
+ biscuit: Uint8Array;
+
+ /**
+ * When the biscuit expires.
+ *
+ * @generated from field: google.protobuf.Timestamp expire_time = 3;
+ */
+ expireTime?: Timestamp | undefined;
+
+ /**
+ * Control plane signing keys trusted now; a rotation keeps several valid.
+ *
+ * @generated from field: repeated sam.v1.TrustedSigningKey trusted_keys = 4;
+ */
+ trustedKeys: TrustedSigningKey[];
+
+ /**
+ * The keys trusted when the biscuit was issued. A key trusted now that is
+ * absent here means a rotation happened since: the biscuit is signed by a
+ * retiring key and must be refreshed before that key leaves its grace
+ * period.
+ *
+ * @generated from field: repeated bytes issued_under_keys = 5;
+ */
+ issuedUnderKeys: Uint8Array[];
+
+ /**
+ * Router multiaddrs, `/p2p/<peer id>` suffixed.
+ *
+ * @generated from field: repeated string router_addresses = 6;
+ */
+ routerAddresses: string[];
+
+ /**
+ * The session that renews an identity enrolled through the mesh's
+ * identity provider. Unset for a member enrolled with a bootstrap token.
+ *
+ * @generated from field: sam.v1.OIDCSession oidc_session = 7;
+ */
+ oidcSession?: OIDCSession | undefined;
+};
+
+/**
+ * Describes the message sam.v1.MemberCredential.
+ * Use `create(MemberCredentialSchema)` to create a new message.
+ */
+export const MemberCredentialSchema: GenMessage<MemberCredential> = /*@__PURE__*/
+ messageDesc(file_sam, 42);
+
+/**
+ * @generated from message sam.v1.TrustedSigningKey
+ */
+export type TrustedSigningKey = Message<"sam.v1.TrustedSigningKey"> & {
+ /**
+ * Raw ed25519 public key.
+ *
+ * @generated from field: bytes public_key = 1;
+ */
+ publicKey: Uint8Array;
+
+ /**
+ * When the member first learned the key. A key rotated out is dropped a
+ * grace period after this; unset means unknown and is read as now.
+ *
+ * @generated from field: google.protobuf.Timestamp receive_time = 2;
+ */
+ receiveTime?: Timestamp | undefined;
+};
+
+/**
+ * Describes the message sam.v1.TrustedSigningKey.
+ * Use `create(TrustedSigningKeySchema)` to create a new message.
+ */
+export const TrustedSigningKeySchema: GenMessage<TrustedSigningKey> = /*@__PURE__*/
+ messageDesc(file_sam, 43);
+
+/**
+ * @generated from message sam.v1.OIDCSession
+ */
+export type OIDCSession = Message<"sam.v1.OIDCSession"> & {
+ /**
+ * @generated from field: string issuer = 1;
+ */
+ issuer: string;
+
+ /**
+ * @generated from field: string client_id = 2;
+ */
+ clientId: string;
+
+ /**
+ * @generated from field: string audience = 3;
+ */
+ audience: string;
+
+ /**
+ * @generated from field: string refresh_token = 4;
+ */
+ refreshToken: string;
+};
+
+/**
+ * Describes the message sam.v1.OIDCSession.
+ * Use `create(OIDCSessionSchema)` to create a new message.
+ */
+export const OIDCSessionSchema: GenMessage<OIDCSession> = /*@__PURE__*/
+ messageDesc(file_sam, 44);
+
/**
* @generated from enum sam.v1.EnrollmentStatus
*/
diff --git a/sdk/js/src/mesh.test.ts b/sdk/js/src/mesh.test.ts
index 52401208..bffefb24 100644
--- a/sdk/js/src/mesh.test.ts
+++ b/sdk/js/src/mesh.test.ts
@@ -105,8 +105,11 @@ test("enroll persists identity and credential, load resumes them, refresh rotate
await resumed.refresh();
assert.deepEqual(resumed.credential.biscuit, text("biscuit-2"));
- const onDisk = JSON.parse(await readFile(join(dir, "state", "credential.json"), "utf8")) as { biscuit: string };
- assert.equal(Buffer.from(onDisk.biscuit, "base64").toString(), "biscuit-2");
+ const onDisk = JSON.parse(await readFile(join(dir, "state", "credential.json"), "utf8")) as Record<string, unknown>;
+ assert.equal(Buffer.from(onDisk.biscuit as string, "base64").toString(), "biscuit-2");
+ // The file is api.MemberCredential as protojson: proto field names, RFC 3339 instants.
+ assert.deepEqual(Object.keys(onDisk).sort(), ["biscuit", "control_plane_url", "expire_time", "issued_under_keys", "router_addresses", "trusted_keys"]);
+ assert.match(onDisk.expire_time as string, /^\d{4}-\d{2}-\d{2}T.*Z$/);
// Enrolling again from the same directory resumes the saved credential
// without a token; another control plane or an expiring credential
@@ -121,10 +124,10 @@ test("enroll persists identity and credential, load resumes them, refresh rotate
const elsewhere = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.2:1", stateDir: join(dir, "state"), bootstrapToken: "sbt_secret", fetch: cp.fetch });
assert.equal(elsewhere.peerId, mesh.peerId);
assert.equal(cp.issued, issuedBefore + 1);
- assert.equal(elsewhere.credential.controlPlaneUrl, "http://127.0.0.2:1/");
+ assert.equal(elsewhere.credential.controlPlaneUrl, "http://127.0.0.2:1");
- const expiring = JSON.parse(await readFile(join(dir, "state", "credential.json"), "utf8")) as { expiration: number };
- expiring.expiration = Math.floor(Date.now() / 1000) + 60;
+ const expiring = JSON.parse(await readFile(join(dir, "state", "credential.json"), "utf8")) as { expire_time: string };
+ expiring.expire_time = new Date(Date.now() + 60_000).toISOString();
await writeFile(join(dir, "state", "credential.json"), JSON.stringify(expiring));
await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.2:1", stateDir: join(dir, "state"), bootstrapToken: "sbt_secret", fetch: cp.fetch });
assert.equal(cp.issued, issuedBefore + 2);
diff --git a/sdk/js/src/mesh.ts b/sdk/js/src/mesh.ts
index 33c12f5f..85cbafab 100644
--- a/sdk/js/src/mesh.ts
+++ b/sdk/js/src/mesh.ts
@@ -113,7 +113,7 @@ export class AgentMesh {
const controlPlane = newClient(options);
if (options.stateDir !== undefined && saved !== undefined && saved.peerId === identity.peerId) {
const credential = await loadCredential(options.stateDir);
- if (credential !== undefined && credential.controlPlaneUrl === controlPlane.url.toString() && credentialTimeToLiveSeconds(credential) > REUSE_MIN_TTL_SECONDS) {
+ if (credential !== undefined && sameBaseUrl(credential.controlPlaneUrl, controlPlane.url) && credentialTimeToLiveSeconds(credential) > REUSE_MIN_TTL_SECONDS) {
return new AgentMesh(identity, controlPlane, credential, options.stateDir);
}
}
@@ -153,7 +153,7 @@ export class AgentMesh {
identity,
controlPlane,
{
- controlPlaneUrl: controlPlane.url.toString(),
+ controlPlaneUrl: baseUrl(controlPlane.url),
biscuit: enrollment.biscuit,
expiration: enrollment.expiration,
controlPlaneKeys,
@@ -335,6 +335,15 @@ async function loadCredential(stateDir: string): Promise<MeshCredential | undefi
}
}
+/** The form every implementation persists: scheme, host, port, path, no trailing slash. */
+function baseUrl(url: URL | string): string {
+ return String(url).replace(/\/+$/, "");
+}
+
+function sameBaseUrl(a: URL | string, b: URL | string): boolean {
+ return baseUrl(a) === baseUrl(b);
+}
+
async function writeAtomic(path: string, data: Uint8Array | string, mode: number): Promise<void> {
const tmp = `${path}.tmp`;
await writeFile(tmp, data, { mode });
diff --git a/sdk/python/src/agent_mesh/_proto/sam_pb2.py b/sdk/python/src/agent_mesh/_proto/sam_pb2.py
index f3fa586e..a4cde925 100644
--- a/sdk/python/src/agent_mesh/_proto/sam_pb2.py
+++ b/sdk/python/src/agent_mesh/_proto/sam_pb2.py
@@ -11,9 +11,10 @@ from google.protobuf import symbol_database as _symbol_database
_sym_db = _symbol_database.Default()
+from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2
-DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\tsam.proto\x12\x06sam.v1\"C\n\tAuthFrame\x12\x0f\n\x07\x62iscuit\x18\x01 \x01(\x0c\x12\x16\n\x0etarget_service\x18\x02 \x01(\t\x12\r\n\x05\x61gent\x18\x03 \x01(\t\"?\n\x0c\x41uthResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\x12\x0f\n\x07\x62iscuit\x18\x03 \x01(\x0c\"\xb9\x01\n\tMeshEvent\x12$\n\x04type\x18\x01 \x01(\x0e\x32\x16.sam.v1.MeshEvent.Type\x12\x0f\n\x07peer_id\x18\x02 \x01(\t\x12\x11\n\ttimestamp\x18\x03 \x01(\x03\x12\x16\n\x0enew_public_key\x18\x04 \x01(\x0c\x12\x11\n\tsignature\x18\x05 \x01(\x0c\"7\n\x04Type\x12\n\n\x06\x42\x41NNED\x10\x00\x12\x10\n\x0cKEY_ROTATION\x10\x01\x12\x11\n\rPOLICY_UPDATE\x10\x02\"\xeb\x01\n\rEnrollRequest\x12\x0b\n\x03jwt\x18\x01 \x01(\t\x12\x0f\n\x07peer_id\x18\x02 \x01(\t\x12\x12\n\npublic_key\x18\x03 \x01(\x0c\x12\x16\n\x0erequested_role\x18\x04 \x01(\t\x12\x31\n\x06labels\x18\x05 \x03(\x0b\x32!.sam.v1.EnrollRequest.LabelsEntry\x12\x11\n\ttimestamp\x18\x06 \x01(\x03\x12\x1b\n\x13\x63hallenge_signature\x18\x07 \x01(\x0c\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x8e\x01\n\x0e\x45nrollResponse\x12\x15\n\rbiscuit_token\x18\x01 \x01(\x0c\x12\x15\n\rerror_message\x18\x02 \x01(\t\x12 \n\x18\x63ontrol_plane_public_key\x18\x03 \x01(\x0c\x12\x18\n\x10router_addresses\x18\x04 \x03(\t\x12\x12\n\nexpiration\x18\x05 \x01(\x03\"\x89\x02\n\x16\x42ootstrapEnrollRequest\x12\x17\n\x0f\x62ootstrap_token\x18\x01 \x01(\t\x12\x0f\n\x07peer_id\x18\x02 \x01(\t\x12\x12\n\npublic_key\x18\x03 \x01(\x0c\x12\x16\n\x0erequested_role\x18\x04 \x01(\t\x12:\n\x06labels\x18\x05 \x03(\x0b\x32*.sam.v1.BootstrapEnrollRequest.LabelsEntry\x12\x11\n\ttimestamp\x18\x06 \x01(\x03\x12\x1b\n\x13\x63hallenge_signature\x18\x07 \x01(\x0c\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\xe0\x01\n\x17\x42ootstrapEnrollResponse\x12(\n\x06status\x18\x01 \x01(\x0e\x32\x18.sam.v1.EnrollmentStatus\x12\x15\n\rbiscuit_token\x18\x02 \x01(\x0c\x12\x1d\n\x15poll_interval_seconds\x18\x03 \x01(\x05\x12\x15\n\rerror_message\x18\x04 \x01(\t\x12 \n\x18\x63ontrol_plane_public_key\x18\x05 \x01(\x0c\x12\x18\n\x10router_addresses\x18\x06 \x03(\t\x12\x12\n\nexpiration\x18\x07 \x01(\x03\"S\n\x0bServiceInfo\x12!\n\x04type\x18\x01 \x01(\x0e\x32\x13.sam.v1.ServiceType\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x03 \x01(\t\"{\n\x0e\x43ommandBackend\x12\x0f\n\x07\x63ommand\x18\x01 \x03(\t\x12,\n\x03\x65nv\x18\x02 \x03(\x0b\x32\x1f.sam.v1.CommandBackend.EnvEntry\x1a*\n\x08\x45nvEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x8a\x01\n\x16RegisterServiceRequest\x12$\n\x07service\x18\x01 \x01(\x0b\x32\x13.sam.v1.ServiceInfo\x12\x14\n\ntarget_url\x18\x02 \x01(\tH\x00\x12)\n\x07\x63ommand\x18\x03 \x01(\x0b\x32\x16.sam.v1.CommandBackendH\x00\x42\t\n\x07\x62\x61\x63kend\"i\n\x12\x44iscoveredProvider\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12\x17\n\x0flocal_proxy_url\x18\x02 \x01(\t\x12\x10\n\x08srv_name\x18\x03 \x01(\t\x12\x17\n\x0fsrv_description\x18\x04 \x01(\t\"\x92\x02\n\x0fServiceAnnounce\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12!\n\x04type\x18\x02 \x01(\x0e\x32\x13.sam.v1.ServiceType\x12\x14\n\x0cservice_name\x18\x03 \x01(\t\x12\x0c\n\x04keys\x18\x04 \x03(\t\x12\x33\n\x06labels\x18\x05 \x03(\x0b\x32#.sam.v1.ServiceAnnounce.LabelsEntry\x12\x17\n\x0f\x61\x63tive_requests\x18\x06 \x01(\r\x12\x17\n\x0flatency_ewma_ms\x18\x07 \x01(\x01\x12\x11\n\ttimestamp\x18\x08 \x01(\x03\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x87\x01\n\x18\x43ontrolPlaneInfoResponse\x12\x13\n\x0boidc_issuer\x18\x01 \x01(\t\x12\x11\n\tclient_id\x18\x02 \x01(\t\x12\x10\n\x08\x61udience\x18\x03 \x01(\t\x12\x18\n\x10router_addresses\x18\x04 \x03(\t\x12\x17\n\x0f\x62\x61nned_peer_ids\x18\x05 \x03(\t\"\xa4\x01\n\x12RouterLeaseRequest\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12\x11\n\taddresses\x18\x02 \x03(\t\x12\x0f\n\x07\x62iscuit\x18\x03 \x01(\x0c\x12\x17\n\x0f\x63onnected_peers\x18\x04 \x03(\t\x12\x10\n\x08\x64ht_size\x18\x05 \x01(\x05\x12\x11\n\ttimestamp\x18\x06 \x01(\x03\x12\x1b\n\x13\x63hallenge_signature\x18\x07 \x01(\x0c\"I\n\x13RouterLeaseResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\x12\x12\n\nexpires_at\x18\x03 \x01(\x03\"\x95\x01\n\nPolicyRole\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x17\n\x0f\x61llowed_targets\x18\x02 \x03(\t\x12\x18\n\x10\x61llowed_services\x18\x03 \x03(\t\x12\x16\n\x0e\x63ustom_datalog\x18\x04 \x03(\t\x12\x16\n\x0e\x61llowed_agents\x18\x05 \x03(\t\x12\x16\n\x0e\x61llowed_labels\x18\x06 \x03(\t\".\n\rPolicyBinding\x12\x0c\n\x04role\x18\x01 \x01(\t\x12\x0f\n\x07members\x18\x02 \x03(\t\"Z\n\x0cPolicyConfig\x12!\n\x05roles\x18\x01 \x03(\x0b\x32\x12.sam.v1.PolicyRole\x12\'\n\x08\x62indings\x18\x02 \x03(\x0b\x32\x15.sam.v1.PolicyBinding\"\x18\n\x16PolicyConfigGetRequest\"M\n\x17PolicyConfigGetResponse\x12\x15\n\rdatalog_rules\x18\x03 \x03(\tJ\x04\x08\x01\x10\x02J\x04\x08\x02\x10\x03R\x05rolesR\x08\x62indings\"<\n\x1aPolicyConfigUpdateResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\"J\n\x0cKeysResponse\x12\x13\n\x0bpublic_keys\x18\x01 \x03(\x0c\x12\x11\n\ttimestamp\x18\x02 \x01(\x03\x12\x12\n\nsignatures\x18\x03 \x03(\x0c\"V\n\x13TokenRefreshRequest\x12\x1b\n\x13\x63hallenge_signature\x18\x01 \x01(\x0c\x12\x11\n\ttimestamp\x18\x02 \x01(\x03\x12\x0f\n\x07peer_id\x18\x03 \x01(\t\"X\n\x14TokenRefreshResponse\x12\x15\n\rbiscuit_token\x18\x01 \x01(\x0c\x12\x12\n\nexpires_at\x18\x02 \x01(\x03\x12\x15\n\rerror_message\x18\x03 \x01(\t\":\n\x11NodeCatalogReport\x12%\n\x08services\x18\x01 \x03(\x0b\x32\x13.sam.v1.ServiceInfo\"%\n\x12TokenRevokeRequest\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\"5\n\x13TokenRevokeResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\"R\n\x0b\x41gentSecret\x12\x0c\n\x04host\x18\x01 \x01(\t\x12\x0c\n\x04kind\x18\x02 \x01(\t\x12\x13\n\x0bheader_name\x18\x03 \x01(\t\x12\x12\n\nvalue_path\x18\x04 \x01(\t\"B\n\x0b\x41gentEgress\x12\r\n\x05\x61llow\x18\x01 \x03(\t\x12$\n\x07secrets\x18\x02 \x03(\x0b\x32\x13.sam.v1.AgentSecret\"b\n\x0c\x41gentIngress\x12!\n\x04type\x18\x01 \x01(\x0e\x32\x13.sam.v1.ServiceType\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x0c\n\x04port\x18\x03 \x01(\r\x12\x13\n\x0b\x64\x65scription\x18\x04 \x01(\t\"\xaa\x01\n\x0b\x41gentBundle\x12\x0f\n\x07version\x18\x01 \x01(\t\x12\x10\n\x08\x61gent_id\x18\x02 \x01(\t\x12\x13\n\x0b\x65xternal_id\x18\x03 \x01(\t\x12\x17\n\x0f\x63redential_path\x18\x04 \x01(\t\x12#\n\x06\x65gress\x18\x05 \x01(\x0b\x32\x13.sam.v1.AgentEgress\x12%\n\x07ingress\x18\x06 \x03(\x0b\x32\x14.sam.v1.AgentIngress\"9\n\x12\x41gentAttachRequest\x12#\n\x06\x62undle\x18\x01 \x01(\x0b\x32\x13.sam.v1.AgentBundle\"S\n\x13\x41gentAttachResponse\x12\x15\n\regress_socket\x18\x01 \x01(\t\x12\x16\n\x0eingress_socket\x18\x02 \x01(\t\x12\r\n\x05\x65rror\x18\x03 \x01(\t\"&\n\x12\x41gentDetachRequest\x12\x10\n\x08\x61gent_id\x18\x01 \x01(\t\"5\n\x13\x41gentDetachResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\"@\n\x13\x41gentRefreshRequest\x12\x10\n\x08\x61gent_id\x18\x01 \x01(\t\x12\x17\n\x0f\x63redential_path\x18\x02 \x01(\t\"J\n\x14\x41gentRefreshResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\x12\x12\n\nexpires_at\x18\x03 \x01(\x03\"&\n\x12\x41gentStatusRequest\x12\x10\n\x08\x61gent_id\x18\x01 \x01(\t\"w\n\x0b\x41gentStatus\x12\x10\n\x08\x61gent_id\x18\x01 \x01(\t\x12\x10\n\x08\x61ttached\x18\x02 \x01(\x08\x12%\n\x07ingress\x18\x03 \x03(\x0b\x32\x14.sam.v1.AgentIngress\x12\x1d\n\x15\x63redential_expires_at\x18\x04 \x01(\x03\"I\n\x13\x41gentStatusResponse\x12#\n\x06\x61gents\x18\x01 \x03(\x0b\x32\x13.sam.v1.AgentStatus\x12\r\n\x05\x65rror\x18\x02 \x01(\t\"\xab\x01\n\x18IdentityEvidenceResponse\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12\x0f\n\x07\x62iscuit\x18\x02 \x01(\x0c\x12\x1a\n\x12\x62iscuit_expires_at\x18\x03 \x01(\x03\x12\x19\n\x11\x63ontrol_plane_url\x18\x04 \x01(\t\x12\"\n\x1atrusted_control_plane_keys\x18\x05 \x03(\x0c\x12\x12\n\nchecked_at\x18\x06 \x01(\x03\"\x87\x02\n\x14PeerEvidenceResponse\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12\x0f\n\x07\x62iscuit\x18\x02 \x01(\x0c\x12\x15\n\rverifying_key\x18\x03 \x01(\x0c\x12\r\n\x05roles\x18\x04 \x03(\t\x12\x38\n\x06labels\x18\x05 \x03(\x0b\x32(.sam.v1.PeerEvidenceResponse.LabelsEntry\x12\x12\n\nexpiration\x18\x06 \x01(\x03\x12\x16\n\x0erevocation_ids\x18\x07 \x03(\t\x12\x12\n\nchecked_at\x18\x08 \x01(\x03\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01*\x94\x01\n\x10\x45nrollmentStatus\x12!\n\x1d\x45NROLLMENT_STATUS_UNSPECIFIED\x10\x00\x12\x1d\n\x19\x45NROLLMENT_STATUS_PENDING\x10\x01\x12\x1e\n\x1a\x45NROLLMENT_STATUS_APPROVED\x10\x02\x12\x1e\n\x1a\x45NROLLMENT_STATUS_REJECTED\x10\x03*s\n\x0bServiceType\x12\x1c\n\x18SERVICE_TYPE_UNSPECIFIED\x10\x00\x12\x14\n\x10SERVICE_TYPE_MCP\x10\x01\x12\x1a\n\x16SERVICE_TYPE_INFERENCE\x10\x02\x12\x14\n\x10SERVICE_TYPE_A2A\x10\x03\x42\x1bZ\x19github.com/google/sam/apib\x06proto3')
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\tsam.proto\x12\x06sam.v1\x1a\x1fgoogle/protobuf/timestamp.proto\"C\n\tAuthFrame\x12\x0f\n\x07\x62iscuit\x18\x01 \x01(\x0c\x12\x16\n\x0etarget_service\x18\x02 \x01(\t\x12\r\n\x05\x61gent\x18\x03 \x01(\t\"?\n\x0c\x41uthResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\x12\x0f\n\x07\x62iscuit\x18\x03 \x01(\x0c\"\xb9\x01\n\tMeshEvent\x12$\n\x04type\x18\x01 \x01(\x0e\x32\x16.sam.v1.MeshEvent.Type\x12\x0f\n\x07peer_id\x18\x02 \x01(\t\x12\x11\n\ttimestamp\x18\x03 \x01(\x03\x12\x16\n\x0enew_public_key\x18\x04 \x01(\x0c\x12\x11\n\tsignature\x18\x05 \x01(\x0c\"7\n\x04Type\x12\n\n\x06\x42\x41NNED\x10\x00\x12\x10\n\x0cKEY_ROTATION\x10\x01\x12\x11\n\rPOLICY_UPDATE\x10\x02\"\xeb\x01\n\rEnrollRequest\x12\x0b\n\x03jwt\x18\x01 \x01(\t\x12\x0f\n\x07peer_id\x18\x02 \x01(\t\x12\x12\n\npublic_key\x18\x03 \x01(\x0c\x12\x16\n\x0erequested_role\x18\x04 \x01(\t\x12\x31\n\x06labels\x18\x05 \x03(\x0b\x32!.sam.v1.EnrollRequest.LabelsEntry\x12\x11\n\ttimestamp\x18\x06 \x01(\x03\x12\x1b\n\x13\x63hallenge_signature\x18\x07 \x01(\x0c\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x8e\x01\n\x0e\x45nrollResponse\x12\x15\n\rbiscuit_token\x18\x01 \x01(\x0c\x12\x15\n\rerror_message\x18\x02 \x01(\t\x12 \n\x18\x63ontrol_plane_public_key\x18\x03 \x01(\x0c\x12\x18\n\x10router_addresses\x18\x04 \x03(\t\x12\x12\n\nexpiration\x18\x05 \x01(\x03\"\x89\x02\n\x16\x42ootstrapEnrollRequest\x12\x17\n\x0f\x62ootstrap_token\x18\x01 \x01(\t\x12\x0f\n\x07peer_id\x18\x02 \x01(\t\x12\x12\n\npublic_key\x18\x03 \x01(\x0c\x12\x16\n\x0erequested_role\x18\x04 \x01(\t\x12:\n\x06labels\x18\x05 \x03(\x0b\x32*.sam.v1.BootstrapEnrollRequest.LabelsEntry\x12\x11\n\ttimestamp\x18\x06 \x01(\x03\x12\x1b\n\x13\x63hallenge_signature\x18\x07 \x01(\x0c\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\xe0\x01\n\x17\x42ootstrapEnrollResponse\x12(\n\x06status\x18\x01 \x01(\x0e\x32\x18.sam.v1.EnrollmentStatus\x12\x15\n\rbiscuit_token\x18\x02 \x01(\x0c\x12\x1d\n\x15poll_interval_seconds\x18\x03 \x01(\x05\x12\x15\n\rerror_message\x18\x04 \x01(\t\x12 \n\x18\x63ontrol_plane_public_key\x18\x05 \x01(\x0c\x12\x18\n\x10router_addresses\x18\x06 \x03(\t\x12\x12\n\nexpiration\x18\x07 \x01(\x03\"S\n\x0bServiceInfo\x12!\n\x04type\x18\x01 \x01(\x0e\x32\x13.sam.v1.ServiceType\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x03 \x01(\t\"{\n\x0e\x43ommandBackend\x12\x0f\n\x07\x63ommand\x18\x01 \x03(\t\x12,\n\x03\x65nv\x18\x02 \x03(\x0b\x32\x1f.sam.v1.CommandBackend.EnvEntry\x1a*\n\x08\x45nvEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x8a\x01\n\x16RegisterServiceRequest\x12$\n\x07service\x18\x01 \x01(\x0b\x32\x13.sam.v1.ServiceInfo\x12\x14\n\ntarget_url\x18\x02 \x01(\tH\x00\x12)\n\x07\x63ommand\x18\x03 \x01(\x0b\x32\x16.sam.v1.CommandBackendH\x00\x42\t\n\x07\x62\x61\x63kend\"i\n\x12\x44iscoveredProvider\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12\x17\n\x0flocal_proxy_url\x18\x02 \x01(\t\x12\x10\n\x08srv_name\x18\x03 \x01(\t\x12\x17\n\x0fsrv_description\x18\x04 \x01(\t\"\x92\x02\n\x0fServiceAnnounce\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12!\n\x04type\x18\x02 \x01(\x0e\x32\x13.sam.v1.ServiceType\x12\x14\n\x0cservice_name\x18\x03 \x01(\t\x12\x0c\n\x04keys\x18\x04 \x03(\t\x12\x33\n\x06labels\x18\x05 \x03(\x0b\x32#.sam.v1.ServiceAnnounce.LabelsEntry\x12\x17\n\x0f\x61\x63tive_requests\x18\x06 \x01(\r\x12\x17\n\x0flatency_ewma_ms\x18\x07 \x01(\x01\x12\x11\n\ttimestamp\x18\x08 \x01(\x03\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x87\x01\n\x18\x43ontrolPlaneInfoResponse\x12\x13\n\x0boidc_issuer\x18\x01 \x01(\t\x12\x11\n\tclient_id\x18\x02 \x01(\t\x12\x10\n\x08\x61udience\x18\x03 \x01(\t\x12\x18\n\x10router_addresses\x18\x04 \x03(\t\x12\x17\n\x0f\x62\x61nned_peer_ids\x18\x05 \x03(\t\"\xa4\x01\n\x12RouterLeaseRequest\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12\x11\n\taddresses\x18\x02 \x03(\t\x12\x0f\n\x07\x62iscuit\x18\x03 \x01(\x0c\x12\x17\n\x0f\x63onnected_peers\x18\x04 \x03(\t\x12\x10\n\x08\x64ht_size\x18\x05 \x01(\x05\x12\x11\n\ttimestamp\x18\x06 \x01(\x03\x12\x1b\n\x13\x63hallenge_signature\x18\x07 \x01(\x0c\"I\n\x13RouterLeaseResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\x12\x12\n\nexpires_at\x18\x03 \x01(\x03\"\x95\x01\n\nPolicyRole\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x17\n\x0f\x61llowed_targets\x18\x02 \x03(\t\x12\x18\n\x10\x61llowed_services\x18\x03 \x03(\t\x12\x16\n\x0e\x63ustom_datalog\x18\x04 \x03(\t\x12\x16\n\x0e\x61llowed_agents\x18\x05 \x03(\t\x12\x16\n\x0e\x61llowed_labels\x18\x06 \x03(\t\".\n\rPolicyBinding\x12\x0c\n\x04role\x18\x01 \x01(\t\x12\x0f\n\x07members\x18\x02 \x03(\t\"Z\n\x0cPolicyConfig\x12!\n\x05roles\x18\x01 \x03(\x0b\x32\x12.sam.v1.PolicyRole\x12\'\n\x08\x62indings\x18\x02 \x03(\x0b\x32\x15.sam.v1.PolicyBinding\"\x18\n\x16PolicyConfigGetRequest\"M\n\x17PolicyConfigGetResponse\x12\x15\n\rdatalog_rules\x18\x03 \x03(\tJ\x04\x08\x01\x10\x02J\x04\x08\x02\x10\x03R\x05rolesR\x08\x62indings\"<\n\x1aPolicyConfigUpdateResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\"J\n\x0cKeysResponse\x12\x13\n\x0bpublic_keys\x18\x01 \x03(\x0c\x12\x11\n\ttimestamp\x18\x02 \x01(\x03\x12\x12\n\nsignatures\x18\x03 \x03(\x0c\"V\n\x13TokenRefreshRequest\x12\x1b\n\x13\x63hallenge_signature\x18\x01 \x01(\x0c\x12\x11\n\ttimestamp\x18\x02 \x01(\x03\x12\x0f\n\x07peer_id\x18\x03 \x01(\t\"X\n\x14TokenRefreshResponse\x12\x15\n\rbiscuit_token\x18\x01 \x01(\x0c\x12\x12\n\nexpires_at\x18\x02 \x01(\x03\x12\x15\n\rerror_message\x18\x03 \x01(\t\":\n\x11NodeCatalogReport\x12%\n\x08services\x18\x01 \x03(\x0b\x32\x13.sam.v1.ServiceInfo\"%\n\x12TokenRevokeRequest\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\"5\n\x13TokenRevokeResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\"R\n\x0b\x41gentSecret\x12\x0c\n\x04host\x18\x01 \x01(\t\x12\x0c\n\x04kind\x18\x02 \x01(\t\x12\x13\n\x0bheader_name\x18\x03 \x01(\t\x12\x12\n\nvalue_path\x18\x04 \x01(\t\"B\n\x0b\x41gentEgress\x12\r\n\x05\x61llow\x18\x01 \x03(\t\x12$\n\x07secrets\x18\x02 \x03(\x0b\x32\x13.sam.v1.AgentSecret\"b\n\x0c\x41gentIngress\x12!\n\x04type\x18\x01 \x01(\x0e\x32\x13.sam.v1.ServiceType\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x0c\n\x04port\x18\x03 \x01(\r\x12\x13\n\x0b\x64\x65scription\x18\x04 \x01(\t\"\xaa\x01\n\x0b\x41gentBundle\x12\x0f\n\x07version\x18\x01 \x01(\t\x12\x10\n\x08\x61gent_id\x18\x02 \x01(\t\x12\x13\n\x0b\x65xternal_id\x18\x03 \x01(\t\x12\x17\n\x0f\x63redential_path\x18\x04 \x01(\t\x12#\n\x06\x65gress\x18\x05 \x01(\x0b\x32\x13.sam.v1.AgentEgress\x12%\n\x07ingress\x18\x06 \x03(\x0b\x32\x14.sam.v1.AgentIngress\"9\n\x12\x41gentAttachRequest\x12#\n\x06\x62undle\x18\x01 \x01(\x0b\x32\x13.sam.v1.AgentBundle\"S\n\x13\x41gentAttachResponse\x12\x15\n\regress_socket\x18\x01 \x01(\t\x12\x16\n\x0eingress_socket\x18\x02 \x01(\t\x12\r\n\x05\x65rror\x18\x03 \x01(\t\"&\n\x12\x41gentDetachRequest\x12\x10\n\x08\x61gent_id\x18\x01 \x01(\t\"5\n\x13\x41gentDetachResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\"@\n\x13\x41gentRefreshRequest\x12\x10\n\x08\x61gent_id\x18\x01 \x01(\t\x12\x17\n\x0f\x63redential_path\x18\x02 \x01(\t\"J\n\x14\x41gentRefreshResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\x12\x12\n\nexpires_at\x18\x03 \x01(\x03\"&\n\x12\x41gentStatusRequest\x12\x10\n\x08\x61gent_id\x18\x01 \x01(\t\"w\n\x0b\x41gentStatus\x12\x10\n\x08\x61gent_id\x18\x01 \x01(\t\x12\x10\n\x08\x61ttached\x18\x02 \x01(\x08\x12%\n\x07ingress\x18\x03 \x03(\x0b\x32\x14.sam.v1.AgentIngress\x12\x1d\n\x15\x63redential_expires_at\x18\x04 \x01(\x03\"I\n\x13\x41gentStatusResponse\x12#\n\x06\x61gents\x18\x01 \x03(\x0b\x32\x13.sam.v1.AgentStatus\x12\r\n\x05\x65rror\x18\x02 \x01(\t\"\xab\x01\n\x18IdentityEvidenceResponse\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12\x0f\n\x07\x62iscuit\x18\x02 \x01(\x0c\x12\x1a\n\x12\x62iscuit_expires_at\x18\x03 \x01(\x03\x12\x19\n\x11\x63ontrol_plane_url\x18\x04 \x01(\t\x12\"\n\x1atrusted_control_plane_keys\x18\x05 \x03(\x0c\x12\x12\n\nchecked_at\x18\x06 \x01(\x03\"\x87\x02\n\x14PeerEvidenceResponse\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12\x0f\n\x07\x62iscuit\x18\x02 \x01(\x0c\x12\x15\n\rverifying_key\x18\x03 \x01(\x0c\x12\r\n\x05roles\x18\x04 \x03(\t\x12\x38\n\x06labels\x18\x05 \x03(\x0b\x32(.sam.v1.PeerEvidenceResponse.LabelsEntry\x12\x12\n\nexpiration\x18\x06 \x01(\x03\x12\x16\n\x0erevocation_ids\x18\x07 \x03(\t\x12\x12\n\nchecked_at\x18\x08 \x01(\x03\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x80\x02\n\x10MemberCredential\x12\x19\n\x11\x63ontrol_plane_url\x18\x01 \x01(\t\x12\x0f\n\x07\x62iscuit\x18\x02 \x01(\x0c\x12/\n\x0b\x65xpire_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0ctrusted_keys\x18\x04 \x03(\x0b\x32\x19.sam.v1.TrustedSigningKey\x12\x19\n\x11issued_under_keys\x18\x05 \x03(\x0c\x12\x18\n\x10router_addresses\x18\x06 \x03(\t\x12)\n\x0coidc_session\x18\x07 \x01(\x0b\x32\x13.sam.v1.OIDCSession\"Y\n\x11TrustedSigningKey\x12\x12\n\npublic_key\x18\x01 \x01(\x0c\x12\x30\n\x0creceive_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"Y\n\x0bOIDCSession\x12\x0e\n\x06issuer\x18\x01 \x01(\t\x12\x11\n\tclient_id\x18\x02 \x01(\t\x12\x10\n\x08\x61udience\x18\x03 \x01(\t\x12\x15\n\rrefresh_token\x18\x04 \x01(\t*\x94\x01\n\x10\x45nrollmentStatus\x12!\n\x1d\x45NROLLMENT_STATUS_UNSPECIFIED\x10\x00\x12\x1d\n\x19\x45NROLLMENT_STATUS_PENDING\x10\x01\x12\x1e\n\x1a\x45NROLLMENT_STATUS_APPROVED\x10\x02\x12\x1e\n\x1a\x45NROLLMENT_STATUS_REJECTED\x10\x03*s\n\x0bServiceType\x12\x1c\n\x18SERVICE_TYPE_UNSPECIFIED\x10\x00\x12\x14\n\x10SERVICE_TYPE_MCP\x10\x01\x12\x1a\n\x16SERVICE_TYPE_INFERENCE\x10\x02\x12\x14\n\x10SERVICE_TYPE_A2A\x10\x03\x42\x1bZ\x19github.com/google/sam/apib\x06proto3')
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'sam_pb2', globals())
@@ -31,104 +32,110 @@ if _descriptor._USE_C_DESCRIPTORS == False:
_SERVICEANNOUNCE_LABELSENTRY._serialized_options = b'8\001'
_PEEREVIDENCERESPONSE_LABELSENTRY._options = None
_PEEREVIDENCERESPONSE_LABELSENTRY._serialized_options = b'8\001'
- _ENROLLMENTSTATUS._serialized_start=4686
- _ENROLLMENTSTATUS._serialized_end=4834
- _SERVICETYPE._serialized_start=4836
- _SERVICETYPE._serialized_end=4951
- _AUTHFRAME._serialized_start=21
- _AUTHFRAME._serialized_end=88
- _AUTHRESPONSE._serialized_start=90
- _AUTHRESPONSE._serialized_end=153
- _MESHEVENT._serialized_start=156
- _MESHEVENT._serialized_end=341
- _MESHEVENT_TYPE._serialized_start=286
- _MESHEVENT_TYPE._serialized_end=341
- _ENROLLREQUEST._serialized_start=344
- _ENROLLREQUEST._serialized_end=579
- _ENROLLREQUEST_LABELSENTRY._serialized_start=534
- _ENROLLREQUEST_LABELSENTRY._serialized_end=579
- _ENROLLRESPONSE._serialized_start=582
- _ENROLLRESPONSE._serialized_end=724
- _BOOTSTRAPENROLLREQUEST._serialized_start=727
- _BOOTSTRAPENROLLREQUEST._serialized_end=992
- _BOOTSTRAPENROLLREQUEST_LABELSENTRY._serialized_start=534
- _BOOTSTRAPENROLLREQUEST_LABELSENTRY._serialized_end=579
- _BOOTSTRAPENROLLRESPONSE._serialized_start=995
- _BOOTSTRAPENROLLRESPONSE._serialized_end=1219
- _SERVICEINFO._serialized_start=1221
- _SERVICEINFO._serialized_end=1304
- _COMMANDBACKEND._serialized_start=1306
- _COMMANDBACKEND._serialized_end=1429
- _COMMANDBACKEND_ENVENTRY._serialized_start=1387
- _COMMANDBACKEND_ENVENTRY._serialized_end=1429
- _REGISTERSERVICEREQUEST._serialized_start=1432
- _REGISTERSERVICEREQUEST._serialized_end=1570
- _DISCOVEREDPROVIDER._serialized_start=1572
- _DISCOVEREDPROVIDER._serialized_end=1677
- _SERVICEANNOUNCE._serialized_start=1680
- _SERVICEANNOUNCE._serialized_end=1954
- _SERVICEANNOUNCE_LABELSENTRY._serialized_start=534
- _SERVICEANNOUNCE_LABELSENTRY._serialized_end=579
- _CONTROLPLANEINFORESPONSE._serialized_start=1957
- _CONTROLPLANEINFORESPONSE._serialized_end=2092
- _ROUTERLEASEREQUEST._serialized_start=2095
- _ROUTERLEASEREQUEST._serialized_end=2259
- _ROUTERLEASERESPONSE._serialized_start=2261
- _ROUTERLEASERESPONSE._serialized_end=2334
- _POLICYROLE._serialized_start=2337
- _POLICYROLE._serialized_end=2486
- _POLICYBINDING._serialized_start=2488
- _POLICYBINDING._serialized_end=2534
- _POLICYCONFIG._serialized_start=2536
- _POLICYCONFIG._serialized_end=2626
- _POLICYCONFIGGETREQUEST._serialized_start=2628
- _POLICYCONFIGGETREQUEST._serialized_end=2652
- _POLICYCONFIGGETRESPONSE._serialized_start=2654
- _POLICYCONFIGGETRESPONSE._serialized_end=2731
- _POLICYCONFIGUPDATERESPONSE._serialized_start=2733
- _POLICYCONFIGUPDATERESPONSE._serialized_end=2793
- _KEYSRESPONSE._serialized_start=2795
- _KEYSRESPONSE._serialized_end=2869
- _TOKENREFRESHREQUEST._serialized_start=2871
- _TOKENREFRESHREQUEST._serialized_end=2957
- _TOKENREFRESHRESPONSE._serialized_start=2959
- _TOKENREFRESHRESPONSE._serialized_end=3047
- _NODECATALOGREPORT._serialized_start=3049
- _NODECATALOGREPORT._serialized_end=3107
- _TOKENREVOKEREQUEST._serialized_start=3109
- _TOKENREVOKEREQUEST._serialized_end=3146
- _TOKENREVOKERESPONSE._serialized_start=3148
- _TOKENREVOKERESPONSE._serialized_end=3201
- _AGENTSECRET._serialized_start=3203
- _AGENTSECRET._serialized_end=3285
- _AGENTEGRESS._serialized_start=3287
- _AGENTEGRESS._serialized_end=3353
- _AGENTINGRESS._serialized_start=3355
- _AGENTINGRESS._serialized_end=3453
- _AGENTBUNDLE._serialized_start=3456
- _AGENTBUNDLE._serialized_end=3626
- _AGENTATTACHREQUEST._serialized_start=3628
- _AGENTATTACHREQUEST._serialized_end=3685
- _AGENTATTACHRESPONSE._serialized_start=3687
- _AGENTATTACHRESPONSE._serialized_end=3770
- _AGENTDETACHREQUEST._serialized_start=3772
- _AGENTDETACHREQUEST._serialized_end=3810
- _AGENTDETACHRESPONSE._serialized_start=3812
- _AGENTDETACHRESPONSE._serialized_end=3865
- _AGENTREFRESHREQUEST._serialized_start=3867
- _AGENTREFRESHREQUEST._serialized_end=3931
- _AGENTREFRESHRESPONSE._serialized_start=3933
- _AGENTREFRESHRESPONSE._serialized_end=4007
- _AGENTSTATUSREQUEST._serialized_start=4009
- _AGENTSTATUSREQUEST._serialized_end=4047
- _AGENTSTATUS._serialized_start=4049
- _AGENTSTATUS._serialized_end=4168
- _AGENTSTATUSRESPONSE._serialized_start=4170
- _AGENTSTATUSRESPONSE._serialized_end=4243
- _IDENTITYEVIDENCERESPONSE._serialized_start=4246
- _IDENTITYEVIDENCERESPONSE._serialized_end=4417
- _PEEREVIDENCERESPONSE._serialized_start=4420
- _PEEREVIDENCERESPONSE._serialized_end=4683
- _PEEREVIDENCERESPONSE_LABELSENTRY._serialized_start=534
- _PEEREVIDENCERESPONSE_LABELSENTRY._serialized_end=579
+ _ENROLLMENTSTATUS._serialized_start=5160
+ _ENROLLMENTSTATUS._serialized_end=5308
+ _SERVICETYPE._serialized_start=5310
+ _SERVICETYPE._serialized_end=5425
+ _AUTHFRAME._serialized_start=54
+ _AUTHFRAME._serialized_end=121
+ _AUTHRESPONSE._serialized_start=123
+ _AUTHRESPONSE._serialized_end=186
+ _MESHEVENT._serialized_start=189
+ _MESHEVENT._serialized_end=374
+ _MESHEVENT_TYPE._serialized_start=319
+ _MESHEVENT_TYPE._serialized_end=374
+ _ENROLLREQUEST._serialized_start=377
+ _ENROLLREQUEST._serialized_end=612
+ _ENROLLREQUEST_LABELSENTRY._serialized_start=567
+ _ENROLLREQUEST_LABELSENTRY._serialized_end=612
+ _ENROLLRESPONSE._serialized_start=615
+ _ENROLLRESPONSE._serialized_end=757
+ _BOOTSTRAPENROLLREQUEST._serialized_start=760
+ _BOOTSTRAPENROLLREQUEST._serialized_end=1025
+ _BOOTSTRAPENROLLREQUEST_LABELSENTRY._serialized_start=567
+ _BOOTSTRAPENROLLREQUEST_LABELSENTRY._serialized_end=612
+ _BOOTSTRAPENROLLRESPONSE._serialized_start=1028
+ _BOOTSTRAPENROLLRESPONSE._serialized_end=1252
+ _SERVICEINFO._serialized_start=1254
+ _SERVICEINFO._serialized_end=1337
+ _COMMANDBACKEND._serialized_start=1339
+ _COMMANDBACKEND._serialized_end=1462
+ _COMMANDBACKEND_ENVENTRY._serialized_start=1420
+ _COMMANDBACKEND_ENVENTRY._serialized_end=1462
+ _REGISTERSERVICEREQUEST._serialized_start=1465
+ _REGISTERSERVICEREQUEST._serialized_end=1603
+ _DISCOVEREDPROVIDER._serialized_start=1605
+ _DISCOVEREDPROVIDER._serialized_end=1710
+ _SERVICEANNOUNCE._serialized_start=1713
+ _SERVICEANNOUNCE._serialized_end=1987
+ _SERVICEANNOUNCE_LABELSENTRY._serialized_start=567
+ _SERVICEANNOUNCE_LABELSENTRY._serialized_end=612
+ _CONTROLPLANEINFORESPONSE._serialized_start=1990
+ _CONTROLPLANEINFORESPONSE._serialized_end=2125
+ _ROUTERLEASEREQUEST._serialized_start=2128
+ _ROUTERLEASEREQUEST._serialized_end=2292
+ _ROUTERLEASERESPONSE._serialized_start=2294
+ _ROUTERLEASERESPONSE._serialized_end=2367
+ _POLICYROLE._serialized_start=2370
+ _POLICYROLE._serialized_end=2519
+ _POLICYBINDING._serialized_start=2521
+ _POLICYBINDING._serialized_end=2567
+ _POLICYCONFIG._serialized_start=2569
+ _POLICYCONFIG._serialized_end=2659
+ _POLICYCONFIGGETREQUEST._serialized_start=2661
+ _POLICYCONFIGGETREQUEST._serialized_end=2685
+ _POLICYCONFIGGETRESPONSE._serialized_start=2687
+ _POLICYCONFIGGETRESPONSE._serialized_end=2764
+ _POLICYCONFIGUPDATERESPONSE._serialized_start=2766
+ _POLICYCONFIGUPDATERESPONSE._serialized_end=2826
+ _KEYSRESPONSE._serialized_start=2828
+ _KEYSRESPONSE._serialized_end=2902
+ _TOKENREFRESHREQUEST._serialized_start=2904
+ _TOKENREFRESHREQUEST._serialized_end=2990
+ _TOKENREFRESHRESPONSE._serialized_start=2992
+ _TOKENREFRESHRESPONSE._serialized_end=3080
+ _NODECATALOGREPORT._serialized_start=3082
+ _NODECATALOGREPORT._serialized_end=3140
+ _TOKENREVOKEREQUEST._serialized_start=3142
+ _TOKENREVOKEREQUEST._serialized_end=3179
+ _TOKENREVOKERESPONSE._serialized_start=3181
+ _TOKENREVOKERESPONSE._serialized_end=3234
+ _AGENTSECRET._serialized_start=3236
+ _AGENTSECRET._serialized_end=3318
+ _AGENTEGRESS._serialized_start=3320
+ _AGENTEGRESS._serialized_end=3386
+ _AGENTINGRESS._serialized_start=3388
+ _AGENTINGRESS._serialized_end=3486
+ _AGENTBUNDLE._serialized_start=3489
+ _AGENTBUNDLE._serialized_end=3659
+ _AGENTATTACHREQUEST._serialized_start=3661
+ _AGENTATTACHREQUEST._serialized_end=3718
+ _AGENTATTACHRESPONSE._serialized_start=3720
+ _AGENTATTACHRESPONSE._serialized_end=3803
+ _AGENTDETACHREQUEST._serialized_start=3805
+ _AGENTDETACHREQUEST._serialized_end=3843
+ _AGENTDETACHRESPONSE._serialized_start=3845
+ _AGENTDETACHRESPONSE._serialized_end=3898
+ _AGENTREFRESHREQUEST._serialized_start=3900
+ _AGENTREFRESHREQUEST._serialized_end=3964
+ _AGENTREFRESHRESPONSE._serialized_start=3966
+ _AGENTREFRESHRESPONSE._serialized_end=4040
+ _AGENTSTATUSREQUEST._serialized_start=4042
+ _AGENTSTATUSREQUEST._serialized_end=4080
+ _AGENTSTATUS._serialized_start=4082
+ _AGENTSTATUS._serialized_end=4201
+ _AGENTSTATUSRESPONSE._serialized_start=4203
+ _AGENTSTATUSRESPONSE._serialized_end=4276
+ _IDENTITYEVIDENCERESPONSE._serialized_start=4279
+ _IDENTITYEVIDENCERESPONSE._serialized_end=4450
+ _PEEREVIDENCERESPONSE._serialized_start=4453
+ _PEEREVIDENCERESPONSE._serialized_end=4716
+ _PEEREVIDENCERESPONSE_LABELSENTRY._serialized_start=567
+ _PEEREVIDENCERESPONSE_LABELSENTRY._serialized_end=612
+ _MEMBERCREDENTIAL._serialized_start=4719
+ _MEMBERCREDENTIAL._serialized_end=4975
+ _TRUSTEDSIGNINGKEY._serialized_start=4977
+ _TRUSTEDSIGNINGKEY._serialized_end=5066
+ _OIDCSESSION._serialized_start=5068
+ _OIDCSESSION._serialized_end=5157
# @@protoc_insertion_point(module_scope)
diff --git a/sdk/python/src/agent_mesh/_proto/sam_pb2.pyi b/sdk/python/src/agent_mesh/_proto/sam_pb2.pyi
index 5e2c4816..52c7c1ca 100644
--- a/sdk/python/src/agent_mesh/_proto/sam_pb2.pyi
+++ b/sdk/python/src/agent_mesh/_proto/sam_pb2.pyi
@@ -1,3 +1,4 @@
+from google.protobuf import timestamp_pb2 as _timestamp_pb2
from google.protobuf.internal import containers as _containers
from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper
from google.protobuf import descriptor as _descriptor
@@ -305,6 +306,24 @@ class KeysResponse(_message.Message):
timestamp: int
def __init__(self, public_keys: _Optional[_Iterable[bytes]] = ..., timestamp: _Optional[int] = ..., signatures: _Optional[_Iterable[bytes]] = ...) -> None: ...
+class MemberCredential(_message.Message):
+ __slots__ = ["biscuit", "control_plane_url", "expire_time", "issued_under_keys", "oidc_session", "router_addresses", "trusted_keys"]
+ BISCUIT_FIELD_NUMBER: _ClassVar[int]
+ CONTROL_PLANE_URL_FIELD_NUMBER: _ClassVar[int]
+ EXPIRE_TIME_FIELD_NUMBER: _ClassVar[int]
+ ISSUED_UNDER_KEYS_FIELD_NUMBER: _ClassVar[int]
+ OIDC_SESSION_FIELD_NUMBER: _ClassVar[int]
+ ROUTER_ADDRESSES_FIELD_NUMBER: _ClassVar[int]
+ TRUSTED_KEYS_FIELD_NUMBER: _ClassVar[int]
+ biscuit: bytes
+ control_plane_url: str
+ expire_time: _timestamp_pb2.Timestamp
+ issued_under_keys: _containers.RepeatedScalarFieldContainer[bytes]
+ oidc_session: OIDCSession
+ router_addresses: _containers.RepeatedScalarFieldContainer[str]
+ trusted_keys: _containers.RepeatedCompositeFieldContainer[TrustedSigningKey]
+ def __init__(self, control_plane_url: _Optional[str] = ..., biscuit: _Optional[bytes] = ..., expire_time: _Optional[_Union[_timestamp_pb2.Timestamp, _Mapping]] = ..., trusted_keys: _Optional[_Iterable[_Union[TrustedSigningKey, _Mapping]]] = ..., issued_under_keys: _Optional[_Iterable[bytes]] = ..., router_addresses: _Optional[_Iterable[str]] = ..., oidc_session: _Optional[_Union[OIDCSession, _Mapping]] = ...) -> None: ...
+
class MeshEvent(_message.Message):
__slots__ = ["new_public_key", "peer_id", "signature", "timestamp", "type"]
class Type(int, metaclass=_enum_type_wrapper.EnumTypeWrapper):
@@ -330,6 +349,18 @@ class NodeCatalogReport(_message.Message):
services: _containers.RepeatedCompositeFieldContainer[ServiceInfo]
def __init__(self, services: _Optional[_Iterable[_Union[ServiceInfo, _Mapping]]] = ...) -> None: ...
+class OIDCSession(_message.Message):
+ __slots__ = ["audience", "client_id", "issuer", "refresh_token"]
+ AUDIENCE_FIELD_NUMBER: _ClassVar[int]
+ CLIENT_ID_FIELD_NUMBER: _ClassVar[int]
+ ISSUER_FIELD_NUMBER: _ClassVar[int]
+ REFRESH_TOKEN_FIELD_NUMBER: _ClassVar[int]
+ audience: str
+ client_id: str
+ issuer: str
+ refresh_token: str
+ def __init__(self, issuer: _Optional[str] = ..., client_id: _Optional[str] = ..., audience: _Optional[str] = ..., refresh_token: _Optional[str] = ...) -> None: ...
+
class PeerEvidenceResponse(_message.Message):
__slots__ = ["biscuit", "checked_at", "expiration", "labels", "peer_id", "revocation_ids", "roles", "verifying_key"]
class LabelsEntry(_message.Message):
@@ -516,6 +547,14 @@ class TokenRevokeResponse(_message.Message):
success: bool
def __init__(self, success: bool = ..., error: _Optional[str] = ...) -> None: ...
+class TrustedSigningKey(_message.Message):
+ __slots__ = ["public_key", "receive_time"]
+ PUBLIC_KEY_FIELD_NUMBER: _ClassVar[int]
+ RECEIVE_TIME_FIELD_NUMBER: _ClassVar[int]
+ public_key: bytes
+ receive_time: _timestamp_pb2.Timestamp
+ def __init__(self, public_key: _Optional[bytes] = ..., receive_time: _Optional[_Union[_timestamp_pb2.Timestamp, _Mapping]] = ...) -> None: ...
+
class EnrollmentStatus(int, metaclass=_enum_type_wrapper.EnumTypeWrapper):
__slots__ = []
diff --git a/sdk/python/src/agent_mesh/credential.py b/sdk/python/src/agent_mesh/credential.py
index b5929b0a..5bcd9865 100644
--- a/sdk/python/src/agent_mesh/credential.py
+++ b/sdk/python/src/agent_mesh/credential.py
@@ -14,10 +14,12 @@
from __future__ import annotations
-import base64
-import json
import time
from dataclasses import dataclass, field
+from typing import Optional
+
+from google.protobuf import json_format
+from google.protobuf.timestamp_pb2 import Timestamp
from ._proto import sam_pb2 as pb
@@ -40,6 +42,11 @@ class MeshCredential:
issued_under_keys: list[bytes] = field(default_factory=list)
# Router multiaddrs, `/p2p/<peer id>` suffixed, as handed out at enrollment.
router_addresses: list[str] = field(default_factory=list)
+ # What other implementations persist in the same file and this SDK does
+ # not use: when each key was learned (by key bytes) and sam-node's OIDC
+ # session. Carried through so a state directory survives a round trip.
+ receive_times: dict[bytes, Timestamp] = field(default_factory=dict, compare=False)
+ oidc_session: Optional[pb.OIDCSession] = field(default=None, compare=False)
def time_to_live_seconds(self, now: float | None = None) -> int:
"""Seconds of validity left on the biscuit; negative once expired."""
@@ -51,34 +58,55 @@ class MeshCredential:
return any(bytes(k) not in issued for k in self.control_plane_keys)
def to_json(self) -> str:
- return json.dumps(
- {
- "control_plane_url": self.control_plane_url,
- "biscuit": base64.b64encode(self.biscuit).decode(),
- "expiration": self.expiration,
- "control_plane_keys": [base64.b64encode(k).decode() for k in self.control_plane_keys],
- "issued_under_keys": [base64.b64encode(k).decode() for k in self.issued_under_keys],
- "router_addresses": list(self.router_addresses),
- },
- indent=2,
- ) + "\n"
+ """credential.json: the api.MemberCredential message as protojson with
+ proto field names, the layout `sam-node state export` writes and every
+ SDK reads."""
+ message = pb.MemberCredential(
+ control_plane_url=self.control_plane_url,
+ biscuit=self.biscuit,
+ issued_under_keys=[bytes(k) for k in self.issued_under_keys],
+ router_addresses=list(self.router_addresses),
+ )
+ message.expire_time.FromSeconds(self.expiration)
+ for k in self.control_plane_keys:
+ entry = message.trusted_keys.add(public_key=bytes(k))
+ if (received := self.receive_times.get(bytes(k))) is not None:
+ entry.receive_time.CopyFrom(received)
+ if self.oidc_session is not None:
+ message.oidc_session.CopyFrom(self.oidc_session)
+ return json_format.MessageToJson(message, preserving_proto_field_name=True, indent=2) + "\n"
@classmethod
def from_json(cls, text: str) -> "MeshCredential":
- raw = json.loads(text)
+ """Reads credential.json. An unknown field is an error, as on every SAM surface."""
try:
- control_plane_keys = [base64.b64decode(k) for k in raw.get("control_plane_keys", [])]
- return cls(
- control_plane_url=str(raw["control_plane_url"]),
- biscuit=base64.b64decode(raw["biscuit"]),
- expiration=int(raw["expiration"]),
- control_plane_keys=control_plane_keys,
- # A file from before this field: the set known then is the best answer.
- issued_under_keys=[base64.b64decode(k) for k in raw["issued_under_keys"]] if "issued_under_keys" in raw else control_plane_keys,
- router_addresses=[str(a) for a in raw.get("router_addresses", [])],
- )
- except (KeyError, TypeError, ValueError) as err:
- raise ValueError("malformed credential file") from err
+ message = json_format.Parse(text, pb.MemberCredential())
+ except json_format.ParseError as err:
+ raise ValueError(f"malformed credential file: {err}") from err
+ if not message.control_plane_url or not message.biscuit or not message.HasField("expire_time"):
+ raise ValueError("malformed credential file: control_plane_url, biscuit and expire_time are required")
+ control_plane_keys = [bytes(k.public_key) for k in message.trusted_keys]
+ receive_times: dict[bytes, Timestamp] = {}
+ for k in message.trusted_keys:
+ if k.HasField("receive_time"):
+ received = Timestamp()
+ received.CopyFrom(k.receive_time)
+ receive_times[bytes(k.public_key)] = received
+ oidc_session = None
+ if message.HasField("oidc_session"):
+ oidc_session = pb.OIDCSession()
+ oidc_session.CopyFrom(message.oidc_session)
+ return cls(
+ control_plane_url=message.control_plane_url,
+ biscuit=bytes(message.biscuit),
+ expiration=message.expire_time.ToSeconds(),
+ control_plane_keys=control_plane_keys,
+ # A file that recorded no issuance set: the keys trusted then are the best answer.
+ issued_under_keys=[bytes(k) for k in message.issued_under_keys] or list(control_plane_keys),
+ router_addresses=list(message.router_addresses),
+ receive_times=receive_times,
+ oidc_session=oidc_session,
+ )
def encode_auth_frame(biscuit: bytes, target_service: str = "", agent: str = "") -> bytes:
diff --git a/sdk/python/src/agent_mesh/mesh.py b/sdk/python/src/agent_mesh/mesh.py
index eb5f6c3e..748c006e 100644
--- a/sdk/python/src/agent_mesh/mesh.py
+++ b/sdk/python/src/agent_mesh/mesh.py
@@ -98,7 +98,7 @@ class AgentMesh:
control_plane = ControlPlaneClient(control_plane_url, allow_insecure=allow_insecure, transport=transport)
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 == control_plane.url and credential.time_to_live_seconds() > _REUSE_MIN_TTL_SECONDS:
+ 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))
if given != 1:
diff --git a/sdk/python/tests/test_mesh.py b/sdk/python/tests/test_mesh.py
index de783b3b..a19bc29c 100644
--- a/sdk/python/tests/test_mesh.py
+++ b/sdk/python/tests/test_mesh.py
@@ -16,6 +16,7 @@ import json
import stat
import time
import urllib.parse
+from datetime import datetime, timezone
import pytest
@@ -84,6 +85,9 @@ def test_enroll_persists_load_resumes_refresh_rotates(tmp_path):
assert resumed.credential.biscuit == b"biscuit-2"
on_disk = json.loads((state / "credential.json").read_text())
assert on_disk["biscuit"] == "YmlzY3VpdC0y" # base64("biscuit-2")
+ # The file is api.MemberCredential as protojson: proto field names, RFC 3339 instants.
+ assert sorted(on_disk) == ["biscuit", "control_plane_url", "expire_time", "issued_under_keys", "router_addresses", "trusted_keys"]
+ assert on_disk["expire_time"].endswith("Z")
# Enrolling again from the same directory resumes the saved credential
# without a token; another control plane or an expiring credential
@@ -102,7 +106,7 @@ def test_enroll_persists_load_resumes_refresh_rotates(tmp_path):
assert elsewhere.credential.control_plane_url == "http://127.0.0.2:1"
expiring = json.loads((state / "credential.json").read_text())
- expiring["expiration"] = int(time.time()) + 60
+ expiring["expire_time"] = datetime.fromtimestamp(time.time() + 60, tz=timezone.utc).isoformat().replace("+00:00", "Z")
(state / "credential.json").write_text(json.dumps(expiring))
AgentMesh.enroll("http://127.0.0.2:1", bootstrap_token="sbt_secret", state_dir=state, transport=cp.transport)
assert cp.issued == issued_before + 2
diff --git a/site/content/docs/guides/native-sdks.md b/site/content/docs/guides/native-sdks.md
index 6f62b1ea..3be874cc 100644
--- a/site/content/docs/guides/native-sdks.md
+++ b/site/content/docs/guides/native-sdks.md
@@ -397,7 +397,10 @@ and received a credential: a signed token that names the member, its role
and the routers it may use. The identity key and the credential live in the
state directory, so the next run resumes without a token, and the SDK
renews the credential before it expires. Delete the directory to enroll
-afresh, for instance with other labels.
+afresh, for instance with other labels. The directory has the same layout
+in both SDKs and in `sam-node`: a program in one language resumes a
+directory written by the other, and `sam-node state import` runs the same
+identity as a node (see the [sam-node reference](../../reference/sam-node/#state)).
`join` connected to the routers named in the credential, proved the
program's identity to each and verified the router's own credential, and
diff --git a/site/content/docs/reference/sam-node.md b/site/content/docs/reference/sam-node.md
index b6c93bb6..24a30041 100644
--- a/site/content/docs/reference/sam-node.md
+++ b/site/content/docs/reference/sam-node.md
@@ -10,6 +10,7 @@ weight: 1
sam-node join [control-plane-url] [flags] enroll and store a credential
sam-node run [flags] run the node
sam-node reset [--all] [--yes] forget the credential or everything
+sam-node state export|import <dir> move the identity to or from a state directory
sam-node skill install|list|show manage the agent skill document
```
@@ -22,7 +23,7 @@ macOS). It is created with mode `0700` and holds:
| File | Contents |
|---|---|
-| `agent.db` | The node's key, credential, control plane URL and public key, router addresses, and OIDC refresh token. A running node holds a lock on this file. A second node started on the same directory refuses to start. |
+| `agent.db` | The node's key and its `MemberCredential` (`api/sam.proto`): biscuit, expiry, trusted control plane keys, router addresses, control plane URL and OIDC session. A running node holds a lock on this file. A second node started on the same directory refuses to start. A database written by an earlier release, which kept these as separate entries, is converted on first open. |
| `sam.sock` | The local API Unix socket, mode `0600`, removed on exit. |
| `api-token` | Generated by `--daemonize` when no token is configured. |
| `sam-node.pid`, `sam-node.log` | Written by `--daemonize`. |
@@ -128,6 +129,20 @@ enroll.
Both variants refuse while a node has the store locked.
+## `state`
+
+A state directory is how the [native SDKs](../../guides/native-sdks/) keep a
+member: `identity.key`, the libp2p private key, and `credential.json`, the
+`MemberCredential` message of `api/sam.proto` as JSON with proto field names.
+It is the same message `agent.db` holds, so a member moves between a
+`sam-node` and a program written with an SDK by copying files. Both
+subcommands refuse while a node has the store locked.
+
+| Command | Meaning |
+|---|---|
+| `state export <dir>` | Write this node's key and credential to `<dir>`, creating it with mode `0700` and the files with mode `0600`. The files are the node's identity; whoever reads them is this member. |
+| `state import <dir>` | Replace this node's key and credential with the directory's. Refuses when the data directory already holds an identity unless `--yes` is passed. The next `sam-node run` resumes as that member; no token is needed. |
+
## `skill`
Installs the `SKILL.md` document that teaches an agent harness how to use the
diff --git a/tests/integration/sdk_examples_test.go b/tests/integration/sdk_examples_test.go
index d28eb883..202df849 100644
--- a/tests/integration/sdk_examples_test.go
+++ b/tests/integration/sdk_examples_test.go
@@ -205,10 +205,62 @@ func TestNativeSDKExamples(t *testing.T) {
if !strings.Contains(models, `"gemma3"`) || !strings.Contains(models, caller) {
t.Fatalf("models %q: want gemma3 owned by the caller %s", models, caller)
}
+
+ // The state directory is the same layout in every implementation:
+ // the other SDK's call example resumes this identity from it, and
+ // so does a sam-node after `state import`. Each proves it by
+ // reaching a greeter as the same peer.
+ for _, other := range launchers {
+ if other.name == l.name {
+ continue
+ }
+ out := runExample(t, mesh, other, withoutToken, "mcp://greeter", "greet", `{"name": "sam"}`)
+ if got := expectLine(t, out, "on the mesh as "); got != caller {
+ t.Fatalf("%s resumed %s's state directory as %s, want %s", other.name, l.name, got, caller)
+ }
+ expectLine(t, out, "hello sam")
+ }
+ importedNode := importStateIntoNode(t, mesh, stateDir)
+ if importedNode.peerID.String() != caller {
+ t.Fatalf("sam-node imported %s's state directory as %s, want %s", l.name, importedNode.peerID, caller)
+ }
+ importedAPI := importedNode.waitForAPI(t)
+ waitForPeerOnRouter(t, mesh.cpPort, mesh.adminToken, caller, 10*time.Second)
+ answer, err := callMCPAllowError(t, importedAPI, "imported-token", "call_remote_tool", map[string]any{
+ "peer_id": servers[0].peerID, "tool_name": "mcp://greeter/greet", "arguments": map[string]any{"name": "node"},
+ })
+ if err != nil || !strings.Contains(answer, "hello node") {
+ t.Fatalf("sam-node running %s's identity could not call greeter: %v\n%s", l.name, err, answer)
+ }
})
}
}
+// importStateIntoNode runs `sam-node state import` on a fresh data directory
+// and starts a node from it, so the node runs as the member the directory
+// holds. The import refuses a token: the identity is already enrolled.
+func importStateIntoNode(t *testing.T, mesh *sdkMesh, stateDir string) *backgroundNode {
+ t.Helper()
+ nodeBin := buildBinary(t, "./cmd/sam-node")
+ nodeHome := filepath.Join(t.TempDir(), "imported")
+ dataDir := filepath.Join(nodeHome, "data")
+ importCmd := exec.Command(nodeBin, "state", "import", stateDir, "--data-dir", dataDir)
+ importCmd.Dir = mesh.root
+ if out, err := importCmd.CombinedOutput(); err != nil {
+ t.Fatalf("sam-node state import: %v\n%s", err, out)
+ }
+ return launchNode(t, nodeBin,
+ append(os.Environ(), "HOME="+nodeHome, "XDG_CONFIG_HOME="+filepath.Join(nodeHome, ".config")),
+ nodeHome, "run",
+ "--data-dir", dataDir,
+ "--control-plane", mesh.baseURL,
+ "--allow-loopback",
+ "--api-token-path", tokenPath(t, "imported-token"),
+ "--discovery-interval", "100ms",
+ "--log-level", "debug",
+ )
+}
+
// startExampleServer starts a configured serve example and waits for its
// "serving ... as <peer>" line. Safe to call from several goroutines at
// once, so it reports failures instead of ending the test.