1use rmcp::model::{CallToolResult, ContentBlock};
15
16use crate::core::policy::runtime::{self, ActivePolicy};
17
18mod release;
19pub(crate) use release::release_result;
20
21const EXEMPT_TOOLS: &[&str] = &["ctx", "ctx_session", "ctx_policy"];
24
25pub struct PolicyCheckResult {
26 pub blocked: bool,
27 pub policy_name: Option<String>,
28 pub message: Option<String>,
29}
30
31pub fn check_tool_access(tool_name: &str) -> PolicyCheckResult {
34 let check = evaluate_with_exemptions(
35 runtime::active().as_deref(),
36 tool_name,
37 std::env::var_os(runtime::REQUIRED_POLICY_ROOT_ENV).is_none(),
38 );
39 if check.blocked
40 && let Some(policy) = &check.policy_name
41 {
42 crate::core::events::emit_policy_violation(
43 policy,
44 tool_name,
45 "tool denied by context policy pack",
46 );
47 crate::core::audit_trail::record(crate::core::audit_trail::AuditEntryData {
48 agent_id: "unknown".into(),
49 tool: tool_name.to_string(),
50 action: None,
51 input_hash: String::new(),
52 output_tokens: 0,
53 role: policy.clone(),
54 event_type: crate::core::audit_trail::AuditEventType::ToolDenied,
55 });
56 }
57 check
58}
59
60#[cfg(test)]
62fn evaluate(active: Option<&ActivePolicy>, tool_name: &str) -> PolicyCheckResult {
63 evaluate_with_exemptions(active, tool_name, true)
64}
65
66fn evaluate_with_exemptions(
67 active: Option<&ActivePolicy>,
68 tool_name: &str,
69 allow_operator_recovery: bool,
70) -> PolicyCheckResult {
71 if allow_operator_recovery && EXEMPT_TOOLS.contains(&tool_name) {
74 return PolicyCheckResult {
75 blocked: false,
76 policy_name: None,
77 message: None,
78 };
79 }
80 let Some(active) = active else {
81 return PolicyCheckResult {
82 blocked: false,
83 policy_name: None,
84 message: None,
85 };
86 };
87 if active.tool_allowed(tool_name) {
88 return PolicyCheckResult {
89 blocked: false,
90 policy_name: Some(active.resolved.name.clone()),
91 message: None,
92 };
93 }
94 let policy_name = active.resolved.name.clone();
95 let detail = match &active.resolved.allow_tools {
96 Some(allow) => format!("Allowed tools: {}", allow.join(", ")),
97 None => format!("Denied tools: {}", active.resolved.deny_tools.join(", ")),
98 };
99 let message = format!(
100 "[POLICY DENIED] Tool '{tool_name}' is blocked by context policy pack '{policy_name}'.\n{detail}\n\
101 Adjust .lean-ctx/policy.toml or switch policy to proceed."
102 );
103 PolicyCheckResult {
104 blocked: true,
105 policy_name: Some(policy_name),
106 message: Some(message),
107 }
108}
109
110pub fn into_call_tool_result(check: &PolicyCheckResult) -> Option<CallToolResult> {
111 check.blocked.then(|| {
112 CallToolResult::success(vec![ContentBlock::text(
113 check
114 .message
115 .as_deref()
116 .unwrap_or("Blocked by context policy"),
117 )])
118 })
119}
120
121#[must_use]
126pub fn redact_result(text: &str) -> (String, usize) {
127 match runtime::active() {
128 Some(active) if !active.redaction.is_empty() => {
129 crate::core::redaction::redact_with_patterns(text, &active.redaction)
130 }
131 _ => (text.to_string(), 0),
132 }
133}
134
135pub fn protect_result(tool: &str, text: &str) -> Result<String, &'static str> {
139 let Some(active) = runtime::active() else {
140 return Ok(text.to_owned());
141 };
142 let outcome = crate::core::policy::content::evaluate_text(text, &active);
143 audit_filter(tool, &outcome.audit, outcome.blocked);
144 if outcome.blocked {
145 return Err("[POLICY BLOCKED] Content withheld by the active context policy.");
146 }
147 let mut text = outcome.text;
148 for warning in outcome.warnings {
149 let rendered = format!("[FILTER] {warning}");
150 if !text.lines().any(|line| line == rendered) {
151 text.push_str("\n\n");
152 text.push_str(&rendered);
153 }
154 }
155 Ok(text)
156}
157
158pub fn redact_model_text(text: &str) -> String {
164 let (policy_redacted, _) = redact_result(text);
165 let redacted = crate::core::redaction::redact_text_if_enabled(&policy_redacted);
166 crate::core::context_admission::admit_source(&redacted, "protocol:model-text", false)
167 .unwrap_or_else(|error| format!("[lean-ctx gateway: {error}]"))
168}
169
170pub fn audit_filter(tool: &str, audit: &[(String, usize)], blocked: bool) {
175 if audit.is_empty() {
176 return;
177 }
178 let policy =
179 runtime::active().map_or_else(|| "policy".to_string(), |a| a.resolved.name.clone());
180 let summary = audit
181 .iter()
182 .map(|(class, n)| format!("{class}×{n}"))
183 .collect::<Vec<_>>()
184 .join(", ");
185 if blocked {
186 crate::core::events::emit_policy_violation(
187 &policy,
188 tool,
189 &format!("input filter blocked: {summary}"),
190 );
191 }
192 crate::core::audit_trail::record(crate::core::audit_trail::AuditEntryData {
193 agent_id: "unknown".into(),
194 tool: tool.to_string(),
195 action: None,
196 input_hash: String::new(),
197 output_tokens: 0,
198 role: policy,
199 event_type: if blocked {
200 crate::core::audit_trail::AuditEventType::ToolDenied
201 } else {
202 crate::core::audit_trail::AuditEventType::SecretDetected
203 },
204 });
205}
206
207pub fn audit_egress(tool: &str, reason: &str) {
211 let policy =
212 runtime::active().map_or_else(|| "policy".to_string(), |a| a.resolved.name.clone());
213 crate::core::events::emit_policy_violation(&policy, tool, &format!("egress blocked: {reason}"));
214 crate::core::audit_trail::record(crate::core::audit_trail::AuditEntryData {
215 agent_id: "unknown".into(),
216 tool: tool.to_string(),
217 action: None,
218 input_hash: String::new(),
219 output_tokens: 0,
220 role: policy,
221 event_type: crate::core::audit_trail::AuditEventType::ToolDenied,
222 });
223}
224
225#[cfg(test)]
226mod tests {
227 use super::*;
228 use crate::core::policy::ResolvedPolicy;
229 use std::collections::BTreeMap;
230
231 fn active(allow: Option<Vec<&str>>, deny: Vec<&str>) -> ActivePolicy {
232 ActivePolicy::from_resolved(ResolvedPolicy {
233 name: "acme".into(),
234 version: "1.0.0".into(),
235 description: "t".into(),
236 chain: vec![],
237 default_read_mode: None,
238 allow_tools: allow.map(|a| a.into_iter().map(String::from).collect()),
239 deny_tools: deny.into_iter().map(String::from).collect(),
240 max_context_tokens: None,
241 audit_retention_days: None,
242 redaction: BTreeMap::new(),
243 filters: crate::core::policy::FilterRules::default(),
244 egress: crate::core::policy::EgressRules::default(),
245 routing: crate::core::policy::RoutingPolicyRules::default(),
246 budgets: crate::core::policy::BudgetRules::default(),
247 })
248 }
249
250 #[test]
251 fn no_pack_allows_everything() {
252 let r = evaluate(None, "ctx_shell");
253 assert!(!r.blocked);
254 }
255
256 #[test]
257 fn deny_tool_is_blocked_with_message() {
258 let p = active(None, vec!["ctx_url_read"]);
259 let r = evaluate(Some(&p), "ctx_url_read");
260 assert!(r.blocked);
261 assert_eq!(r.policy_name.as_deref(), Some("acme"));
262 assert!(r.message.unwrap().contains("[POLICY DENIED]"));
263 }
264
265 #[test]
266 fn allowlist_blocks_unlisted_tool() {
267 let p = active(Some(vec!["ctx_read"]), vec![]);
268 assert!(!evaluate(Some(&p), "ctx_read").blocked);
269 assert!(evaluate(Some(&p), "ctx_shell").blocked);
270 }
271
272 #[test]
273 fn exempt_tools_never_blocked_even_under_allowlist() {
274 let p = active(Some(vec!["ctx_read"]), vec![]);
277 for t in ["ctx", "ctx_session", "ctx_policy"] {
278 assert!(!evaluate(Some(&p), t).blocked, "{t} must be exempt");
279 }
280 }
281
282 #[test]
283 fn protected_clients_cannot_use_operator_recovery_exemptions() {
284 let p = active(Some(vec!["ctx_read"]), vec![]);
285 for tool in EXEMPT_TOOLS {
286 assert!(evaluate_with_exemptions(Some(&p), tool, false).blocked);
287 }
288 assert!(!evaluate_with_exemptions(Some(&p), "ctx_read", false).blocked);
289 }
290
291 #[test]
292 fn into_result_renders_denial() {
293 let p = active(None, vec!["ctx_shell"]);
294 let r = evaluate(Some(&p), "ctx_shell");
295 assert!(into_call_tool_result(&r).is_some());
296 let allowed = evaluate(None, "ctx_shell");
297 assert!(into_call_tool_result(&allowed).is_none());
298 }
299
300 #[test]
305 fn global_active_drives_allow_and_redaction() {
306 let mut redaction = BTreeMap::new();
307 redaction.insert("employee_id".to_string(), r"EMP-\d{4}".to_string());
308 {
309 let _policy = runtime::TestPolicyOverride::set(Some(ResolvedPolicy {
310 name: "itest".into(),
311 version: "1.0.0".into(),
312 description: "t".into(),
313 chain: vec![],
314 default_read_mode: Some("map".into()),
315 allow_tools: None,
316 deny_tools: vec!["ctx_url_read".into()],
317 max_context_tokens: Some(5_000),
318 audit_retention_days: None,
319 redaction,
320 filters: crate::core::policy::FilterRules::default(),
321 egress: crate::core::policy::EgressRules::default(),
322 routing: crate::core::policy::RoutingPolicyRules::default(),
323 budgets: crate::core::policy::BudgetRules::default(),
324 }));
325
326 assert!(!check_tool_access("ctx_read").blocked);
327 assert!(!check_tool_access("ctx_session").blocked, "exempt tool");
328 let (out, hits) = redact_result("contact EMP-1234 today");
329 assert_eq!(hits, 1);
330 assert!(out.contains("[REDACTED:employee_id]"));
331 assert!(out.starts_with("contact "));
332 assert!(out.ends_with(" today"));
333 }
334 assert!(
335 !check_tool_access("ctx_url_read").blocked,
336 "no pack → allow"
337 );
338 assert_eq!(redact_result("contact EMP-1234 today").1, 0);
339 }
340}