stratum-node-core 0.1.0-alpha.4

Zero-I/O core types for Stratum pod nodes: did:nostr principals, typed identifiers, a strict NIP-98 signed-request verifier and bootstrap claim bodies
Documentation
//! The offered grant: the WAC authorisations the node offers an
//! installation's key, rendered as Turtle.
//!
//! The controller renders them at installation and stores each container's
//! text and hash; the client renders them again from the manifest and
//! compares, so the bytes must be identical on both sides. For each
//! container `C` there is one authorisation: agent the application key's
//! `did:nostr`, `acl:default <C>`, and the manifest's modes. One
//! `acl:default` rule gives the key read (and write) on `C`'s listing, its
//! existing and new children and nested containers, and nothing outside
//! `C`, not even `C`'s own ACL.
//!
//! The combined grant, whose hash consent names, is the per-container
//! texts in manifest order joined by one blank line.

use serde::{Deserialize, Serialize};

use crate::did::DidNostr;
use crate::id::Sha256Digest;
use crate::manifest::{ContainerGrant, ContainerPath};

/// The authorisation offered for one container.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct OfferedContainer {
    /// The container, relative to the pod root.
    pub path: ContainerPath,
    /// The authorisation as Turtle, ending in a newline.
    pub turtle: String,
    /// The SHA-256 of [`turtle`](Self::turtle)'s UTF-8 bytes.
    pub sha256: Sha256Digest,
}

/// The whole offered grant: the combined text and hash, and each
/// container's.
///
/// On the wire it is the tenant answer's `grant` member,
/// `{"turtle":str,"sha256":hex,"containers":[{"path","turtle","sha256"}]}`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct OfferedGrant {
    /// The per-container texts in manifest order, joined by one blank line.
    pub turtle: String,
    /// The SHA-256 of [`turtle`](Self::turtle); consent must name it.
    pub sha256: Sha256Digest,
    /// Each container's authorisation, in manifest order.
    pub containers: Vec<OfferedContainer>,
}

impl OfferedGrant {
    /// Combines per-container authorisations, as stored, into the grant
    /// whose hash consent compares. The containers must be in manifest
    /// order.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_core::{render_offered, ContainerGrant, DidNostr, OfferedGrant};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let app = DidNostr::from_hex(&"c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5")?;
    /// let owner = DidNostr::from_hex(&"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")?;
    /// let grants: Vec<ContainerGrant> = serde_json::from_str(
    ///     r#"[{"path":"a/","modes":["Read"],"operations":["GET"]},
    ///         {"path":"b/","modes":["Read","Write"],"operations":["PUT"]}]"#,
    /// )?;
    /// let offered = render_offered(&app, &owner, &grants);
    /// assert_eq!(OfferedGrant::from_containers(offered.containers.clone()), offered);
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_containers(containers: Vec<OfferedContainer>) -> Self {
        let turtle = containers
            .iter()
            .map(|c| c.turtle.as_str())
            .collect::<Vec<_>>()
            .join("\n");
        let sha256 = Sha256Digest::of(turtle.as_bytes());
        Self {
            turtle,
            sha256,
            containers,
        }
    }
}

/// Renders one container's offered authorisation.
///
/// `owner` is the pod's owner; the container IRI is root-relative,
/// `</pods/<owner>/<path>>`, as the profile ACL writes its IRIs.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{render_container, ContainerGrant, DidNostr};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let app = DidNostr::from_hex(&"c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5")?;
/// let owner = DidNostr::from_hex(&"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")?;
/// let grant: ContainerGrant =
///     serde_json::from_str(r#"{"path":"reports/","modes":["Read","Write"],"operations":["GET","PUT"]}"#)?;
/// let offered = render_container(&app, &owner, &grant);
/// assert!(offered.turtle.contains(&format!("acl:agent <{app}>")));
/// assert!(offered.turtle.contains(&format!("acl:default </pods/{}/reports/>", owner.to_hex())));
/// assert!(offered.turtle.contains("acl:mode acl:Read, acl:Write ."));
/// assert!(!offered.turtle.contains("acl:accessTo"));
/// # Ok(())
/// # }
/// ```
pub fn render_container(
    app: &DidNostr,
    owner: &DidNostr,
    grant: &ContainerGrant,
) -> OfferedContainer {
    let container = grant.path.under(owner);
    let modes = grant
        .modes
        .iter()
        .map(|m| m.iri())
        .collect::<Vec<_>>()
        .join(", ");
    let turtle = format!(
        "@prefix acl: <http://www.w3.org/ns/auth/acl#> .\n\
         \n\
         <#app-{app_hex}> a acl:Authorization ;\n    \
             acl:agent <{app}> ;\n    \
             acl:default <{container}> ;\n    \
             acl:mode {modes} .\n",
        app_hex = app.to_hex(),
        container = container.as_str(),
    );
    let sha256 = Sha256Digest::of(turtle.as_bytes());
    OfferedContainer {
        path: grant.path.clone(),
        turtle,
        sha256,
    }
}

/// Renders the offered grant for an application key `app` in `owner`'s
/// pod, one authorisation per container in manifest order.
///
/// The same function runs in the controller and in the client, so the
/// combined hash the client checks is the one the controller stored.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{render_offered, ContainerGrant, DidNostr, Sha256Digest};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let app = DidNostr::from_hex(&"c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5")?;
/// let owner = DidNostr::from_hex(&"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")?;
/// let grants: Vec<ContainerGrant> = serde_json::from_str(
///     r#"[{"path":"in/","modes":["Read"],"operations":["GET"]},
///         {"path":"out/","modes":["Read","Write"],"operations":["PUT"]}]"#,
/// )?;
/// let offered = render_offered(&app, &owner, &grants);
/// assert_eq!(offered.containers.len(), 2);
/// assert_eq!(
///     offered.turtle,
///     format!("{}\n{}", offered.containers[0].turtle, offered.containers[1].turtle),
/// );
/// assert_eq!(offered.sha256, Sha256Digest::of(offered.turtle.as_bytes()));
/// # Ok(())
/// # }
/// ```
pub fn render_offered(
    app: &DidNostr,
    owner: &DidNostr,
    containers: &[ContainerGrant],
) -> OfferedGrant {
    OfferedGrant::from_containers(
        containers
            .iter()
            .map(|grant| render_container(app, owner, grant))
            .collect(),
    )
}