tilo-action-policy 0.5.2

Who may invoke which action: grants over the published tree and the one function that decides them.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
//! Nodes of the published tree: workspace › app › resource kind › resource ›
//! item › field › action.
//!
//! An action's node is a concrete path. A grant's node is a pattern over the
//! same levels that may leave a level open (`resource:*`, "every resource of
//! this kind") or skip any depth (`**`, "anywhere below"). A grant covers its
//! node and everything under it.

use std::{fmt, str::FromStr};

use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// The level of a segment in the tree.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Level {
    /// The workspace a grant is written against.
    Workspace,
    App,
    /// A resource kind the app publishes (`snippets.library`).
    Kind,
    /// One resource of that kind.
    Resource,
    Item,
    /// A field, possibly nested; field edits are actions under it.
    Field,
    /// An action: a verb's public id or a field edit (`set`, `splice`, ...).
    Action,
}

impl Level {
    pub const ALL: [Self; 7] = [
        Self::Workspace,
        Self::App,
        Self::Kind,
        Self::Resource,
        Self::Item,
        Self::Field,
        Self::Action,
    ];

    /// The tag of the level in the text form of a path.
    #[must_use]
    pub const fn tag(self) -> &'static str {
        match self {
            Self::Workspace => "workspace",
            Self::App => "app",
            Self::Kind => "kind",
            Self::Resource => "resource",
            Self::Item => "item",
            Self::Field => "field",
            Self::Action => "action",
        }
    }

    /// The level as people read it ("every resource").
    #[must_use]
    pub const fn noun(self) -> &'static str {
        match self {
            Self::Workspace => "workspace",
            Self::App => "app",
            Self::Kind => "kind",
            Self::Resource => "resource",
            Self::Item => "item",
            Self::Field => "field",
            Self::Action => "action",
        }
    }

    /// The level a text form's tag names.
    fn from_tag(tag: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|level| level.tag() == tag)
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Segment {
    Name(Level, String),
    Any(Level),
    /// Any number of segments, including none.
    Rest,
}

impl Segment {
    /// How specific the segment is when comparing grants: a name beats an open
    /// level, which beats any depth.
    const fn weight(&self) -> u8 {
        match self {
            Self::Name(..) => 2,
            Self::Any(_) => 1,
            Self::Rest => 0,
        }
    }

    /// Whether this pattern segment covers one segment of a path.
    fn covers(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Name(level, id), Self::Name(other_level, other_id)) => {
                level == other_level && id == other_id
            }
            (Self::Any(level), Self::Name(other_level, _) | Self::Any(other_level)) => {
                level == other_level
            }
            _ => false,
        }
    }

    #[must_use]
    pub const fn level(&self) -> Option<Level> {
        match self {
            Self::Name(level, _) | Self::Any(level) => Some(*level),
            Self::Rest => None,
        }
    }

    #[must_use]
    pub fn id(&self) -> Option<&str> {
        match self {
            Self::Name(_, id) => Some(id),
            _ => None,
        }
    }
}

/// A node, or a pattern of nodes, in the published tree.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TreePath(Vec<Segment>);

/// How specific a grant's node is. Greater is more specific: names beat open
/// levels position by position, and a deeper node beats its ancestors.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Specificity(Vec<u8>);

impl TreePath {
    /// The root of the tree: covers every workspace.
    #[must_use]
    pub const fn root() -> Self {
        Self(Vec::new())
    }

    #[must_use]
    pub fn workspace(id: impl Into<String>) -> Self {
        Self::root().push(Level::Workspace, id)
    }

    /// Appends a named segment.
    #[must_use]
    pub fn push(mut self, level: Level, id: impl Into<String>) -> Self {
        self.0.push(Segment::Name(level, id.into()));
        self
    }

    #[must_use]
    pub fn app(self, id: impl Into<String>) -> Self {
        self.push(Level::App, id)
    }

    #[must_use]
    pub fn kind(self, id: impl Into<String>) -> Self {
        self.push(Level::Kind, id)
    }

    #[must_use]
    pub fn resource(self, id: impl Into<String>) -> Self {
        self.push(Level::Resource, id)
    }

    #[must_use]
    pub fn item(self, id: impl Into<String>) -> Self {
        self.push(Level::Item, id)
    }

    /// Appends a field path; dots separate nested fields.
    #[must_use]
    pub fn field(mut self, path: &str) -> Self {
        for part in path.split('.').filter(|part| !part.is_empty()) {
            self.0.push(Segment::Name(Level::Field, part.to_owned()));
        }
        self
    }

    #[must_use]
    pub fn action(self, id: impl Into<String>) -> Self {
        self.push(Level::Action, id)
    }

    /// Appends "every node at this level".
    #[must_use]
    pub fn any(mut self, level: Level) -> Self {
        self.0.push(Segment::Any(level));
        self
    }

    /// Appends "anywhere below". A trailing `rest` adds nothing (a node already
    /// covers everything under it) and is dropped when the path is compared.
    #[must_use]
    pub fn rest(mut self) -> Self {
        if self.0.last() != Some(&Segment::Rest) {
            self.0.push(Segment::Rest);
        }
        self
    }

