use super::{PathFlagEntry, PathRole, Sep, data_path_verdict, exec_path_verdict};
use crate::verdict::{SafetyLevel, Verdict};
pub(super) fn option_string_verdict(value: &str, allowed: &[String], path_flags: &[PathFlagEntry]) -> Verdict {
let raw: Vec<&str> = value.split_whitespace().collect();
let mut verdict = Verdict::Allowed(SafetyLevel::Inert);
let mut i = 0;
while i < raw.len() {
if let Some((role, path, used)) = path_flag_match(raw[i], raw.get(i + 1).copied(), path_flags) {
if path.is_empty() {
return Verdict::Denied;
}
verdict = verdict.combine(gate_path(role, path));
i += used;
continue;
}
let joined;
let unit = if raw[i].len() <= 2 && raw[i].starts_with('-') && i + 1 < raw.len() && !raw[i + 1].starts_with('-') {
joined = format!("{}{}", raw[i], raw[i + 1]);
i += 2;
joined.as_str()
} else {
i += 1;
raw[i - 1]
};
if !allowed.iter().any(|a| flag_matches(unit, a)) {
return Verdict::Denied;
}
}
verdict
}
fn path_flag_match<'a>(tok: &'a str, next: Option<&'a str>, path_flags: &[PathFlagEntry]) -> Option<(PathRole, &'a str, usize)> {
path_flags.iter().find_map(|pf| match pf.sep {
Sep::Equals => tok.split_once('=').filter(|(f, _)| *f == pf.flag).map(|(_, v)| (pf.role, v, 1)),
Sep::Space => (tok == pf.flag).then_some(match next {
Some(v) if !v.starts_with('-') => (pf.role, v, 2),
_ => (pf.role, "", 1),
}),
})
}
fn gate_path(role: PathRole, path: &str) -> Verdict {
match role {
PathRole::Read => data_path_verdict(path, true),
PathRole::Write => crate::engine::resolve::write_target_verdict(path),
PathRole::Exec => exec_path_verdict(path, true),
}
}
pub(super) fn flag_matches(token: &str, entry: &str) -> bool {
match entry.strip_suffix('*') {
Some(prefix) => token.starts_with(prefix),
None => token == entry || token.strip_prefix(entry).is_some_and(|r| r.starts_with('=')),
}
}