tilo-action-policy 0.5.2

Who may invoke which action: grants over the published tree and the one function that decides them.
Documentation
//! Sharing one resource with a workspace: the grants a share is.
//!
//! A person who shares something they work on (a note shown live in a chat
//! channel) lets the workspace's members see it, or also change it. That is not
//! a promise kept by the sharing app: a share is grants on the shared
//! resource's own node, decided by [`crate::decide`] at every action API and by
//! every receiver like any other grant, and revoked when the share ends.
//!
//! - **One resource.** A share names one resource
//!   (`workspace › app › kind › resource`) or one item of it
//!   (`… › resource › item`). An app's own document of the workspace travels under
//!   an empty route that a node cannot name, so an item of it is named under
//!   `resource:*`: item ids are unique, so the node stays one item. A bare
//!   `resource:*` would be every resource of the kind and is refused.
//! - **Everyone in the workspace.** One grant to the Viewer role, which every
//!   higher role holds too: Read for a view share, Read and Undoable for an
//!   edit share. A grant covers only the kinds it names, so a view share
//!   strips no one: an Editor's Undoable on the shared item is still decided
//!   by their role's grant on the workspace.
//! - **Never more than the sharer holds.** Each grant is bounded by the
//!   sharer's own holdings on its node ([`check_held`]), so a Viewer cannot
//!   hand out edit.
//! - **Never past a decision about a person.** A share grants roles, and a
//!   sharer may not lift a ban or a restriction, so neither does the share:
//!   a person's ban or restriction holds over every grant to their role,
//!   however specific ([`crate::Party::held_off`]).

use std::str::FromStr;

use serde::{Deserialize, Serialize};

use crate::{
    ActionKind, Answer, Authority, Context, Grant, Grantee, KindSet, Level, Role, Segment,
    TreePath, WorkspacePolicy,
};

/// What a share lets the workspace do with the resource.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ShareAccess {
    /// See it.
    View,
    /// See it and make undoable changes to it.
    Edit,
}

impl ShareAccess {
    /// The kinds the share's grants cover.
    #[must_use]
    pub const fn kinds(self) -> KindSet {
        match self {
            Self::View => KindSet::of(ActionKind::Read),
            Self::Edit => KindSet::of(ActionKind::Read).with(ActionKind::Undoable),
        }
    }

    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::View => "view",
            Self::Edit => "edit",
        }
    }
}

impl FromStr for ShareAccess {
    type Err = ShareRefusal;

    fn from_str(text: &str) -> Result<Self, Self::Err> {
        match text {
            "view" => Ok(Self::View),
            "edit" => Ok(Self::Edit),
            _ => Err(ShareRefusal::Access(text.to_owned())),
        }
    }
}

/// Why a share cannot be made.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ShareRefusal {
    /// The share's id is empty, too long or has characters ids may not.
    Id,
    /// The node is not one resource or one item of a resource of this workspace.
    Node(String),
    /// The access is neither `view` nor `edit`.
    Access(String),
    /// The sharer does not hold what the share would give.
    NotHeld(crate::Refusal),
}

impl std::fmt::Display for ShareRefusal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Id => f.write_str("a share's id is 1 to 128 letters, digits or . _ : -"),
            Self::Node(why) => write!(
                f,
                "only one resource or one item of it can be shared: {why}"
            ),
            Self::Access(access) => write!(f, "a share gives `view` or `edit`, not `{access}`"),
            Self::NotHeld(refusal) => write!(f, "you can't share more than you hold: {refusal}"),
        }
    }
}

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

/// The longest share id.
const MAX_SHARE_ID: usize = 128;

/// The start of the id of every grant of the share `share`.
#[must_use]
pub fn share_id_prefix(share: &str) -> String {
    format!("share:{share}:")
}

/// Whether `grant` is one of the share `share`'s.
#[must_use]
pub fn is_of_share(grant: &Grant, share: &str) -> bool {
    grant.id.as_str().starts_with(&share_id_prefix(share))
}

