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 the path of the access-control resource beside this one, or
161 /// `None` when this path is itself an access-control resource.
162 ///
163 /// The pod server keeps an ACL as a sibling: the ACL of the pod root
164 /// `/pods/<pk>/` is `/pods/<pk>.acl`, of a container `/pods/<pk>/a/` is
165 /// `/pods/<pk>/a.acl`, and of a resource `/pods/<pk>/a/x.txt` is
166 /// `/pods/<pk>/a/x.txt.acl`. A resource (not a container) whose name ends
167 /// in `.acl`, and the root ACL, are access-control resources and have no
168 /// ACL of their own.
169 pub fn acl_path(&self) -> Option<Self> {
170 if self.is_root_acl() || (!self.is_container() && self.path.ends_with(ACL_SUFFIX)) {
171 return None;
172 }
173 let base = self.path.strip_suffix('/').unwrap_or(&self.path);
174 Some(Self {
175 path: format!("{base}{ACL_SUFFIX}"),
176 owner: self.owner,
177 })
178 }
179}
180
181/// Checks the prefix and the key, and what immediately follows the key.
182fn parse_owner(path: &str) -> Result<DidNostr, ParsePodPathError> {
183 let rest = path
184 .strip_prefix(PODS_PREFIX)
185 .ok_or(ParsePodPathError::NotAPodPath)?;
186 let key = rest
187 .get(..KEY_HEX_LEN)
188 .filter(|key| encoding::is_lower_hex(key))
189 .ok_or(ParsePodPathError::NotAPodPath)?;
190 let after = &rest[KEY_HEX_LEN..];
191 if !(after == ACL_SUFFIX || after.starts_with('/')) {
192 return Err(ParsePodPathError::NotAPodPath);
193 }
194 DidNostr::from_hex(key).map_err(|_| ParsePodPathError::NotAPodPath)
195}
196
197/// Checks the segments after `/pods/<pk>/`: none is `.` or `..`, and none is
198/// empty except the one after a single trailing `/`.
199fn check_segments(inner: &str) -> Result<(), ParsePodPathError> {
200 let body = inner.strip_suffix('/').unwrap_or(inner);
201 if inner.is_empty() {
202 return Ok(());
203 }
204 let mut empty = false;
205 for segment in body.split('/') {
206 if segment == "." || segment == ".." {
207 return Err(ParsePodPathError::DotSegment);
208 }
209 empty |= segment.is_empty();
210 }
211 if empty {
212 return Err(ParsePodPathError::EmptySegment);
213 }
214 Ok(())
215}
216
217/// Returns `true` for the bytes a pod path may hold:
218/// `A–Z a–z 0–9 - . _ ~ /`.
219fn is_path_byte(b: u8) -> bool {
220 b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~' | b'/')
221}
222
223/// Returns `true` when `query` is acceptable as the query string of a pod
224/// request.
225///
226/// `query` is the text after the `?`, which a gate forwards as received. It
227/// may be empty and may hold only the pod-path characters
228/// `A–Z a–z 0–9 - . _ ~ /` and `= & % +`. No decoding is done: `%` is allowed
229/// here because the query is passed through verbatim and only ever compared
230/// byte for byte.
231///
232/// # Examples
233///
234/// ```
235/// use stratum_node_core::is_valid_pod_query;
236///
237/// assert!(is_valid_pod_query("a=1&b=x%20y+z"));
238/// assert!(is_valid_pod_query(""));
239/// assert!(!is_valid_pod_query("a=1;b=2"));
240/// assert!(!is_valid_pod_query("a=#"));
241/// ```
242pub fn is_valid_pod_query(query: &str) -> bool {
243 query
244 .bytes()
245 .all(|b| is_path_byte(b) || matches!(b, b'=' | b'&' | b'%' | b'+'))
246}
247
248impl fmt::Display for PodPath {
249 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250 f.write_str(&self.path)
251 }
252}
253
254impl fmt::Debug for PodPath {
255 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
256 write!(f, "PodPath({})", self.path)
257 }
258}
259
260impl FromStr for PodPath {
261 type Err = ParsePodPathError;
262
263 fn from_str(text: &str) -> Result<Self, Self::Err> {
264 Self::parse(text)
265 }
266}
267
268impl AsRef<str> for PodPath {
269 fn as_ref(&self) -> &str {
270 &self.path
271 }
272}
273
274impl Serialize for PodPath {
275 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
276 serializer.serialize_str(&self.path)
277 }
278}
279
280impl<'de> Deserialize<'de> for PodPath {
281 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
282 let text = String::deserialize(deserializer)?;
283 Self::parse(&text).map_err(serde::de::Error::custom)
284 }
285}
286
287/// The reasons a path can fail to be a [`PodPath`].
288///
289/// [`is_not_a_pod_path`](Self::is_not_a_pod_path) splits them into the two
290/// answers a gate gives: a path outside the allow-list (404) and a pod path
291/// with a forbidden shape (400). Match on that method rather than on the
292/// variants, so that a variant added later is classified by this crate.
293#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
294#[non_exhaustive]
295pub enum ParsePodPathError {
296 /// The path is outside the allow-list: it is not `/pods/` followed by a
297 /// valid 64-digit lowercase hex key and then `/` or exactly `.acl`.
298 #[error("not a pod path")]
299 NotAPodPath,
300 /// The path holds a character outside `A–Z a–z 0–9 - . _ ~ /`.
301 #[error("pod path holds a character outside A-Z a-z 0-9 - . _ ~ /")]
302 ForbiddenCharacter,
303 /// A segment of the path is `.` or `..`.
304 #[error("pod path has a . or .. segment")]
305 DotSegment,
306 /// A segment of the path is empty (`//`), other than after a single
307 /// trailing `/`.
308 #[error("pod path has an empty segment")]
309 EmptySegment,
310 /// [`PodPath::join`] was called on a path that is not a container.
311 #[error("pod path is not a container")]
312 NotAContainer,
313}
314
315impl ParsePodPathError {
316 /// Returns `true` when the path is outside the allow-list altogether
317 /// (a gate answers 404) and `false` when it is a pod path of a forbidden
318 /// shape (a gate answers 400).
319 pub fn is_not_a_pod_path(&self) -> bool {
320 matches!(self, Self::NotAPodPath)
321 }
322}
323
324#[cfg(test)]
325mod tests {
326 use super::*;
327
328 #[test]
329 fn segments_accept_a_single_trailing_slash_only() {
330 assert_eq!(check_segments(""), Ok(()), "pod root");
331 assert_eq!(check_segments("a/"), Ok(()), "container");
332 assert_eq!(check_segments("a/b"), Ok(()), "resource");
333 assert_eq!(
334 check_segments("a//"),
335 Err(ParsePodPathError::EmptySegment),
336 "double trailing slash"
337 );
338 assert_eq!(
339 check_segments("/a"),
340 Err(ParsePodPathError::EmptySegment),
341 "leading empty"
342 );
343 assert_eq!(
344 check_segments("/"),
345 Err(ParsePodPathError::EmptySegment),
346 "root with extra slash"
347 );
348 assert_eq!(
349 check_segments("a/./b"),
350 Err(ParsePodPathError::DotSegment),
351 "dot"
352 );
353 assert_eq!(
354 check_segments("../"),
355 Err(ParsePodPathError::DotSegment),
356 "dot dot container"
357 );
358 }
359}