Skip to main content

stratum_node_core/
pod_path.rs

1//! Pod request paths under the Stratum gate's allow-list and shape rules.
2
3use std::fmt;
4use std::str::FromStr;
5
6use serde::{Deserialize, Deserializer, Serialize, Serializer};
7
8use crate::did::DidNostr;
9use crate::encoding;
10
11/// The prefix every pod path starts with.
12const PODS_PREFIX: &str = "/pods/";
13
14/// The suffix of an access-control resource, and of the root ACL.
15const ACL_SUFFIX: &str = ".acl";
16
17/// The length of the owner key in a pod path: 64 lowercase hex digits.
18const KEY_HEX_LEN: usize = 64;
19
20/// A validated pod request path.
21///
22/// A `PodPath` is one of two shapes, and nothing else:
23///
24/// - `/pods/<pk>/<rest>`: a resource or container inside the pod of `<pk>`.
25///   `<rest>` may be empty, which names the pod root `/pods/<pk>/`.
26/// - exactly `/pods/<pk>.acl`: the pod's root access-control resource, which
27///   the pod server keeps beside the pod rather than inside it.
28///
29/// Here `<pk>` is 64 lowercase hexadecimal digits naming a valid BIP-340
30/// x-only key, available as [`owner`](Self::owner). In addition, every
31/// character of the whole path is one of `A–Z a–z 0–9 - . _ ~ /`; no segment
32/// is `.` or `..`; and no segment is empty, except that a single trailing `/`
33/// is allowed and marks a [container](Self::is_container). There is no
34/// percent-encoding: `%` is refused, so the path a caller sees is the path
35/// the pod server acts on.
36///
37/// The text form is the path itself; [`Display`](fmt::Display),
38/// [`FromStr`] and serde all use it, and deserialisation applies the same
39/// checks as [`parse`](Self::parse).
40///
41/// # Examples
42///
43/// ```
44/// use stratum_node_core::{DidNostr, PodPath};
45///
46/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
47/// let owner = DidNostr::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")?;
48/// let root = PodPath::pod_root(&owner);
49/// assert_eq!(root.as_str(), format!("/pods/{}/", owner.to_hex()));
50///
51/// let note = root.join("private/")?.join("x.txt")?;
52/// assert_eq!(note.owner(), owner);
53/// assert!(!note.is_container());
54///
55/// let acl = note.acl_path().ok_or("a resource has an acl")?;
56/// assert_eq!(acl.as_str(), format!("/pods/{}/private/x.txt.acl", owner.to_hex()));
57/// assert_eq!(
58///     root.acl_path().ok_or("the pod root has an acl")?.as_str(),
59///     format!("/pods/{}.acl", owner.to_hex()),
60/// );
61///
62/// // 404 for anything outside the allow-list, 400 for a forbidden shape.
63/// assert!(PodPath::parse("/.well-known/solid").unwrap_err().is_not_a_pod_path());
64/// let dotted = format!("/pods/{}/a/../b", owner.to_hex());
65/// assert!(!PodPath::parse(&dotted).unwrap_err().is_not_a_pod_path());
66/// # Ok(())
67/// # }
68/// ```
69#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
70pub struct PodPath {
71    path: String,
72    owner: DidNostr,
73}
74
75impl PodPath {
76    /// Parses and validates a request path.
77    ///
78    /// `path` is the path part of the request target only, without the
79    /// query string or the `?` that introduces it.
80    ///
81    /// # Errors
82    ///
83    /// Returns [`ParsePodPathError::NotAPodPath`] when the path is outside
84    /// the allow-list: it does not start with `/pods/`, the key is not 64
85    /// lowercase hex digits naming a valid key, or what follows the key is
86    /// neither `/` nor exactly `.acl`. Otherwise returns
87    /// [`ParsePodPathError::ForbiddenCharacter`],
88    /// [`ParsePodPathError::DotSegment`] or
89    /// [`ParsePodPathError::EmptySegment`] for a pod path of a forbidden
90    /// shape, checked in that order.
91    /// [`ParsePodPathError::is_not_a_pod_path`] tells the two groups apart.
92    pub fn parse(path: &str) -> Result<Self, ParsePodPathError> {
93        let owner = parse_owner(path)?;
94        if !path.bytes().all(is_path_byte) {
95            return Err(ParsePodPathError::ForbiddenCharacter);
96        }
97        let rest = &path[PODS_PREFIX.len() + KEY_HEX_LEN..];
98        if let Some(inner) = rest.strip_prefix('/') {
99            check_segments(inner)?;
100        }
101        Ok(Self {
102            path: path.to_owned(),
103            owner,
104        })
105    }
106
107    /// Returns the pod root of `owner`: `/pods/<pk>/`.
108    pub fn pod_root(owner: &DidNostr) -> Self {
109        Self {
110            path: format!("{PODS_PREFIX}{}/", owner.to_hex()),
111            owner: *owner,
112        }
113    }
114
115    /// Returns the owner of the pod this path is in, from the key in the
116    /// path.
117    pub fn owner(&self) -> DidNostr {
118        self.owner
119    }
120
121    /// Returns `true` for the root access-control resource `/pods/<pk>.acl`.
122    pub fn is_root_acl(&self) -> bool {
123        self.path.len() == PODS_PREFIX.len() + KEY_HEX_LEN + ACL_SUFFIX.len()
124            && self.path.ends_with(ACL_SUFFIX)
125    }
126
127    /// Returns `true` when the path ends in `/`, which names a container.
128    /// The pod root is a container; the root ACL is not.
129    pub fn is_container(&self) -> bool {
130        self.path.ends_with('/')
131    }
132
133    /// Returns the path text.
134    pub fn as_str(&self) -> &str {
135        &self.path
136    }
137
138    /// Appends a relative child to this container.
139    ///
140    /// `child` is one or more segments with no leading `/`, such as `x.txt`,
141    /// `private/` or `a/b.txt`; a trailing `/` makes the result a container.
142    /// The result is validated as a whole by [`parse`](Self::parse).
143    ///
144    /// # Errors
145    ///
146    /// Returns [`ParsePodPathError::NotAContainer`] when `self` is not a
147    /// container (including the root ACL), and otherwise the error
148    /// [`parse`](Self::parse) gives for the joined path: an empty `child` or
149    /// one starting with `/` is [`ParsePodPathError::EmptySegment`].
150    pub fn join(&self, child: &str) -> Result<Self, ParsePodPathError> {
151        if !self.is_container() {
152            return Err(ParsePodPathError::NotAContainer);
153        }
154        if child.is_empty() {
155            return Err(ParsePodPathError::EmptySegment);
156        }
157        Self::parse(&format!("{}{child}", self.path))
158    }
159
160    /// Returns `true` when this path is an access-control resource: the root
161    /// ACL `/pods/<pk>.acl` or a non-container whose last segment ends in the
162    /// four bytes `.acl`, compared byte for byte and case-sensitively.
163    ///
164    /// Uses [`is_acl_path`], the one ACL predicate shared by the gate, signer,
165    /// proxy and manifest validation.
166    pub fn is_acl(&self) -> bool {
167        is_acl_path(&self.path)
168    }
169
170    /// Returns the path of the access-control resource beside this one, or
171    /// `None` when this path is itself an access-control resource.
172    ///
173    /// The pod server keeps an ACL as a sibling: the ACL of the pod root
174    /// `/pods/<pk>/` is `/pods/<pk>.acl`, of a container `/pods/<pk>/a/` is
175    /// `/pods/<pk>/a.acl`, and of a resource `/pods/<pk>/a/x.txt` is
176    /// `/pods/<pk>/a/x.txt.acl`. A resource (not a container) whose name ends
177    /// in `.acl`, and the root ACL, are access-control resources and have no
178    /// ACL of their own.
179    pub fn acl_path(&self) -> Option<Self> {
180        if self.is_acl() {
181            return None;
182        }
183        let base = self.path.strip_suffix('/').unwrap_or(&self.path);
184        Some(Self {
185            path: format!("{base}{ACL_SUFFIX}"),
186            owner: self.owner,
187        })
188    }
189}
190
191/// Returns `true` when `path` names an access-control resource.
192///
193/// This is the single ACL predicate shared by the gate, the signer, the pod
194/// proxy and manifest validation. `path` may be a full pod path
195/// (`/pods/<owner>/…` or `/pods/<owner>.acl`) or a relative path inside a pod.
196/// It is an ACL if and only if it does not end in `/` and its last segment
197/// ends in the four ASCII bytes `.acl`, compared byte for byte and
198/// case-sensitively.
199///
200/// # Examples
201///
202/// ```
203/// use stratum_node_core::is_acl_path;
204///
205/// assert!(is_acl_path(".acl"));
206/// assert!(is_acl_path("a.acl"));
207/// assert!(is_acl_path("profile/card.acl"));
208/// assert!(is_acl_path("reports.acl"));
209/// assert!(is_acl_path("/pods/79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798.acl"));
210/// assert!(!is_acl_path("a.acl/"));
211/// assert!(!is_acl_path("a.ACL"));
212/// assert!(!is_acl_path("/pods/79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798/"));
213/// ```
214pub fn is_acl_path(path: &str) -> bool {
215    !path.ends_with('/') && path.ends_with(ACL_SUFFIX)
216}
217
218/// Checks the prefix and the key, and what immediately follows the key.
219fn parse_owner(path: &str) -> Result<DidNostr, ParsePodPathError> {
220    let rest = path
221        .strip_prefix(PODS_PREFIX)
222        .ok_or(ParsePodPathError::NotAPodPath)?;
223    let key = rest
224        .get(..KEY_HEX_LEN)
225        .filter(|key| encoding::is_lower_hex(key))
226        .ok_or(ParsePodPathError::NotAPodPath)?;
227    let after = &rest[KEY_HEX_LEN..];
228    if !(after == ACL_SUFFIX || after.starts_with('/')) {
229        return Err(ParsePodPathError::NotAPodPath);
230    }
231    DidNostr::from_hex(key).map_err(|_| ParsePodPathError::NotAPodPath)
232}
233
234/// Checks the segments after `/pods/<pk>/`: none is `.` or `..`, and none is
235/// empty except the one after a single trailing `/`.
236fn check_segments(inner: &str) -> Result<(), ParsePodPathError> {
237    let body = inner.strip_suffix('/').unwrap_or(inner);
238    if inner.is_empty() {
239        return Ok(());
240    }
241    let mut empty = false;
242    for segment in body.split('/') {
243        if segment == "." || segment == ".." {
244            return Err(ParsePodPathError::DotSegment);
245        }
246        empty |= segment.is_empty();
247    }
248    if empty {
249        return Err(ParsePodPathError::EmptySegment);
250    }
251    Ok(())
252}
253
254/// Returns `true` for the bytes a pod path may hold:
255/// `A–Z a–z 0–9 - . _ ~ /`.
256fn is_path_byte(b: u8) -> bool {
257    b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~' | b'/')
258}
259
260/// Returns `true` when `query` is acceptable as the query string of a pod
261/// request.
262///
263/// `query` is the text after the `?`, which a gate forwards as received. It
264/// may be empty and may hold only the pod-path characters
265/// `A–Z a–z 0–9 - . _ ~ /` and `= & % +`. No decoding is done: `%` is allowed
266/// here because the query is passed through verbatim and only ever compared
267/// byte for byte.
268///
269/// # Examples
270///
271/// ```
272/// use stratum_node_core::is_valid_pod_query;
273///
274/// assert!(is_valid_pod_query("a=1&b=x%20y+z"));
275/// assert!(is_valid_pod_query(""));
276/// assert!(!is_valid_pod_query("a=1;b=2"));
277/// assert!(!is_valid_pod_query("a=#"));
278/// ```
279pub fn is_valid_pod_query(query: &str) -> bool {
280    query
281        .bytes()
282        .all(|b| is_path_byte(b) || matches!(b, b'=' | b'&' | b'%' | b'+'))
283}
284
285impl fmt::Display for PodPath {
286    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287        f.write_str(&self.path)
288    }
289}
290
291impl fmt::Debug for PodPath {
292    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293        write!(f, "PodPath({})", self.path)
294    }
295}
296
297impl FromStr for PodPath {
298    type Err = ParsePodPathError;
299
300    fn from_str(text: &str) -> Result<Self, Self::Err> {
301        Self::parse(text)
302    }
303}
304
305impl AsRef<str> for PodPath {
306    fn as_ref(&self) -> &str {
307        &self.path
308    }
309}
310
311impl Serialize for PodPath {
312    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
313        serializer.serialize_str(&self.path)
314    }
315}
316
317impl<'de> Deserialize<'de> for PodPath {
318    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
319        let text = String::deserialize(deserializer)?;
320        Self::parse(&text).map_err(serde::de::Error::custom)
321    }
322}
323
324/// The reasons a path can fail to be a [`PodPath`].
325///
326/// [`is_not_a_pod_path`](Self::is_not_a_pod_path) splits them into the two
327/// answers a gate gives: a path outside the allow-list (404) and a pod path
328/// with a forbidden shape (400). Match on that method rather than on the
329/// variants, so that a variant added later is classified by this crate.
330#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
331#[non_exhaustive]
332pub enum ParsePodPathError {
333    /// The path is outside the allow-list: it is not `/pods/` followed by a
334    /// valid 64-digit lowercase hex key and then `/` or exactly `.acl`.
335    #[error("not a pod path")]
336    NotAPodPath,
337    /// The path holds a character outside `A–Z a–z 0–9 - . _ ~ /`.
338    #[error("pod path holds a character outside A-Z a-z 0-9 - . _ ~ /")]
339    ForbiddenCharacter,
340    /// A segment of the path is `.` or `..`.
341    #[error("pod path has a . or .. segment")]
342    DotSegment,
343    /// A segment of the path is empty (`//`), other than after a single
344    /// trailing `/`.
345    #[error("pod path has an empty segment")]
346    EmptySegment,
347    /// [`PodPath::join`] was called on a path that is not a container.
348    #[error("pod path is not a container")]
349    NotAContainer,
350}
351
352impl ParsePodPathError {
353    /// Returns `true` when the path is outside the allow-list altogether
354    /// (a gate answers 404) and `false` when it is a pod path of a forbidden
355    /// shape (a gate answers 400).
356    pub fn is_not_a_pod_path(&self) -> bool {
357        matches!(self, Self::NotAPodPath)
358    }
359}
360
361#[cfg(test)]
362mod tests {
363    use super::*;
364
365    #[test]
366    fn segments_accept_a_single_trailing_slash_only() {
367        assert_eq!(check_segments(""), Ok(()), "pod root");
368        assert_eq!(check_segments("a/"), Ok(()), "container");
369        assert_eq!(check_segments("a/b"), Ok(()), "resource");
370        assert_eq!(
371            check_segments("a//"),
372            Err(ParsePodPathError::EmptySegment),
373            "double trailing slash"
374        );
375        assert_eq!(
376            check_segments("/a"),
377            Err(ParsePodPathError::EmptySegment),
378            "leading empty"
379        );
380        assert_eq!(
381            check_segments("/"),
382            Err(ParsePodPathError::EmptySegment),
383            "root with extra slash"
384        );
385        assert_eq!(
386            check_segments("a/./b"),
387            Err(ParsePodPathError::DotSegment),
388            "dot"
389        );
390        assert_eq!(
391            check_segments("../"),
392            Err(ParsePodPathError::DotSegment),
393            "dot dot container"
394        );
395    }
396}