use std::str::FromStr;
use serde::{Deserialize, Serialize};
use crate::{
ActionKind, Answer, Authority, Context, Grant, Grantee, KindSet, Level, Role, Segment,
TreePath, WorkspacePolicy,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ShareAccess {
View,
Edit,
}
impl ShareAccess {
#[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())),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ShareRefusal {
Id,
Node(String),
Access(String),
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 {}
const MAX_SHARE_ID: usize = 128;
#[must_use]
pub fn share_id_prefix(share: &str) -> String {
format!("share:{share}:")
}
#[must_use]
pub fn is_of_share(grant: &Grant, share: &str) -> bool {
grant.id.as_str().starts_with(&share_id_prefix(share))
}
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()),
)])
}
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(()),
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(),
)),
}
}
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")
}
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());
}
}
}