Skip to main content

tilo_action_policy/
edits.rs

1//! When a generic field edit asks for confirmation.
2//!
3//! Every action API decides it the same way, from the edit alone: no app code is
4//! needed to read a field edit. Removing an item of a collection asks, as a
5//! delete verb does, unless the resource publishes that collection's removals
6//! as quiet. Any edit of a field the resource publishes as guarded asks: one
7//! whose change can weaken the person's security or expose them. A field
8//! that weakens only one way ([`Weaker`]) asks only for a change that way.
9//! Otherwise setting, splicing, adding, upserting an item by its key, moving
10//! and an outbox's `settle` and `forget` ask nothing.
11
12/// The tag a published field edit carries.
13pub const FIELD_EDIT_TAG: &str = "confirmation:field-edit";
14
15/// The tag prefix naming one collection, by its dotted path from the edit's
16/// root (`*` for an item), whose removals ask nothing.
17pub const QUIET_REMOVAL_TAG: &str = "confirmation:quiet-removal:";
18
19/// The tag prefix naming one field, by its dotted path from the edit's root
20/// (`*` for an item), any edit at or below which asks.
21pub const GUARDED_FIELD_TAG: &str = "confirmation:guarded-field:";
22
23/// The tag prefix of a field that weakens security only one way
24/// ([`weakening_tag`]): an edit making it weaker asks, any other does not.
25pub const WEAKENING_FIELD_TAG: &str = "confirmation:weakening-field:";
26
27/// Which way a field's value weakens the person's security.
28#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
29pub enum Weaker<'a> {
30    /// A higher number is weaker (a lock's delay); `weakest`, when set, is
31    /// weaker than any (the delay's `0`, never).
32    Higher { weakest: Option<i64> },
33    /// A lower number is weaker; `weakest`, when set, is weaker than any.
34    Lower { weakest: Option<i64> },
35    /// The values, as JSON text, from the strongest to the weakest (`true`
36    /// then `false` for a switch that protects when on); any other value is
37    /// weaker than all of them.
38    Order(&'a [&'a str]),
39}
40
41impl Weaker<'_> {
42    /// How weak `value` (JSON text) is: higher is weaker, `None` when it is
43    /// not a value this ranks.
44    fn rank(&self, value: &str) -> Option<f64> {
45        let number = |weakest: Option<i64>, sign: f64| {
46            let number: f64 = value.parse().ok()?;
47            #[allow(clippy::cast_precision_loss, reason = "a sentinel such as 0 or -1")]
48            let weakest = weakest.map(|weakest| weakest as f64);
49            Some(if weakest == Some(number) {
50                f64::INFINITY
51            } else {
52                number * sign
53            })
54        };
55        match *self {
56            Self::Higher { weakest } => number(weakest, 1.0),
57            Self::Lower { weakest } => number(weakest, -1.0),
58            Self::Order(order) => {
59                let at = order.iter().position(|known| *known == value);
60                #[allow(
61                    clippy::cast_precision_loss,
62                    reason = "the position among a short list of known values"
63                )]
64                Some(at.map_or(f64::INFINITY, |at| at as f64))
65            }
66        }
67    }
68
69    /// Whether `next` is weaker than `now`, both JSON text. Not knowing the
70    /// value now, or either value not being one this ranks, counts as
71    /// weaker.
72    #[must_use]
73    pub fn weakens(&self, now: Option<&str>, next: &str) -> bool {
74        match (now.and_then(|now| self.rank(now)), self.rank(next)) {
75            (Some(now), Some(next)) => next > now,
76            _ => true,
77        }
78    }
79}
80
81/// The [`WEAKENING_FIELD_TAG`] publishing that the field at `path` (dotted,
82/// as [`dotted`] spells it) weakens `weaker`'s way and holds `now` (JSON
83/// text), when known.
84#[must_use]
85pub fn weakening_tag(path: &str, now: Option<&str>, weaker: Weaker<'_>) -> String {
86    let mut tag = format!("{WEAKENING_FIELD_TAG}{path}\t{}\t", now.unwrap_or_default());
87    let bound = |tag: &mut String, name: &str, weakest: Option<i64>| {
88        tag.push_str(name);
89        if let Some(weakest) = weakest {
90            tag.push('\t');
91            tag.push_str(&weakest.to_string());
92        }
93    };
94    match weaker {
95        Weaker::Higher { weakest } => bound(&mut tag, "higher", weakest),
96        Weaker::Lower { weakest } => bound(&mut tag, "lower", weakest),
97        Weaker::Order(order) => {
98            tag.push_str("order");
99            for value in order {
100                tag.push('\t');
101                tag.push_str(value);
102            }
103        }
104    }
105    tag
106}
107
108/// A field that weakens one way, read back from its [`weakening_tag`]
109/// (without the prefix). JSON text holds no raw tab, so tabs part it.
110#[derive(Clone, Debug, PartialEq, Eq)]
111pub struct WeakeningField<'t> {
112    /// Its dotted path.
113    pub path: &'t str,
114    /// Its value now, as JSON text, when known.
115    pub now: Option<&'t str>,
116    rule: &'t str,
117    values: Vec<&'t str>,
118}
119
120impl<'t> WeakeningField<'t> {
121    /// The field `text` (a tag after [`WEAKENING_FIELD_TAG`]) publishes.
122    #[must_use]
123    pub fn parse(text: &'t str) -> Option<Self> {
124        let mut parts = text.split('\t');
125        let path = parts.next()?;
126        let now = parts.next()?;
127        let rule = parts.next()?;
128        Some(Self {
129            path,
130            now: (!now.is_empty()).then_some(now),
131            rule,
132            values: parts.collect(),
133        })
134    }
135
136    /// Which way it weakens; `None` for a rule this version does not know.
137    #[must_use]
138    pub fn weaker(&self) -> Option<Weaker<'_>> {
139        let weakest = || match self.values.as_slice() {
140            [] => Some(None),
141            [weakest] => weakest.parse().ok().map(Some),
142            _ => None,
143        };
144        match self.rule {
145            "higher" => weakest().map(|weakest| Weaker::Higher { weakest }),
146            "lower" => weakest().map(|weakest| Weaker::Lower { weakest }),
147            "order" => Some(Weaker::Order(&self.values)),
148            _ => None,
149        }
150    }
151}
152
153/// Whether the field edit `op` at `path`, setting `value` (JSON text) when
154/// it is a set, can weaken one of `fields`: a set of the field itself to a
155/// weaker value, and any other edit at or below it, which is not read.
156#[must_use]
157pub fn weakening_edit(
158    op: &str,
159    path: &[EditStep<'_>],
160    value: Option<&str>,
161    fields: &[WeakeningField<'_>],
162) -> bool {
163    let at = dotted(path);
164    fields.iter().any(|field| {
165        if !guarded_at(path, &[field.path]) {
166            return false;
167        }
168        match (op, value, field.weaker()) {
169            ("set", Some(value), Some(weaker)) if at == field.path => {
170                weaker.weakens(field.now, value)
171            }
172            _ => true,
173        }
174    })
175}
176
177/// One step of a field edit's path, as the decision reads it.
178#[derive(Clone, Copy, Debug, PartialEq, Eq)]
179pub enum EditStep<'a> {
180    /// A field of a resource, by its key.
181    Field(&'a str),
182    /// An item, an entry or a cell, whichever it is.
183    Item,
184}
185
186/// `path` as the dotted pattern [`QUIET_REMOVAL_TAG`] names collections by.
187#[must_use]
188pub fn dotted(path: &[EditStep<'_>]) -> String {
189    path.iter()
190        .map(|step| match step {
191            EditStep::Field(key) => *key,
192            EditStep::Item => "*",
193        })
194        .collect::<Vec<_>>()
195        .join(".")
196}
197
198/// Whether the field edit `op` (its JSON name) at `path` asks for
199/// confirmation before it runs, where `quiet` names the collections whose
200/// removals ask nothing and `guarded` the fields whose every edit asks.
201#[must_use]
202pub fn field_edit_asks(op: &str, path: &[EditStep<'_>], quiet: &[&str], guarded: &[&str]) -> bool {
203    guarded_at(path, guarded) || (op == "remove-item" && !quiet.contains(&dotted(path).as_str()))
204}
205
206/// Whether `path` is one of the `guarded` fields or lies below one.
207#[must_use]
208pub fn guarded_at(path: &[EditStep<'_>], guarded: &[&str]) -> bool {
209    (1..=path.len())
210        .filter_map(|len| path.get(..len))
211        .any(|prefix| guarded.contains(&dotted(prefix).as_str()))
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217
218    tilo_test_env::scenario! {
219        fn guarded_edits_ask_when_they_weaken;
220
221        phase only_a_loud_collections_removal_asks;
222        {
223            let notes = [EditStep::Field("notes")];
224            let tags = [
225                EditStep::Field("notes"),
226                EditStep::Item,
227                EditStep::Field("tags"),
228            ];
229            let quiet = ["notes.*.tags"];
230            assert!(field_edit_asks("remove-item", &notes, &quiet, &[]));
231            assert!(!field_edit_asks("remove-item", &tags, &quiet, &[]));
232            for op in [
233                "set",
234                "splice",
235                "insert-item",
236                "upsert-item",
237                "move-to",
238                "settle",
239                "forget",
240                "remove-key",
241            ] {
242                assert!(!field_edit_asks(op, &notes, &quiet, &[]), "{op}");
243            }
244            assert_eq!(dotted(&tags), "notes.*.tags");
245        }
246
247        phase every_edit_at_or_below_a_guarded_field_asks;
248        {
249            let lock = [EditStep::Field("lock")];
250            let delay = [EditStep::Field("lock"), EditStep::Field("delay")];
251            let other = [EditStep::Field("locked")];
252            let guarded = ["lock"];
253            for op in ["set", "splice", "insert-item", "remove-item"] {
254                assert!(field_edit_asks(op, &lock, &[], &guarded), "{op}");
255                assert!(field_edit_asks(op, &delay, &[], &guarded), "{op}");
256            }
257            assert!(!field_edit_asks("set", &other, &[], &guarded));
258            assert!(
259                field_edit_asks("remove-item", &lock, &["lock"], &guarded),
260                "a quiet removal of a guarded field still asks"
261            );
262        }
263
264        phase a_number_weakens_its_way_and_its_weakest_value_beats_all;
265        {
266            let delay = Weaker::Higher { weakest: Some(0) };
267            assert!(!delay.weakens(Some("5"), "1"), "shorter is stricter");
268            assert!(!delay.weakens(Some("5"), "5"));
269            assert!(delay.weakens(Some("5"), "10"));
270            assert!(delay.weakens(Some("60"), "0"), "never is the weakest");
271            assert!(!delay.weakens(Some("0"), "60"), "any delay beats never");
272            assert!(delay.weakens(None, "1"), "not knowing the value now asks");
273            assert!(
274                delay.weakens(Some("5"), "\"soon\""),
275                "an unranked value asks"
276            );
277            let floor = Weaker::Lower { weakest: None };
278            assert!(floor.weakens(Some("8"), "4"));
279            assert!(!floor.weakens(Some("8"), "12"));
280        }
281
282        phase a_switch_and_a_choice_weaken_down_their_order;
283        {
284            let shown = Weaker::Order(&["false", "true"]);
285            assert!(shown.weakens(Some("false"), "true"));
286            assert!(!shown.weakens(Some("true"), "false"));
287            let zone = Weaker::Order(&["\"drop\"", "\"public\"", "\"trusted\""]);
288            assert!(zone.weakens(Some("\"public\""), "\"trusted\""));
289            assert!(!zone.weakens(Some("\"public\""), "\"drop\""));
290            assert!(zone.weakens(Some("\"drop\""), "\"other\""));
291        }
292
293        phase a_published_weakening_field_reads_back_and_decides_its_edits;
294        {
295            let order = ["false", "true"];
296            let tags = [
297                weakening_tag("lock", Some("5"), Weaker::Higher { weakest: Some(0) }),
298                weakening_tag("shown", Some("false"), Weaker::Order(&order)),
299                weakening_tag("rules.*.on", None, Weaker::Order(&order)),
300            ];
301            let fields: Vec<WeakeningField<'_>> = tags
302                .iter()
303                .map(|tag| WeakeningField::parse(tag.strip_prefix(WEAKENING_FIELD_TAG).unwrap()))
304                .collect::<Option<_>>()
305                .unwrap();
306            assert_eq!(
307                fields[0].weaker(),
308                Some(Weaker::Higher { weakest: Some(0) })
309            );
310            assert_eq!(fields[1].weaker(), Some(Weaker::Order(&order)));
311            let lock = [EditStep::Field("lock")];
312            let shown = [EditStep::Field("shown")];
313            let rule = [
314                EditStep::Field("rules"),
315                EditStep::Item,
316                EditStep::Field("on"),
317            ];
318            assert!(!weakening_edit("set", &lock, Some("1"), &fields));
319            assert!(weakening_edit("set", &lock, Some("0"), &fields));
320            assert!(weakening_edit("splice", &lock, None, &fields));
321            assert!(weakening_edit("set", &shown, Some("true"), &fields));
322            assert!(!weakening_edit("set", &shown, Some("false"), &fields));
323            assert!(
324                weakening_edit("set", &rule, Some("false"), &fields),
325                "an item's value is not published, so any edit asks"
326            );
327            assert!(!weakening_edit(
328                "set",
329                &[EditStep::Field("other")],
330                Some("1"),
331                &fields
332            ));
333        }
334    }
335}