1use std::path::{Path, PathBuf};
46use std::sync::OnceLock;
47
48use serde::Deserialize;
49use serde_json::{json, Value as Json};
50
51use crate::clients::Os;
52use crate::persist::datadir::{Env, RealEnv};
53
54pub const FILE_NAME: &str = "policy.toml";
56
57const DIR_NAME: &str = "memfork";
59
60pub const EXTRA_ENV: &str = "MEMFORK_POLICY_FILE";
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum Feature {
67 Brain,
70 Race,
72 Autopilot,
74 MaintenanceTasks,
76 Sampling,
78 SecretOverrides,
80}
81
82impl Feature {
83 pub const ALL: [Feature; 6] = [
85 Feature::Brain,
86 Feature::Race,
87 Feature::Autopilot,
88 Feature::MaintenanceTasks,
89 Feature::Sampling,
90 Feature::SecretOverrides,
91 ];
92
93 pub fn key(self) -> &'static str {
95 match self {
96 Feature::Brain => "brain",
97 Feature::Race => "race",
98 Feature::Autopilot => "autopilot",
99 Feature::MaintenanceTasks => "maintenance_tasks",
100 Feature::Sampling => "sampling",
101 Feature::SecretOverrides => "secret_overrides",
102 }
103 }
104
105 pub fn describe(self) -> &'static str {
107 match self {
108 Feature::Brain => "the Brain",
109 Feature::Race => "race",
110 Feature::Autopilot => "autopilot",
111 Feature::MaintenanceTasks => "maintenance tasks",
112 Feature::Sampling => "sampling",
113 Feature::SecretOverrides => "secret overrides",
114 }
115 }
116}
117
118#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
120#[serde(deny_unknown_fields)]
121struct File {
122 brain: Option<bool>,
123 race: Option<bool>,
124 autopilot: Option<bool>,
125 maintenance_tasks: Option<bool>,
126 sampling: Option<bool>,
127 secret_overrides: Option<bool>,
128 data_dir: Option<String>,
129}
130
131impl File {
132 fn get(&self, feature: Feature) -> Option<bool> {
133 match feature {
134 Feature::Brain => self.brain,
135 Feature::Race => self.race,
136 Feature::Autopilot => self.autopilot,
137 Feature::MaintenanceTasks => self.maintenance_tasks,
138 Feature::Sampling => self.sampling,
139 Feature::SecretOverrides => self.secret_overrides,
140 }
141 }
142}
143
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub enum Origin {
147 Machine,
149 Extra,
151}
152
153#[derive(Debug, Clone, PartialEq, Eq)]
155pub struct Policy {
156 pub machine_path: Option<PathBuf>,
160 pub machine_present: bool,
162 pub extra_path: Option<PathBuf>,
164 forbidden: Vec<(Feature, Origin)>,
166 data_dir: Option<(PathBuf, Origin)>,
168}
169
170impl Policy {
171 pub fn permissive() -> Self {
173 Policy {
174 machine_path: None,
175 machine_present: false,
176 extra_path: None,
177 forbidden: Vec::new(),
178 data_dir: None,
179 }
180 }
181
182 pub fn allows(&self, feature: Feature) -> bool {
184 !self.forbidden.iter().any(|(f, _)| *f == feature)
185 }
186
187 pub fn forbidden_by(&self, feature: Feature) -> Option<Origin> {
189 self.forbidden
190 .iter()
191 .find(|(f, _)| *f == feature)
192 .map(|(_, o)| *o)
193 }
194
195 pub fn data_dir(&self) -> Option<&Path> {
197 self.data_dir.as_ref().map(|(p, _)| p.as_path())
198 }
199
200 pub fn in_force(&self) -> bool {
202 self.machine_present || self.extra_path.is_some()
203 }
204
205 pub fn path_of(&self, origin: Origin) -> String {
207 let path = match origin {
208 Origin::Machine => self.machine_path.as_deref(),
209 Origin::Extra => self.extra_path.as_deref(),
210 };
211 path.map_or_else(|| "the policy".to_owned(), crate::style::path)
212 }
213
214 pub fn refusal(&self, feature: Feature) -> String {
217 let origin = self.forbidden_by(feature).unwrap_or(Origin::Machine);
218 format!(
219 "{} {} switched off by the machine policy at {}. Nothing on the command \
220 line, in the environment or in a project can turn it back on; an \
221 administrator would change that file.",
222 first_upper(feature.describe()),
223 if feature.describe().ends_with('s') {
224 "are"
225 } else {
226 "is"
227 },
228 self.path_of(origin)
229 )
230 }
231
232 pub fn summary(&self) -> String {
234 if !self.in_force() {
235 return "none".to_owned();
236 }
237 let mut parts: Vec<String> = self
238 .forbidden
239 .iter()
240 .map(|(f, _)| format!("{} off", f.describe()))
241 .collect();
242 if let Some((dir, _)) = &self.data_dir {
243 parts.push(format!(
244 "data directory pinned to {}",
245 crate::style::path(dir)
246 ));
247 }
248 if parts.is_empty() {
249 "a policy file is present and switches nothing off".to_owned()
250 } else {
251 parts.join(", ")
252 }
253 }
254
255 pub fn to_json(&self) -> Json {
257 let mut features = serde_json::Map::new();
258 for f in Feature::ALL {
259 features.insert(f.key().to_owned(), json!(self.allows(f)));
260 }
261 json!({
262 "machine_file": self.machine_path.as_deref().map(crate::style::path),
263 "machine_file_present": self.machine_present,
264 "extra_file": self.extra_path.as_deref().map(crate::style::path),
265 "in_force": self.in_force(),
266 "allows": features,
267 "data_dir": self.data_dir.as_ref().map(|(p, _)| crate::style::path(p)),
268 })
269 }
270}
271
272fn first_upper(s: &str) -> String {
273 let mut chars = s.chars();
274 match chars.next() {
275 Some(c) => c.to_uppercase().collect::<String>() + chars.as_str(),
276 None => String::new(),
277 }
278}
279
280#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
282#[error(
283 "the policy file {path} could not be read: {why}\n\
284 MemFork stops rather than run with a machine-wide rule it cannot \
285 understand. An administrator would fix that file; `memfork doctor` \
286 reports it in the meantime."
287)]
288pub struct Error {
289 pub path: String,
291 pub why: String,
293}
294
295pub fn machine_path(os: Os, env: &impl Env) -> Option<PathBuf> {
300 let base = match os {
301 Os::Windows => env
302 .get("ProgramData")
303 .or_else(|| env.get("PROGRAMDATA"))
304 .or_else(|| env.get("ALLUSERSPROFILE"))?,
305 Os::MacOs => "/Library/Application Support".to_owned(),
306 Os::Linux => "/etc".to_owned(),
307 };
308 let sep = os.separator();
312 Some(PathBuf::from(format!(
313 "{}{sep}{DIR_NAME}{sep}{FILE_NAME}",
314 base.trim_end_matches(['/', '\\'])
315 )))
316}
317
318fn read(path: &Path) -> Result<Option<String>, Error> {
320 match std::fs::read_to_string(path) {
321 Ok(text) => Ok(Some(text)),
322 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
323 Err(e) => Err(Error {
324 path: crate::style::path(path),
325 why: e.to_string(),
326 }),
327 }
328}
329
330fn parse(path: &Path, text: &str) -> Result<File, Error> {
331 toml::from_str(text).map_err(|e| Error {
332 path: crate::style::path(path),
333 why: e.message().to_owned(),
334 })
335}
336
337fn combine(
340 machine_path: Option<PathBuf>,
341 machine: Option<&File>,
342 extra: Option<(&Path, &File)>,
343) -> Policy {
344 let mut policy = Policy {
345 machine_path,
346 machine_present: machine.is_some(),
347 extra_path: extra.map(|(p, _)| p.to_path_buf()),
348 forbidden: Vec::new(),
349 data_dir: None,
350 };
351 let layers = [
352 extra.map(|(_, f)| (f, Origin::Extra)),
353 machine.map(|f| (f, Origin::Machine)),
354 ];
355 for (file, origin) in layers.into_iter().flatten() {
356 for feature in Feature::ALL {
357 if let Some(allowed) = file.get(feature) {
358 policy.forbidden.retain(|(f, _)| *f != feature);
359 if !allowed {
360 policy.forbidden.push((feature, origin));
361 }
362 }
363 }
364 if let Some(dir) = &file.data_dir {
365 policy.data_dir = Some((PathBuf::from(dir), origin));
366 }
367 }
368 policy
369 .forbidden
370 .sort_by_key(|(f, _)| Feature::ALL.iter().position(|x| x == f));
371 policy
372}
373
374pub fn load(os: Os, env: &impl Env) -> Result<Policy, Error> {
377 let machine_path = machine_path(os, env);
378 let machine = match &machine_path {
379 Some(p) => read(p)?.map(|text| parse(p, &text)).transpose()?,
380 None => None,
381 };
382 let extra_path = env.get(EXTRA_ENV).map(PathBuf::from);
383 let extra = match &extra_path {
384 Some(p) => read(p)?.map(|text| parse(p, &text)).transpose()?,
385 None => None,
386 };
387 Ok(combine(
388 machine_path,
389 machine.as_ref(),
390 extra_path.as_deref().zip(extra.as_ref()),
391 ))
392}
393
394pub fn current() -> Result<&'static Policy, Error> {
396 static POLICY: OnceLock<Result<Policy, Error>> = OnceLock::new();
397 POLICY
398 .get_or_init(|| load(Os::current(), &RealEnv))
399 .as_ref()
400 .map_err(Clone::clone)
401}
402
403pub fn allows(feature: Feature) -> bool {
408 current().is_ok_and(|p| p.allows(feature))
409}
410
411pub fn refusal(feature: Feature) -> String {
413 match current() {
414 Ok(p) => p.refusal(feature),
415 Err(e) => e.to_string(),
416 }
417}
418
419#[cfg(test)]
420mod tests {
421 use super::*;
422 use crate::persist::datadir::MapEnv;
423
424 fn file(text: &str) -> File {
425 parse(Path::new("t.toml"), text).expect("parses")
426 }
427
428 #[test]
429 fn the_machine_file_has_one_place_per_os() {
430 let win = MapEnv::from(&[("ProgramData", r"C:\ProgramData")]);
431 assert_eq!(
432 machine_path(Os::Windows, &win),
433 Some(PathBuf::from(r"C:\ProgramData\memfork\policy.toml"))
434 );
435 assert_eq!(
436 machine_path(Os::MacOs, &MapEnv::default()),
437 Some(PathBuf::from(
438 "/Library/Application Support/memfork/policy.toml"
439 ))
440 );
441 assert_eq!(
442 machine_path(Os::Linux, &MapEnv::default()),
443 Some(PathBuf::from("/etc/memfork/policy.toml"))
444 );
445 assert_eq!(machine_path(Os::Windows, &MapEnv::default()), None);
447 }
448
449 #[test]
450 fn nothing_written_means_everything_allowed() {
451 let p = combine(Some(PathBuf::from("/etc/memfork/policy.toml")), None, None);
452 for f in Feature::ALL {
453 assert!(p.allows(f), "{f:?}");
454 }
455 assert!(p.data_dir().is_none());
456 assert!(!p.in_force());
457 assert_eq!(p.summary(), "none");
458 }
459
460 #[test]
461 fn the_machine_file_wins_wherever_both_speak() {
462 let machine = file("maintenance_tasks = false\nsampling = true\n");
463 let extra =
464 file("maintenance_tasks = true\nsampling = false\nrace = false\ndata_dir = \"/x\"\n");
465 let p = combine(
466 Some(PathBuf::from("/etc/memfork/policy.toml")),
467 Some(&machine),
468 Some((Path::new("/home/ada/policy.toml"), &extra)),
469 );
470 assert!(!p.allows(Feature::MaintenanceTasks));
472 assert_eq!(
473 p.forbidden_by(Feature::MaintenanceTasks),
474 Some(Origin::Machine)
475 );
476 assert!(
477 p.allows(Feature::Sampling),
478 "the extra file cannot switch off what the machine file allows"
479 );
480 assert!(!p.allows(Feature::Race));
482 assert_eq!(p.forbidden_by(Feature::Race), Some(Origin::Extra));
483 assert_eq!(p.data_dir(), Some(Path::new("/x")));
484 assert!(p.in_force());
485 }
486
487 #[test]
488 fn a_pinned_data_dir_in_the_machine_file_beats_the_extra_one() {
489 let machine = file("data_dir = \"/srv/memfork\"\n");
490 let extra = file("data_dir = \"/tmp/mine\"\n");
491 let p = combine(
492 Some(PathBuf::from("/etc/memfork/policy.toml")),
493 Some(&machine),
494 Some((Path::new("/e.toml"), &extra)),
495 );
496 assert_eq!(p.data_dir(), Some(Path::new("/srv/memfork")));
497 }
498
499 #[test]
500 fn an_unknown_key_is_an_error_not_a_silence() {
501 let err =
502 parse(Path::new("/etc/memfork/policy.toml"), "brian = false\n").expect_err("refused");
503 assert!(err.why.contains("brian"), "{err}");
504 assert!(err.to_string().contains("administrator"), "{err}");
505 let err = parse(Path::new("p"), "brain = \"no\"\n").expect_err("refused");
506 assert!(
507 err.why.contains("bool") || err.why.contains("boolean"),
508 "{err}"
509 );
510 }
511
512 #[test]
513 fn a_refusal_says_what_and_who_can_change_it() {
514 let machine = file("secret_overrides = false\n");
515 let p = combine(
516 Some(PathBuf::from("/etc/memfork/policy.toml")),
517 Some(&machine),
518 None,
519 );
520 let why = p.refusal(Feature::SecretOverrides);
521 assert!(
522 why.starts_with("Secret overrides are switched off"),
523 "{why}"
524 );
525 assert!(
526 why.contains(&crate::style::path(Path::new("/etc/memfork/policy.toml"))),
527 "{why}"
528 );
529 assert!(why.contains("administrator"), "{why}");
530 let why = p.refusal(Feature::Brain);
531 assert!(why.starts_with("The Brain is"), "{why}");
532 }
533
534 #[test]
535 fn the_summary_and_json_say_what_is_in_force() {
536 let machine = file("race = false\nmaintenance_tasks = false\ndata_dir = \"/srv/m\"\n");
537 let p = combine(
538 Some(PathBuf::from("/etc/memfork/policy.toml")),
539 Some(&machine),
540 None,
541 );
542 let s = p.summary();
543 assert!(s.contains("race off"), "{s}");
544 assert!(s.contains("maintenance tasks off"), "{s}");
545 assert!(s.contains("pinned to"), "{s}");
546 let j = p.to_json();
547 assert_eq!(j["allows"]["race"], false);
548 assert_eq!(j["allows"]["brain"], true);
549 assert_eq!(j["machine_file_present"], true);
550 assert_eq!(j["in_force"], true);
551 }
552
553 #[test]
554 fn a_file_that_is_present_but_empty_is_in_force_and_forbids_nothing() {
555 let p = combine(
556 Some(PathBuf::from("/etc/memfork/policy.toml")),
557 Some(&file("")),
558 None,
559 );
560 assert!(p.in_force());
561 assert!(Feature::ALL.iter().all(|f| p.allows(*f)));
562 assert!(p.summary().contains("switches nothing off"));
563 }
564
565 #[test]
566 fn loading_reads_the_extra_file_from_disk() {
567 let dir = tempfile::tempdir().expect("tempdir");
568 let extra = dir.path().join("policy.toml");
569 std::fs::write(&extra, "autopilot = false\n").expect("written");
570 let env = MapEnv::from(&[
573 (EXTRA_ENV, &extra.display().to_string()),
574 (
575 "ProgramData",
576 &dir.path().join("no-such").display().to_string(),
577 ),
578 ]);
579 for os in Os::all() {
580 let p = load(os, &env).expect("loaded");
581 assert!(!p.allows(Feature::Autopilot), "{os:?}");
582 assert!(!p.machine_present);
583 assert_eq!(p.extra_path.as_deref(), Some(extra.as_path()));
584 }
585 std::fs::write(&extra, "not = = toml").expect("written");
587 let err = load(Os::Linux, &env).expect_err("refused");
588 assert!(err.path.contains("policy.toml"), "{err}");
589 }
590}