Elffuss BraidHub

utopia-ia/elffuss-braid public

2da7deeea818 · 7.8 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Token scopes: which repositories a token reaches, and what it may do
5//! there. A scope's `repo` is `owner/name`, `owner/*` or `*`; a right is
6//! `read`, `interact`, `write`, `land:<ref glob>` or `admin`.
7//!
8//! `write` includes `read`, and `admin` includes both. `interact` covers the
9//! social writes (stars, watching, following, issues, comments, reviews and
10//! forks) on what the account may read; `write` and `admin` include it, and
11//! it gives no read of its own. A `land:<glob>` right lets a token land on
12//! the refs its glob matches, and only together with `write`.
13
14use std::fmt;
15
16use crate::api::Scope;
17use crate::names::{NameError, RepoPath, is_owner};
18
19/// Why a scope is not valid.
20#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
21pub enum ScopeError {
22 /// The `repo` of a scope is none of `owner/name`, `owner/*` and `*`.
23 #[error("{0:?} is not a repository pattern: expected \"owner/name\", \"owner/*\" or \"*\"")]
24 Repo(String),
25 /// A right that does not exist.
26 #[error("{0:?} is not a right: expected read, interact, write, admin or land:<ref glob>")]
27 Right(String),
28 /// A scope without rights.
29 #[error("the scope for {0:?} grants no right")]
30 NoRights(String),
31}
32
33/// One right of a scope.
34#[derive(Clone, Debug, PartialEq, Eq, Hash)]
35pub enum Right {
36 /// Every `GET` and `HEAD`, `lacks`, `missing` and the ref watch.
37 Read,
38 /// Stars, watching, following, issues, comments, reviews and forks, on
39 /// what the account may read. It gives no read of its own; `write` and
40 /// `admin` include it.
41 Interact,
42 /// Uploads, and `read`.
43 Write,
44 /// Settings, collaborators and deleting the repository, and `write`.
45 Admin,
46 /// Landing on the refs the glob matches (see
47 /// [`glob_matches`](crate::names::glob_matches)), with `write`.
48 Land(String),
49}
50
51impl Right {
52 /// Reads `read`, `interact`, `write`, `admin` or `land:<glob>`. A glob
53 /// is not empty and holds no control character.
54 pub fn parse(text: &str) -> Result<Right, ScopeError> {
55 match text {
56 "read" => Ok(Right::Read),
57 "interact" => Ok(Right::Interact),
58 "write" => Ok(Right::Write),
59 "admin" => Ok(Right::Admin),
60 _ => match text.strip_prefix("land:") {
61 Some(glob)
62 if !glob.is_empty()
63 && glob.len() <= 4096
64 && !glob.chars().any(char::is_control) =>
65 {
66 Ok(Right::Land(glob.to_owned()))
67 }
68 _ => Err(ScopeError::Right(text.to_owned())),
69 },
70 }
71 }
72}
73
74impl fmt::Display for Right {
75 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76 match self {
77 Right::Read => f.write_str("read"),
78 Right::Interact => f.write_str("interact"),
79 Right::Write => f.write_str("write"),
80 Right::Admin => f.write_str("admin"),
81 Right::Land(glob) => write!(f, "land:{glob}"),
82 }
83 }
84}
85
86/// The repositories a scope reaches.
87#[derive(Clone, Debug, PartialEq, Eq, Hash)]
88pub enum ScopeRepo {
89 /// `*`: every repository.
90 All,
91 /// `owner/*`: every repository of one owner, lowercase.
92 Owner(String),
93 /// `owner/name`: one repository.
94 Repo(RepoPath),
95}
96
97impl ScopeRepo {
98 /// Reads `*`, `owner/*` or `owner/name`.
99 pub fn parse(text: &str) -> Result<ScopeRepo, ScopeError> {
100 if text == "*" {
101 return Ok(ScopeRepo::All);
102 }
103 let invalid = || ScopeError::Repo(text.to_owned());
104 match text.split_once('/') {
105 Some((owner, "*")) if is_owner(owner) => {
106 Ok(ScopeRepo::Owner(owner.to_ascii_lowercase()))
107 }
108 Some(_) => text
109 .parse::<RepoPath>()
110 .map(ScopeRepo::Repo)
111 .map_err(|_: NameError| invalid()),
112 None => Err(invalid()),
113 }
114 }
115
116 /// Whether the scope reaches `repo`. Owners and names are compared
117 /// without regard to case.
118 pub fn matches(&self, repo: &RepoPath) -> bool {
119 match self {
120 ScopeRepo::All => true,
121 ScopeRepo::Owner(owner) => owner.eq_ignore_ascii_case(&repo.owner),
122 ScopeRepo::Repo(path) => {
123 path.owner.eq_ignore_ascii_case(&repo.owner)
124 && path.name.eq_ignore_ascii_case(&repo.name)
125 }
126 }
127 }
128}
129
130impl fmt::Display for ScopeRepo {
131 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132 match self {
133 ScopeRepo::All => f.write_str("*"),
134 ScopeRepo::Owner(owner) => write!(f, "{owner}/*"),
135 ScopeRepo::Repo(path) => write!(f, "{path}"),
136 }
137 }
138}
139
140/// A scope, read and checked.
141#[derive(Clone, Debug, PartialEq, Eq)]
142pub struct ParsedScope {
143 /// The repositories it reaches.
144 pub repo: ScopeRepo,
145 /// What it allows there, at least one right.
146 pub rights: Vec<Right>,
147}
148
149impl ParsedScope {
150 /// Checks a scope as it comes on the wire.
151 pub fn parse(scope: &Scope) -> Result<ParsedScope, ScopeError> {
152 let repo = ScopeRepo::parse(&scope.repo)?;
153 if scope.rights.is_empty() {
154 return Err(ScopeError::NoRights(scope.repo.clone()));
155 }
156 let rights = scope
157 .rights
158 .iter()
159 .map(|right| Right::parse(right))
160 .collect::<Result<Vec<_>, _>>()?;
161 Ok(ParsedScope { repo, rights })
162 }
163
164 /// The scope as it goes on the wire, in canonical spelling.
165 pub fn to_scope(&self) -> Scope {
166 Scope {
167 repo: self.repo.to_string(),
168 rights: self.rights.iter().map(Right::to_string).collect(),
169 }
170 }
171}
172
173#[cfg(test)]
174mod tests {
175 use super::*;
176
177 #[test]
178 fn rights() {
179 for (text, right) in [
180 ("read", Right::Read),
181 ("interact", Right::Interact),
182 ("write", Right::Write),
183 ("admin", Right::Admin),
184 ("land:*", Right::Land("*".into())),
185 ("land:release/*", Right::Land("release/*".into())),
186 ] {
187 assert_eq!(Right::parse(text), Ok(right.clone()));
188 assert_eq!(right.to_string(), text);
189 }
190 for bad in [
191 "",
192 "READ",
193 "Interact",
194 "interact:*",
195 "land:",
196 "land",
197 "push",
198 "land:a\nb",
199 ] {
200 assert!(Right::parse(bad).is_err(), "{bad:?}");
201 }
202 }
203
204 #[test]
205 fn repositories() {
206 let demo: RepoPath = "ada/Demo".parse().unwrap();
207 let other: RepoPath = "bob/demo".parse().unwrap();
208 let all = ScopeRepo::parse("*").unwrap();
209 let ada = ScopeRepo::parse("Ada/*").unwrap();
210 let one = ScopeRepo::parse("ada/demo").unwrap();
211 assert!(all.matches(&demo) && all.matches(&other));
212 assert!(ada.matches(&demo) && !ada.matches(&other));
213 assert!(one.matches(&demo) && !one.matches(&other));
214 assert_eq!(ada.to_string(), "ada/*");
215 for bad in [
216 "", "ada", "ada/", "/demo", "ada/*/x", "a--b/*", "ada/.x", "**",
217 ] {
218 assert!(ScopeRepo::parse(bad).is_err(), "{bad:?}");
219 }
220 }
221
222 #[test]
223 fn scopes() {
224 let scope = Scope {
225 repo: "ada/*".into(),
226 rights: vec!["read".into(), "land:main".into()],
227 };
228 let parsed = ParsedScope::parse(&scope).unwrap();
229 assert_eq!(parsed.rights, [Right::Read, Right::Land("main".into())]);
230 assert_eq!(parsed.to_scope(), scope);
231 let empty = Scope {
232 repo: "*".into(),
233 rights: Vec::new(),
234 };
235 assert_eq!(
236 ParsedScope::parse(&empty),
237 Err(ScopeError::NoRights("*".into()))
238 );
239 }
240}