forked from microsoft/agent-governance-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
186 lines (162 loc) · 5.47 KB
/
lib.rs
File metadata and controls
186 lines (162 loc) · 5.47 KB
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//! # AgentMesh Rust SDK
//!
//! Rust SDK for the [Agent Governance Toolkit](https://github.com/microsoft/agent-governance-toolkit)
//! — policy evaluation, trust scoring, hash-chain audit logging, and Ed25519 agent identity.
//!
//! ## Quick Start
//!
//! ```rust
//! use agentmesh::AgentMeshClient;
//!
//! let client = AgentMeshClient::new("my-agent")
//! .expect("failed to create client");
//!
//! let result = client.execute_with_governance("data.read", None);
//! assert!(result.allowed);
//! ```
pub mod audit;
pub mod identity;
pub mod policy;
pub mod trust;
pub mod types;
pub use audit::AuditLogger;
pub use identity::{AgentIdentity, PublicIdentity};
pub use policy::{PolicyEngine, PolicyError};
pub use trust::{TrustConfig, TrustManager};
pub use types::{
AuditEntry, AuditFilter, CandidateDecision, ConflictResolutionStrategy, GovernanceResult,
PolicyDecision, PolicyScope, ResolutionResult, TrustScore, TrustTier,
};
use std::collections::HashMap;
/// Unified governance client combining identity, policy, trust, and audit.
///
/// This is the primary entry point for most users.
pub struct AgentMeshClient {
pub identity: AgentIdentity,
pub trust: TrustManager,
pub policy: PolicyEngine,
pub audit: AuditLogger,
}
/// Builder options for [`AgentMeshClient`].
pub struct ClientOptions {
pub capabilities: Vec<String>,
pub trust_config: Option<TrustConfig>,
pub policy_yaml: Option<String>,
}
impl Default for ClientOptions {
fn default() -> Self {
Self {
capabilities: Vec::new(),
trust_config: None,
policy_yaml: None,
}
}
}
impl AgentMeshClient {
/// Create a new client with default configuration.
pub fn new(agent_id: &str) -> Result<Self, ClientError> {
Self::with_options(agent_id, ClientOptions::default())
}
/// Create a new client with custom options.
pub fn with_options(agent_id: &str, opts: ClientOptions) -> Result<Self, ClientError> {
let identity = AgentIdentity::generate(agent_id, opts.capabilities)
.map_err(ClientError::Identity)?;
let trust_config = opts.trust_config.unwrap_or_default();
let trust = TrustManager::new(trust_config);
let policy = PolicyEngine::new();
if let Some(yaml) = &opts.policy_yaml {
policy.load_from_yaml(yaml).map_err(ClientError::Policy)?;
}
Ok(Self {
identity,
trust,
policy,
audit: AuditLogger::new(),
})
}
/// Run an action through the full governance pipeline:
/// policy → audit → trust update.
pub fn execute_with_governance(
&self,
action: &str,
context: Option<&HashMap<String, serde_yaml::Value>>,
) -> GovernanceResult {
let decision = self.policy.evaluate(action, context);
let audit_entry = self.audit.log(&self.identity.did, action, decision.label());
let trust_score = self.trust.get_trust_score(&self.identity.did);
match &decision {
PolicyDecision::Allow => self.trust.record_success(&self.identity.did),
PolicyDecision::Deny(_) => self.trust.record_failure(&self.identity.did),
_ => {}
}
GovernanceResult {
allowed: decision.is_allowed(),
decision,
trust_score,
audit_entry,
}
}
}
/// Errors returned by [`AgentMeshClient`] construction.
#[derive(Debug, thiserror::Error)]
pub enum ClientError {
#[error("identity error: {0}")]
Identity(identity::IdentityError),
#[error("policy error: {0}")]
Policy(policy::PolicyError),
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_client_default_allows_everything() {
let client = AgentMeshClient::new("test-agent").unwrap();
let result = client.execute_with_governance("anything", None);
assert!(result.allowed);
assert_eq!(result.decision, PolicyDecision::Allow);
}
#[test]
fn test_client_with_policy() {
let yaml = r#"
version: "1.0"
agent: test
policies:
- name: gate
type: capability
allowed_actions:
- "data.read"
denied_actions:
- "shell:*"
"#;
let opts = ClientOptions {
policy_yaml: Some(yaml.to_string()),
..Default::default()
};
let client = AgentMeshClient::with_options("test", opts).unwrap();
let r1 = client.execute_with_governance("data.read", None);
assert!(r1.allowed);
let r2 = client.execute_with_governance("shell:rm", None);
assert!(!r2.allowed);
assert!(matches!(r2.decision, PolicyDecision::Deny(_)));
}
#[test]
fn test_governance_updates_trust() {
let client = AgentMeshClient::new("trust-test").unwrap();
let did = client.identity.did.clone();
client.execute_with_governance("action1", None); // allow → +trust
client.execute_with_governance("action2", None); // allow → +trust
let score = client.trust.get_trust_score(&did);
assert!(score.score > 500);
}
#[test]
fn test_governance_creates_audit_chain() {
let client = AgentMeshClient::new("audit-test").unwrap();
client.execute_with_governance("a", None);
client.execute_with_governance("b", None);
client.execute_with_governance("c", None);
assert!(client.audit.verify());
assert_eq!(client.audit.entries().len(), 3);
}
}