tilo-action-policy 0.5.2

Who may invoke which action: grants over the published tree and the one function that decides them.
Documentation
//! Admitting one invocation: the decision every action API that runs an action
//! takes from the grants' answers, the same on every host.
//!
//! [`decide`](crate::decide) answers whether a party may take an action of
//! some kind at some node. Running one invocation weighs that answer with
//! who asks and how: someone acting for a person is asked before an action
//! its person attends or one that changes something outside Tilo, an ask
//! goes to the person only where they can be reached, and a resource's own
//! grants can ask or refuse as well.
//! [`admit`] is that weighing, so a broker admitting a caller's invocation,
//! a window checking its own and a page admitting its person's agree on
//! every answer.

use crate::{ActionKind, Answer};

/// How far an invocation was admitted to reach: the kind of action it is,
/// and whether it exercises authority over the workspace or others in it.
///
/// What an invocation's effect asks for while it runs (another resource's
/// action, an edit of its own resource) continues it, and goes no further
/// than it without being asked for: a reading invocation's child that
/// edits, or a child that is privileged under one that was not, runs only
/// once the person confirmed that child itself. The cap carries down a
/// chain: what a child was admitted to reach is its own reach narrowed by
/// its parent's, unless the person confirmed it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Reach {
    pub kind: ActionKind,
    pub privileged: bool,
}

impl Reach {
    /// Whether an action of `kind`, privileged when `privileged`, stays
    /// within this reach.
    #[must_use]
    pub fn covers(self, kind: ActionKind, privileged: bool) -> bool {
        kind <= self.kind && (self.privileged || !privileged)
    }

    /// The part of this reach `other` covers too.
    #[must_use]
    pub fn narrowed(self, other: Self) -> Self {
        Self {
            kind: self.kind.min(other.kind),
            privileged: self.privileged && other.privileged,
        }
    }
}

/// Who an invocation is admitted for, as admission weighs an ask.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Asker {
    /// Whether the person can be asked to confirm before it runs: they act
    /// themselves, or the host reaches them on a device of theirs. Where
    /// nobody can be asked, an ask refuses.
    pub reachable: bool,
    /// Whether someone acts for the person (a delegated agent): they are
    /// asked before an action the person attends, whatever the grants
    /// allow.
    pub delegated: bool,
}

/// What the invocation is, as admission weighs it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Invoked {
    /// The grants' answer for the action at its node ([`crate::decide`]).
    pub answer: Answer,
    /// Whether the action needs its person attending.
    pub attended: bool,
    /// Whether the action changes something outside Tilo (sends a message, calls a service):
    /// what someone acting for its person never does unasked.
    pub outside: bool,
    /// Whether this Allow is the person's own answer given in advance for this very action or
    /// resource ([`crate::Authority::answered_in_advance`]): asking them again would put to
    /// them what they answered.
    pub answered_in_advance: bool,
    /// The answer for the resource the invocation changes, where it is one.
    pub resource: Option<Answer>,
}

/// How an invocation is admitted.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Admission {
    /// It runs.
    Runs,
    /// It runs once the person confirmed it.
    AsksFirst,
}

/// Why an invocation is refused: whose answer refused it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Refused {
    /// The grants for the action itself, or an ask nobody can answer.
    Action,
    /// The grants for the resource it changes.
    Resource,
}

