use std::fs;
use std::path::{Component, Path, PathBuf};
use std::str::FromStr as _;
use anyhow::{Context as _, Result, bail, ensure};
use openmoat_core::RepoPolicy;
use openmoat_hosts::Host;
use serde::{Deserialize, Serialize};
use super::settings::Settings;
use crate::home::{Home, create_private_dir, write_private};
use crate::integrity::sha256_hex;
use crate::signing::{self, Signed};
pub const FORMAT: &str = "openmoat-team-bundle-v1";
pub const MANIFEST: &str = "openmoat-team.yaml";
pub const SIGNATURE: &str = "openmoat-team.yaml.sig";
pub const POLICY_NAME: &str = "policy";
const MAX_FILES: usize = 32;
const MAX_FILE_BYTES: u64 = 1 << 20;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Manifest {
pub format: String,
pub name: String,
pub serial: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub policy: Option<FileRef>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub packs: Vec<PackRef>,
#[serde(default)]
pub settings: Settings,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub require_hooks: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FileRef {
pub path: String,
pub sha256: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PackRef {
pub name: String,
pub path: String,
pub sha256: String,
}
impl Manifest {
pub fn parse(text: &str) -> Result<Self> {
let manifest: Self = openmoat_core::yaml::from_str(text)
.with_context(|| format!("not a team bundle manifest ({MANIFEST})"))?;
ensure!(
manifest.format == FORMAT,
"{MANIFEST}: format is `{}`; this build reads `{FORMAT}`",
manifest.format
);
crate::packs::check_name(&manifest.name).context("the team's name")?;
ensure!(manifest.serial >= 1, "{MANIFEST}: serial starts at 1");
let files = manifest.files();
ensure!(
files.len() <= MAX_FILES,
"{MANIFEST}: at most {MAX_FILES} rule files"
);
for (n, (name, path, sha)) in files.iter().enumerate() {
crate::packs::check_name(name)?;
ensure!(
(n == 0 && manifest.policy.is_some()) || *name != POLICY_NAME,
"pack name `{POLICY_NAME}` is the `policy:` file's"
);
ensure!(
!files[..n].iter().any(|(other, _, _)| other == name),
"two rule files are named `{name}`"
);
check_path(path)?;
ensure!(
sha.len() == 64
&& sha
.chars()
.all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c)),
"`{path}`: sha256 must be 64 lowercase hex digits"
);
}
manifest.settings.check()?;
manifest.hooks()?;
Ok(manifest)
}
pub fn files(&self) -> Vec<(&str, &str, &str)> {
let policy = self
.policy
.iter()
.map(|f| (POLICY_NAME, f.path.as_str(), f.sha256.as_str()));
let packs = self
.packs
.iter()
.map(|p| (p.name.as_str(), p.path.as_str(), p.sha256.as_str()));
policy.chain(packs).collect()
}
pub fn hooks(&self) -> Result<Vec<Host>> {
self.require_hooks
.iter()
.map(|id| {
Host::from_str(id)
.ok()
.filter(|host| Host::ALL.contains(host))
.with_context(|| {
format!("require_hooks: `{id}` is not an agent OpenMoat hooks")
})
})
.collect()
}
}
fn check_path(path: &str) -> Result<()> {
let plain = !path.is_empty()
&& !path.contains('\\')
&& Path::new(path)
.components()
.all(|c| matches!(c, Component::Normal(_)));
ensure!(
plain && Path::new(path).extension().is_some_and(|e| e == "yaml"),
"`{path}` must be a relative `.yaml` path inside the bundle's folder, without `..`"
);
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuleFile {
pub name: String,
pub text: String,
pub rules: RepoPolicy,
}
#[derive(Debug, Clone)]
pub struct Bundle {
pub manifest: Manifest,
pub manifest_bytes: Vec<u8>,
pub signature: Vec<u8>,
pub files: Vec<RuleFile>,
pub signer: String,
}
impl Bundle {
#[must_use]
pub fn digest(&self) -> String {
sha256_hex(&self.manifest_bytes)
}
}
pub fn parse_rules(name: &str, text: &str) -> Result<RepoPolicy> {
let rules = crate::packs::parse(text).with_context(|| format!("rule file `{name}`"))?;
if let Some(group) = rules.allow.first() {
bail!(
"rule file `{name}`: allow rule `{}`: a team bundle only narrows; allow rules \
belong in a person's own policy or a pack they install",
group.id
);
}
Ok(rules)
}
pub fn verify(home: &Home, signers: &Path, dir: &Path) -> Result<Bundle> {
let program = signing::require(home)?;
let dir = fs::canonicalize(dir).with_context(|| format!("reading {}", dir.display()))?;
ensure!(dir.is_dir(), "{} is not a folder", dir.display());
let manifest_bytes = read_inside(&dir, MANIFEST)?;
let signature = read_inside(&dir, SIGNATURE)?;
let staging = std::env::temp_dir().join(format!(
"openmoat-team-{}-{}",
std::process::id(),
crate::time::now_ms()
));
create_private_dir(&staging)?;
let staged = staging.join("bundle.sig");
let written = write_private(&staged, &signature);
let signer = written.and_then(|()| {
signing::verify(
&program,
signers,
&manifest_bytes,
&staged,
Signed::TeamBundle,
)
});
let _ = fs::remove_dir_all(&staging);
let Some(signer) = signer? else {
bail!(
"refusing the bundle in {}: {SIGNATURE} does not verify against the team's key \
(sign {MANIFEST} with `ssh-keygen -Y sign -n {}`)",
dir.display(),
signing::TEAM_NAMESPACE
);
};
let text = std::str::from_utf8(&manifest_bytes).context("the manifest must be UTF-8")?;
let manifest = Manifest::parse(text)?;
let mut files = Vec::new();
for (name, path, sha) in manifest.files() {
let bytes = read_inside(&dir, path)?;
ensure!(
sha256_hex(&bytes) == sha,
"`{path}` does not match the digest {MANIFEST} gives it: the bundle changed after it \
was signed"
);
let text = String::from_utf8(bytes).with_context(|| format!("`{path}` must be UTF-8"))?;
let rules = parse_rules(name, &text)?;
files.push(RuleFile {
name: name.to_owned(),
text,
rules,
});
}
Ok(Bundle {
manifest,
manifest_bytes,
signature,
files,
signer,
})
}
fn read_inside(dir: &Path, rel: &str) -> Result<Vec<u8>> {
let path: PathBuf = dir.join(rel);
let meta =
fs::symlink_metadata(&path).with_context(|| format!("reading {}", path.display()))?;
ensure!(
meta.file_type().is_file(),
"{} is not a regular file",
path.display()
);
ensure!(
meta.len() <= MAX_FILE_BYTES,
"{} is larger than {MAX_FILE_BYTES} bytes",
path.display()
);
let resolved =
fs::canonicalize(&path).with_context(|| format!("reading {}", path.display()))?;
ensure!(
resolved.starts_with(dir),
"{} is outside the bundle's folder",
path.display()
);
fs::read(&resolved).with_context(|| format!("reading {}", path.display()))
}