agentmesh 3.7.0

Public Preview — Rust SDK for the Agent Governance Toolkit (policy, trust, audit, identity)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Ed25519-based agent identity with DID support.

use ed25519_dalek::{Signer, SigningKey, Verifier, VerifyingKey};
use rand::rngs::OsRng;
use serde::{Deserialize, Serialize};

/// Maximum delegation depth to prevent Sybil attacks via infinite chains.
pub const MAX_DELEGATION_DEPTH: u32 = 10;

/// An agent's cryptographic identity (Ed25519 key pair + DID).
#[derive(Debug, Clone)]
pub struct AgentIdentity {
    /// Decentralised identifier, e.g. `did:agentmesh:my-agent`.
    pub did: String,
    /// Ed25519 public key.
    pub public_key: VerifyingKey,
    /// Capabilities declared by this agent.
    pub capabilities: Vec<String>,
    /// Parent agent DID if this identity was created via delegation.
    pub parent_did: Option<String>,
    /// Depth in the delegation chain (0 = root).
    pub delegation_depth: u32,
    pub(crate) signing_key: SigningKey,
}

impl AgentIdentity {
    /// Generate a new Ed25519-based identity for the given agent.
    pub fn generate(agent_id: &str, capabilities: Vec<String>) -> Result<Self, IdentityError> {
        let signing_key = SigningKey::generate(&mut OsRng);
        let public_key = signing_key.verifying_key();
        Ok(Self {
            did: format!("did:agentmesh:{}", agent_id),
            public_key,
            capabilities,
            parent_did: None,
            delegation_depth: 0,
            signing_key,
        })
    }

    /// Sign arbitrary data with the agent's private key.
    pub fn sign(&self, data: &[u8]) -> Vec<u8> {
        self.signing_key.sign(data).to_bytes().to_vec()
    }

    /// Verify a signature against data using this identity's public key.
    pub fn verify(&self, data: &[u8], signature: &[u8]) -> bool {
        let Ok(sig_bytes) = <[u8; 64]>::try_from(signature) else {
            return false;
        };
        let sig = ed25519_dalek::Signature::from_bytes(&sig_bytes);
        self.public_key.verify(data, &sig).is_ok()
    }

    /// Delegate to a child agent with narrowed capabilities.
    ///
    /// The child's capabilities **must** be a subset of the parent's.
    /// Delegation depth is incremented; exceeding [`MAX_DELEGATION_DEPTH`]
    /// returns an error.
    pub fn delegate(&self, name: &str, capabilities: Vec<String>) -> Result<Self, IdentityError> {
        if self.delegation_depth >= MAX_DELEGATION_DEPTH {
            return Err(IdentityError::DelegationDepthExceeded {
                current: self.delegation_depth,
                max: MAX_DELEGATION_DEPTH,
            });
        }

        // Capabilities must be a subset of parent's
        for cap in &capabilities {
            if !self.capabilities.contains(cap) {
                return Err(IdentityError::CapabilityNotInParent {
                    capability: cap.clone(),
                });
            }
        }

        let signing_key = SigningKey::generate(&mut OsRng);
        let public_key = signing_key.verifying_key();

        Ok(Self {
            did: format!("did:agentmesh:{}", name),
            public_key,
            capabilities,
            parent_did: Some(self.did.clone()),
            delegation_depth: self.delegation_depth + 1,
            signing_key,
        })
    }

    /// Serialise the public portion of the identity to JSON.
    pub fn to_json(&self) -> Result<String, IdentityError> {
        let public = PublicIdentity {
            did: self.did.clone(),
            public_key: self.public_key.to_bytes().to_vec(),
            capabilities: self.capabilities.clone(),
        };
        serde_json::to_string(&public).map_err(IdentityError::Serialization)
    }

    /// Deserialise a public identity from JSON.
    ///
    /// The returned identity can verify signatures but cannot sign.
    pub fn from_json(json: &str) -> Result<PublicIdentity, IdentityError> {
        serde_json::from_str(json).map_err(IdentityError::Serialization)
    }
}

/// The public (verifiable) portion of an agent identity.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PublicIdentity {
    pub did: String,
    pub public_key: Vec<u8>,
    #[serde(default)]
    pub capabilities: Vec<String>,
}

impl PublicIdentity {
    /// Verify a signature using this public identity.
    pub fn verify(&self, data: &[u8], signature: &[u8]) -> bool {
        let Ok(key_bytes) = <[u8; 32]>::try_from(self.public_key.as_slice()) else {
            return false;
        };
        let Ok(sig_bytes) = <[u8; 64]>::try_from(signature) else {
            return false;
        };
        let Ok(verifying_key) = VerifyingKey::from_bytes(&key_bytes) else {
            return false;
        };
        let sig = ed25519_dalek::Signature::from_bytes(&sig_bytes);
        verifying_key.verify(data, &sig).is_ok()
    }
}

