stratum-node-core 0.1.0-alpha.3

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
//! Pod request paths under the Stratum gate's allow-list and shape rules.

use std::fmt;
use std::str::FromStr;

use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::did::DidNostr;
use crate::encoding;

/// The prefix every pod path starts with.
const PODS_PREFIX: &str = "/pods/";

/// The suffix of an access-control resource, and of the root ACL.
const ACL_SUFFIX: &str = ".acl";

/// The length of the owner key in a pod path: 64 lowercase hex digits.
const KEY_HEX_LEN: usize = 64;

/// A validated pod request path.
///
/// A `PodPath` is one of two shapes, and nothing else:
///
/// - `/pods/<pk>/<rest>`: a resource or container inside the pod of `<pk>`.
///   `<rest>` may be empty, which names the pod root `/pods/<pk>/`.
/// - exactly `/pods/<pk>.acl`: the pod's root access-control resource, which
///   the pod server keeps beside the pod rather than inside it.
///
/// Here `<pk>` is 64 lowercase hexadecimal digits naming a valid BIP-340
/// x-only key, available as [`owner`](Self::owner). In addition, every
/// character of the whole path is one of `A–Z a–z 0–9 - . _ ~ /`; no segment
/// is `.` or `..`; and no segment is empty, except that a single trailing `/`
/// is allowed and marks a [container](Self::is_container). There is no
/// percent-encoding: `%` is refused, so the path a caller sees is the path
/// the pod server acts on.
///
/// The text form is the path itself; [`Display`](fmt::Display),
/// [`FromStr`] and serde all use it, and deserialisation applies the same
/// checks as [`parse`](Self::parse).
///
/// # Examples
///
/// ```
/// use stratum_node_core::{DidNostr, PodPath};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let owner = DidNostr::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")?;
/// let root = PodPath::pod_root(&owner);
/// assert_eq!(root.as_str(), format!("/pods/{}/", owner.to_hex()));
///
/// let note = root.join("private/")?.join("x.txt")?;
/// assert_eq!(note.owner(), owner);
/// assert!(!note.is_container());
///
/// let acl = note.acl_path().ok_or("a resource has an acl")?;
/// assert_eq!(acl.as_str(), format!("/pods/{}/private/x.txt.acl", owner.to_hex()));
/// assert_eq!(
///     root.acl_path().ok_or("the pod root has an acl")?.as_str(),
///     format!("/pods/{}.acl", owner.to_hex()),
/// );
///
/// // 404 for anything outside the allow-list, 400 for a forbidden shape.
/// assert!(PodPath::parse("/.well-known/solid").unwrap_err().is_not_a_pod_path());
/// let dotted = format!("/pods/{}/a/../b", owner.to_hex());
/// assert!(!PodPath::parse(&dotted).unwrap_err().is_not_a_pod_path());
/// # Ok(())
/// # }
/// ```
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PodPath {
    path: String,
    owner: DidNostr,
}

impl PodPath {
    /// Parses and validates a request path.
    ///
    /// `path` is the path part of the request target only, without the
    /// query string or the `?` that introduces it.
    ///
    /// # Errors
    ///
    /// Returns [`ParsePodPathError::NotAPodPath`] when the path is outside
    /// the allow-list: it does not start with `/pods/`, the key is not 64
    /// lowercase hex digits naming a valid key, or what follows the key is
    /// neither `/` nor exactly `.acl`. Otherwise returns
    /// [`ParsePodPathError::ForbiddenCharacter`],
    /// [`ParsePodPathError::DotSegment`] or
    /// [`ParsePodPathError::EmptySegment`] for a pod path of a forbidden
    /// shape, checked in that order.
    /// [`ParsePodPathError::is_not_a_pod_path`] tells the two groups apart.
    pub fn parse(path: &str) -> Result<Self, ParsePodPathError> {
        let owner = parse_owner(path)?;
        if !path.bytes().all(is_path_byte) {
            return Err(ParsePodPathError::ForbiddenCharacter);
        }
        let rest = &path[PODS_PREFIX.len() + KEY_HEX_LEN..];
        if let Some(inner) = rest.strip_prefix('/') {
            check_segments(inner)?;
        }
        Ok(Self {
            path: path.to_owned(),
            owner,
        })
    }

    /// Returns the pod root of `owner`: `/pods/<pk>/`.
    pub fn pod_root(owner: &DidNostr) -> Self {
        Self {
            path: format!("{PODS_PREFIX}{}/", owner.to_hex()),
            owner: *owner,
        }
    }

    /// Returns the owner of the pod this path is in, from the key in the
    /// path.
    pub fn owner(&self) -> DidNostr {
        self.owner
    }

