stratum-node-cli 0.1.0-alpha.4

The `stratum` client for Stratum pod nodes: operator key files, bootstrap, config, backup, invitations and members over the loopback API; join, pod access and export for tenants through the gate
Documentation
//! Container listings: the JSON-LD the pod server returns for a container,
//! and the rule for which listed children a client may follow.

use serde_json::Value as Json;
use stratum_node_core::{ParsePodPathError, PodPath};

use crate::error::CliError;
use crate::origin::CanonicalOrigin;
use crate::output::sanitize;

/// The names the `ldp:contains` property can appear under in the JSON-LD
/// the pod server writes: compacted with the `ldp` prefix, compacted to a
/// bare term, or expanded.
const CONTAINS_KEYS: [&str; 3] = [
    "ldp:contains",
    "contains",
    "http://www.w3.org/ns/ldp#contains",
];

/// The longest listed identifier quoted back in a report.
const MAX_QUOTED_ID: usize = 200;

/// One child named in a listing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Child {
    /// A child that may be followed.
    Accepted(PodPath),
    /// A child that is not followed, with the listed identifier (sanitised
    /// and shortened) and the reason.
    Refused { id: String, reason: String },
}

/// Reads the children of `container` from its listing `body`, resolving
/// each against the listing's own address.
///
/// # Errors
///
/// [`CliError::Protocol`] when the body is not JSON.
pub(crate) fn children(
    origin: &CanonicalOrigin,
    container: &PodPath,
    body: &[u8],
) -> Result<Vec<Child>, CliError> {
    let value: Json = serde_json::from_slice(body).map_err(|_| {
        CliError::Protocol(format!(
            "the listing of {container} is not JSON-LD that this client reads"
        ))
    })?;
    let mut ids = Vec::new();
    let nodes: Vec<&Json> = match value.get("@graph").and_then(Json::as_array) {
        Some(graph) => graph.iter().collect(),
        None => match &value {
            Json::Array(items) => items.iter().collect(),
            other => vec![other],
        },
    };
    for node in nodes {
        for key in CONTAINS_KEYS {
            match node.get(key) {
                Some(Json::Array(items)) => ids.extend(items.iter()),
                Some(item) => ids.push(item),
                None => {}
            }
        }
    }
    Ok(ids
        .into_iter()
        .map(|item| {
            let id = match item {
                Json::String(id) => Some(id.as_str()),
                Json::Object(map) => map.get("@id").and_then(Json::as_str),
                _ => None,
            };
            match id {
                None => Child::Refused {
                    id: String::new(),
                    reason: "the entry has no @id".to_owned(),
                },
                Some(id) => match resolve(origin, container, id) {
                    Ok(path) => Child::Accepted(path),
                    Err(reason) => Child::Refused {
                        id: quote(id),
                        reason,
                    },
                },
            }
        })
        .collect())
}

/// Resolves a listed `@id` against the listing's address,
/// `<origin><container>`, and returns it if it may be followed.
///
/// Three forms are understood: an absolute URL on exactly the canonical
/// origin, a root-relative path and a relative path. The result must parse
/// as a [`PodPath`] (so it obeys the gate's path rules: no dot segment is
/// ever resolved away), must be in the same pod as the container, and must
/// lie strictly under the container. Anything else is refused with a
/// reason: another origin, another scheme, a network-path reference, a
/// query, fragment or percent-encoding.
pub(crate) fn resolve(
    origin: &CanonicalOrigin,
    container: &PodPath,
    id: &str,
) -> Result<PodPath, String> {
    if id.is_empty() {
        return Err("the @id is empty".to_owned());
    }
    if id.contains(['?', '#', '%']) || id.chars().any(|c| c.is_whitespace() || c.is_control()) {
        return Err("the @id holds a query, fragment, percent-encoding or whitespace".to_owned());
    }
    let path = if id.contains("://") {
        let prefix = origin.as_str();
        match id.strip_prefix(prefix.as_str()) {
            Some(rest) if rest.starts_with('/') => rest.to_owned(),
            _ => return Err(format!("the @id is not on the canonical origin {prefix}")),
        }
    } else if id.starts_with("//") {
        return Err("the @id names another authority".to_owned());
    } else if id.starts_with('/') {
        id.to_owned()
    } else if id
        .split('/')
        .next()
        .is_some_and(|first| first.contains(':'))
    {
        return Err("the @id uses another scheme".to_owned());
    } else {
        format!("{}{id}", container.as_str())
    };
    let child = PodPath::parse(&path).map_err(refusal)?;
    if child.owner() != container.owner() {
        return Err(format!(
            "the @id is in another pod ({})",
            PodPath::pod_root(&child.owner())
        ));
    }
    if child.as_str().len() <= container.as_str().len()
        || !child.as_str().starts_with(container.as_str())
    {
        return Err(format!("the @id is not under {container}"));
    }
    Ok(child)
}