    #[must_use]
    pub fn segments(&self) -> &[Segment] {
        &self.0
    }

    #[must_use]
    pub const fn is_root(&self) -> bool {
        self.0.is_empty()
    }

    /// This path without the workspace it starts at, if it starts at one:
    /// where it applies within its workspace.
    #[must_use]
    pub fn within_workspace(&self) -> Self {
        let workspace = matches!(
            self.0.first(),
            Some(Segment::Name(Level::Workspace, _) | Segment::Any(Level::Workspace))
        );
        Self(
            self.0
                .iter()
                .skip(usize::from(workspace))
                .cloned()
                .collect(),
        )
    }

    /// The parent node, or `None` at the root.
    #[must_use]
    pub fn parent(&self) -> Option<Self> {
        let (_, parent) = self.0.split_last()?;
        Some(Self(parent.to_vec()))
    }

    /// The first named id at `level`.
    #[must_use]
    pub fn id_at(&self, level: Level) -> Option<&str> {
        self.0.iter().find_map(|segment| match segment {
            Segment::Name(at, id) if *at == level => Some(id.as_str()),
            _ => None,
        })
    }

    /// `self` followed by every segment of `rest`.
    #[must_use]
    pub fn join(&self, rest: &Self) -> Self {
        self.clone().joined(rest)
    }

    /// [`Self::join`], taking `self`.
    #[must_use]
    pub fn joined(self, rest: &Self) -> Self {
        let mut path = self;
        path.0.reserve(rest.0.len());
        for segment in &rest.0 {
            path = match segment {
                Segment::Rest => path.rest(),
                segment => {
                    path.0.push(segment.clone());
                    path
                }
            };
        }
        path
    }

    /// The same path with a leading `workspace:<from>` renamed to
    /// `workspace:<to>`.
    #[must_use]
    pub fn with_workspace(&self, from: &str, to: &str) -> Self {
        let mut path = self.clone();
        if let Some(Segment::Name(Level::Workspace, id)) = path.0.first_mut()
            && id == from
        {
            to.clone_into(id);
        }
        path
    }

    #[must_use]
    pub fn workspace_id(&self) -> Option<&str> {
        self.id_at(Level::Workspace)
    }

    /// Whether `self`, read as a grant's node, covers `path`: `path` is the
    /// node itself or lies below it.
    #[must_use]
    pub fn covers(&self, path: &Self) -> bool {
        covers(self.trimmed(), &path.0)
    }

    /// Whether some node lies at or below both `self` and `other`: a grant on
    /// one can decide an action under the other.
    #[must_use]
    pub fn overlaps(&self, other: &Self) -> bool {
        overlaps(self.trimmed(), other.trimmed())
    }

    /// The node at or below `self` that `pattern`, a grant's node, names:
    /// `self`'s names at the levels it has, and the pattern's at the levels it
    /// adds. `None` when no node lies below both, or either goes on past an
    /// open rest, whose depth names no one node.
    #[must_use]
    pub fn toward(&self, pattern: &Self) -> Option<Self> {
        let (mine, theirs) = (self.trimmed(), pattern.trimmed());
        if !overlaps(mine, theirs)
            || mine.contains(&Segment::Rest)
            || theirs.contains(&Segment::Rest)
        {
            return None;
        }
        let at = |segments: &[Segment], level| {
            segments
                .iter()
                .find(|segment| segment.level() == Some(level))
                .cloned()
        };
        let node = Self(
            Level::ALL
                .into_iter()
                .filter_map(|level| match (at(mine, level), at(theirs, level)) {
                    (Some(named @ Segment::Name(..)), _) | (_, Some(named @ Segment::Name(..))) => {
                        Some(named)
                    }
                    (mine, theirs) => mine.or(theirs),
                })
                .collect(),
        );
        self.covers(&node).then_some(node)
    }

    /// Whether `self` lies at or below `ancestor`.
    #[must_use]
    pub fn is_within(&self, ancestor: &Self) -> bool {
        ancestor.covers(self)
    }

    #[must_use]
    pub fn specificity(&self) -> Specificity {
        Specificity(self.trimmed().iter().map(Segment::weight).collect())
    }

    /// How many segments the path has.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Drops every segment after the first `len`: back to an ancestor a
    /// caller extended, to extend it again.
    pub fn truncate(&mut self, len: usize) {
        self.0.truncate(len);
    }

    /// Appends a named segment in place.
    pub fn push_name(&mut self, level: Level, id: impl Into<String>) {
        self.0.push(Segment::Name(level, id.into()));
    }

    /// `self.specificity().cmp(&other.specificity())`, without building either.
    pub(crate) fn cmp_specificity(&self, other: &Self) -> std::cmp::Ordering {
        let theirs = other.trimmed().iter().map(Segment::weight);
        self.trimmed().iter().map(Segment::weight).cmp(theirs)
    }

