OXYGENHUB
◆ v0.9.5 oxygenhub / crates / hub / src / repos / names.rs
4.9 KiB · Rust · last changed Drops: per-user gists, each a small hidden Oxygen repository (#279) 15 days ago source blame history raw
1
//! Owner and repository names (hub spec §3.2) and the top-level path
2
//! segments no owner may take.
3
4
use std::fmt;
5
6
/// `owner/name`, both validated.
7
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
8
pub struct RepoName {
9
    pub owner: String,
10
    pub name: String,
11
}
12
13
/// Top-level path segments reserved for the hub itself.
14
pub const RESERVED: &[&str] = &[
15
    "api",
16
    "static",
17
    "login",
18
    "logout",
19
    "register",
20
    "settings",
21
    "explore",
22
    "search",
23
    "notifications",
24
    "new",
25
    "orgs",
26
    "admin",
27
    "style.css",
28
    "favicon.ico",
29
    "favicon.svg",
30
    "health",
31
    "avatar",
32
    "help",
33
    "projects",
34
    "assets",
35
    ".well-known",
36
    // Live pages, CSP reports and the security pages (oxygenhub#204, #222, #224, #230).
37
    "live",
38
    "csp-report",
39
    "security.txt",
40
    "security-contact",
41
    // The transparency log, the metrics and Insights (oxygenhub#238, #212, #257).
42
    "log",
43
    "metrics",
44
    "insights",
45
    // Drops: `/drops` is the viewer's own (oxygenhub#279).
46
    "drops",
47
];
48
49
/// The repository name no repository may take: `/{owner}/drops` is the
50
/// owner's Drops page, and `/{owner}/drops/{id}` a drop (oxygenhub#279).
51
pub const DROPS: &str = "drops";
52
53
/// A drop's id: lowercase hex, 16 to 40 characters (they are made with
54
/// 24, 96 random bits, so a secret drop's address cannot be guessed).
55
pub fn valid_drop_id(s: &str) -> bool {
56
    (16..=40).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
57
}
58
59
/// A repository name: a segment, not `drops`; or a drop's, `drops/ID`,
60
/// which no repository name can be, since it holds a slash.
61
pub fn valid_repo_name(s: &str) -> bool {
62
    match s.split_once('/') {
63
        Some((DROPS, id)) => valid_drop_id(id),
64
        Some(_) => false,
65
        None => valid_segment(s) && !s.eq_ignore_ascii_case(DROPS),
66
    }
67
}
68
69
/// `[A-Za-z0-9][A-Za-z0-9._-]{0,63}`, not `.`/`..`, not ending in `.git`.
70
pub fn valid_segment(s: &str) -> bool {
71
    let mut chars = s.chars();
72
    let Some(first) = chars.next() else { return false };
73
    if !first.is_ascii_alphanumeric() || s.len() > 64 {
74
        return false;
75
    }
76
    if !chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')) {
77
        return false;
78
    }
79
    s != "." && s != ".." && !s.ends_with(".git")
80
}
81
82
pub fn valid_owner(s: &str) -> bool {
83
    valid_segment(s) && !RESERVED.contains(&s)
84
}
85
86
impl RepoName {
87
    pub fn new(owner: &str, name: &str) -> Option<RepoName> {
88
        if valid_owner(owner) && valid_repo_name(name) {
89
            Some(RepoName { owner: owner.into(), name: name.into() })
90
        } else {
91
            None
92
        }
93
    }
94
95
    /// `owner/name`.
96
    pub fn parse(slug: &str) -> Option<RepoName> {
97
        let (owner, name) = slug.split_once('/')?;
98
        RepoName::new(owner, name)
99
    }
100
101
    pub fn url(&self) -> String {
102
        format!("/{}/{}", self.owner, self.name)
103
    }
104
105
    /// A drop's repository, `owner/drops/ID`.
106
    pub fn drop(owner: &str, id: &str) -> Option<RepoName> {
107
        RepoName::new(owner, &format!("{DROPS}/{id}"))
108
    }
109
110
    /// The drop's id, when this is a drop's repository.
111
    pub fn drop_id(&self) -> Option<&str> {
112
        self.name.strip_prefix(DROPS)?.strip_prefix('/')
113
    }
114
}
115
116
impl fmt::Display for RepoName {
117
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118
        write!(f, "{}/{}", self.owner, self.name)
119
    }
120
}
121
122
#[cfg(test)]
123
mod tests {
124
    use super::*;
125
126
    #[test]
127
    fn names() {
128
        assert!(RepoName::parse("andy/oxygen").is_some());
129
        assert!(RepoName::parse("andy/oxy.gen-2_x").is_some());
130
        assert!(RepoName::parse("api/x").is_none(), "reserved owner");
131
        assert!(RepoName::parse("andy/x.git").is_none(), "mirror URL");
132
        assert!(RepoName::parse("andy/..").is_none());
133
        assert!(RepoName::parse(".andy/x").is_none());
134
        assert!(RepoName::parse("andy/a b").is_none());
135
        assert!(RepoName::parse("andy").is_none());
136
        assert!(RepoName::parse(&format!("andy/{}", "a".repeat(65))).is_none());
137
        assert_eq!(RepoName::parse("andy/oxygen").unwrap().url(), "/andy/oxygen");
138
        // `drops` is the Drops page; a drop is `drops/ID` (#279).
139
        assert!(RepoName::parse("andy/drops").is_none() && RepoName::parse("andy/Drops").is_none());
140
        assert!(RepoName::parse("drops/x").is_none(), "reserved owner");
141
        let d = RepoName::parse("andy/drops/0123456789abcdef01234567").unwrap();
142
        assert_eq!(d.drop_id(), Some("0123456789abcdef01234567"));
143
        assert_eq!(d.url(), "/andy/drops/0123456789abcdef01234567");
144
        assert_eq!(RepoName::drop("andy", "0123456789abcdef01234567"), Some(d));
145
        assert!(RepoName::parse("andy/drops/short").is_none());
146
        assert!(RepoName::parse("andy/drops/0123456789ABCDEF01234567").is_none());
147
        assert!(RepoName::parse("andy/x/0123456789abcdef01234567").is_none());
148
        assert_eq!(RepoName::parse("andy/oxygen").unwrap().drop_id(), None);
149
    }
150
}