Skip to main content

stratum_node_core/
grant.rs

1//! The offered grant: the WAC authorisations the node offers an
2//! installation's key, rendered as Turtle.
3//!
4//! The controller renders them at installation and stores each container's
5//! text and hash; the client renders them again from the manifest and
6//! compares, so the bytes must be identical on both sides. For each
7//! container `C` there is one authorisation: agent the application key's
8//! `did:nostr`, `acl:default <C>`, and the manifest's modes. One
9//! `acl:default` rule gives the key read (and write) on `C`'s listing, its
10//! existing and new children and nested containers, and nothing outside
11//! `C`, not even `C`'s own ACL.
12//!
13//! The combined grant, whose hash consent names, is the per-container
14//! texts in manifest order joined by one blank line.
15
16use serde::{Deserialize, Serialize};
17
18use crate::did::DidNostr;
19use crate::id::Sha256Digest;
20use crate::manifest::{ContainerGrant, ContainerPath};
21
22/// The authorisation offered for one container.
23#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
24pub struct OfferedContainer {
25    /// The container, relative to the pod root.
26    pub path: ContainerPath,
27    /// The authorisation as Turtle, ending in a newline.
28    pub turtle: String,
29    /// The SHA-256 of [`turtle`](Self::turtle)'s UTF-8 bytes.
30    pub sha256: Sha256Digest,
31}
32
33/// The whole offered grant: the combined text and hash, and each
34/// container's.
35///
36/// On the wire it is the tenant answer's `grant` member,
37/// `{"turtle":str,"sha256":hex,"containers":[{"path","turtle","sha256"}]}`.
38#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
39pub struct OfferedGrant {
40    /// The per-container texts in manifest order, joined by one blank line.
41    pub turtle: String,
42    /// The SHA-256 of [`turtle`](Self::turtle); consent must name it.
43    pub sha256: Sha256Digest,
44    /// Each container's authorisation, in manifest order.
45    pub containers: Vec<OfferedContainer>,
46}
47
48impl OfferedGrant {
49    /// Combines per-container authorisations, as stored, into the grant
50    /// whose hash consent compares. The containers must be in manifest
51    /// order.
52    ///
53    /// # Examples
54    ///
55    /// ```
56    /// use stratum_node_core::{render_offered, ContainerGrant, DidNostr, OfferedGrant};
57    ///
58    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
59    /// let app = DidNostr::from_hex(&"c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5")?;
60    /// let owner = DidNostr::from_hex(&"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")?;
61    /// let grants: Vec<ContainerGrant> = serde_json::from_str(
62    ///     r#"[{"path":"a/","modes":["Read"],"operations":["GET"]},
63    ///         {"path":"b/","modes":["Read","Write"],"operations":["PUT"]}]"#,
64    /// )?;
65    /// let offered = render_offered(&app, &owner, &grants);
66    /// assert_eq!(OfferedGrant::from_containers(offered.containers.clone()), offered);
67    /// # Ok(())
68    /// # }
69    /// ```
70    pub fn from_containers(containers: Vec<OfferedContainer>) -> Self {
71        let turtle = containers
72            .iter()
73            .map(|c| c.turtle.as_str())
74            .collect::<Vec<_>>()
75            .join("\n");
76        let sha256 = Sha256Digest::of(turtle.as_bytes());
77        Self {
78            turtle,
79            sha256,
80            containers,
81        }
82    }
83}
84
85/// Renders one container's offered authorisation.
86///
87/// `owner` is the pod's owner; the container IRI is root-relative,
88/// `</pods/<owner>/<path>>`, as the profile ACL writes its IRIs.
89///
90/// # Examples
91///
92/// ```
93/// use stratum_node_core::{render_container, ContainerGrant, DidNostr};
94///
95/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
96/// let app = DidNostr::from_hex(&"c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5")?;
97/// let owner = DidNostr::from_hex(&"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")?;
98/// let grant: ContainerGrant =
99///     serde_json::from_str(r#"{"path":"reports/","modes":["Read","Write"],"operations":["GET","PUT"]}"#)?;
100/// let offered = render_container(&app, &owner, &grant);
101/// assert!(offered.turtle.contains(&format!("acl:agent <{app}>")));
102/// assert!(offered.turtle.contains(&format!("acl:default </pods/{}/reports/>", owner.to_hex())));
103/// assert!(offered.turtle.contains("acl:mode acl:Read, acl:Write ."));
104/// assert!(!offered.turtle.contains("acl:accessTo"));
105/// # Ok(())
106/// # }
107/// ```
108pub fn render_container(
109    app: &DidNostr,
110    owner: &DidNostr,
111    grant: &ContainerGrant,
112) -> OfferedContainer {
113    let container = grant.path.under(owner);
114    let modes = grant
115        .modes
116        .iter()
117        .map(|m| m.iri())
118        .collect::<Vec<_>>()
119        .join(", ");
120    let turtle = format!(
121        "@prefix acl: <http://www.w3.org/ns/auth/acl#> .\n\
122         \n\
123         <#app-{app_hex}> a acl:Authorization ;\n    \
124             acl:agent <{app}> ;\n    \
125             acl:default <{container}> ;\n    \
126             acl:mode {modes} .\n",
127        app_hex = app.to_hex(),
128        container = container.as_str(),
129    );
130    let sha256 = Sha256Digest::of(turtle.as_bytes());
131    OfferedContainer {
132        path: grant.path.clone(),
133        turtle,
134        sha256,
135    }
136}
137
138/// Renders the offered grant for an application key `app` in `owner`'s
139/// pod, one authorisation per container in manifest order.
140///
141/// The same function runs in the controller and in the client, so the
142/// combined hash the client checks is the one the controller stored.
143///
144/// # Examples
145///
146/// ```
147/// use stratum_node_core::{render_offered, ContainerGrant, DidNostr, Sha256Digest};
148///
149/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
150/// let app = DidNostr::from_hex(&"c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5")?;
151/// let owner = DidNostr::from_hex(&"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")?;
152/// let grants: Vec<ContainerGrant> = serde_json::from_str(
153///     r#"[{"path":"in/","modes":["Read"],"operations":["GET"]},
154///         {"path":"out/","modes":["Read","Write"],"operations":["PUT"]}]"#,
155/// )?;
156/// let offered = render_offered(&app, &owner, &grants);
157/// assert_eq!(offered.containers.len(), 2);
158/// assert_eq!(
159///     offered.turtle,
160///     format!("{}\n{}", offered.containers[0].turtle, offered.containers[1].turtle),
161/// );
162/// assert_eq!(offered.sha256, Sha256Digest::of(offered.turtle.as_bytes()));
163/// # Ok(())
164/// # }
165/// ```
166pub fn render_offered(
167    app: &DidNostr,
168    owner: &DidNostr,
169    containers: &[ContainerGrant],
170) -> OfferedGrant {
171    OfferedGrant::from_containers(
172        containers
173            .iter()
174            .map(|grant| render_container(app, owner, grant))
175            .collect(),
176    )
177}