Skip to main content

crucible_wire/permissions/
resource_ref.rs

1use std::fmt;
2
3use super::{MissingResource, ResourceInfo, Target};
4use crate::error::Error;
5
6/// One resource instance a check is made against: the resource and its
7/// identifiers, root to leaf, so the parent chain (the tenant at its root)
8/// travels with it. The leaf may be [`Target::All`].
9#[derive(Debug, Clone, PartialEq, Eq, Hash)]
10pub struct ResourceRef {
11    resource: &'static ResourceInfo,
12    identifiers: Vec<Target>,
13}
14
15impl ResourceRef {
16    /// `resource` named by `identifiers`, root to leaf: one per identifier
17    /// of the resource. A check whose count differs is refused by the
18    /// `Permissions` interceptor as a wiring error.
19    pub fn new<I>(resource: &'static ResourceInfo, identifiers: I) -> Self
20    where
21        I: IntoIterator,
22        I::Item: Into<Target>,
23    {
24        Self {
25            resource,
26            identifiers: identifiers.into_iter().map(Into::into).collect(),
27        }
28    }
29
30    /// Every instance of `resource` under `parents` (root to leaf: every
31    /// identifier but the resource's own): `Inbox(*)` in a workspace.
32    pub fn all<I>(resource: &'static ResourceInfo, parents: I) -> Self
33    where
34        I: IntoIterator,
35        I::Item: Into<Target>,
36    {
37        let mut reference = Self::new(resource, parents);
38        reference.identifiers.push(Target::All);
39        reference
40    }
41
42    pub fn resource(&self) -> &'static ResourceInfo {
43        self.resource
44    }
45
46    /// Root to leaf.
47    pub fn identifiers(&self) -> &[Target] {
48        &self.identifiers
49    }
50
51    /// The identifier the resource calls `name` (`"workspaceId"`).
52    pub fn identifier(&self, name: &str) -> Option<&Target> {
53        self.resource
54            .identifiers
55            .iter()
56            .position(|identifier| *identifier == name)
57            .and_then(|index| self.identifiers.get(index))
58    }
59
60    /// Whether every identifier of the resource is bound, once, with only
61    /// the leaf possibly `All`.
62    pub fn is_complete(&self) -> bool {
63        let Some((_, parents)) = self.identifiers.split_last() else {
64            return false;
65        };
66        self.identifiers.len() == self.resource.identifiers.len()
67            && parents.iter().all(|target| *target != Target::All)
68    }
69
70    /// Whether nothing of the request is bound: a root resource with `*`.
71    /// There is nothing to hide then, so a Hidden verdict on it is Denied.
72    pub fn binds_nothing(&self) -> bool {
73        matches!(self.identifiers.as_slice(), [Target::All])
74    }
75
76    /// The 404 for this instance, identical whether it is hidden or
77    /// genuinely missing: a [`MissingResource`], which the server answers as
78    /// the framework's NotFound, or as the service's own not-found error
79    /// when the model designates one.
80    pub fn not_found(&self) -> Error {
81        Error::new(MissingResource::new(self.clone()))
82    }
83}
84
85/// `inbox(w-1, i-1)`, for logs.
86impl fmt::Display for ResourceRef {
87    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88        write!(f, "{}(", self.resource.name)?;
89        for (index, target) in self.identifiers.iter().enumerate() {
90            if index > 0 {
91                f.write_str(", ")?;
92            }
93            write!(f, "{target}")?;
94        }
95        f.write_str(")")
96    }
97}
98
99#[cfg(test)]
100mod tests {
101    use super::{MissingResource, ResourceInfo, ResourceRef, Target};
102    use crate::error::FrameworkError;
103
104    static INBOX: ResourceInfo = ResourceInfo {
105        name: "inbox",
106        identifiers: &["workspaceId", "inboxId"],
107        not_found: "No such inbox.",
108    };
109    static WORKSPACE: ResourceInfo = ResourceInfo {
110        name: "workspace",
111        identifiers: &["workspaceId"],
112        not_found: "No such workspace.",
113    };
114
115    #[test]
116    fn a_reference_binds_every_identifier_root_to_leaf() {
117        let workspace = "w-1".to_owned();
118        let inbox = ResourceRef::new(&INBOX, [&workspace, &"i-1".to_owned()]);
119        assert!(inbox.is_complete());
120        assert_eq!(inbox.identifier("inboxId"), Some(&Target::from("i-1")));
121        assert_eq!(inbox.identifier("domainId"), None);
122        assert_eq!(inbox.to_string(), "inbox(w-1, i-1)");
123
124        let every = ResourceRef::all(&INBOX, [&workspace]);
125        assert!(every.is_complete());
126        assert_eq!(every.identifiers()[1], Target::All);
127        assert_eq!(every.to_string(), "inbox(w-1, *)");
128        assert!(!every.binds_nothing());
129
130        assert!(!ResourceRef::new(&INBOX, ["w-1"]).is_complete());
131        assert!(!ResourceRef::new(&INBOX, [Target::All, Target::from("i")]).is_complete());
132        assert!(ResourceRef::all(&WORKSPACE, Vec::<String>::new()).binds_nothing());
133    }
134
135    #[test]
136    fn not_found_names_only_the_resource_type() {
137        let error = ResourceRef::new(&INBOX, ["w-1", "secret-id"]).not_found();
138        let missing = error.downcast_ref::<MissingResource>().unwrap();
139        assert_eq!(
140            missing.reference().identifiers()[1],
141            Target::from("secret-id")
142        );
143        assert_eq!(error.to_string(), "No such inbox.");
144        let framework = missing.framework_error();
145        assert_eq!(framework, FrameworkError::NotFound { resource: &INBOX });
146        assert!(!framework.message().contains("secret-id"));
147    }
148}