    /// Returns `true` for the root access-control resource `/pods/<pk>.acl`.
    pub fn is_root_acl(&self) -> bool {
        self.path.len() == PODS_PREFIX.len() + KEY_HEX_LEN + ACL_SUFFIX.len()
            && self.path.ends_with(ACL_SUFFIX)
    }

    /// Returns `true` when the path ends in `/`, which names a container.
    /// The pod root is a container; the root ACL is not.
    pub fn is_container(&self) -> bool {
        self.path.ends_with('/')
    }

    /// Returns the path text.
    pub fn as_str(&self) -> &str {
        &self.path
    }

    /// Appends a relative child to this container.
    ///
    /// `child` is one or more segments with no leading `/`, such as `x.txt`,
    /// `private/` or `a/b.txt`; a trailing `/` makes the result a container.
    /// The result is validated as a whole by [`parse`](Self::parse).
    ///
    /// # Errors
    ///
    /// Returns [`ParsePodPathError::NotAContainer`] when `self` is not a
    /// container (including the root ACL), and otherwise the error
    /// [`parse`](Self::parse) gives for the joined path: an empty `child` or
    /// one starting with `/` is [`ParsePodPathError::EmptySegment`].
    pub fn join(&self, child: &str) -> Result<Self, ParsePodPathError> {
        if !self.is_container() {
            return Err(ParsePodPathError::NotAContainer);
        }
        if child.is_empty() {
            return Err(ParsePodPathError::EmptySegment);
        }
        Self::parse(&format!("{}{child}", self.path))
    }

    /// Returns `true` when this path is an access-control resource: the root
    /// ACL `/pods/<pk>.acl` or a non-container whose last segment ends in the
    /// four bytes `.acl`, compared byte for byte and case-sensitively.
    ///
    /// Uses [`is_acl_path`], the one ACL predicate shared by the gate, signer,
    /// proxy and manifest validation.
    pub fn is_acl(&self) -> bool {
        is_acl_path(&self.path)
    }

    /// Returns the path of the access-control resource beside this one, or
    /// `None` when this path is itself an access-control resource.
    ///
    /// The pod server keeps an ACL as a sibling: the ACL of the pod root
    /// `/pods/<pk>/` is `/pods/<pk>.acl`, of a container `/pods/<pk>/a/` is
    /// `/pods/<pk>/a.acl`, and of a resource `/pods/<pk>/a/x.txt` is
    /// `/pods/<pk>/a/x.txt.acl`. A resource (not a container) whose name ends
    /// in `.acl`, and the root ACL, are access-control resources and have no
    /// ACL of their own.
    pub fn acl_path(&self) -> Option<Self> {
        if self.is_acl() {
            return None;
        }
        let base = self.path.strip_suffix('/').unwrap_or(&self.path);
        Some(Self {
            path: format!("{base}{ACL_SUFFIX}"),
            owner: self.owner,
        })
    }
}

/// Returns `true` when `path` names an access-control resource.
///
/// This is the single ACL predicate shared by the gate, the signer, the pod
/// proxy and manifest validation. `path` may be a full pod path
/// (`/pods/<owner>/…` or `/pods/<owner>.acl`) or a relative path inside a pod.
/// It is an ACL if and only if it does not end in `/` and its last segment
/// ends in the four ASCII bytes `.acl`, compared byte for byte and
/// case-sensitively.
///
/// # Examples
///
/// ```
/// use stratum_node_core::is_acl_path;
///
/// assert!(is_acl_path(".acl"));
/// assert!(is_acl_path("a.acl"));
/// assert!(is_acl_path("profile/card.acl"));
/// assert!(is_acl_path("reports.acl"));
/// assert!(is_acl_path("/pods/79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798.acl"));
/// assert!(!is_acl_path("a.acl/"));
/// assert!(!is_acl_path("a.ACL"));
/// assert!(!is_acl_path("/pods/79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798/"));
/// ```
pub fn is_acl_path(path: &str) -> bool {
    !path.ends_with('/') && path.ends_with(ACL_SUFFIX)
}

/// Checks the prefix and the key, and what immediately follows the key.
fn parse_owner(path: &str) -> Result<DidNostr, ParsePodPathError> {
    let rest = path
        .strip_prefix(PODS_PREFIX)
        .ok_or(ParsePodPathError::NotAPodPath)?;
    let key = rest
        .get(..KEY_HEX_LEN)
        .filter(|key| encoding::is_lower_hex(key))
        .ok_or(ParsePodPathError::NotAPodPath)?;
    let after = &rest[KEY_HEX_LEN..];
    if !(after == ACL_SUFFIX || after.starts_with('/')) {
        return Err(ParsePodPathError::NotAPodPath);
    }
    DidNostr::from_hex(key).map_err(|_| ParsePodPathError::NotAPodPath)
}

