agix-base 0.5.0

Agix — foundation types, traits, and context
Documentation
//! The policy of a build without the permission engine: the engine's default
//! mode with no rules. What reaches the policy as data still counts: a
//! credential path the call names, a change under a host skill directory, a
//! system file or destructive command line (`is_path_bypass_immune`), all
//! refused in every mode, a `PreToolUse` hook's block or approve, the
//! tool's own refusal, the sandbox `sandbox.require` holds a command to, the
//! host's own policy, a host tool's declaration, and the deny rules a
//! delegation adds, which nothing here can read and so refuse the call. A call
//! that stays where the session works runs; any other is asked about, and
//! refused where nobody can be asked.
//!
//! The default mode's table, and the reading of a call's words as paths, are
//! kept here rather than taken from the engine, which is an optional unit base
//! cannot depend on: the engine reads them through its own shell lexer and
//! path resolution. What the refusals look for — `SensitivePaths`, the host's
//! `protected_dirs`, `is_path_bypass_immune` — is base's, shared with it.
//! PERMIT-1 (`crates/permissions/src/policy/tests/permit_all_parity.rs`)
//! holds this copy to never let through more than the engine does.

use async_trait::async_trait;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use super::{
    Answerable, Attendance, Basis, ExecProfile, HookAnswer, Obligations, PermissionOutcome,
    PermissionPolicy, PermissionRequest, Reach, Reason, Stage, Subject,
};
use crate::interface::exec::Enforcement;
use crate::interface::tool::ToolOrigin;
use crate::permission::{is_path_bypass_immune, RuleBehavior};

pub struct PermitAll {
    host: Option<Arc<dyn PermissionPolicy>>,
}

impl PermitAll {
    pub fn new(host: Option<Arc<dyn PermissionPolicy>>) -> Self {
        Self { host }
    }
}

#[async_trait]
impl PermissionPolicy for PermitAll {
    async fn decide(&self, req: &PermissionRequest<'_>) -> PermissionOutcome {
        match self.judge(req).await {
            Judged::Permit(basis) => {
                let profile = ExecProfile::for_permit(&basis, req.facts.runs, req.attendance);
                PermissionOutcome::Permit {
                    basis,
                    profile,
                    obligations: Obligations::after(req.facts.runs, profile),
                }
            }
            Judged::Otherwise(outcome) => outcome,
        }
    }
}

enum Judged {
    Permit(Basis),
    Otherwise(PermissionOutcome),
}

impl PermitAll {
    async fn judge(&self, req: &PermissionRequest<'_>) -> Judged {
        if let Some((stage, message)) = refusal(req) {
            return Judged::Otherwise(PermissionOutcome::deny(stage, message));
        }
        if let Some(host) = &self.host {
            match host.decide(req).await {
                PermissionOutcome::Permit { .. } => return Judged::Permit(Basis::NoPolicy),
                PermissionOutcome::Deny { reason } => {
                    return Judged::Otherwise(PermissionOutcome::Deny { reason })
                }
                PermissionOutcome::Prompt {
                    reason, answerable, ..
                } => return asked(req, reason, answerable, None),
            }
        }
        match default_mode_question(req) {
            None => Judged::Permit(Basis::NoPolicy),
            Some(reason)
                if reason.stage == Stage::ModeDefault
                    && req.attendance == Attendance::Unattended
                    && req.facts.runs.is_some()
                    && matches!(req.facts.reach, Reach::Unknown | Reach::Inside)
                    && req.ctx.confinement.holds_unattended() =>
            {
                Judged::Permit(Basis::UnattendedConfined)
            }
            Some(reason) => {
                let remedy = match req.facts.origin {
                    ToolOrigin::Host => {
                        "declare it `permit: \"allow\"`, or build with the `permissions` unit"
                    }
                    _ => "build with the `permissions` unit",
                };
                asked(req, reason, Answerable::HookOrPerson, Some(remedy))
            }
        }
    }
}