/// Explains why a path is not a [`PodPath`], for a listed child.
fn refusal(err: ParsePodPathError) -> String {
    match err {
        ParsePodPathError::DotSegment => "the @id has a . or .. segment".to_owned(),
        ParsePodPathError::ForbiddenCharacter => {
            "the @id holds a character outside the Step 2 rule (A-Z a-z 0-9 - . _ ~)".to_owned()
        }
        ParsePodPathError::EmptySegment => "the @id has an empty segment".to_owned(),
        _ => "the @id is not a pod path".to_owned(),
    }
}

/// Returns `id` sanitised and shortened for a report.
fn quote(id: &str) -> String {
    let short: String = id.chars().take(MAX_QUOTED_ID).collect();
    let mut text = sanitize(&short);
    if id.chars().count() > MAX_QUOTED_ID {
        text.push('…');
    }
    text
}

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

    const A: &str = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798";
    const B: &str = "c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5";

    fn setup() -> (CanonicalOrigin, PodPath) {
        let origin: CanonicalOrigin = "https://pod.example".parse().expect("origin");
        let owner = DidNostr::from_hex(A).expect("key");
        let container = PodPath::pod_root(&owner).join("docs/").expect("container");
        (origin, container)
    }

    #[test]
    fn three_forms_resolve_under_the_container() {
        let (origin, container) = setup();
        for id in [
            format!("/pods/{A}/docs/x.txt"),
            format!("https://pod.example/pods/{A}/docs/x.txt"),
            "x.txt".to_owned(),
        ] {
            let path = resolve(&origin, &container, &id).expect("accepted");
            assert_eq!(path.as_str(), format!("/pods/{A}/docs/x.txt"), "{id}");
        }
        let nested = resolve(&origin, &container, "sub/").expect("container");
        assert!(nested.is_container());
    }

    #[test]
    fn everything_else_is_refused() {
        let (origin, container) = setup();
        for id in [
            format!("/pods/{B}/docs/x.txt"),
            format!("https://other.example/pods/{A}/docs/x.txt"),
            format!("http://pod.example/pods/{A}/docs/x.txt"),
            format!("https://pod.example:8443/pods/{A}/docs/x.txt"),
            format!("//other.example/pods/{A}/docs/x.txt"),
            format!("/pods/{A}/docs/../secret.txt"),
            "../x.txt".to_owned(),
            "./x.txt".to_owned(),
            format!("/pods/{A}/other.txt"),
            format!("/pods/{A}/docs/"),
            format!("/pods/{A}.acl"),
            "x.txt?a=1".to_owned(),
            "x%20y.txt".to_owned(),
            "x y.txt".to_owned(),
            "mailto:a@b".to_owned(),
            "/.well-known/solid".to_owned(),
            String::new(),
        ] {
            assert!(resolve(&origin, &container, &id).is_err(), "{id}");
        }
    }

    #[test]
    fn listings_are_read_in_the_observed_shape() {
        let (origin, container) = setup();
        let body = serde_json::json!({
            "@context": {"ldp": "http://www.w3.org/ns/ldp#"},
            "@id": container.as_str(),
            "@type": ["ldp:Container", "ldp:BasicContainer"],
            "ldp:contains": [
                {"@id": format!("/pods/{A}/docs/a.txt"), "@type": ["ldp:Resource"]},
                {"@id": format!("/pods/{B}/docs/b.txt"), "@type": ["ldp:Resource"]},
                {"@type": ["ldp:Resource"]},
            ],
        });
        let read = children(&origin, &container, body.to_string().as_bytes()).expect("json");
        assert_eq!(read.len(), 3);
        assert!(matches!(&read[0], Child::Accepted(p) if p.as_str().ends_with("/docs/a.txt")));
        assert!(matches!(&read[1], Child::Refused { .. }));
        assert!(matches!(&read[2], Child::Refused { .. }));
        let single = serde_json::json!({"contains": {"@id": "c.txt"}});
        let read = children(&origin, &container, single.to_string().as_bytes()).expect("json");
        assert!(matches!(&read[0], Child::Accepted(_)));
    }
}