Skip to main content

memfork/
policy.rs

1//! The machine-wide policy an administrator can place (DESIGN §5.4).
2//!
3//! One file, in a location only an administrator can write, switches features
4//! off for every user of the machine and can pin where memory is kept. Nothing
5//! a user sets — a flag, an environment variable, a project's own `.memfork`
6//! directory, `memfork maintain on` — overrides it. `memfork doctor` shows the
7//! policy in force and where it came from.
8//!
9//! The file is TOML, and every key is optional:
10//!
11//! ```toml
12//! # Features. Each defaults to allowed; `false` switches it off machine-wide.
13//! brain = false
14//! race = false
15//! autopilot = false
16//! maintenance_tasks = false
17//! sampling = false
18//! # Whether a write that looks like a credential may be forced through with
19//! # `allow_secret` (`--allow-secret`). Defaults to allowed.
20//! secret_overrides = false
21//! # Where memory is kept, for every user and every project. Unset, each
22//! # user's own data directory is used as usual.
23//! data_dir = "/srv/memfork"
24//! ```
25//!
26//! Where it lives, per operating system:
27//!
28//! | OS | Path |
29//! |---|---|
30//! | Windows | `%ProgramData%\memfork\policy.toml` |
31//! | macOS | `/Library/Application Support/memfork/policy.toml` |
32//! | Linux | `/etc/memfork/policy.toml` |
33//!
34//! A second file may be named in `MEMFORK_POLICY_FILE`. It exists so the
35//! tests, and a person trying a policy out, can apply one without writing to
36//! a system directory; it cannot weaken the machine file, because wherever
37//! both set a key the machine file wins. A user can therefore only ever add
38//! restrictions through it, never remove one.
39//!
40//! A policy file that cannot be read — malformed, or naming a key this
41//! version does not know — stops every command except `memfork doctor`, which
42//! reports it. A typo in a machine-wide rule should be found by the
43//! administrator who made it, not enforced as nothing.
44
45use 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
54/// The file's name, in whichever directory the OS puts it.
55pub const FILE_NAME: &str = "policy.toml";
56
57/// The directory under the system-wide location.
58const DIR_NAME: &str = "memfork";
59
60/// Environment variable naming a second policy file, read beneath the
61/// machine one.
62pub const EXTRA_ENV: &str = "MEMFORK_POLICY_FILE";
63
64/// A feature the policy can switch off.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum Feature {
67    /// The Brain: `memfork brain` and `memfork demo`, and the page the
68    /// daemon serves for them.
69    Brain,
70    /// `memfork race`, which runs agents unattended.
71    Race,
72    /// Autopilot: memory following the git branch, and automatic forks.
73    Autopilot,
74    /// Maintenance tasks MemFork adds to a project's board.
75    MaintenanceTasks,
76    /// Asking a client's model for a summary through MCP sampling.
77    Sampling,
78    /// `allow_secret`, which writes something the secret detector refused.
79    SecretOverrides,
80}
81
82impl Feature {
83    /// Every feature, in the order the file and the report list them.
84    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    /// The key in the file.
94    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    /// The words for it in a sentence.
106    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/// The file as written. Every key optional; an unknown key is an error.
119#[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/// Where a setting came from.
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub enum Origin {
147    /// The machine file.
148    Machine,
149    /// The file `MEMFORK_POLICY_FILE` names.
150    Extra,
151}
152
153/// The policy in force.
154#[derive(Debug, Clone, PartialEq, Eq)]
155pub struct Policy {
156    /// Where the machine file is, or would be, on this OS. `None` when the
157    /// location cannot be worked out, which happens only on Windows with no
158    /// `ProgramData` at all.
159    pub machine_path: Option<PathBuf>,
160    /// Whether the machine file is present and was read.
161    pub machine_present: bool,
162    /// The extra file, if `MEMFORK_POLICY_FILE` named one that was read.
163    pub extra_path: Option<PathBuf>,
164    /// Each feature switched off, and by which file.
165    forbidden: Vec<(Feature, Origin)>,
166    /// The pinned data directory, and by which file.
167    data_dir: Option<(PathBuf, Origin)>,
168}
169
170impl Policy {
171    /// No file anywhere: everything allowed.
172    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    /// Whether a feature may be used.
183    pub fn allows(&self, feature: Feature) -> bool {
184        !self.forbidden.iter().any(|(f, _)| *f == feature)
185    }
186
187    /// Which file switched a feature off, if one did.
188    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    /// The data directory the policy pins, if it pins one.
196    pub fn data_dir(&self) -> Option<&Path> {
197        self.data_dir.as_ref().map(|(p, _)| p.as_path())
198    }
199
200    /// Whether any file was read at all.
201    pub fn in_force(&self) -> bool {
202        self.machine_present || self.extra_path.is_some()
203    }
204
205    /// The path of the file an origin names, for messages.
206    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    /// What to tell someone whose request a feature switch-off refused:
215    /// what happened, and that only an administrator can change it.
216    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    /// One line for `memfork doctor`: what is in force.
233    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    /// The policy as data, for `memfork doctor --json`.
256    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/// Why the policy could not be read. Every command but `doctor` stops on it.
281#[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    /// The file.
290    pub path: String,
291    /// What was wrong with it.
292    pub why: String,
293}
294
295/// Where the machine file is on an OS.
296///
297/// Written against an explicit OS and environment, like the data directory,
298/// so all three answers are tested wherever the tests run.
299pub 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    // Joined as text with the named OS's separator, not with `PathBuf::join`,
309    // which would use the running OS's: the tests render every platform's
310    // path from any one of them.
311    let sep = os.separator();
312    Some(PathBuf::from(format!(
313        "{}{sep}{DIR_NAME}{sep}{FILE_NAME}",
314        base.trim_end_matches(['/', '\\'])
315    )))
316}
317
318/// Read one file's text, `None` if it does not exist.
319fn 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
337/// Combine what the files say. The machine file is applied last, so wherever
338/// both speak it wins.
339fn 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
374/// Read the policy for an OS and an environment. The files themselves are
375/// read from disk at the paths worked out.
376pub 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
394/// The policy this process runs under, read once.
395pub 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
403/// Whether the policy this process runs under allows a feature. A policy
404/// that could not be read allows nothing it could have switched off: the
405/// refusal that stops every command says why, and this is the answer for
406/// the daemon's own checks in the meantime.
407pub fn allows(feature: Feature) -> bool {
408    current().is_ok_and(|p| p.allows(feature))
409}
410
411/// The refusal for a feature under this process's policy.
412pub 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        // Windows with no ProgramData at all: no guess.
446        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        // Set by both: the machine file's answer.
471        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        // Set only by the extra file: it may add a restriction.
481        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        // A machine location that does not exist, so only the extra file is
571        // read, on every OS.
572        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        // And a broken one stops the load with its path.
586        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}