/// The grants `sharer` gives the workspace `workspace` by sharing `node` with
/// `access`, under the share id `share` (unique per share, such as the id of
/// the message that shares it).
///
/// # Errors
/// [`ShareRefusal::Id`] for a malformed id and [`ShareRefusal::Node`] for a
/// node that is not one resource or one item of it in `workspace`.
pub fn share_grants(
    workspace: &str,
    sharer: &str,
    share: &str,
    node: &TreePath,
    access: ShareAccess,
) -> Result<Vec<Grant>, ShareRefusal> {
    if share.is_empty()
        || share.len() > MAX_SHARE_ID
        || !share
            .chars()
            .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '.' | '_' | ':' | '-'))
    {
        return Err(ShareRefusal::Id);
    }
    check_node(workspace, node)?;
    Ok(vec![Grant::new(
        format!("{}viewer", share_id_prefix(share)),
        Grantee::role(Role::Viewer),
        node.clone(),
        access.kinds(),
        Answer::Allow,
        Grantee::person(sharer.to_owned()),
    )])
}

/// Whether `node` names one resource of `workspace`, or one item of a resource.
fn check_node(workspace: &str, node: &TreePath) -> Result<(), ShareRefusal> {
    let named = |segment: Option<&Segment>, level: Level| matches!(segment, Some(Segment::Name(at, id)) if *at == level && !id.is_empty());
    let segments = node.segments();
    if node.workspace_id() != Some(workspace) {
        return Err(ShareRefusal::Node("it is not in this workspace".into()));
    }
    if !(named(segments.first(), Level::Workspace)
        && named(segments.get(1), Level::App)
        && named(segments.get(2), Level::Kind))
    {
        return Err(ShareRefusal::Node("it names no app and kind".into()));
    }
    let item = match segments.len() {
        4 => false,
        5 if named(segments.get(4), Level::Item) => true,
        _ => return Err(ShareRefusal::Node("it is not a resource or an item".into())),
    };
    match segments.get(3) {
        Some(segment) if named(Some(segment), Level::Resource) => Ok(()),
        // An item of the app's own document, which no name names.
        Some(Segment::Any(Level::Resource)) if item => Ok(()),
        _ => Err(ShareRefusal::Node(
            "it names no one resource (every resource of a kind can't be shared)".into(),
        )),
    }
}