    /// The text form of `self`.
    fn write_with(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.0.is_empty() {
            return f.write_str("/");
        }
        for (index, segment) in self.0.iter().enumerate() {
            if index > 0 {
                f.write_str("/")?;
            }
            match segment {
                Segment::Name(level, id) => {
                    write!(f, "{}:", level.tag())?;
                    if id == "*" {
                        f.write_str("%2A")?;
                    } else {
                        for ch in id.chars() {
                            match ch {
                                '%' => f.write_str("%25")?,
                                '/' => f.write_str("%2F")?,
                                _ => fmt::Write::write_char(f, ch)?,
                            }
                        }
                    }
                }
                Segment::Any(level) => write!(f, "{}:*", level.tag())?,
                Segment::Rest => f.write_str("**")?,
            }
        }
        Ok(())
    }

    fn trimmed(&self) -> &[Segment] {
        let mut segments = self.0.as_slice();
        while let [init @ .., Segment::Rest] = segments {
            segments = init;
        }
        segments
    }
}

fn covers(pattern: &[Segment], path: &[Segment]) -> bool {
    let Some((first, rest)) = pattern.split_first() else {
        return true;
    };
    // A route names the resource directly, while the app can also name
    // its kind. A grant on the route covers the same resource in the app.
    if first.level() == Some(Level::Resource)
        && let Some((kind, resource)) = path.split_first()
        && kind.level() == Some(Level::Kind)
    {
        return covers(pattern, resource);
    }
    match first {
        Segment::Rest => {
            let mut tail = path;
            loop {
                if covers(rest, tail) {
                    return true;
                }
                let Some((_, shorter)) = tail.split_first() else {
                    return false;
                };
                tail = shorter;
            }
        }
        _ => path
            .split_first()
            .is_some_and(|(head, tail)| first.covers(head) && covers(rest, tail)),
    }
}

fn overlaps(left: &[Segment], right: &[Segment]) -> bool {
    let (Some((first, left_rest)), Some((second, right_rest))) =
        (left.split_first(), right.split_first())
    else {
        return true;
    };
    match (first.level(), second.level()) {
        (Some(Level::Resource), Some(Level::Kind)) => return overlaps(left, right_rest),
        (Some(Level::Kind), Some(Level::Resource)) => return overlaps(left_rest, right),
        _ => {}
    }
    match (first, second) {
        // Any depth either matches nothing or absorbs the other side's next
        // segment.
        (Segment::Rest, _) | (_, Segment::Rest) => {
            overlaps(left_rest, right) || overlaps(left, right_rest)
        }
        _ => compatible(first, second) && overlaps(left_rest, right_rest),
    }
}

fn compatible(left: &Segment, right: &Segment) -> bool {
    match (left, right) {
        (Segment::Name(level, id), Segment::Name(other_level, other_id)) => {
            level == other_level && id == other_id
        }
        (Segment::Name(level, _) | Segment::Any(level), Segment::Any(other_level))
        | (Segment::Any(level), Segment::Name(other_level, _)) => level == other_level,
        _ => false,
    }
}

impl fmt::Display for TreePath {
    /// The form a path is stored and sent in: `workspace:r/app:mail/
    /// kind:mail.message/resource:*/action:send`, `**` for any depth, `/` for
    /// the root. An empty resource id addresses the app's primary document.
    /// Ids escape `%` and `/` as `%25` and `%2F`, and an id that is
    /// exactly `*` as `%2A`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.write_with(f)
    }
}

/// A path that does not parse.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PathError(pub String);

impl fmt::Display for PathError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "invalid tree path: {}", self.0)
    }
}

impl std::error::Error for PathError {}

impl FromStr for TreePath {
    type Err = PathError;

    fn from_str(text: &str) -> Result<Self, Self::Err> {
        if text == "/" || text.is_empty() {
            return Ok(Self::root());
        }
        let mut path = Self::root();
        for part in text.split('/') {
            if part == "**" {
                path = path.rest();
                continue;
            }
            let (tag, id) = part
                .split_once(':')
                .ok_or_else(|| PathError(format!("segment `{part}` has no level")))?;
            let level =
                Level::from_tag(tag).ok_or_else(|| PathError(format!("unknown level `{tag}`")))?;
            if id == "*" {
                path = path.any(level);
            } else if id.is_empty() && level != Level::Resource {
                return Err(PathError(format!("segment `{part}` has no id")));
            } else {
                path = path.push(level, unescape(id)?);
            }
        }
        Ok(path)
    }
}

fn unescape(id: &str) -> Result<String, PathError> {
    let mut out = String::with_capacity(id.len());
    let mut chars = id.chars();
    while let Some(ch) = chars.next() {
        if ch != '%' {
            out.push(ch);
            continue;
        }
        let code: String = chars.by_ref().take(2).collect();
        out.push(match code.as_str() {
            "25" => '%',
            "2F" | "2f" => '/',
            "2A" | "2a" => '*',
            _ => return Err(PathError(format!("bad escape in `{id}`"))),
        });
    }
    Ok(out)
}

impl Serialize for TreePath {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for TreePath {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        String::deserialize(deserializer)?
            .parse()
            .map_err(serde::de::Error::custom)
    }
}