/// Errors returned by identity operations.
#[derive(Debug, thiserror::Error)]
pub enum IdentityError {
    #[error("serialization error: {0}")]
    Serialization(serde_json::Error),

    #[error("invalid input for {field}: {message}")]
    InvalidInput {
        field: &'static str,
        message: String,
    },

    #[error("base64 decoding failed: {0}")]
    Base64(String),

    #[error("operation requires a private key")]
    MissingPrivateKey,

    #[error("unsupported operation: {0}")]
    UnsupportedOperation(String),

    #[error("maximum delegation depth ({max}) exceeded (current depth: {current})")]
    DelegationDepthExceeded { current: u32, max: u32 },

    #[error("cannot delegate capability '{capability}' — not in parent's capabilities")]
    CapabilityNotInParent { capability: String },
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_generate_and_did() {
        let id = AgentIdentity::generate("test-agent", vec!["data.read".into()]).unwrap();
        assert_eq!(id.did, "did:agentmesh:test-agent");
        assert_eq!(id.capabilities, vec!["data.read"]);
    }

    #[test]
    fn test_sign_and_verify() {
        let id = AgentIdentity::generate("signer", vec![]).unwrap();
        let data = b"hello world";
        let sig = id.sign(data);
        assert!(id.verify(data, &sig));
        assert!(!id.verify(b"wrong data", &sig));
    }

    #[test]
    fn test_json_roundtrip() {
        let id = AgentIdentity::generate("json-agent", vec!["cap1".into()]).unwrap();
        let json = id.to_json().unwrap();
        let public = AgentIdentity::from_json(&json).unwrap();
        assert_eq!(public.did, "did:agentmesh:json-agent");
        assert_eq!(public.capabilities, vec!["cap1"]);

        // Public identity can verify signatures
        let sig = id.sign(b"payload");
        assert!(public.verify(b"payload", &sig));
    }

    #[test]
    fn test_bad_signature_rejected() {
        let id = AgentIdentity::generate("agent", vec![]).unwrap();
        assert!(!id.verify(b"data", &[0u8; 64]));
        assert!(!id.verify(b"data", &[0u8; 32])); // wrong length
    }

    #[test]
    fn test_multiple_identities_different_dids() {
        let id1 = AgentIdentity::generate("agent-1", vec![]).unwrap();
        let id2 = AgentIdentity::generate("agent-2", vec![]).unwrap();
        assert_ne!(id1.did, id2.did);
    }

    #[test]
    fn test_multiple_identities_different_key_pairs() {
        let id1 = AgentIdentity::generate("agent-a", vec![]).unwrap();
        let id2 = AgentIdentity::generate("agent-b", vec![]).unwrap();
        assert_ne!(id1.public_key.to_bytes(), id2.public_key.to_bytes());
    }

    #[test]
    fn test_sign_empty_data() {
        let id = AgentIdentity::generate("empty-signer", vec![]).unwrap();
        let sig = id.sign(b"");
        assert_eq!(sig.len(), 64);
        assert!(id.verify(b"", &sig));
    }

    #[test]
    fn test_cross_identity_verification_fails() {
        let id1 = AgentIdentity::generate("signer-1", vec![]).unwrap();
        let id2 = AgentIdentity::generate("signer-2", vec![]).unwrap();
        let sig = id1.sign(b"test data");
        // id2 should NOT verify a signature produced by id1
        assert!(!id2.verify(b"test data", &sig));
    }

    #[test]
    fn test_public_identity_from_json_verifies_signatures() {
        let id = AgentIdentity::generate("json-verify", vec!["read".into()]).unwrap();
        let json = id.to_json().unwrap();
        let public = AgentIdentity::from_json(&json).unwrap();
        let data = b"important payload";
        let sig = id.sign(data);
        assert!(public.verify(data, &sig));
        // Should fail with wrong data
        assert!(!public.verify(b"wrong data", &sig));
    }