/// What every mode refuses, whoever attends: a credential, a host skill
/// directory or a bypass-immune path named, a hook's block, a tool the
/// session lacks, a delegation's rules nothing here reads, a command the
/// required sandbox cannot hold, the tool's own refusal.
fn refusal(req: &PermissionRequest<'_>) -> Option<(Stage, String)> {
    if let Some(word) = credential_named(req) {
        return Some((
            Stage::Credentials,
            format!("'{word}' holds credentials; no tool reads or writes it"),
        ));
    }
    if let Some(word) = host_skill_dir_named(req) {
        return Some((
            Stage::HostSkillDir,
            format!(
                "'{word}' is under a directory of the host's: a skill directory it lists for \
                     a session or one of its own packages; no tool writes under it, in any \
                     permission mode"
            ),
        ));
    }
    if let HookAnswer::Block { reason, .. } = req.hook {
        return Some((Stage::Hook, format!("Blocked by PreToolUse hook: {reason}")));
    }
    if req.tool.is_none() {
        return Some((
            Stage::UnknownTool,
            format!("`{}` is not a tool this session has", req.tool_name),
        ));
    }
    let held = req.delegate.is_some_and(|d| {
        d.rules
            .iter()
            .any(|rule| rule.behavior != RuleBehavior::Allow)
    });
    if held {
        return Some((
            Stage::DelegateRule,
            "this call is held to rules of the delegation it runs in, and this build has no \
                 permission engine to read them"
                .into(),
        ));
    }
    if runs_in_required_sandbox(req) && req.ctx.confinement.session != Enforcement::Full {
        return Some((
            Stage::Confinement,
            format!(
                "Refused: {} would run under a sandbox policy this build cannot enforce all \
                     of, and `sandbox.require` is on",
                req.tool_name
            ),
        ));
    }
    if let Reach::Refused(why) = &req.facts.reach {
        return Some((Stage::ToolRefusal, why.clone()));
    }
    if let Some(word) = bypass_immune_named(req) {
        return Some((
            Stage::BypassImmune,
            format!(
                "access to protected path '{word}' is blocked regardless of permission mode \
                     — this path is bypass-immune"
            ),
        ));
    }
    None
}

/// What the engine's default mode asks about the call when no rule matches
/// it, or `None` where it lets the call through: a call that stays where the
/// session works, unless it runs on in the background, writes configuration,
/// or would run under a strict profile the required sandbox does not hold;
/// and a host tool its host declared `permit: "allow"`.
fn default_mode_question(req: &PermissionRequest<'_>) -> Option<Reason> {
    let facts = req.facts;
    if facts.host_permits {
        return None;
    }
    let writes_configuration = !facts.traits.read_only && names_configuration(req);
    let background = facts.runs.is_some_and(|r| r.background);
    let strict_unheld =
        runs_in_required_sandbox(req) && req.ctx.confinement.strict != Enforcement::Full;
    let contained = matches!(
        facts.reach,
        Reach::SessionOnly | Reach::Delegates | Reach::Operator | Reach::Inside
    );
    if contained && !background && !writes_configuration && !strict_unheld {
        return None;
    }
    let stage = if writes_configuration {
        Stage::Configuration
    } else {
        Stage::ModeDefault
    };
    let message = match (&facts.origin, &facts.question) {
        (ToolOrigin::Host, _) => format!(
            "`{}` is a host tool declared to be asked about (`permit: \"ask\"`)",
            req.tool_name
        ),
        (_, Some(question)) => question.clone(),
        (_, None) => format!("Allow {}?", req.tool_name),
    };
    Some(Reason::new(stage, message))
}

fn runs_in_required_sandbox(req: &PermissionRequest<'_>) -> bool {
    req.facts.runs.is_some()
        && !req.ctx.config.sandbox.disabled
        && req.ctx.confinement.require_enforcement
}

