use anyhow::Result;
use openmoat_core::{Kind, Policy, RuleGroup, lint::covers};
use serde::{Deserialize, Serialize};
use crate::context::{absolute, path_string};
use crate::home::Home;
const PROJECT: &str = "${project}";
const OLD_REASONS: [&str; 2] = [
"approved with `moat allow --dir` on ",
"approved with `openmoat allow --dir` on ",
];
const GLOB_CHARS: [char; 7] = ['*', '?', '[', ']', '{', '}', '\\'];
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DirGrant {
pub id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
pub dir: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub except: Vec<String>,
}
impl DirGrant {
#[must_use]
pub fn rule(&self, policy: &Policy, places: &Places) -> RuleGroup {
let tree = tree(&self.dir);
let left_out = exclusions(policy, &self.dir, places)
.into_iter()
.chain(self.except.iter().cloned())
.map(|p| format!("!{p}"));
RuleGroup {
id: self.id.clone(),
reason: self.reason.clone(),
fs_read: tree.clone(),
fs_write: tree.into_iter().chain(left_out).collect(),
..RuleGroup::default()
}
}
#[must_use]
pub fn from_rule(rule: &RuleGroup, policy: &Policy, places: &Places) -> Option<Self> {
let (dir, left_out) = old_shape(rule)?;
let now = exclusions(policy, &dir, places);
let except = left_out
.into_iter()
.filter(|old| !now.iter().any(|p| covers(Kind::FsWrite, p, old)))
.map(str::to_owned)
.collect();
Some(Self {
id: rule.id.clone(),
reason: rule.reason.clone(),
dir,
except,
})
}
}
#[must_use]
pub fn is_old_rule(rule: &RuleGroup) -> bool {
old_shape(rule).is_some()
}
fn old_shape(rule: &RuleGroup) -> Option<(Vec<String>, Vec<&str>)> {
let reason = rule.reason.as_deref()?;
if !OLD_REASONS.iter().any(|old| reason.starts_with(old)) {
return None;
}
let dir: Vec<String> = rule.fs_read.iter().step_by(2).cloned().collect();
let tree = tree(&dir);
let bare = RuleGroup {
id: rule.id.clone(),
reason: rule.reason.clone(),
fs_read: tree.clone(),
fs_write: rule.fs_write.clone(),
..RuleGroup::default()
};
let plain = !dir.is_empty() && *rule == bare && dir.iter().all(|d| plain_dir(d));
let left_out: Vec<&str> = rule
.fs_write
.strip_prefix(tree.as_slice())?
.iter()
.map(|p| p.strip_prefix('!'))
.collect::<Option<_>>()?;
let inside = left_out.iter().all(|p| dir.iter().any(|d| below(p, d)));
(plain && inside).then_some((dir, left_out))
}
#[must_use]
pub fn plain_dir(dir: &str) -> bool {
!dir.is_empty() && !dir.contains(GLOB_CHARS) && !dir.ends_with('/')
}
fn tree(dir: &[String]) -> Vec<String> {
dir.iter()
.flat_map(|d| [d.clone(), format!("{d}/**")])
.collect()
}
fn below(pattern: &str, dir: &str) -> bool {
pattern
.strip_prefix(dir)
.is_some_and(|rest| rest.starts_with('/'))
}
#[must_use]
pub fn exclusions(policy: &Policy, dir: &[String], places: &Places) -> Vec<String> {
let mut kept: Vec<String> = Vec::new();
let protected = policy
.review
.iter()
.flat_map(|g| &g.fs_write)
.filter(|p| !p.starts_with('!'));
for pattern in protected {
for spelling in dir {
if let Some(found) = in_dir(pattern, spelling, places) {
keep_broadest(&mut kept, found);
}
}
}
kept
}
fn in_dir(pattern: &str, dir: &str, places: &Places) -> Option<String> {
if let Some(rest) = pattern.strip_prefix(PROJECT) {
return (rest.is_empty() || rest.starts_with('/')).then(|| format!("{dir}{rest}"));
}
if let Some(rest) = pattern.strip_prefix("**/") {
return Some(format!("{dir}/**/{rest}"));
}
let lies_in = places
.spellings(pattern)
.is_none_or(|spelled| spelled.iter().any(|s| may_lie_in(s, dir)));
lies_in.then(|| pattern.to_owned())
}
fn keep_broadest(kept: &mut Vec<String>, found: String) {
if kept.iter().any(|p| covers(Kind::FsWrite, p, &found)) {
return;
}
kept.retain(|p| !covers(Kind::FsWrite, &found, p));
kept.push(found);
}
fn may_lie_in(spelled: &str, dir: &str) -> bool {
let (spelled, dir) = (spelled.to_lowercase(), dir.to_lowercase());
let stem = &spelled[..spelled.find(GLOB_CHARS).unwrap_or(spelled.len())];
let inside = format!("{dir}/");
stem == dir
|| stem.starts_with(&inside)
|| (stem.len() < spelled.len() && inside.starts_with(stem))
}
#[derive(Debug, Clone, Default)]
pub struct Places {
pub homes: Vec<String>,
pub moved: Vec<(String, String)>,
}
impl Places {
pub fn here(home: &Home) -> Result<Self> {
let written = absolute(&crate::home::user_home()?)?;
let mut homes = vec![path_string(&written)];
if let Ok(real) = std::fs::canonicalize(&written).map(|r| path_string(&r))
&& real != homes[0]
{
homes.push(real);
}
Ok(Self {
homes,
moved: crate::context::moved_dirs(home)?,
})
}
fn spellings(&self, pattern: &str) -> Option<Vec<String>> {
let mut out: Vec<String> = self
.moved
.iter()
.filter_map(|(default, dir)| {
let rest = pattern.strip_prefix(default.as_str())?;
(rest.is_empty() || rest.starts_with('/')).then(|| format!("{dir}{rest}"))
})
.collect();
match pattern.strip_prefix('~') {
Some(rest) if rest.is_empty() || rest.starts_with('/') => {
out.extend(self.homes.iter().map(|home| format!("{home}{rest}")));
}
Some(_) => return None,
None => out.push(pattern.to_owned()),
}
Some(out)
}
}
#[cfg(test)]
mod tests;