use openmoat_core::boundary::{ProtectionScore, ToolToken};
use serde::Serialize;
use super::boundary::{Plan, plan};
use super::isolation::{Asked, Lightweight, Offered, Tier};
use super::platform;
pub const LABEL: &str = "protection";
#[derive(Debug, Clone, Serialize)]
pub struct TierScore {
pub tier: &'static str,
pub score: Option<ProtectionScore>,
#[serde(skip_serializing_if = "Option::is_none")]
pub why: Option<String>,
}
impl TierScore {
pub fn line(&self) -> String {
let text = match (&self.score, &self.why) {
(Some(score), _) => score.line(),
(None, Some(why)) => why.clone(),
(None, None) => String::new(),
};
format!("{LABEL:<16} {:<11} {text}", self.tier)
}
pub fn warns(&self) -> bool {
self.score.as_ref().is_none_or(|s| !s.complete())
}
}
const HOOK_ONLY: &str = "0/100: no kernel feature is in force; an allowed call runs with your \
permissions, so a classifier mistake is a bypass. `openmoat run` or the \
agent's own sandbox confines it";
pub fn tiers() -> Vec<TierScore> {
let mut out = Vec::new();
if let Some(why) = platform::unavailable() {
out.push(TierScore {
tier: "run",
score: None,
why: Some(format!("0/100: {why}")),
});
} else {
let kernel = platform::landlock();
let scored = |tier: &Tier, port_only: Option<String>| {
plan(Plan {
asked: Asked::Default,
tier,
port_only,
kernel: kernel.as_ref(),
token: ToolToken::UnknownAgent,
port: None,
project_top_open: false,
})
.score
};
match platform::isolation() {
Offered::Available => out.push(TierScore {
tier: "isolated",
score: scored(&Tier::Isolated { asked: false }, None),
why: None,
}),
Offered::Unavailable(why) => out.push(TierScore {
tier: "isolated",
score: None,
why: Some(format!("cannot start here: {why}")),
}),
Offered::Not => {}
}
let lightweight = Tier::Lightweight(Lightweight::Platform);
out.push(TierScore {
tier: "lightweight",
score: scored(&lightweight, platform::no_network_namespace()),
why: None,
});
}
out.push(TierScore {
tier: "hook-only",
score: None,
why: Some(HOOK_ONLY.to_owned()),
});
out
}
pub fn default_run() -> Option<u32> {
tiers().into_iter().find_map(|t| t.score).map(|s| s.points)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_default_run_is_scored_where_it_can_start() {
match platform::unavailable() {
Some(_) => assert_eq!(default_run(), None),
None => assert!(default_run().is_some_and(|p| p <= 100)),
}
}
#[test]
fn the_hook_alone_is_last_and_every_tier_is_scored() {
let tiers = tiers();
let last = tiers.last().unwrap();
assert_eq!(last.tier, "hook-only");
assert!(last.line().contains("0/100"), "{}", last.line());
assert!(last.warns());
for tier in &tiers {
if let Some(score) = &tier.score {
assert!(score.points <= 100, "{tier:?}");
}
assert!(tier.line().starts_with("protection"), "{}", tier.line());
}
}
}