    #[test]
    fn test_invalid_json_returns_error() {
        let result = AgentIdentity::from_json("not valid json {{{");
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            IdentityError::Serialization(_)
        ));
    }

    #[test]
    fn test_public_identity_empty_public_key_rejects() {
        let public = PublicIdentity {
            did: "did:agentmesh:test".to_string(),
            public_key: vec![], // empty
            capabilities: vec![],
        };
        assert!(!public.verify(b"data", &[0u8; 64]));
    }

    #[test]
    fn test_public_identity_oversize_public_key_rejects() {
        // Exercises the let-else on `<[u8; 32]>::try_from(public_key)`:
        // 33 bytes (one too many) must be rejected, not panic.
        let public = PublicIdentity {
            did: "did:agentmesh:test".to_string(),
            public_key: vec![0u8; 33],
            capabilities: vec![],
        };
        assert!(!public.verify(b"data", &[0u8; 64]));
    }

    #[test]
    fn test_public_identity_oversize_signature_rejects() {
        // Exercises the let-else on `<[u8; 64]>::try_from(signature)`.
        let id = AgentIdentity::generate("oversize-sig", vec![]).unwrap();
        let json = id.to_json().unwrap();
        let public = AgentIdentity::from_json(&json).unwrap();
        assert!(!public.verify(b"data", &[0u8; 65]));
        assert!(!public.verify(b"data", &[0u8; 63]));
        assert!(!public.verify(b"data", &[]));
    }

    #[test]
    fn test_capabilities_roundtrip_json() {
        let caps = vec![
            "data.read".to_string(),
            "data.write".to_string(),
            "admin".to_string(),
        ];
        let id = AgentIdentity::generate("cap-agent", caps.clone()).unwrap();
        let json = id.to_json().unwrap();
        let public = AgentIdentity::from_json(&json).unwrap();
        assert_eq!(public.capabilities, caps);
    }

    #[test]
    fn test_did_format() {
        let id = AgentIdentity::generate("my-agent", vec![]).unwrap();
        assert!(id.did.starts_with("did:agentmesh:"));
        assert_eq!(id.did, "did:agentmesh:my-agent");
    }

    // ------------------------------------------------------------------
    // Delegation tests (Issue #607)
    // ------------------------------------------------------------------

    #[test]
    fn test_delegate_creates_child_with_parent_did() {
        let parent =
            AgentIdentity::generate("parent", vec!["read".into(), "write".into()]).unwrap();
        let child = parent.delegate("child", vec!["read".into()]).unwrap();
        assert_eq!(child.parent_did, Some("did:agentmesh:parent".to_string()));
        assert_eq!(child.delegation_depth, 1);
        assert_eq!(child.capabilities, vec!["read"]);
    }

    #[test]
    fn test_delegate_narrows_capabilities() {
        let parent =
            AgentIdentity::generate("parent", vec!["read".into(), "write".into()]).unwrap();
        let child = parent.delegate("child", vec!["read".into()]).unwrap();
        assert!(!child.capabilities.contains(&"write".to_string()));
    }

    #[test]
    fn test_delegate_rejects_superset() {
        let parent = AgentIdentity::generate("parent", vec!["read".into()]).unwrap();
        let result = parent.delegate("child", vec!["read".into(), "admin".into()]);
        assert!(result.is_err());
        match result.unwrap_err() {
            IdentityError::CapabilityNotInParent { capability } => {
                assert_eq!(capability, "admin");
            }
            other => panic!("expected CapabilityNotInParent, got {:?}", other),
        }
    }

    #[test]
    fn test_delegate_depth_increments() {
        let root = AgentIdentity::generate("root", vec!["read".into()]).unwrap();
        let d1 = root.delegate("d1", vec!["read".into()]).unwrap();
        let d2 = d1.delegate("d2", vec!["read".into()]).unwrap();
        assert_eq!(d2.delegation_depth, 2);
        assert_eq!(d2.parent_did, Some("did:agentmesh:d1".to_string()));
    }

    #[test]
    fn test_delegate_max_depth_enforced() {
        let mut current = AgentIdentity::generate("root", vec!["read".into()]).unwrap();
        for i in 0..MAX_DELEGATION_DEPTH {
            current = current
                .delegate(&format!("child-{}", i), vec!["read".into()])
                .unwrap();
        }
        let result = current.delegate("one-too-many", vec!["read".into()]);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            IdentityError::DelegationDepthExceeded { .. }
        ));
    }

    #[test]
    fn test_delegate_child_has_own_keypair() {
        let parent = AgentIdentity::generate("parent", vec!["read".into()]).unwrap();
        let child = parent.delegate("child", vec!["read".into()]).unwrap();
        assert_ne!(parent.public_key.to_bytes(), child.public_key.to_bytes());
    }

    #[test]
    fn test_delegate_child_can_sign_and_verify() {
        let parent = AgentIdentity::generate("parent", vec!["read".into()]).unwrap();
        let child = parent.delegate("child", vec!["read".into()]).unwrap();
        let data = b"delegation payload";
        let sig = child.sign(data);
        assert!(child.verify(data, &sig));
        // Parent should NOT verify child's signature
        assert!(!parent.verify(data, &sig));
    }

    #[test]
    fn test_root_identity_has_no_parent() {
        let root = AgentIdentity::generate("root", vec![]).unwrap();
        assert!(root.parent_did.is_none());
        assert_eq!(root.delegation_depth, 0);
    }

    #[test]
    fn test_delegate_empty_capabilities_allowed() {
        let parent = AgentIdentity::generate("parent", vec!["read".into()]).unwrap();
        let child = parent.delegate("child", vec![]).unwrap();
        assert!(child.capabilities.is_empty());
        assert_eq!(child.delegation_depth, 1);
    }
}