/// Checks the segments after `/pods/<pk>/`: none is `.` or `..`, and none is
/// empty except the one after a single trailing `/`.
fn check_segments(inner: &str) -> Result<(), ParsePodPathError> {
    let body = inner.strip_suffix('/').unwrap_or(inner);
    if inner.is_empty() {
        return Ok(());
    }
    let mut empty = false;
    for segment in body.split('/') {
        if segment == "." || segment == ".." {
            return Err(ParsePodPathError::DotSegment);
        }
        empty |= segment.is_empty();
    }
    if empty {
        return Err(ParsePodPathError::EmptySegment);
    }
    Ok(())
}

/// Returns `true` for the bytes a pod path may hold:
/// `A–Z a–z 0–9 - . _ ~ /`.
fn is_path_byte(b: u8) -> bool {
    b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~' | b'/')
}

/// Returns `true` when `query` is acceptable as the query string of a pod
/// request.
///
/// `query` is the text after the `?`, which a gate forwards as received. It
/// may be empty and may hold only the pod-path characters
/// `A–Z a–z 0–9 - . _ ~ /` and `= & % +`. No decoding is done: `%` is allowed
/// here because the query is passed through verbatim and only ever compared
/// byte for byte.
///
/// # Examples
///
/// ```
/// use stratum_node_core::is_valid_pod_query;
///
/// assert!(is_valid_pod_query("a=1&b=x%20y+z"));
/// assert!(is_valid_pod_query(""));
/// assert!(!is_valid_pod_query("a=1;b=2"));
/// assert!(!is_valid_pod_query("a=#"));
/// ```
pub fn is_valid_pod_query(query: &str) -> bool {
    query
        .bytes()
        .all(|b| is_path_byte(b) || matches!(b, b'=' | b'&' | b'%' | b'+'))
}

impl fmt::Display for PodPath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.path)
    }
}

impl fmt::Debug for PodPath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "PodPath({})", self.path)
    }
}

impl FromStr for PodPath {
    type Err = ParsePodPathError;

    fn from_str(text: &str) -> Result<Self, Self::Err> {
        Self::parse(text)
    }
}

impl AsRef<str> for PodPath {
    fn as_ref(&self) -> &str {
        &self.path
    }
}

impl Serialize for PodPath {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.path)
    }
}

impl<'de> Deserialize<'de> for PodPath {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let text = String::deserialize(deserializer)?;
        Self::parse(&text).map_err(serde::de::Error::custom)
    }
}

/// The reasons a path can fail to be a [`PodPath`].
///
/// [`is_not_a_pod_path`](Self::is_not_a_pod_path) splits them into the two
/// answers a gate gives: a path outside the allow-list (404) and a pod path
/// with a forbidden shape (400). Match on that method rather than on the
/// variants, so that a variant added later is classified by this crate.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ParsePodPathError {
    /// The path is outside the allow-list: it is not `/pods/` followed by a
    /// valid 64-digit lowercase hex key and then `/` or exactly `.acl`.
    #[error("not a pod path")]
    NotAPodPath,
    /// The path holds a character outside `A–Z a–z 0–9 - . _ ~ /`.
    #[error("pod path holds a character outside A-Z a-z 0-9 - . _ ~ /")]
    ForbiddenCharacter,
    /// A segment of the path is `.` or `..`.
    #[error("pod path has a . or .. segment")]
    DotSegment,
    /// A segment of the path is empty (`//`), other than after a single
    /// trailing `/`.
    #[error("pod path has an empty segment")]
    EmptySegment,
    /// [`PodPath::join`] was called on a path that is not a container.
    #[error("pod path is not a container")]
    NotAContainer,
}

impl ParsePodPathError {
    /// Returns `true` when the path is outside the allow-list altogether
    /// (a gate answers 404) and `false` when it is a pod path of a forbidden
    /// shape (a gate answers 400).
    pub fn is_not_a_pod_path(&self) -> bool {
        matches!(self, Self::NotAPodPath)
    }
}

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

    #[test]
    fn segments_accept_a_single_trailing_slash_only() {
        assert_eq!(check_segments(""), Ok(()), "pod root");
        assert_eq!(check_segments("a/"), Ok(()), "container");
        assert_eq!(check_segments("a/b"), Ok(()), "resource");
        assert_eq!(
            check_segments("a//"),
            Err(ParsePodPathError::EmptySegment),
            "double trailing slash"
        );
        assert_eq!(
            check_segments("/a"),
            Err(ParsePodPathError::EmptySegment),
            "leading empty"
        );
        assert_eq!(
            check_segments("/"),
            Err(ParsePodPathError::EmptySegment),
            "root with extra slash"
        );
        assert_eq!(
            check_segments("a/./b"),
            Err(ParsePodPathError::DotSegment),
            "dot"
        );
        assert_eq!(
            check_segments("../"),
            Err(ParsePodPathError::DotSegment),
            "dot dot container"
        );
    }
}