use anyhow::{Result, bail};
use openmoat_core::{Decision, Policy, Require, RequiredBy, RequiredLevel, Requirement, Verdict};
use openmoat_hosts::Host;
use serde::Serialize;
use super::{Level, os_sandboxed_by_lock};
use crate::home::Home;
use crate::integrity::Drift;
use crate::sandbox::install as host_sandbox;
pub mod boundary;
pub use boundary::Boundary;
pub const RULE: &str = "protection-required";
impl Level {
pub fn meets(self, required: RequiredLevel) -> bool {
rank(self) >= rank(level_of(required))
}
}
pub fn level_of(required: RequiredLevel) -> Level {
match required {
RequiredLevel::HookOnly => Level::HookOnly,
RequiredLevel::HookAndOsSandbox => Level::HookAndOsSandbox,
}
}
fn rank(level: Level) -> u8 {
match level {
Level::HookAndOsSandbox => 2,
Level::HookOnly => 1,
Level::NotProtected | Level::NotSetUp | Level::NotFound => 0,
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Required {
pub level: RequiredLevel,
pub by: String,
pub met: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub missing: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub fix: Option<String>,
}
impl Required {
pub fn of(host: Host, level: Level, requirement: &Requirement) -> Self {
let gap = missing(host, level, requirement.level);
Self {
level: requirement.level,
by: by(&requirement.by),
met: gap.is_none(),
missing: gap.as_ref().map(|(what, _)| what.clone()),
fix: gap.map(|(_, fix)| fix),
}
}
pub fn label(&self) -> &'static str {
level_of(self.level).label()
}
}
pub fn by(by: &RequiredBy) -> String {
match by {
RequiredBy::Policy => "your policy".to_owned(),
RequiredBy::Repository => "the repository policy".to_owned(),
RequiredBy::Pack(name) => format!("the policy pack `{name}`"),
}
}
pub fn in_force(home: &Home, host: Host, drifted: &[Drift], within_run: bool) -> Level {
if within_run || os_sandboxed_by_lock(home, host, drifted) {
Level::HookAndOsSandbox
} else {
Level::HookOnly
}
}
pub fn missing(host: Host, level: Level, required: RequiredLevel) -> Option<(String, String)> {
if level.meets(required) {
return None;
}
let name = host.display_name();
Some(match level {
Level::HookOnly | Level::HookAndOsSandbox => no_sandbox(host),
Level::NotSetUp => (
format!("OpenMoat's hook is not set up for {name}"),
format!("run `openmoat init --hosts {}`", host.id()),
),
Level::NotProtected | Level::NotFound => (
format!("OpenMoat's hook does not run for {name}"),
"run `openmoat doctor` in your terminal, which names what stops it".to_owned(),
),
})
}
fn no_sandbox(host: Host) -> (String, String) {
let name = host.display_name();
let run = crate::commands::sandboxing_command();
if super::writes_sandbox(host) {
return (
format!(
"the OS sandbox settings OpenMoat wrote for {name} are missing or differ from \
the policy"
),
"run `openmoat sandbox sync` in your terminal".to_owned(),
);
}
let what = host_sandbox::unavailable(host).map_or_else(
|| format!("OpenMoat writes no OS sandbox for {name}"),
str::to_owned,
);
match crate::commands::run_unavailable() {
Some(_) => (
format!("{what}, and `openmoat run` has no OS sandbox on this system"),
format!("lower the level of {name} in `require.agents` with `openmoat edit`"),
),
None => (what, format!("start {name} with {run}")),
}
}
pub fn unmet(policy: &Policy, host: Host, level: impl FnOnce() -> Level) -> Option<Decision> {
let requirement = policy.required_for(Some(host.id()))?;
let level = level();
let (what, fix) = missing(host, level, requirement.level)?;
let reason = format!(
"{} requires {} for {}; this call has {}: {what}; to meet it, {fix}",
by(&requirement.by),
level_of(requirement.level).label(),
host.display_name(),
level.label(),
);
Some(Decision::single(Verdict::Deny, RULE, reason))
}
pub fn policy_in(home: &Home, ctx: &openmoat_core::EvalContext) -> Result<Policy> {
crate::repo::with_repo_denies(home, ctx, home.load_policy()?)
}
pub fn check_agents(require: Option<&Require>) -> Result<()> {
for id in require.iter().flat_map(|r| r.agent_ids()) {
if !Host::ALL.iter().any(|h| h.id() == id) {
let known: Vec<&str> = Host::ALL.iter().map(|h| h.id()).collect();
bail!(
"require.agents: `{id}` is not an agent OpenMoat knows; use one of {}",
known.join(", ")
);
}
}
Ok(())
}
pub fn check_policy(policy: &Policy) -> Result<()> {
check_agents(policy.require.as_ref())?;
policy
.require_added
.iter()
.try_for_each(|(_, added)| check_agents(Some(added)))
}
#[cfg(test)]
mod tests;