/// Whether `sharer`, deciding as `actor`, holds everything each of
/// `grants` gives on its node.
///
/// # Errors
/// [`ShareRefusal::NotHeld`] for the first grant above the sharer's own.
pub fn check_held(
    actor: &Authority<'_>,
    grants: &[Grant],
    cx: &Context<'_>,
) -> Result<(), ShareRefusal> {
    grants
        .iter()
        .try_for_each(|grant| WorkspacePolicy::check_within(actor, grant, cx))
        .map_err(ShareRefusal::NotHeld)
}

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

    const WORKSPACE: &str = "r1";

    fn item(id: &str) -> TreePath {
        TreePath::workspace(WORKSPACE)
            .app("so.tilo.notes")
            .kind("notes.notebook")
            .any(Level::Resource)
            .item(id)
    }

    fn edit_at(node: &TreePath) -> TreePath {
        node.clone().field("body").action("field-edit")
    }

    /// A workspace owned by `ada` with `bo` as a Viewer and `cy` as an Editor.
    fn workspace() -> WorkspacePolicy {
        let mut policy = WorkspacePolicy::new(WORKSPACE, "ada");
        policy.members.insert("bo".into(), Role::Viewer);
        policy.members.insert("cy".into(), Role::Editor);
        policy
    }

    fn may(policy: &WorkspacePolicy, person: &str, node: &TreePath, kind: ActionKind) -> bool {
        Authority::person(policy.party(person))
            .decide(node, kind, &Context::at(0))
            .answer
            == Answer::Allow
    }

    fn shared(access: ShareAccess) -> WorkspacePolicy {
        let mut policy = workspace();
        let grants = share_grants(WORKSPACE, "ada", "m1", &item("p1"), access).unwrap();
        check_held(
            &Authority::person(policy.party("ada")),
            &grants,
            &Context::at(0),
        )
        .unwrap();
        policy.grants.extend(grants);
        policy
    }

    tilo_test_env::scenario! {
        fn a_share_reaches_one_item_within_its_sharers_access;

        phase an_edit_share_lets_a_viewer_change_that_item_only;
        {
            let before = workspace();
            assert!(!may(
                &before,
                "bo",
                &edit_at(&item("p1")),
                ActionKind::Undoable
            ));
            let edit = shared(ShareAccess::Edit);
            assert!(may(
                &edit,
                "bo",
                &edit_at(&item("p1")),
                ActionKind::Undoable
            ));
            assert!(
                !may(&edit, "bo", &edit_at(&item("p2")), ActionKind::Undoable),
                "a sibling item stays as the role has it"
            );
            let view = shared(ShareAccess::View);
            assert!(!may(
                &view,
                "bo",
                &edit_at(&item("p1")),
                ActionKind::Undoable
            ));
            assert!(may(&view, "bo", &edit_at(&item("p1")), ActionKind::Read));
        }

        phase a_view_share_strips_no_one;
        {
            let view = shared(ShareAccess::View);
            assert!(
                may(&view, "cy", &edit_at(&item("p1")), ActionKind::Undoable),
                "an Editor still edits the shared item through their role"
            );
        }

        phase a_share_lifts_no_ban_or_restriction;
        {
            let mut edit = shared(ShareAccess::Edit);
            edit.grants.push(crate::roles::restriction_grant(
                WORKSPACE,
                "bo",
                1_000,
                Grantee::person("ada"),
            ));
            assert!(
                !may(&edit, "bo", &edit_at(&item("p1")), ActionKind::Undoable),
                "a restricted Viewer changes nothing, the shared item included"
            );
            assert!(
                may(&edit, "bo", &edit_at(&item("p1")), ActionKind::Read),
                "a restriction leaves reading alone"
            );
            let lapsed = Authority::person(edit.party("bo"))
                .decide(
                    &edit_at(&item("p1")),
                    ActionKind::Undoable,
                    &Context::at(2_000),
                )
                .answer;
            assert_eq!(
                lapsed,
                Answer::Allow,
                "a lapsed restriction holds nothing off"
            );
            edit.grants.push(edit.block("cy", Grantee::person("ada")));
            assert!(
                !may(&edit, "cy", &edit_at(&item("p1")), ActionKind::Read),
                "a ban keeps the person out of what the workspace shares too"
            );
        }

        phase a_share_gives_no_more_than_its_sharer_holds;
        {
            let policy = workspace();
            let grants = share_grants(WORKSPACE, "bo", "m1", &item("p1"), ShareAccess::Edit).unwrap();
            assert!(matches!(
                check_held(
                    &Authority::person(policy.party("bo")),
                    &grants,
                    &Context::at(0)
                ),
                Err(ShareRefusal::NotHeld(_))
            ));
            let grants = share_grants(WORKSPACE, "bo", "m1", &item("p1"), ShareAccess::View).unwrap();
            assert!(
                check_held(
                    &Authority::person(policy.party("bo")),
                    &grants,
                    &Context::at(0)
                )
                .is_ok()
            );
        }

        phase a_share_is_one_resource_or_one_item_of_this_workspace;
        {
            let resource = TreePath::workspace(WORKSPACE)
                .app("so.tilo.notes")
                .kind("notes.notebook")
                .resource("plan");
            let ok = |node: &TreePath| share_grants(WORKSPACE, "ada", "m1", node, ShareAccess::View);
            assert_eq!(ok(&resource).unwrap().len(), 1);
            assert!(ok(&resource.clone().item("p1")).is_ok());
            assert!(ok(&item("p1")).is_ok());
            let every = TreePath::workspace(WORKSPACE)
                .app("so.tilo.notes")
                .kind("notes.notebook")
                .any(Level::Resource);
            for refused in [
                every,
                TreePath::workspace(WORKSPACE).app("so.tilo.notes"),
                TreePath::workspace("r2")
                    .app("so.tilo.notes")
                    .kind("notes.notebook")
                    .resource("plan"),
                resource.clone().item("p1").field("body"),
                TreePath::workspace(WORKSPACE).rest(),
            ] {
                assert!(
                    matches!(ok(&refused), Err(ShareRefusal::Node(_))),
                    "{refused}"
                );
            }
            assert_eq!(
                share_grants(WORKSPACE, "ada", "", &resource, ShareAccess::View),
                Err(ShareRefusal::Id)
            );
            assert_eq!(
                share_grants(WORKSPACE, "ada", "a/b", &resource, ShareAccess::View),
                Err(ShareRefusal::Id)
            );
            let grants = ok(&resource).unwrap();
            assert!(grants.iter().all(|grant| is_of_share(grant, "m1")
                && grant.granted_by == Grantee::person("ada")
                && grant.answer == Answer::Allow));
            assert!(
                !grants
                    .iter()
                    .any(|grant| grant.grantee == Grantee::role(Role::Owner))
            );
            assert_eq!("edit".parse::<ShareAccess>(), Ok(ShareAccess::Edit));
            assert!("own".parse::<ShareAccess>().is_err());
        }
    }
}