1use crate::{ActionReviewTrigger, PathAccess, ProcessActionIntent};
9use merry_core::{PendingToolCall, ToolName};
10
11const REQUEST_PERMISSIONS_TOOL_NAME: &str = "request_permissions";
12const MAX_PERMISSION_REASON_BYTES: usize = 2048;
13pub const MAX_PERMISSION_USER_NOTE_BYTES: usize = 2048;
15const MAX_REVIEW_RULES_PER_CATEGORY: usize = 64;
16const MAX_REVIEW_RULE_BYTES: usize = 512;
17const DEFAULT_PERMISSION_STDOUT_LIMIT_BYTES: usize = 64 * 1024;
18const DEFAULT_PERMISSION_STDERR_LIMIT_BYTES: usize = 64 * 1024;
19mod channel;
20mod decision;
21pub(crate) mod environment;
22mod guidance;
23mod input;
24mod payload;
25mod request_json;
26mod review;
27
28pub use channel::{
29 ChannelPermissionAdmissionSource, PermissionReviewRequest, PermissionReviewResponse,
30 PermissionReviewResponseError,
31};
32pub use decision::{
33 HostFallbackReason, PermissionActor, PermissionAdmissionContext, PermissionAdmissionDecision,
34 PermissionAdmissionError, PermissionAdmissionFuture, PermissionAdmissionResult,
35 PermissionAdmissionReview, PermissionAdmissionReviewSource, PermissionAdmissionSource,
36 PermissionReviewRisk, PermissionUserAuthorization,
37};
38pub(crate) use environment::{PermissionReviewEnvironmentMetadata, probe_environment_metadata};
39pub(crate) use guidance::{
40 MAX_RECORDED_PERMISSION_DECISIONS, RecordedPermissionDecision,
41 render_workspace_review_note_json_line,
42};
43pub use guidance::{
44 MAX_SESSION_REVIEW_GUIDANCE, ReviewGuidanceDecision, ReviewGuidanceEntry, ReviewGuidanceId,
45 SessionReviewGuidance, WorkspaceReviewNotes,
46};
47pub(crate) use input::{
48 RequestedCapabilitiesInput, normalize_requested_capabilities, normalize_requested_path,
49 permission_reason_schema_for_schemars, permission_request_from_call,
50 permission_request_from_process_call, process_cwd_schema_for_schemars,
51 requested_capabilities_schema_for_schemars, validate_optional_reason,
52 validate_optional_user_note,
53};
54pub use input::{
55 parse_permission_request, request_permissions_tool, validate_permission_user_note,
56};
57pub(crate) use payload::{
58 permission_blocked_outcome, permission_denied_outcome, permission_invalid_arguments_outcome,
59 permission_review_error_outcome,
60};
61pub(crate) use request_json::permission_request_fingerprint_json;
62pub(crate) use review::ModelBackedPermissionAdmissionSource;
63
64#[derive(Debug, Clone, Default, PartialEq, Eq)]
67pub struct ActivePermissionGrants {
68 grants: Vec<crate::SessionPermissionGrant>,
69 review_guidance: Vec<ReviewGuidanceEntry>,
70}
71
72impl ActivePermissionGrants {
73 #[must_use]
75 pub fn new(
76 grants: Vec<crate::SessionPermissionGrant>,
77 review_guidance: Vec<ReviewGuidanceEntry>,
78 ) -> Self {
79 Self {
80 grants,
81 review_guidance,
82 }
83 }
84
85 #[must_use]
87 pub fn grants(&self) -> &[crate::SessionPermissionGrant] {
88 &self.grants
89 }
90
91 #[must_use]
93 pub fn review_guidance(&self) -> &[ReviewGuidanceEntry] {
94 &self.review_guidance
95 }
96
97 #[must_use]
99 pub fn has_elevated_network(&self) -> bool {
100 self.grants.iter().any(|grant| {
101 matches!(
102 grant.kind(),
103 crate::SessionPermissionGrantKind::Network
104 | crate::SessionPermissionGrantKind::NetworkDomain(_)
105 )
106 })
107 }
108
109 #[must_use]
111 pub fn has_elevated_host_integrations(&self) -> bool {
112 self.grants.iter().any(|grant| {
113 matches!(
114 grant.kind(),
115 crate::SessionPermissionGrantKind::HostIntegration(_)
116 )
117 })
118 }
119
120 #[must_use]
122 pub fn is_empty(&self) -> bool {
123 self.grants.is_empty() && self.review_guidance.is_empty()
124 }
125}
126
127#[derive(Debug, Clone, Default, PartialEq, Eq)]
132pub struct PermissionReviewRules {
133 environment: Vec<String>,
134 allow: Vec<String>,
135 soft_deny: Vec<String>,
136 hard_deny: Vec<String>,
137}
138
139impl PermissionReviewRules {
140 pub fn new(
142 environment: Vec<String>,
143 allow: Vec<String>,
144 soft_deny: Vec<String>,
145 hard_deny: Vec<String>,
146 ) -> Result<Self, PermissionAdmissionError> {
147 Ok(Self {
148 environment: validate_review_rule_list("environment", environment)?,
149 allow: validate_review_rule_list("allow", allow)?,
150 soft_deny: validate_review_rule_list("soft_deny", soft_deny)?,
151 hard_deny: validate_review_rule_list("hard_deny", hard_deny)?,
152 })
153 }
154
155 #[must_use]
157 pub fn is_empty(&self) -> bool {
158 self.environment.is_empty()
159 && self.allow.is_empty()
160 && self.soft_deny.is_empty()
161 && self.hard_deny.is_empty()
162 }
163
164 #[must_use]
166 pub fn environment(&self) -> &[String] {
167 &self.environment
168 }
169
170 #[must_use]
172 pub fn allow(&self) -> &[String] {
173 &self.allow
174 }
175
176 #[must_use]
178 pub fn soft_deny(&self) -> &[String] {
179 &self.soft_deny
180 }
181
182 #[must_use]
184 pub fn hard_deny(&self) -> &[String] {
185 &self.hard_deny
186 }
187}
188
189fn validate_review_rule_list(
190 category: &str,
191 entries: Vec<String>,
192) -> Result<Vec<String>, PermissionAdmissionError> {
193 if entries.len() > MAX_REVIEW_RULES_PER_CATEGORY {
194 return Err(PermissionAdmissionError::InvalidArguments {
195 message: format!(
196 "permissions.review.{category} may contain at most {MAX_REVIEW_RULES_PER_CATEGORY} entries"
197 ),
198 });
199 }
200 let mut normalized = Vec::with_capacity(entries.len());
201 for entry in entries {
202 let trimmed = entry.trim();
203 if trimmed.is_empty() {
204 return Err(PermissionAdmissionError::InvalidArguments {
205 message: format!("permissions.review.{category} entries must not be blank"),
206 });
207 }
208 if trimmed.len() > MAX_REVIEW_RULE_BYTES {
209 return Err(PermissionAdmissionError::InvalidArguments {
210 message: format!(
211 "permissions.review.{category} entry exceeds {MAX_REVIEW_RULE_BYTES} bytes"
212 ),
213 });
214 }
215 if trimmed.chars().any(char::is_control) {
216 return Err(PermissionAdmissionError::InvalidArguments {
217 message: format!(
218 "permissions.review.{category} entries must not contain control characters"
219 ),
220 });
221 }
222 normalized.push(trimmed.to_owned());
223 }
224 Ok(normalized)
225}
226
227#[derive(Debug, Clone, Copy, PartialEq, Eq)]
229pub enum RuntimeTrustLevel {
230 Agent,
232 TrustedSdk,
234}
235
236#[derive(Debug, Clone, Copy, PartialEq, Eq)]
238pub enum PermissionReviewMode {
239 DefaultForTrust,
241 Required,
243 HostDecisionOnly,
245 ModelThenHostFallback,
248 FullyTrusted,
251 DenyAll,
254}
255
256impl PermissionReviewMode {
257 pub(crate) const fn is_fully_trusted(self) -> bool {
259 matches!(self, Self::FullyTrusted)
260 }
261
262 pub(crate) const fn is_deny_all(self) -> bool {
264 matches!(self, Self::DenyAll)
265 }
266
267 pub(crate) fn requires_model_review(self, trust_level: RuntimeTrustLevel) -> bool {
268 match self {
269 Self::DefaultForTrust => trust_level == RuntimeTrustLevel::Agent,
270 Self::Required => true,
271 Self::HostDecisionOnly => false,
272 Self::ModelThenHostFallback => true,
273 Self::FullyTrusted | Self::DenyAll => false,
274 }
275 }
276}
277
278#[derive(Debug, Clone, PartialEq, Eq)]
280pub enum RequestedCapability {
281 Network,
283 NetworkDomain(String),
285 Path(RequestedPathCapability),
287 HostIntegration(HostIntegration),
290}
291
292#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
298pub enum HostIntegration {
299 SshAgent,
301 SessionBus,
303 GpgAgent,
305}
306
307impl HostIntegration {
308 #[must_use]
310 pub const fn as_str(self) -> &'static str {
311 match self {
312 Self::SshAgent => "ssh-agent",
313 Self::SessionBus => "dbus",
314 Self::GpgAgent => "gpg-agent",
315 }
316 }
317}
318
319#[derive(Debug, Clone, PartialEq, Eq)]
321pub struct RequestedPathCapability {
322 path: String,
323 access: PathAccess,
324}
325
326impl RequestedPathCapability {
327 pub fn new(path: String, access: PathAccess) -> Result<Self, PermissionAdmissionError> {
328 let path = normalize_requested_path(&path)?;
329 Ok(Self { path, access })
330 }
331
332 #[must_use]
333 pub fn path(&self) -> &str {
334 &self.path
335 }
336
337 #[must_use]
338 pub const fn access(&self) -> PathAccess {
339 self.access
340 }
341}
342
343#[derive(Debug, Clone, PartialEq, Eq)]
345pub enum PermissionedAction {
346 Process(ProcessActionIntent),
348 FileRead { path: String },
350 FileWrite { paths: Vec<String> },
352 NetworkUrl {
354 tool: String,
356 url: String,
358 host: String,
360 },
361}
362
363impl PermissionedAction {
364 #[must_use]
365 pub fn kind(&self) -> &'static str {
366 match self {
367 Self::Process(_) => "process",
368 Self::FileRead { .. } => "file_read",
369 Self::FileWrite { .. } => "file_write",
370 Self::NetworkUrl { .. } => "network_url",
371 }
372 }
373
374 #[must_use]
375 pub fn summary(&self) -> String {
376 match self {
377 Self::Process(intent) => intent.summary().to_owned(),
378 Self::FileRead { path } => format!("read {path}"),
379 Self::FileWrite { paths } => format!("write {}", paths.join(", ")),
380 Self::NetworkUrl { tool, url, .. } => format!("{tool} {url}"),
381 }
382 }
383}
384
385#[derive(Debug, Clone, PartialEq, Eq)]
387pub struct PermissionRequest {
388 tool_call_id: merry_core::ToolCallId,
389 tool_name: ToolName,
390 reason: Option<String>,
391 requested: Vec<RequestedCapability>,
392 action: PermissionedAction,
393 review_context: Vec<PermissionReviewContextEntry>,
394 review_only: bool,
395 protected_target: bool,
396 triggers: Vec<ActionReviewTrigger>,
397}
398
399impl PermissionRequest {
400 pub(crate) fn new(
401 call: &PendingToolCall,
402 reason: Option<String>,
403 requested: Vec<RequestedCapability>,
404 action: PermissionedAction,
405 review_context: Vec<PermissionReviewContextEntry>,
406 ) -> Result<Self, PermissionAdmissionError> {
407 if requested.is_empty() {
408 return Err(PermissionAdmissionError::InvalidArguments {
409 message: "request_permissions requires at least one requested capability"
410 .to_owned(),
411 });
412 }
413 if let Some(reason) = reason.as_deref() {
414 validate_optional_reason(reason)?;
415 }
416
417 let requested = normalize_requested_capabilities(requested)?;
418 let triggers = match &action {
419 PermissionedAction::Process(intent) => {
420 crate::process::classify_process_action_review_triggers(intent)
421 }
422 PermissionedAction::FileRead { .. }
423 | PermissionedAction::FileWrite { .. }
424 | PermissionedAction::NetworkUrl { .. } => Vec::new(),
425 };
426
427 Ok(Self {
428 tool_call_id: call.id().clone(),
429 tool_name: call.name().clone(),
430 reason,
431 requested,
432 action,
433 review_context,
434 review_only: false,
435 protected_target: false,
436 triggers,
437 })
438 }
439
440 pub fn for_network_url(
443 call: &PendingToolCall,
444 tool: impl Into<String>,
445 url: impl Into<String>,
446 host: impl Into<String>,
447 reason: Option<String>,
448 ) -> Result<Self, PermissionAdmissionError> {
449 let host = host.into();
450 Self::new(
451 call,
452 reason,
453 vec![RequestedCapability::NetworkDomain(host.clone())],
454 PermissionedAction::NetworkUrl {
455 tool: tool.into(),
456 url: url.into(),
457 host,
458 },
459 Vec::new(),
460 )
461 }
462
463 #[must_use]
466 pub(crate) const fn with_protected_target(mut self) -> Self {
467 self.protected_target = true;
468 self
469 }
470
471 pub(crate) fn for_action_review(
477 call: &PendingToolCall,
478 reason: impl Into<String>,
479 action: PermissionedAction,
480 review_context: Vec<PermissionReviewContextEntry>,
481 triggers: Vec<ActionReviewTrigger>,
482 ) -> Self {
483 Self {
484 tool_call_id: call.id().clone(),
485 tool_name: call.name().clone(),
486 reason: Some(reason.into()),
487 requested: Vec::new(),
488 action,
489 review_context,
490 review_only: true,
491 protected_target: false,
492 triggers,
493 }
494 }
495
496 #[must_use]
497 pub fn tool_call_id(&self) -> &merry_core::ToolCallId {
498 &self.tool_call_id
499 }
500
501 #[must_use]
502 pub fn tool_name(&self) -> &ToolName {
503 &self.tool_name
504 }
505
506 #[must_use]
507 pub fn reason(&self) -> Option<&str> {
508 self.reason.as_deref()
509 }
510
511 #[must_use]
512 pub fn requested(&self) -> &[RequestedCapability] {
513 &self.requested
514 }
515
516 #[must_use]
518 pub fn triggers(&self) -> &[ActionReviewTrigger] {
519 &self.triggers
520 }
521
522 #[must_use]
529 pub fn allows_session_scope(&self) -> bool {
530 if self.protected_target {
531 return false;
532 }
533 if self
534 .triggers
535 .iter()
536 .any(|trigger| !trigger.is_session_grantable())
537 {
538 return false;
539 }
540 if self.requested.iter().any(|capability| {
541 matches!(
542 capability,
543 RequestedCapability::Path(path) if is_git_metadata_path_str(path.path())
544 )
545 }) {
546 return false;
547 }
548 !self.requested.is_empty() || !self.triggers.is_empty()
549 }
550
551 #[must_use]
559 pub fn allows_workspace_persistence(&self) -> bool {
560 if !self.allows_session_scope()
561 || self.review_only
562 || !self.triggers.is_empty()
563 || self.requested.is_empty()
564 {
565 return false;
566 }
567 self.requested.iter().all(|capability| match capability {
568 RequestedCapability::Network => true,
569 RequestedCapability::NetworkDomain(domain) => {
570 !crate::is_explicit_local_network_host(domain)
571 }
572 RequestedCapability::Path(path) => {
573 path.access() != PathAccess::Deny && !is_git_metadata_path_str(path.path())
574 }
575 RequestedCapability::HostIntegration(_) => false,
576 })
577 }
578
579 #[must_use]
586 pub fn allows_workspace_persistence_for_fallback(
587 &self,
588 fallback_reason: Option<&HostFallbackReason>,
589 ) -> bool {
590 let is_critical = matches!(
591 fallback_reason,
592 Some(HostFallbackReason::ModelDenied(review))
593 if review.risk() == PermissionReviewRisk::Critical
594 );
595 !is_critical && self.allows_workspace_persistence()
596 }
597
598 #[must_use]
601 pub fn is_high_risk(&self) -> bool {
602 self.protected_target
603 || self.triggers.iter().any(ActionReviewTrigger::is_high_risk)
604 || self.requested.iter().any(|capability| {
605 matches!(capability, RequestedCapability::HostIntegration(_))
606 || matches!(
607 capability,
608 RequestedCapability::Path(path) if is_git_metadata_path_str(path.path())
609 )
610 })
611 }
612
613 #[must_use]
615 pub fn requests_network(&self) -> bool {
616 self.requested
617 .iter()
618 .any(|capability| matches!(capability, RequestedCapability::Network))
619 }
620
621 #[must_use]
624 pub const fn is_protected_target(&self) -> bool {
625 self.protected_target
626 }
627
628 #[must_use]
631 pub fn is_action_review(&self) -> bool {
632 self.review_only
633 }
634
635 #[must_use]
636 pub fn action(&self) -> &PermissionedAction {
637 &self.action
638 }
639
640 #[must_use]
641 pub(crate) fn review_context(&self) -> &[PermissionReviewContextEntry] {
642 &self.review_context
643 }
644
645 #[must_use]
647 pub fn fingerprint(&self) -> String {
648 crate::process::stable_process_input_fingerprint(
649 permission_request_fingerprint_json(self)
650 .to_string()
651 .as_bytes(),
652 )
653 }
654
655 #[must_use]
657 pub fn approval_id(&self) -> String {
658 format!("{}:{}", self.tool_call_id(), self.fingerprint())
659 }
660}
661
662#[derive(Debug, Clone, PartialEq, Eq)]
663pub(crate) struct PermissionReviewContextEntry {
664 role: &'static str,
665 text: String,
666}
667
668impl PermissionReviewContextEntry {
669 pub(crate) fn new(role: &'static str, text: String) -> Self {
670 Self { role, text }
671 }
672
673 fn role(&self) -> &'static str {
674 self.role
675 }
676
677 fn text(&self) -> &str {
678 &self.text
679 }
680}
681
682fn is_git_metadata_path_str(path: &str) -> bool {
683 crate::is_git_metadata_path(std::path::Path::new(path))
684}
685
686#[cfg(test)]
687mod tests;