trusty_code/rbac/mod.rs
1//! Role-based access control for tool execution in tcode.
2//!
3//! Why: tcode exposes tools over multiple transports (CLI, API, TUI). Some
4//! tools (memory writes, shell exec) are unsafe for arbitrary callers while
5//! still being essential for the trusted operator. RBAC gates tool execution
6//! on a small, totally-ordered tier ladder so the same agent definition can be
7//! safely exposed across transports without per-deployment code branches.
8//! What: Defines `ServiceTier` (re-exported from `tools::traits`),
9//! `UserIdentity` (the per-request principal), and `filter_tools_for_user`.
10//! Test: See unit tests below — covers default identity, every tier × restriction
11//! combination, and the filter helper.
12
13use std::sync::Arc;
14
15use serde::{Deserialize, Serialize};
16
17pub use crate::tools::traits::ServiceTier;
18use crate::tools::traits::ToolExecutor;
19
20/// Per-request principal carried from transport into tool dispatch.
21///
22/// Why: Every inbound request (CLI, API call, TUI keystroke) arrives with some
23/// notion of "who is asking". Modeling it as a single `UserIdentity` value
24/// means the tool dispatch layer doesn't have to care which transport produced
25/// the request, and unit tests can construct one without spinning up a transport.
26/// What: `id` is the transport-native identifier; `name` is a human-readable
27/// label for logging; `tier` is the privilege bucket enforced by `can_access_tier`.
28/// Test: `default_is_local_cli_all`, plus indirect coverage via `can_access_tier` cases.
29#[derive(Debug, Clone, Deserialize, Serialize)]
30pub struct UserIdentity {
31 /// Transport-native identifier (e.g. `"cli"`, `"api"`, Slack `"U…"`).
32 pub id: String,
33 /// Human-readable label, used only for logging.
34 pub name: String,
35 /// Privilege tier enforced at dispatch.
36 pub tier: ServiceTier,
37}
38
39impl Default for UserIdentity {
40 fn default() -> Self {
41 Self {
42 id: "cli".into(),
43 name: "local".into(),
44 tier: ServiceTier::All,
45 }
46 }
47}
48
49impl UserIdentity {
50 /// Construct a new identity with a given tier.
51 ///
52 /// Why: Transport layers need to mint identities with custom IDs per
53 /// inbound request without hand-rolling the struct literal.
54 /// What: Helper constructor; no validation beyond moving fields.
55 /// Test: `new_constructs_with_fields`.
56 pub fn new(id: impl Into<String>, name: impl Into<String>, tier: ServiceTier) -> Self {
57 Self {
58 id: id.into(),
59 name: name.into(),
60 tier,
61 }
62 }
63
64 /// Whether this identity may invoke a tool whose `restricted_tiers` list
65 /// is `restricted`.
66 ///
67 /// Why: Tools express restrictions as an *inverted* list — they name the
68 /// tiers that are NOT allowed to call them — because that reads naturally
69 /// in config files (`restricted_tiers = ["read_only"]` blocks one tier).
70 /// An empty restriction list always permits access.
71 /// What: Returns `true` if `restricted` is empty, or if `self.tier` is not
72 /// present in `restricted`. Check is membership-based, NOT ordering-based.
73 /// Test: `can_access_tier_empty_always_allows`, `can_access_tier_blocks_listed_tier`,
74 /// `can_access_tier_allows_other_tiers`.
75 pub fn can_access_tier(&self, restricted: &[ServiceTier]) -> bool {
76 restricted.is_empty() || !restricted.contains(&self.tier)
77 }
78}
79
80/// Filter a list of tools to those callable by `user`.
81///
82/// Why: The LLM should not even see tools it isn't allowed to call — presenting
83/// them and then denying at dispatch wastes context and invites retries.
84/// What: Drops any tool whose `restricted_tiers()` blocks `user.tier`. Tools
85/// that haven't opted into RBAC (empty `restricted_tiers`) pass through unchanged.
86/// Test: Exercised in `ToolRegistry::filter_tools_for_user` tests.
87pub fn filter_tools_for_user(
88 tools: &[Arc<dyn ToolExecutor>],
89 user: &UserIdentity,
90) -> Vec<Arc<dyn ToolExecutor>> {
91 tools
92 .iter()
93 .filter(|t| user.can_access_tier(t.restricted_tiers()))
94 .cloned()
95 .collect()
96}
97
98// ── Tests ─────────────────────────────────────────────────────────────────────
99
100#[cfg(test)]
101mod tests {
102 use super::*;
103
104 #[test]
105 fn default_service_tier_is_all() {
106 assert_eq!(ServiceTier::default(), ServiceTier::All);
107 }
108
109 #[test]
110 fn service_tier_serializes_snake_case() {
111 let s = serde_json::to_string(&ServiceTier::ReadOnly).expect("serialize");
112 assert_eq!(s, "\"read_only\"");
113 let r: ServiceTier = serde_json::from_str("\"analytics\"").expect("deserialize");
114 assert_eq!(r, ServiceTier::Analytics);
115 }
116
117 #[test]
118 fn default_identity_is_local_cli_all() {
119 let u = UserIdentity::default();
120 assert_eq!(u.id, "cli");
121 assert_eq!(u.name, "local");
122 assert_eq!(u.tier, ServiceTier::All);
123 }
124
125 #[test]
126 fn new_constructs_with_fields() {
127 let u = UserIdentity::new("U123", "alice", ServiceTier::Analytics);
128 assert_eq!(u.id, "U123");
129 assert_eq!(u.name, "alice");
130 assert_eq!(u.tier, ServiceTier::Analytics);
131 }
132
133 #[test]
134 fn can_access_tier_empty_always_allows() {
135 let u = UserIdentity::new("x", "x", ServiceTier::ReadOnly);
136 assert!(u.can_access_tier(&[]));
137 let u = UserIdentity::new("x", "x", ServiceTier::All);
138 assert!(u.can_access_tier(&[]));
139 }
140
141 #[test]
142 fn can_access_tier_blocks_listed_tier() {
143 let u = UserIdentity::new("x", "x", ServiceTier::ReadOnly);
144 assert!(!u.can_access_tier(&[ServiceTier::ReadOnly]));
145 assert!(!u.can_access_tier(&[ServiceTier::All, ServiceTier::ReadOnly]));
146 }
147
148 #[test]
149 fn can_access_tier_allows_other_tiers() {
150 // `All` is not in the blocklist — allowed even though `ReadOnly` is named.
151 let u = UserIdentity::new("x", "x", ServiceTier::All);
152 assert!(u.can_access_tier(&[ServiceTier::ReadOnly]));
153 let u = UserIdentity::new("x", "x", ServiceTier::Analytics);
154 assert!(u.can_access_tier(&[ServiceTier::ReadOnly]));
155 assert!(!u.can_access_tier(&[ServiceTier::Analytics]));
156 }
157
158 #[test]
159 fn can_access_tier_no_implicit_ordering() {
160 // Restrictions are explicit memberships, not ordered comparisons.
161 let u = UserIdentity::new("x", "x", ServiceTier::ReadOnly);
162 assert!(u.can_access_tier(&[ServiceTier::Analytics]));
163 }
164}