/// A question: answered by a hook's approve where a hook may answer it, put
/// to the person attending, and refused where nobody can be asked, with
/// `remedy` for a question only the missing permission layer could answer.
fn asked(
    req: &PermissionRequest<'_>,
    reason: Reason,
    answerable: Answerable,
    remedy: Option<&str>,
) -> Judged {
    if let (HookAnswer::Approve { hook }, Answerable::HookOrPerson) = (req.hook, answerable) {
        return Judged::Permit(Basis::HookApproved(hook.clone()));
    }
    let why = match req.attendance {
        Attendance::Attended => {
            return Judged::Otherwise(PermissionOutcome::Prompt {
                prompt_id: uuid::Uuid::new_v4().to_string(),
                message: reason.message.clone(),
                paths: Vec::new(),
                reason,
                answerable,
            })
        }
        Attendance::Unattended => "nobody is attending this session to approve it",
        Attendance::NoOneToAsk(why) => why,
    };
    let message = match remedy {
        Some(remedy) => format!(
            "{} — {why}. This build has no permission layer to allow it unattended: {remedy}",
            reason.message
        ),
        None => format!("{} — {why}", reason.message),
    };
    Judged::Otherwise(PermissionOutcome::deny(Stage::Attendance, message))
}

/// The first word of the call that names a credential location, each taken
/// as a path from the session's cwd, as is the value of a `--flag=value`.
/// A command line is split on blanks and operators with its quotes and
/// escapes dropped: coarser than the permission engine's reading, and only
/// ever refusing more.
fn credential_named(req: &PermissionRequest<'_>) -> Option<String> {
    let sensitive = &req.ctx.config.sandbox.paths;
    word_naming(req, |_, paths| {
        paths.iter().any(|p| sensitive.is_credential(p))
    })
}

/// The first word of a call that changes something naming a path under a
/// host skill directory, read as `credential_named` reads its words.
fn host_skill_dir_named(req: &PermissionRequest<'_>) -> Option<String> {
    if req.facts.traits.read_only || matches!(req.facts.subject, Subject::ReadPath(_)) {
        return None;
    }
    let protected = &req.ctx.session.env().protected_dirs;
    word_naming(req, |_, paths| {
        paths.iter().any(|p| protected.holding(p).is_some())
    })
}

/// The call's content, or the first of its words, that is bypass-immune: the
/// whole line for a destructive command, a word or its path for a system file.
fn bypass_immune_named(req: &PermissionRequest<'_>) -> Option<String> {
    let content = req.facts.subject.content()?;
    if is_path_bypass_immune(content) {
        return Some(content.to_string());
    }
    word_naming(req, |word, paths| {
        is_path_bypass_immune(word)
            || paths
                .iter()
                .any(|p| is_path_bypass_immune(&p.to_string_lossy()))
    })
}

fn names_configuration(req: &PermissionRequest<'_>) -> bool {
    let sensitive = &req.ctx.config.sandbox.paths;
    word_naming(req, |word, paths| {
        sensitive.names_configuration(word)
            || paths
                .iter()
                .any(|p| sensitive.names_configuration(&p.to_string_lossy()))
    })
    .is_some()
}

fn word_naming(
    req: &PermissionRequest<'_>,
    names: impl Fn(&str, &[PathBuf]) -> bool,
) -> Option<String> {
    let content = req.facts.subject.content()?;
    let words: Vec<String> = match &req.facts.subject {
        Subject::Shell(line) => line
            .split(|c: char| c.is_whitespace() || ";|&<>()`".contains(c))
            .map(|word| word.replace(['\'', '"', '\\'], ""))
            .collect(),
        _ => vec![content.to_string()],
    };
    words.into_iter().find(|word| {
        std::iter::once(word.as_str())
            .chain(word.split_once('=').map(|(_, value)| value))
            .filter(|w| !w.is_empty())
            .any(|w| names(w, &spellings(w, &req.ctx.cwd)))
    })
}

fn spellings(word: &str, cwd: &Path) -> Vec<PathBuf> {
    let written = match word.strip_prefix("~/").zip(crate::paths::home_dir()) {
        Some((rest, home)) => home.join(rest),
        None => cwd.join(word),
    };
    let lexical = crate::path::normalize_lexically(&written);
    vec![
        crate::path::resolve_physically(&lexical),
        crate::path::resolve_physically(&written),
        lexical,
    ]
}