use anyhow::{Context, Result};
use serde_json::{json, Value};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use crate::plm::access_event::LearningModeAccessEvent;
#[derive(Clone, Copy, PartialEq, Eq)]
enum Access {
Read,
Write,
ReadWrite,
None,
}
struct MaskFlag {
bit: u32,
name: &'static str,
access: Access,
}
const ACCESS_FLAGS: &[MaskFlag] = &[
MaskFlag {
bit: 0x1,
name: "READ_DATA",
access: Access::Read,
},
MaskFlag {
bit: 0x2,
name: "FILE_WRITE",
access: Access::Write,
},
MaskFlag {
bit: 0x4,
name: "FILE_APPEND",
access: Access::Write,
},
MaskFlag {
bit: 0x8,
name: "READ_EA",
access: Access::Read,
},
MaskFlag {
bit: 0x10,
name: "WRITE_EA",
access: Access::Write,
},
MaskFlag {
bit: 0x20,
name: "DIRECTORY_TRAVERSE",
access: Access::Read,
},
MaskFlag {
bit: 0x40,
name: "DIRECTORY_DELETE",
access: Access::Write,
},
MaskFlag {
bit: 0x80,
name: "READ_ATTRIBUTES",
access: Access::Read,
},
MaskFlag {
bit: 0x100,
name: "WRITE_ATTRIBUTES",
access: Access::Write,
},
MaskFlag {
bit: 0x10000,
name: "FILE_DELETE",
access: Access::Write,
},
MaskFlag {
bit: 0x20000,
name: "READ_CONTROL",
access: Access::None,
},
MaskFlag {
bit: 0x40000,
name: "WRITE_DAC",
access: Access::Write,
},
MaskFlag {
bit: 0x80000,
name: "WRITE_OWNER",
access: Access::Write,
},
MaskFlag {
bit: 0x100000,
name: "SYNCHRONIZE",
access: Access::None,
},
MaskFlag {
bit: 0x1000_0000,
name: "GENERIC_ALL",
access: Access::ReadWrite,
},
MaskFlag {
bit: 0x2000_0000,
name: "GENERIC_EXECUTE",
access: Access::Read,
},
MaskFlag {
bit: 0x4000_0000,
name: "GENERIC_WRITE",
access: Access::Write,
},
MaskFlag {
bit: 0x8000_0000,
name: "GENERIC_READ",
access: Access::Read,
},
];
const fn compute_mask(want_write: bool) -> u32 {
let mut m = 0u32;
let mut i = 0;
while i < ACCESS_FLAGS.len() {
let hit = match ACCESS_FLAGS[i].access {
Access::Write => want_write,
Access::Read => !want_write,
Access::ReadWrite => true,
Access::None => false,
};
if hit {
m |= ACCESS_FLAGS[i].bit;
}
i += 1;
}
m
}
pub const WRITE_MASK: u32 = compute_mask(true);
pub const READ_MASK: u32 = compute_mask(false);
#[derive(Debug)]
pub struct AddedPaths {
pub readwrite: Vec<String>,
pub readonly: Vec<String>,
}
pub fn load_config(path: &Path) -> Result<Value> {
let raw = std::fs::read_to_string(path)
.with_context(|| format!("failed to read {}", path.display()))?;
let v: Value = serde_json::from_str(&raw)
.with_context(|| format!("failed to parse JSON {}", path.display()))?;
Ok(v)
}
pub fn initialize_filesystem(config: &mut Value) -> Result<()> {
let obj = config
.as_object_mut()
.ok_or_else(|| anyhow::anyhow!("config root must be a JSON object"))?;
if !obj.contains_key("filesystem") {
obj.insert("filesystem".into(), json!({}));
}
let fs = obj
.get_mut("filesystem")
.and_then(|v| v.as_object_mut())
.ok_or_else(|| anyhow::anyhow!("`filesystem` must be a JSON object"))?;
if !fs.contains_key("readwritePaths") {
fs.insert("readwritePaths".into(), json!([]));
} else if !fs["readwritePaths"].is_array() {
anyhow::bail!("`filesystem.readwritePaths` must be a JSON array");
}
if !fs.contains_key("readonlyPaths") {
fs.insert("readonlyPaths".into(), json!([]));
} else if !fs["readonlyPaths"].is_array() {
anyhow::bail!("`filesystem.readonlyPaths` must be a JSON array");
}
Ok(())
}
pub fn deny_file_set(config: &Value) -> HashSet<String> {
let mut out = HashSet::new();
if let Some(arr) = config
.get("filesystem")
.and_then(|fs| fs.get("deniedPaths"))
.and_then(|v| v.as_array())
{
for v in arr {
if let Some(s) = v.as_str() {
out.insert(s.to_string());
}
}
}
out
}
fn strip_verbatim_or_device_prefix(s: &str) -> Option<&str> {
if let Some(head) = s.get(..8) {
if head.eq_ignore_ascii_case("\\\\?\\UNC\\") {
return None;
}
}
if let Some(head) = s.get(..4) {
if head == "\\\\?\\" || head == "\\\\.\\" {
return Some(&s[4..]);
}
if head == "\\??\\" {
return Some(&s[4..]);
}
}
Some(s)
}
fn normalize_path(p: &str) -> Option<String> {
let stripped = strip_verbatim_or_device_prefix(p)?;
let mut s = String::with_capacity(stripped.len());
for c in stripped.chars() {
let c = if c == '/' { '\\' } else { c };
s.push(c.to_ascii_lowercase());
}
for (i, b) in s.bytes().enumerate() {
if b == b':' && i != 1 {
return None;
}
}
let trimmed = s.trim_end_matches('\\');
let mut out = String::with_capacity(trimmed.len());
let mut in_leading_unc = true;
let mut emitted = 0usize;
for (i, part) in trimmed.split('\\').enumerate() {
if i == 0 && part.len() == 2 && part.as_bytes()[1] == b':' {
out.push_str(part);
emitted += 1;
in_leading_unc = false;
continue;
}
if part.is_empty() && in_leading_unc && i < 2 {
if emitted > 0 {
out.push('\\');
}
emitted += 1;
continue;
}
in_leading_unc = false;
let stripped = part.trim_end_matches(['.', ' ']);
if part == "." || part == ".." || stripped.is_empty() {
return None;
}
if emitted > 0 {
out.push('\\');
}
out.push_str(stripped);
emitted += 1;
}
Some(out)
}
fn path_starts_with_any_norm<I: AsRef<str>>(
file_path_norm: &str,
paths_norm: impl IntoIterator<Item = I>,
) -> bool {
let fp_bytes = file_path_norm.as_bytes();
let fp_first = fp_bytes.first().copied();
for p in paths_norm {
let pn = p.as_ref();
if pn.is_empty() {
continue;
}
let pn_bytes = pn.as_bytes();
if pn_bytes.first().copied() != fp_first {
continue;
}
if file_path_norm == pn {
return true;
}
if fp_bytes.len() > pn_bytes.len()
&& fp_bytes[pn_bytes.len()] == b'\\'
&& file_path_norm.starts_with(pn)
{
return true;
}
}
false
}
fn trim_trailing_separators(s: &str) -> &str {
s.trim_end_matches(['\\', '/'])
}
fn is_drive_root(path: &str) -> bool {
let stripped = match strip_verbatim_or_device_prefix(path) {
Some(s) => s,
None => return false,
};
let trimmed = trim_trailing_separators(stripped);
let bytes = trimmed.as_bytes();
bytes.len() == 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':'
}
fn has_short_name_component(norm: &str) -> bool {
norm.split('\\').any(|component| {
let base = component.split('.').next().unwrap_or(component);
match base.find('~') {
Some(tilde) => {
let suffix = &base[tilde + 1..];
!suffix.is_empty() && suffix.bytes().all(|b| b.is_ascii_digit())
}
None => false,
}
})
}
fn json_array_strings(v: &Value) -> Vec<String> {
v.as_array()
.map(|arr| {
arr.iter()
.filter_map(|e| e.as_str().map(|s| s.to_string()))
.collect()
})
.unwrap_or_default()
}
pub fn update_from_access_events(
config: &mut Value,
bin_path: &str,
events: &[LearningModeAccessEvent],
deny_set: &HashSet<String>,
verbose: bool,
) -> Result<AddedPaths> {
let mut added_rw: Vec<String> = Vec::new();
let mut added_ro: Vec<String> = Vec::new();
let bin_path_norm = normalize_path(bin_path);
let deny_norm: Vec<String> = deny_set.iter().filter_map(|s| normalize_path(s)).collect();
let deny_set_norm: HashSet<&str> = deny_norm.iter().map(|s| s.as_str()).collect();
let mut rw_existing_norm: Vec<String> =
json_array_strings(&config["filesystem"]["readwritePaths"])
.into_iter()
.filter_map(|s| normalize_path(&s))
.collect();
let mut rw_existing_set: HashSet<String> = rw_existing_norm.iter().cloned().collect();
let mut ro_existing_norm: Vec<String> =
json_array_strings(&config["filesystem"]["readonlyPaths"])
.into_iter()
.filter_map(|s| normalize_path(&s))
.collect();
let mut ro_existing_set: HashSet<String> = ro_existing_norm.iter().cloned().collect();
for ev in events {
let ev_norm = match normalize_path(&ev.file_path) {
Some(n) => n,
None => {
if verbose {
println!(
"Skipping un-normalizable path (UNC verbatim or stream syntax): {}",
ev.file_path
);
}
continue;
}
};
let is_self_event = ev.file_path.eq_ignore_ascii_case(bin_path)
|| bin_path_norm
.as_ref()
.is_some_and(|bp_norm| bp_norm == &ev_norm);
if is_self_event {
if verbose {
println!("File {} is the binary path, skipping event.", ev.file_path);
}
continue;
}
if has_short_name_component(&ev_norm) {
if verbose {
println!(
"Skipping 8.3 short-name path (cannot prove it isn't a deny alias): {}",
ev.file_path
);
}
continue;
}
if deny_set_norm.contains(ev_norm.as_str())
|| path_starts_with_any_norm(&ev_norm, &deny_norm)
{
continue;
}
if rw_existing_set.contains(&ev_norm) {
continue;
}
if path_starts_with_any_norm(&ev_norm, &rw_existing_norm) {
rw_existing_set.insert(ev_norm.clone());
continue;
}
if (ev.access_mask & WRITE_MASK) != 0 {
if is_drive_root(&ev.file_path) {
if verbose {
println!("Skipping write event at bare drive root: {}", ev.file_path);
}
continue;
}
let arr = config["filesystem"]["readwritePaths"]
.as_array_mut()
.ok_or_else(|| {
anyhow::anyhow!("`filesystem.readwritePaths` must be a JSON array")
})?;
arr.push(Value::String(ev.file_path.clone()));
if rw_existing_set.insert(ev_norm.clone()) {
rw_existing_norm.push(ev_norm);
added_rw.push(ev.file_path.clone());
}
continue;
}
if (ev.access_mask & READ_MASK) != 0 {
if is_drive_root(&ev.file_path) {
if verbose {
println!("Skipping read event at bare drive root: {}", ev.file_path);
}
continue;
}
if ro_existing_set.contains(&ev_norm) {
continue;
}
if path_starts_with_any_norm(&ev_norm, &ro_existing_norm) {
ro_existing_set.insert(ev_norm.clone());
continue;
}
let arr = config["filesystem"]["readonlyPaths"]
.as_array_mut()
.ok_or_else(|| {
anyhow::anyhow!("`filesystem.readonlyPaths` must be a JSON array")
})?;
arr.push(Value::String(ev.file_path.clone()));
if ro_existing_set.insert(ev_norm.clone()) {
ro_existing_norm.push(ev_norm);
added_ro.push(ev.file_path.clone());
}
}
}
Ok(AddedPaths {
readwrite: added_rw,
readonly: added_ro,
})
}
pub fn write_added_paths_summary(added: &AddedPaths, verbose: bool) {
if !verbose {
return;
}
println!();
if !added.readwrite.is_empty() {
println!("Added to readwritePaths ({}):", added.readwrite.len());
for p in &added.readwrite {
println!(" + {p}");
}
}
if !added.readonly.is_empty() {
println!("Added to readonlyPaths ({}):", added.readonly.len());
for p in &added.readonly {
println!(" + {p}");
}
}
}
pub fn resolve_adjusted_config_path(dest_config: &Path) -> Result<PathBuf> {
let leaf = dest_config.file_name().ok_or_else(|| {
anyhow::anyhow!(
"cannot derive adjusted-config path: {} has no file name",
dest_config.display()
)
})?;
let parent = dest_config.parent().ok_or_else(|| {
anyhow::anyhow!(
"cannot derive adjusted-config path: {} has no parent directory",
dest_config.display()
)
})?;
let leaf = leaf.to_string_lossy();
Ok(parent.join(format!("Adjusted_{leaf}")))
}
pub fn save_adjusted_config(config: &Value, path: &Path) -> Result<()> {
use std::io::Write;
let pretty = serde_json::to_string_pretty(config)?;
let dir = path.parent().unwrap_or_else(|| Path::new("."));
let mut tmp = tempfile::NamedTempFile::new_in(dir)
.with_context(|| format!("failed to create temp file in {}", dir.display()))?;
tmp.write_all(pretty.as_bytes())
.and_then(|_| tmp.as_file().sync_all())
.with_context(|| format!("failed to write temp adjusted config in {}", dir.display()))?;
tmp.persist(path)
.map_err(|e| e.error)
.with_context(|| format!("failed to replace {}", path.display()))?;
Ok(())
}
fn decode_access_mask(mask: u32) -> String {
let mut parts: Vec<&str> = Vec::new();
let mut covered: u32 = 0;
for flag in ACCESS_FLAGS {
if mask & flag.bit != 0 {
parts.push(flag.name);
covered |= flag.bit;
}
}
let leftover = mask & !covered;
if leftover != 0 {
let joined = parts.join("|");
if joined.is_empty() {
return format!("OTHER(0x{leftover:X})");
}
return format!("{joined}|OTHER(0x{leftover:X})");
}
if parts.is_empty() {
"NONE".to_string()
} else {
parts.join("|")
}
}
fn classify_mask(mask: u32) -> &'static str {
let w = mask & WRITE_MASK != 0;
let r = mask & READ_MASK != 0;
match (r, w) {
(true, true) => "RW",
(false, true) => "W",
(true, false) => "R",
(false, false) => "-",
}
}
pub fn write_detection_summary(events: &[LearningModeAccessEvent], capabilities: &HashSet<String>) {
use std::collections::BTreeMap;
let mut per_path: BTreeMap<&str, u32> = BTreeMap::new();
for ev in events {
*per_path.entry(ev.file_path.as_str()).or_insert(0) |= ev.access_mask;
}
println!();
println!("Detected file paths ({}):", per_path.len());
if per_path.is_empty() {
println!(" (none)");
} else {
for (path, mask) in &per_path {
println!(
" [{:2}] 0x{:08X} {} {}",
classify_mask(*mask),
mask,
decode_access_mask(*mask),
path
);
}
}
println!();
println!("Detected capabilities ({}):", capabilities.len());
if capabilities.is_empty() {
println!(" (none)");
} else {
let mut sorted: Vec<&String> = capabilities.iter().collect();
sorted.sort();
for c in sorted {
println!(" + {c}");
}
}
}
pub fn write_requested_capabilities_summary(requested: &HashSet<String>, verbose: bool) {
if !verbose {
return;
}
println!();
println!("All requested capabilities ({}):", requested.len());
if requested.is_empty() {
println!(" (none)");
return;
}
let mut sorted: Vec<&String> = requested.iter().collect();
sorted.sort();
for c in sorted {
println!(" {c}");
}
}
const RESERVED_CAPABILITIES: &[&str] = &["learningModeLogging", "permissiveLearningMode"];
use crate::plm::extract_caps::ascii_ci_cmp;
fn object_key_ignore_ascii_case(config: &Value, wanted: &str) -> Option<String> {
config
.as_object()?
.keys()
.find(|k| k.eq_ignore_ascii_case(wanted))
.cloned()
}
pub fn merge_capabilities(config: &mut Value, requested: &HashSet<String>) -> Result<()> {
if requested.is_empty() {
return Ok(());
}
let mergeable: Vec<&str> = requested
.iter()
.map(String::as_str)
.filter(|name| {
!RESERVED_CAPABILITIES
.iter()
.any(|r| r.eq_ignore_ascii_case(name))
})
.collect();
if mergeable.is_empty() {
return Ok(());
}
let Some(pc_key) = object_key_ignore_ascii_case(config, "processContainer") else {
let mut names: Vec<&str> = mergeable.clone();
names.sort_by(|a, b| ascii_ci_cmp(a, b));
eprintln!(
"warning: config has no processContainer block, so this containment backend has no \
capabilities array; {} discovered capability/capabilities not merged: {}",
names.len(),
names.join(", ")
);
return Ok(());
};
let caps_slot = {
let pc = &mut config[&pc_key];
if !pc.is_object() {
eprintln!(
"warning: config's \"{pc_key}\" is not an object; {} discovered capability/\
capabilities not merged",
mergeable.len()
);
return Ok(());
}
match object_key_ignore_ascii_case(pc, "capabilities") {
Some(existing) => existing,
None => {
pc["capabilities"] = json!([]);
"capabilities".to_string()
}
}
};
let slot = &mut config[&pc_key][&caps_slot];
if slot.is_null() {
*slot = json!([]);
}
let Some(existing) = slot.as_array() else {
eprintln!(
"warning: \"{pc_key}.{caps_slot}\" is not an array; {} discovered capability/\
capabilities not merged",
mergeable.len()
);
return Ok(());
};
let mut merged: Vec<String> = Vec::with_capacity(existing.len());
for value in existing {
let Some(name) = value.as_str() else {
eprintln!(
"warning: \"{pc_key}.{caps_slot}\" contains a non-string entry ({value}); {} \
discovered capability/capabilities not merged",
mergeable.len()
);
return Ok(());
};
merged.push(name.to_string());
}
for name in mergeable {
if !merged.iter().any(|e| e.eq_ignore_ascii_case(name)) {
merged.push(name.to_string());
}
}
merged.sort_by(|a, b| ascii_ci_cmp(a, b));
merged.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
*slot = Value::Array(merged.into_iter().map(Value::String).collect());
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::plm::access_event::LearningModeAccessEvent;
use serde_json::json;
fn ev_write(path: &str) -> LearningModeAccessEvent {
LearningModeAccessEvent {
time_created: chrono::Utc::now(),
process_id: 0,
thread_id: 0,
file_path: path.to_string(),
access_mask: 0x2, }
}
fn ev_read(path: &str) -> LearningModeAccessEvent {
LearningModeAccessEvent {
time_created: chrono::Utc::now(),
process_id: 0,
thread_id: 0,
file_path: path.to_string(),
access_mask: 0x1, }
}
fn norm(p: &str) -> String {
normalize_path(p).expect("test input must normalize")
}
#[test]
fn starts_with_any_rejects_sibling_with_shared_prefix() {
assert!(!path_starts_with_any_norm(
&norm("C:\\foobar\\baz"),
[norm("C:\\foo")]
));
}
#[test]
fn starts_with_any_matches_exact() {
assert!(path_starts_with_any_norm(
&norm("C:\\foo"),
[norm("C:\\foo")]
));
}
#[test]
fn starts_with_any_matches_nested_child() {
assert!(path_starts_with_any_norm(
&norm("C:\\foo\\bar\\baz.txt"),
[norm("C:\\foo")]
));
}
#[test]
fn starts_with_any_is_case_insensitive_and_separator_tolerant() {
assert!(path_starts_with_any_norm(
&norm("c:\\Foo\\bar"),
[norm("C:\\foo\\")]
));
}
#[test]
fn is_drive_root_detects_variants() {
assert!(is_drive_root("C:\\"));
assert!(is_drive_root("C:"));
assert!(is_drive_root("c:/"));
assert!(!is_drive_root("C:\\foo"));
assert!(!is_drive_root(""));
}
#[test]
fn is_drive_root_handles_verbatim_and_device_prefix() {
assert!(is_drive_root("\\\\?\\C:\\"));
assert!(is_drive_root("\\\\?\\C:"));
assert!(is_drive_root("\\\\.\\C:\\"));
assert!(!is_drive_root("\\\\?\\C:\\hiberfil.sys"));
assert!(!is_drive_root("\\\\?\\UNC\\server\\share"));
}
#[test]
fn normalize_path_strips_verbatim_prefix() {
assert_eq!(normalize_path("\\\\?\\C:\\Foo").as_deref(), Some("c:\\foo"));
assert_eq!(normalize_path("\\\\.\\C:\\Foo").as_deref(), Some("c:\\foo"));
}
#[test]
fn normalize_path_collapses_separators_and_lowercase() {
assert_eq!(
normalize_path("C:/Foo/Bar").as_deref(),
Some("c:\\foo\\bar")
);
}
#[test]
fn normalize_path_strips_trailing_dot_per_component() {
assert_eq!(
normalize_path("C:\\Secrets.").as_deref(),
Some("c:\\secrets")
);
assert_eq!(
normalize_path("C:\\Secrets ").as_deref(),
Some("c:\\secrets")
);
assert_eq!(
normalize_path("C:\\Secrets\\token. ").as_deref(),
Some("c:\\secrets\\token")
);
}
#[test]
fn normalize_path_rejects_ads_outside_drive_separator() {
assert!(normalize_path("C:\\Secrets:hidden").is_none());
assert!(normalize_path("C:\\Secrets\\token.dat:s").is_none());
}
#[test]
fn normalize_path_rejects_unc_verbatim() {
assert!(normalize_path("\\\\?\\UNC\\server\\share\\x").is_none());
}
#[test]
fn normalize_path_strips_nt_object_prefix() {
assert_eq!(normalize_path("\\??\\C:\\foo").as_deref(), Some("c:\\foo"));
}
#[test]
fn normalize_path_passes_globalroot_through_unchanged() {
let got = normalize_path("\\\\?\\GLOBALROOT\\Device\\HarddiskVolume3\\foo");
assert_eq!(
got.as_deref(),
Some("globalroot\\device\\harddiskvolume3\\foo")
);
}
#[test]
fn normalize_path_accepts_non_verbatim_unc() {
let got = normalize_path("\\\\server\\share\\x");
assert_eq!(got.as_deref(), Some("\\\\server\\share\\x"));
}
#[test]
fn normalize_path_passes_drive_relative_through() {
let got = normalize_path("C:foo");
assert_eq!(got.as_deref(), Some("c:foo"));
}
fn run_update(
config: &mut Value,
events: &[LearningModeAccessEvent],
deny: &[&str],
) -> AddedPaths {
initialize_filesystem(config).unwrap();
let deny_set: HashSet<String> = deny.iter().map(|s| (*s).to_string()).collect();
update_from_access_events(config, "__never_matches__", events, &deny_set, false).unwrap()
}
fn run_update_with_bin(
config: &mut Value,
bin_path: &str,
events: &[LearningModeAccessEvent],
deny: &[&str],
) -> AddedPaths {
initialize_filesystem(config).unwrap();
let deny_set: HashSet<String> = deny.iter().map(|s| (*s).to_string()).collect();
update_from_access_events(config, bin_path, events, &deny_set, false).unwrap()
}
#[test]
fn write_to_denied_path_is_not_promoted() {
let mut cfg = json!({
"filesystem": { "deniedPaths": ["C:\\Secrets\\token.dat"] }
});
let added = run_update(
&mut cfg,
&[ev_write("C:\\Secrets\\token.dat")],
&["C:\\Secrets\\token.dat"],
);
assert!(added.readwrite.is_empty());
assert!(cfg["filesystem"]["readwritePaths"]
.as_array()
.unwrap()
.is_empty());
}
#[test]
fn self_event_filter_skips_raw_bin_path() {
let mut cfg = json!({});
let added = run_update_with_bin(
&mut cfg,
"C:\\bin\\plm.exe",
&[ev_read("C:\\bin\\plm.exe")],
&[],
);
assert!(
added.readonly.is_empty(),
"events referencing the PLM binary itself must be filtered"
);
}
#[test]
fn self_event_filter_skips_verbatim_bin_path_against_plain_event() {
let mut cfg = json!({});
let added = run_update_with_bin(
&mut cfg,
"\\\\?\\C:\\bin\\plm.exe",
&[ev_read("C:\\bin\\plm.exe")],
&[],
);
assert!(
added.readonly.is_empty(),
"verbatim bin_path must self-filter plain-form events"
);
}
#[test]
fn self_event_filter_case_insensitive() {
let mut cfg = json!({});
let added = run_update_with_bin(
&mut cfg,
"C:\\bin\\plm.exe",
&[ev_read("c:\\BIN\\PLM.EXE")],
&[],
);
assert!(
added.readonly.is_empty(),
"self-filter must be case-insensitive on Windows paths"
);
}
#[test]
fn non_self_event_passes_through_self_filter() {
let mut cfg = json!({});
let added = run_update_with_bin(
&mut cfg,
"C:\\bin\\plm.exe",
&[ev_read("C:\\Users\\foo\\bar.txt")],
&[],
);
assert_eq!(
added.readonly.len(),
1,
"non-self event must NOT be filtered: {added:?}"
);
}
#[test]
fn write_to_sibling_does_not_bypass_denied_via_parent() {
let mut cfg = json!({
"filesystem": { "deniedPaths": ["C:\\Secrets"] }
});
let added = run_update(
&mut cfg,
&[ev_write("C:\\Secrets\\scratch.txt")],
&["C:\\Secrets"],
);
assert!(
added.readwrite.is_empty(),
"expected no rw promotion, got: {:?}",
added.readwrite
);
}
#[cfg(target_os = "windows")]
#[test]
fn write_at_drive_root_does_not_grant_whole_volume() {
let mut cfg = json!({});
let added = run_update(&mut cfg, &[ev_write("C:\\hiberfil.sys")], &[]);
assert_eq!(added.readwrite, vec!["C:\\hiberfil.sys".to_string()]);
assert!(
!added.readwrite.iter().any(|p| is_drive_root(p)),
"drive-root grant leaked: {:?}",
added.readwrite
);
}
#[cfg(target_os = "windows")]
#[test]
fn read_at_drive_root_does_not_grant_whole_volume() {
for root in ["C:", "C:\\"] {
let mut cfg = json!({});
let added = run_update(&mut cfg, &[ev_read(root)], &[]);
assert!(
added.readonly.is_empty(),
"drive-root read grant leaked for {root:?}: {:?}",
added.readonly
);
}
}
#[cfg(target_os = "windows")]
#[test]
fn read_via_verbatim_drive_root_does_not_grant_volume() {
let mut cfg = json!({});
let added = run_update(&mut cfg, &[ev_read("\\\\?\\C:\\")], &[]);
assert!(
added.readonly.is_empty(),
"verbatim drive-root read grant leaked: {:?}",
added.readonly
);
}
#[cfg(target_os = "windows")]
#[test]
fn read_of_file_under_drive_root_is_still_granted() {
let mut cfg = json!({});
let added = run_update(&mut cfg, &[ev_read("C:\\pagefile.sys")], &[]);
assert_eq!(added.readonly, vec!["C:\\pagefile.sys".to_string()]);
}
#[cfg(target_os = "windows")]
#[test]
fn write_grants_exact_file_not_parent_directory() {
let mut cfg = json!({});
let added = run_update(&mut cfg, &[ev_write("C:\\a\\b\\c.txt")], &[]);
assert_eq!(added.readwrite, vec!["C:\\a\\b\\c.txt".to_string()]);
}
#[test]
fn read_under_existing_readonly_parent_is_not_duplicated() {
let mut cfg = json!({
"filesystem": { "readonlyPaths": ["C:\\src"] }
});
let added = run_update(&mut cfg, &[ev_read("C:\\src\\main.rs")], &[]);
assert!(added.readonly.is_empty());
}
#[cfg(target_os = "windows")]
#[test]
fn idempotent_on_already_writable_path() {
let mut cfg = json!({
"filesystem": { "readwritePaths": ["C:\\out"] }
});
let added = run_update(&mut cfg, &[ev_write("C:\\out\\foo.txt")], &[]);
assert!(added.readwrite.is_empty());
}
#[cfg(target_os = "windows")]
#[test]
fn write_via_verbatim_drive_root_does_not_grant_volume() {
let mut cfg = json!({});
let added = run_update(&mut cfg, &[ev_write("\\\\?\\C:\\hiberfil.sys")], &[]);
for p in &added.readwrite {
assert!(
normalize_path(p).map(|n| n.len() > 2).unwrap_or(true),
"verbatim drive-root grant leaked: {p}"
);
}
}
#[test]
fn write_to_trailing_dot_variant_of_denied_dir_is_blocked() {
let mut cfg = json!({
"filesystem": { "deniedPaths": ["C:\\Secrets"] }
});
let added = run_update(
&mut cfg,
&[ev_write("C:\\Secrets.\\token.txt")],
&["C:\\Secrets"],
);
assert!(
added.readwrite.is_empty(),
"deny bypass via trailing dot: {:?}",
added.readwrite
);
}
#[test]
fn write_to_ads_on_denied_dir_is_rejected() {
let mut cfg = json!({
"filesystem": { "deniedPaths": ["C:\\Secrets"] }
});
let added = run_update(
&mut cfg,
&[ev_write("C:\\Secrets:hidden")],
&["C:\\Secrets"],
);
assert!(
added.readwrite.is_empty(),
"ADS on denied dir slipped through: {:?}",
added.readwrite
);
}
#[test]
fn mixed_separators_do_not_cause_duplicates() {
let mut cfg = json!({
"filesystem": { "readonlyPaths": ["C:\\src"] }
});
let added = run_update(&mut cfg, &[ev_read("C:/src/main.rs")], &[]);
assert!(
added.readonly.is_empty(),
"mixed separators created duplicate: {:?}",
added.readonly
);
}
#[test]
fn initialize_filesystem_rejects_non_object_root() {
let mut cfg = json!([]);
assert!(initialize_filesystem(&mut cfg).is_err());
}
#[test]
fn initialize_filesystem_rejects_wrong_typed_filesystem() {
let mut cfg = json!({ "filesystem": "deny" });
assert!(initialize_filesystem(&mut cfg).is_err());
}
#[test]
fn load_config_rejects_malformed_json() {
let tmp =
std::env::temp_dir().join(format!("plm_load_cfg_test_{}.json", std::process::id()));
std::fs::write(&tmp, b"{not valid json").unwrap();
let err = load_config(&tmp).unwrap_err();
let _ = std::fs::remove_file(&tmp);
assert!(
format!("{err}").to_ascii_lowercase().contains("json")
|| format!("{err}").contains("parse")
);
}
#[test]
fn read_write_masks_are_disjoint_and_exclude_non_granting_bits() {
assert_eq!(WRITE_MASK & 0x2, 0x2, "FILE_WRITE is a write bit");
assert_eq!(READ_MASK & 0x1, 0x1, "READ_DATA is a read bit");
assert_eq!(READ_MASK & 0x20000, 0, "READ_CONTROL must not be read");
assert_eq!(WRITE_MASK & 0x20000, 0, "READ_CONTROL must not be write");
assert_eq!(READ_MASK & 0x100000, 0, "SYNCHRONIZE must not be read");
assert_eq!(WRITE_MASK & 0x100000, 0, "SYNCHRONIZE must not be write");
assert_eq!(READ_MASK & 0x1000_0000, 0x1000_0000);
assert_eq!(WRITE_MASK & 0x1000_0000, 0x1000_0000);
assert_eq!(READ_MASK & 0x8000_0000, 0x8000_0000);
assert_eq!(WRITE_MASK & 0x8000_0000, 0);
assert_eq!(WRITE_MASK & 0x4000_0000, 0x4000_0000);
assert_eq!(READ_MASK & 0x4000_0000, 0);
}
#[test]
fn classify_mask_table() {
assert_eq!(classify_mask(0x0), "-");
assert_eq!(classify_mask(0x1), "R"); assert_eq!(classify_mask(0x2), "W"); assert_eq!(classify_mask(0x1 | 0x2), "RW");
assert_eq!(classify_mask(0x100000), "-", "SYNCHRONIZE-only");
assert_eq!(classify_mask(0x20000), "-", "READ_CONTROL-only");
assert_eq!(classify_mask(0x8000_0000), "R", "GENERIC_READ");
assert_eq!(classify_mask(0x4000_0000), "W", "GENERIC_WRITE");
assert_eq!(classify_mask(0x1000_0000), "RW", "GENERIC_ALL");
}
#[test]
fn decode_access_mask_table() {
assert_eq!(decode_access_mask(0x0), "NONE");
assert_eq!(decode_access_mask(0x1), "READ_DATA");
assert_eq!(decode_access_mask(0x2), "FILE_WRITE");
assert_eq!(decode_access_mask(0x1 | 0x2), "READ_DATA|FILE_WRITE");
assert_eq!(decode_access_mask(0x100000), "SYNCHRONIZE");
assert_eq!(decode_access_mask(0x20000), "READ_CONTROL");
assert_eq!(decode_access_mask(0x8000_0000), "GENERIC_READ");
assert_eq!(decode_access_mask(0x800), "OTHER(0x800)");
assert_eq!(decode_access_mask(0x1 | 0x800), "READ_DATA|OTHER(0x800)");
}
#[test]
fn generic_only_event_is_promoted() {
let mut cfg = json!({});
let mut ev = ev_read("C:\\data\\gen.dat");
ev.access_mask = 0x8000_0000; let added = run_update(&mut cfg, &[ev], &[]);
assert_eq!(added.readonly, vec!["C:\\data\\gen.dat".to_string()]);
}
#[test]
fn synchronize_only_event_is_not_promoted() {
let mut cfg = json!({});
let mut ev = ev_read("C:\\data\\sync.dat");
ev.access_mask = 0x100000; let added = run_update(&mut cfg, &[ev], &[]);
assert!(
added.readonly.is_empty(),
"SYNCHRONIZE-only must not promote"
);
}
#[test]
fn has_short_name_component_detects_mangled_names() {
assert!(has_short_name_component("c:\\progra~1\\app"));
assert!(has_short_name_component("c:\\secret~1\\token.dat"));
assert!(has_short_name_component("c:\\dir\\file~12.txt"));
assert!(!has_short_name_component("c:\\foo~bar\\baz"));
assert!(!has_short_name_component("c:\\normal\\path.txt"));
}
#[test]
fn short_name_path_is_not_promoted() {
let mut cfg = json!({
"filesystem": { "deniedPaths": ["C:\\Secrets"] }
});
let added = run_update(
&mut cfg,
&[ev_write("C:\\secret~1\\token.dat")],
&["C:\\Secrets"],
);
assert!(
added.readwrite.is_empty(),
"8.3 short-name alias of a denied dir must not be promoted"
);
}
#[test]
fn junction_alias_of_denied_dir_is_a_known_gap() {
let mut cfg = json!({
"filesystem": { "deniedPaths": ["C:\\Secrets"] }
});
let added = run_update(
&mut cfg,
&[ev_write("C:\\work\\link\\token.dat")],
&["C:\\Secrets"],
);
assert_eq!(
added.readwrite,
vec!["C:\\work\\link\\token.dat".to_string()],
"known limitation: reparse-point aliases are not resolved"
);
}
#[test]
fn resolve_adjusted_derives_sibling_name() {
let dest = Path::new("logs").join("config.json");
let got = resolve_adjusted_config_path(&dest).unwrap();
assert_eq!(got, PathBuf::from("logs").join("Adjusted_config.json"));
}
#[test]
fn resolve_adjusted_relative_leaf() {
let got = resolve_adjusted_config_path(Path::new("config.json")).unwrap();
assert_eq!(got, PathBuf::from("Adjusted_config.json"));
}
#[cfg(windows)]
#[test]
fn resolve_adjusted_errors_without_file_name() {
assert!(resolve_adjusted_config_path(Path::new("C:\\")).is_err());
}
#[test]
fn resolve_adjusted_is_pure_no_dir_side_effect() {
let ghost = std::env::temp_dir().join(format!(
"plm_resolve_pure_{}_{}",
std::process::id(),
"does_not_exist"
));
let dest = ghost.join("config.json");
let got = resolve_adjusted_config_path(&dest).unwrap();
assert_eq!(got, ghost.join("Adjusted_config.json"));
assert!(!ghost.exists(), "resolver must not create directories");
}
#[test]
fn save_adjusted_config_round_trips() {
let dir = std::env::temp_dir().join(format!("plm_save_atomic_{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("Adjusted_config.json");
let cfg = json!({"filesystem": {"readonlyPaths": ["C:\\x"]}});
save_adjusted_config(&cfg, &path).unwrap();
let back: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
assert_eq!(back, cfg);
let cfg2 = json!({"filesystem": {"readonlyPaths": ["C:\\y"]}});
save_adjusted_config(&cfg2, &path).unwrap();
let back2: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
assert_eq!(back2, cfg2);
let _ = std::fs::remove_dir_all(&dir);
}
fn caps_of(config: &Value) -> Vec<String> {
config["processContainer"]["capabilities"]
.as_array()
.expect("capabilities array")
.iter()
.map(|v| v.as_str().unwrap().to_string())
.collect()
}
fn requested(names: &[&str]) -> HashSet<String> {
names.iter().map(|s| s.to_string()).collect()
}
#[test]
fn merge_capabilities_adds_to_existing_array_sorted() {
let mut cfg = json!({"processContainer": {"capabilities": ["registryRead"]}});
merge_capabilities(
&mut cfg,
&requested(&["internetClient", "documentsLibrary"]),
)
.unwrap();
assert_eq!(
caps_of(&cfg),
vec!["documentsLibrary", "internetClient", "registryRead"]
);
}
#[test]
fn merge_capabilities_preserves_existing_spelling_and_dedupes_case_insensitively() {
let mut cfg = json!({"processContainer": {"capabilities": ["InternetClient"]}});
merge_capabilities(&mut cfg, &requested(&["internetclient"])).unwrap();
assert_eq!(caps_of(&cfg), vec!["InternetClient"]);
}
#[test]
fn merge_capabilities_creates_missing_array() {
let mut cfg = json!({"processContainer": {"learningMode": true}});
merge_capabilities(&mut cfg, &requested(&["internetClient"])).unwrap();
assert_eq!(caps_of(&cfg), vec!["internetClient"]);
assert_eq!(cfg["processContainer"]["learningMode"], json!(true));
}
#[test]
fn merge_capabilities_replaces_null_array() {
let mut cfg = json!({"processContainer": {"capabilities": null}});
merge_capabilities(&mut cfg, &requested(&["internetClient"])).unwrap();
assert_eq!(caps_of(&cfg), vec!["internetClient"]);
}
#[test]
fn merge_capabilities_resolves_containment_key_case_insensitively() {
let mut cfg = json!({"ProcessContainer": {"capabilities": []}});
merge_capabilities(&mut cfg, &requested(&["internetClient"])).unwrap();
assert!(cfg.get("processContainer").is_none());
assert_eq!(
cfg["ProcessContainer"]["capabilities"],
json!(["internetClient"])
);
}
#[test]
fn merge_capabilities_is_noop_without_process_container() {
let mut cfg = json!({"lxc": {"image": "ubuntu"}});
let before = cfg.clone();
merge_capabilities(&mut cfg, &requested(&["internetClient"])).unwrap();
assert_eq!(cfg, before);
}
#[test]
fn merge_capabilities_drops_reserved_names() {
let mut cfg = json!({"processContainer": {"capabilities": []}});
merge_capabilities(
&mut cfg,
&requested(&[
"permissiveLearningMode",
"learningModeLogging",
"internetClient",
]),
)
.unwrap();
assert_eq!(caps_of(&cfg), vec!["internetClient"]);
}
#[test]
fn merge_capabilities_reserved_only_leaves_config_untouched() {
let mut cfg = json!({"processContainer": {"learningMode": true}});
let before = cfg.clone();
merge_capabilities(&mut cfg, &requested(&["permissiveLearningMode"])).unwrap();
assert_eq!(cfg, before);
}
#[test]
fn merge_capabilities_empty_request_is_noop() {
let mut cfg = json!({"processContainer": {"learningMode": true}});
let before = cfg.clone();
merge_capabilities(&mut cfg, &HashSet::new()).unwrap();
assert_eq!(cfg, before);
}
#[test]
fn merge_capabilities_is_idempotent() {
let mut cfg = json!({"processContainer": {"capabilities": []}});
let req = requested(&["internetClient", "documentsLibrary"]);
merge_capabilities(&mut cfg, &req).unwrap();
let once = cfg.clone();
merge_capabilities(&mut cfg, &req).unwrap();
assert_eq!(cfg, once, "re-merging the same set must not change output");
}
#[test]
fn merge_capabilities_leaves_non_array_capabilities_alone() {
let mut cfg = json!({"processContainer": {"capabilities": "internetClient"}});
let before = cfg.clone();
merge_capabilities(&mut cfg, &requested(&["documentsLibrary"])).unwrap();
assert_eq!(
cfg, before,
"must not clobber a malformed capabilities slot"
);
}
#[test]
fn merge_capabilities_leaves_non_string_entries_alone() {
for bad in [
json!(["internetClient", true]),
json!(["internetClient", null]),
json!(["internetClient", 42]),
json!(["internetClient", {"name": "documentsLibrary"}]),
json!(["internetClient", ["documentsLibrary"]]),
] {
let mut cfg = json!({ "processContainer": { "capabilities": bad } });
let before = cfg.clone();
merge_capabilities(&mut cfg, &requested(&["documentsLibrary"])).unwrap();
assert_eq!(
cfg, before,
"a non-string entry must leave the array exactly as authored"
);
}
}
#[test]
fn merge_capabilities_still_merges_when_every_entry_is_a_string() {
let mut cfg = json!({"processContainer": {"capabilities": ["internetClient"]}});
merge_capabilities(&mut cfg, &requested(&["documentsLibrary"])).unwrap();
assert_eq!(caps_of(&cfg), vec!["documentsLibrary", "internetClient"]);
}
#[test]
fn ascii_ci_cmp_is_a_total_order_including_non_ascii() {
use std::cmp::Ordering;
assert_eq!(ascii_ci_cmp("abc", "ABC"), Ordering::Equal);
assert_eq!(ascii_ci_cmp("abc", "abcd"), Ordering::Less);
assert_eq!(ascii_ci_cmp("Zeta", "alpha"), Ordering::Greater);
let a = "café";
let b = "CAFÉ";
assert_eq!(ascii_ci_cmp(a, b), ascii_ci_cmp(a, b));
assert_eq!(ascii_ci_cmp(a, a), Ordering::Equal);
}
#[test]
fn merge_capabilities_sorts_case_insensitively() {
let mut cfg = json!({"processContainer": {"capabilities": []}});
merge_capabilities(
&mut cfg,
&requested(&["Zebra", "apple", "Banana", "cherry"]),
)
.unwrap();
assert_eq!(caps_of(&cfg), vec!["apple", "Banana", "cherry", "Zebra"]);
}
}