use std::fmt;
use std::str::FromStr;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::did::DidNostr;
use crate::encoding;
const PODS_PREFIX: &str = "/pods/";
const ACL_SUFFIX: &str = ".acl";
const KEY_HEX_LEN: usize = 64;
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PodPath {
path: String,
owner: DidNostr,
}
impl PodPath {
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,
})
}
pub fn pod_root(owner: &DidNostr) -> Self {
Self {
path: format!("{PODS_PREFIX}{}/", owner.to_hex()),
owner: *owner,
}
}
pub fn owner(&self) -> DidNostr {
self.owner
}
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)
}
pub fn is_container(&self) -> bool {
self.path.ends_with('/')
}
pub fn as_str(&self) -> &str {
&self.path
}
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))
}
pub fn is_acl(&self) -> bool {
is_acl_path(&self.path)
}
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,
})
}
}
pub fn is_acl_path(path: &str) -> bool {
!path.ends_with('/') && path.ends_with(ACL_SUFFIX)
}
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)
}
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(())
}
fn is_path_byte(b: u8) -> bool {
b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~' | b'/')
}
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)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ParsePodPathError {
#[error("not a pod path")]
NotAPodPath,
#[error("pod path holds a character outside A-Z a-z 0-9 - . _ ~ /")]
ForbiddenCharacter,
#[error("pod path has a . or .. segment")]
DotSegment,
#[error("pod path has an empty segment")]
EmptySegment,
#[error("pod path is not a container")]
NotAContainer,
}
impl ParsePodPathError {
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"
);
}
}