Skip to main content

merry_runtime/
permission.rs

1//! Runtime-owned permission request and approval review primitives.
2//!
3//! Permission requests wrap an exact planned action and its minimum capabilities.
4//! A process may declare known capabilities before execution; a failed sandboxed
5//! action may instead request capabilities discovered from its durable result.
6//! Runtime owns admission and executes the exact process action after approval.
7
8use 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;
13/// Maximum UTF-8 byte length accepted for a human-supplied permission review note.
14pub 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/// Point-in-time snapshot of all active session-scoped permission grants and
65/// user-authored review guidance retained by a runtime session.
66#[derive(Debug, Clone, Default, PartialEq, Eq)]
67pub struct ActivePermissionGrants {
68    grants: Vec<crate::SessionPermissionGrant>,
69    review_guidance: Vec<ReviewGuidanceEntry>,
70}
71
72impl ActivePermissionGrants {
73    /// Creates an active permission snapshot from session grants and review notes.
74    #[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    /// Returns all active revocable session capability grants.
86    #[must_use]
87    pub fn grants(&self) -> &[crate::SessionPermissionGrant] {
88        &self.grants
89    }
90
91    /// Returns all active revocable session review guidance entries.
92    #[must_use]
93    pub fn review_guidance(&self) -> &[ReviewGuidanceEntry] {
94        &self.review_guidance
95    }
96
97    /// Returns whether outbound network access is actively granted in this session.
98    #[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    /// Returns whether any host integration is actively granted in this session.
110    #[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    /// Returns whether no session grants or session review notes are active.
121    #[must_use]
122    pub fn is_empty(&self) -> bool {
123        self.grants.is_empty() && self.review_guidance.is_empty()
124    }
125}
126
127/// User-trusted custom rules and environment notes for AI permission review.
128///
129/// Sourced exclusively from trusted global configuration (never project-local
130/// hidden files) so a repository cannot silently relax its own review rules.
131#[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    /// Constructs validated reviewer rules from global configuration lists.
141    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    /// Returns whether all four rule lists are empty.
156    #[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    /// Returns trusted environment context entries.
165    #[must_use]
166    pub fn environment(&self) -> &[String] {
167        &self.environment
168    }
169
170    /// Returns custom routine-allow carve-outs (never override hard-deny).
171    #[must_use]
172    pub fn allow(&self) -> &[String] {
173        &self.allow
174    }
175
176    /// Returns custom soft-deny rules (clearable by explicit user authorization).
177    #[must_use]
178    pub fn soft_deny(&self) -> &[String] {
179        &self.soft_deny
180    }
181
182    /// Returns custom hard-deny rules (critical; never auto-approved).
183    #[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/// How much runtime should trust the host/runtime owner for permission gates.
228#[derive(Debug, Clone, Copy, PartialEq, Eq)]
229pub enum RuntimeTrustLevel {
230    /// Agentic/coding-agent runtime. Permissioned actions require review.
231    Agent,
232    /// Trusted SDK or host app runtime. The host may explicitly disable review.
233    TrustedSdk,
234}
235
236/// Review mode for explicit permission requests.
237#[derive(Debug, Clone, Copy, PartialEq, Eq)]
238pub enum PermissionReviewMode {
239    /// Runtime chooses the conservative default for the trust level.
240    DefaultForTrust,
241    /// Always route permission requests through a review source.
242    Required,
243    /// Allow an injected non-model admission source to decide without model review.
244    HostDecisionOnly,
245    /// Try AI review first, then wait on an injected host source when the AI
246    /// review denies the request or cannot produce a decision.
247    ModelThenHostFallback,
248    /// Explicit SDK/host mode that admits configured registered tools without
249    /// an AI or human approval round.
250    FullyTrusted,
251    /// Deny every permission request and action review without consulting a
252    /// reviewer. Actions that need no approval still run.
253    DenyAll,
254}
255
256impl PermissionReviewMode {
257    /// Returns whether the caller explicitly disabled permission review.
258    pub(crate) const fn is_fully_trusted(self) -> bool {
259        matches!(self, Self::FullyTrusted)
260    }
261
262    /// Returns whether every permission request is rejected without review.
263    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/// Extra capability requested for a permissioned action.
279#[derive(Debug, Clone, PartialEq, Eq)]
280pub enum RequestedCapability {
281    /// Allow network access in the selected permissioned backend/profile.
282    Network,
283    /// Allow web/browser network access to one exact hostname.
284    NetworkDomain(String),
285    /// Allow filesystem access to one path in the selected backend/profile.
286    Path(RequestedPathCapability),
287    /// Allow one explicitly configured host integration in the selected
288    /// permissioned backend/profile.
289    HostIntegration(HostIntegration),
290}
291
292/// Host integration and supporting client files exposed to inner process actions.
293/// Trusted global configuration is the capability ceiling and preauthorizes the
294/// inner action sandbox; an integration the configuration did not enable can
295/// still be requested for one permissioned action when the backend supports it
296/// and its endpoint is visible.
297#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
298pub enum HostIntegration {
299    /// The user's SSH authentication agent socket and read-only known-hosts files.
300    SshAgent,
301    /// The user's D-Bus session bus socket, commonly used by keyring clients.
302    SessionBus,
303    /// The native GnuPG agent and read-only public-key client integration, separate from SSH.
304    GpgAgent,
305}
306
307impl HostIntegration {
308    /// Returns the stable model/configuration name for this integration.
309    #[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/// Requested filesystem capability for one path.
320#[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/// Exact action covered by a permission request.
344#[derive(Debug, Clone, PartialEq, Eq)]
345pub enum PermissionedAction {
346    /// Execute one validated process intent.
347    Process(ProcessActionIntent),
348    /// Read a file outside the current workspace access policy via an in-process tool.
349    FileRead { path: String },
350    /// Create, update, or delete file(s) outside the current workspace access policy via an in-process tool.
351    FileWrite { paths: Vec<String> },
352    /// Fetch or navigate to an external URL via an in-process web/browser tool.
353    NetworkUrl {
354        /// Tool name (`web_fetch`, `browser_tab`, etc.).
355        tool: String,
356        /// Target URL being accessed.
357        url: String,
358        /// Normalized exact destination hostname.
359        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/// Runtime-owned normalized permission request.
386#[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    /// Builds a validated domain-scoped network permission request for a web or
441    /// browser tool call.
442    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    /// Marks this request as targeting a built-in Merry protected path so
464    /// approvals remain single-action (`Once`) and default to `Deny` in UIs.
465    #[must_use]
466    pub(crate) const fn with_protected_target(mut self) -> Self {
467        self.protected_target = true;
468        self
469    }
470
471    /// Creates a review-only request for a high-risk action with structured triggers.
472    ///
473    /// Unlike a capability request, this does not grant a filesystem or network
474    /// capability. It reuses the same admission source to review the exact
475    /// action before a separately configured runner executes it.
476    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    /// Returns structured action-review triggers associated with this request.
517    #[must_use]
518    pub fn triggers(&self) -> &[ActionReviewTrigger] {
519        &self.triggers
520    }
521
522    /// Returns whether this request is eligible for [`ApprovalScope::Session`]
523    /// retention under Merry's hard security rules.
524    ///
525    /// Destructive, remote-git, privilege, nested-shell, and unparseable
526    /// triggers are strictly once-only. Requests that touch `.git` metadata
527    /// paths are also once-only.
528    #[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    /// Returns whether this request is eligible for explicit per-workspace
552    /// persistence in `$XDG_STATE_HOME/merry/workspace-permissions.json`.
553    ///
554    /// Protected targets (`providers/`, `MERRY_API_KEY_FILE`, sandboxed
555    /// `config.toml`/`state/`), `.git` metadata, local loopback hosts,
556    /// action-review triggers, and host integrations are never eligible for
557    /// per-workspace persistence.
558    #[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    /// Returns whether this request is eligible for explicit per-workspace
580    /// persistence given an optional AI fallback reason.
581    ///
582    /// In addition to [`Self::allows_workspace_persistence`], requests flagged
583    /// as [`PermissionReviewRisk::Critical`] by the AI reviewer are never
584    /// eligible for per-workspace persistence.
585    #[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    /// Returns whether this request is classified as high-risk (and should
599    /// default to `Deny` in interactive review UIs).
600    #[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    /// Returns whether this request asks for network capability.
614    #[must_use]
615    pub fn requests_network(&self) -> bool {
616        self.requested
617            .iter()
618            .any(|capability| matches!(capability, RequestedCapability::Network))
619    }
620
621    /// Returns whether this request targets a built-in Merry protected path
622    /// (such as `providers/`, `MERRY_API_KEY_FILE`, or sandboxed `config.toml` / `state/`).
623    #[must_use]
624    pub const fn is_protected_target(&self) -> bool {
625        self.protected_target
626    }
627
628    /// Returns whether this request reviews an action without granting a
629    /// capability.
630    #[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    /// Returns the stable fingerprint for the exact action and capability set.
646    #[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    /// Returns the stable identifier used to correlate a host response.
656    #[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;