Skip to main content

codync_network/
rules.rs

1//! Who on the other computers may write to this computer's agents. The receiving computer checks
2//! its own rules before it takes a letter, so none depends on the sender's goodwill: the first rule
3//! that matches decides, and with no rules every member may write (the default).
4
5use anyhow::{Result, bail};
6use serde::{Deserialize, Serialize};
7use std::fmt;
8use std::str::FromStr;
9
10/// Matches any computer or agent.
11pub const ANY: &str = "*";
12/// Enough for any one person's computers, and few enough to check on every letter.
13pub const MAX_RULES: usize = 100;
14
15#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
16#[serde(rename_all = "lowercase")]
17pub enum Access {
18    Allow,
19    Deny,
20}
21
22/// `deny *@server → *`: letters from `from_agent` on `from_computer` to `to_agent` here.
23#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
24#[serde(rename_all = "camelCase")]
25pub struct Rule {
26    /// A computer in the network, or `*`.
27    pub from_computer: String,
28    /// An agent on that computer, or `*`.
29    pub from_agent: String,
30    /// One of this computer's agents, or `*`.
31    pub to_agent: String,
32    pub access: Access,
33}
34
35impl Rule {
36    /// `from` is `agent@computer`, either side `*`, or `*` alone for anyone.
37    pub fn new(access: Access, from: &str, to: &str) -> Result<Self> {
38        let (from_agent, from_computer) = match from.trim() {
39            ANY => (ANY, ANY),
40            from => from.rsplit_once('@').ok_or_else(|| anyhow::anyhow!("from is agent@computer, or *"))?,
41        };
42        let rule = Self {
43            from_computer: from_computer.trim().into(),
44            from_agent: from_agent.trim().into(),
45            to_agent: to.trim().into(),
46            access,
47        };
48        rule.check()?;
49        Ok(rule)
50    }
51
52    fn check(&self) -> Result<()> {
53        // An agent's address name is up to 40 characters of any script, as long as a letter carries.
54        let parts = [
55            (&self.from_computer, 64),
56            (&self.from_agent, crate::wire::MAX_ADDRESS),
57            (&self.to_agent, crate::wire::MAX_ADDRESS),
58        ];
59        for (part, max) in parts {
60            if part.is_empty() || part.len() > max || part.contains(char::is_whitespace) {
61                bail!("each part of a rule is a name or *, without spaces");
62            }
63        }
64        Ok(())
65    }
66
67    fn matches(&self, computer: &str, agent: &str, to: &str) -> bool {
68        let fits = |pattern: &str, name: &str| pattern == ANY || pattern.eq_ignore_ascii_case(name);
69        fits(&self.from_computer, computer) && fits(&self.from_agent, agent) && fits(&self.to_agent, to)
70    }
71}
72
73impl fmt::Display for Rule {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        let access = match self.access {
76            Access::Allow => "allow",
77            Access::Deny => "deny",
78        };
79        write!(f, "{access} {}@{} → {}", self.from_agent, self.from_computer, self.to_agent)
80    }
81}
82
83impl FromStr for Access {
84    type Err = anyhow::Error;
85
86    fn from_str(s: &str) -> Result<Self> {
87        match s {
88            "allow" => Ok(Self::Allow),
89            "deny" => Ok(Self::Deny),
90            _ => bail!("a rule allows or denies"),
91        }
92    }
93}
94
95/// Checks a whole list before it replaces the old one.
96pub fn check_all(rules: &[Rule]) -> Result<()> {
97    if rules.len() > MAX_RULES {
98        bail!("at most {MAX_RULES} rules");
99    }
100    rules.iter().try_for_each(Rule::check)
101}
102
103/// Whether `agent` on `computer` may write to `to` here: the first rule that matches decides.
104pub fn allows(rules: &[Rule], computer: &str, agent: &str, to: &str) -> bool {
105    rules.iter().find(|r| r.matches(computer, agent, to)).is_none_or(|r| r.access == Access::Allow)
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111
112    fn rule(access: Access, from: &str, to: &str) -> Rule {
113        Rule::new(access, from, to).expect("a valid rule")
114    }
115
116    #[test]
117    fn the_first_match_decides_and_no_rules_allow_everyone() {
118        assert!(allows(&[], "server", "lead", "reviewer"));
119        let rules = [rule(Access::Allow, "lead@server", "reviewer"), rule(Access::Deny, "*@server", "*")];
120        assert!(allows(&rules, "server", "lead", "reviewer"));
121        assert!(!allows(&rules, "server", "lead", "coder"), "only the reviewer was allowed");
122        assert!(!allows(&rules, "Server", "other", "reviewer"), "computer names ignore case");
123        assert!(allows(&rules, "laptop", "lead", "coder"), "no rule for the laptop");
124        assert!(!allows(&[rule(Access::Deny, "*", "*")], "laptop", "a", "b"));
125    }
126
127    #[test]
128    fn rules_read_and_show_like_addresses() {
129        let r = rule(Access::Deny, "*@server", "*");
130        assert_eq!((r.from_agent.as_str(), r.from_computer.as_str()), ("*", "server"));
131        assert_eq!(r.to_string(), "deny *@server → *");
132        assert!(Rule::new(Access::Allow, "lead", "x").is_err(), "a bare agent needs its computer");
133        assert!(Rule::new(Access::Allow, "a b@c", "x").is_err());
134        let long = "審".repeat(40);
135        assert!(Rule::new(Access::Allow, &format!("{long}@desk"), &long).is_ok(), "any script's address names");
136        assert!(check_all(&vec![r; MAX_RULES + 1]).is_err());
137        let json = serde_json::to_value(rule(Access::Allow, "lead@desk", "reviewer")).expect("serializes");
138        assert_eq!(json["access"], "allow");
139        assert_eq!(json["fromComputer"], "desk");
140    }
141}