/// Admit `invoked` for `asker`.
///
/// Someone acting for a person is asked before an action its person attends and before one
/// that changes something outside Tilo: what they allow is what they were shown. A person's own
/// call of the same action asks nothing.
///
/// # Errors
/// Whose answer refused it.
pub const fn admit(invoked: Invoked, asker: Asker) -> Result<Admission, Refused> {
    let mut asks = match invoked.answer {
        // Someone acting for a person never leaves the system, or does what its person
        // attends, unasked: what they allow is what they were shown. What they already
        // answered for this very action or resource is no question to put to them again.
        Answer::Allow => {
            asker.delegated && (invoked.attended || invoked.outside) && !invoked.answered_in_advance
        }
        Answer::Ask if asker.reachable => true,
        Answer::Ask | Answer::Deny => return Err(Refused::Action),
    };
    match invoked.resource {
        Some(Answer::Deny) => return Err(Refused::Resource),
        Some(Answer::Ask) => asks = true,
        Some(Answer::Allow) | None => {}
    }
    Ok(if asks {
        Admission::AsksFirst
    } else {
        Admission::Runs
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    const ANSWERS: [Answer; 3] = [Answer::Allow, Answer::Ask, Answer::Deny];

    fn invoked(answer: Answer) -> Invoked {
        Invoked {
            answer,
            attended: false,
            outside: false,
            answered_in_advance: false,
            resource: None,
        }
    }

    tilo_test_env::scenario! {
        fn an_admission_decides_what_asks_the_person;

        phase a_reach_covers_what_goes_no_further;
        {
            let edit = Reach {
                kind: ActionKind::Undoable,
                privileged: false,
            };
            assert!(edit.covers(ActionKind::Read, false));
            assert!(edit.covers(ActionKind::Undoable, false));
            assert!(!edit.covers(ActionKind::Outside, false));
            assert!(
                !edit.covers(ActionKind::Undoable, true),
                "privileged goes further"
            );
            let read = Reach {
                kind: ActionKind::Read,
                privileged: true,
            };
            assert_eq!(
                edit.narrowed(read),
                Reach {
                    kind: ActionKind::Read,
                    privileged: false
                }
            );
        }

        phase an_ask_goes_to_the_person_only_where_they_can_be_reached;
        {
            let person = Asker {
                reachable: true,
                delegated: false,
            };
            let unreachable = Asker {
                reachable: false,
                delegated: false,
            };
            assert_eq!(admit(invoked(Answer::Allow), person), Ok(Admission::Runs));
            assert_eq!(
                admit(invoked(Answer::Ask), person),
                Ok(Admission::AsksFirst)
            );
            assert_eq!(admit(invoked(Answer::Deny), person), Err(Refused::Action));
            assert_eq!(
                admit(invoked(Answer::Allow), unreachable),
                Ok(Admission::Runs)
            );
            assert_eq!(
                admit(invoked(Answer::Ask), unreachable),
                Err(Refused::Action)
            );
        }

        phase whoever_acts_for_the_person_asks_before_an_attended_action;
        {
            let delegate = Asker {
                reachable: true,
                delegated: true,
            };
            let attended = Invoked {
                attended: true,
                ..invoked(Answer::Allow)
            };
            assert_eq!(admit(attended, delegate), Ok(Admission::AsksFirst));
            assert_eq!(admit(invoked(Answer::Allow), delegate), Ok(Admission::Runs));
            let person = Asker {
                delegated: false,
                ..delegate
            };
            assert_eq!(admit(attended, person), Ok(Admission::Runs));
        }

        phase whoever_acts_for_the_person_asks_before_what_leaves_the_system;
        {
            let delegate = Asker {
                reachable: true,
                delegated: true,
            };
            let outside = Invoked {
                outside: true,
                ..invoked(Answer::Allow)
            };
            assert_eq!(
                admit(outside, delegate),
                Ok(Admission::AsksFirst),
                "an agent's send is its person's to allow"
            );
            assert_eq!(
                admit(invoked(Answer::Allow), delegate),
                Ok(Admission::Runs),
                "a change that stays in the workspace runs unasked"
            );
            let person = Asker {
                delegated: false,
                ..delegate
            };
            assert_eq!(
                admit(outside, person),
                Ok(Admission::Runs),
                "a person's own press asks nothing"
            );
        }

        phase a_resource_answer_asks_or_refuses_on_top;
        {
            let person = Asker {
                reachable: true,
                delegated: false,
            };
            for answer in ANSWERS {
                let resource = Invoked {
                    resource: Some(answer),
                    ..invoked(Answer::Allow)
                };
                let expected = match answer {
                    Answer::Allow => Ok(Admission::Runs),
                    Answer::Ask => Ok(Admission::AsksFirst),
                    Answer::Deny => Err(Refused::Resource),
                };
                assert_eq!(admit(resource, person), expected);
            }
            let denied = Invoked {
                resource: Some(Answer::Deny),
                ..invoked(Answer::Deny)
            };
            assert_eq!(
                admit(denied, person),
                Err(Refused::Action),
                "the action's own answer first"
            );
        }
    }
}