| 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>`, `verify:<ref glob>` or |
| 7 | //! `admin`. |
| 8 | //! |
| 9 | //! `write` includes `read`, and `admin` includes both. `interact` covers the |
| 10 | //! social writes (stars, watching, following, issues, comments, reviews and |
| 11 | //! forks) on what the account may read; `write` and `admin` include it, and |
| 12 | //! it gives no read of its own. A `land:<glob>` right lets a token land on |
| 13 | //! the refs its glob matches, and only together with `write`. |
| 14 | //! |
| 15 | //! A `verify:<glob>` right lets a token post verdicts on the branches its |
| 16 | //! glob matches (section 25), and nothing else: it counts only where the |
| 17 | //! token's account may write, and only on a token that reads the repository |
| 18 | //! but holds no `write`, `admin`, `land:` or `interact` there, so that the |
| 19 | //! token of a CI job can say how its tests went and do nothing more. |
| 20 | //! |
| 21 | //! [`Right`] may gain rights: a client keeps a scope it cannot read out of |
| 22 | //! what it decides, as [`ParsedScope::parse`] refuses it whole. |
| 23 | |
| 24 | use std::fmt; |
| 25 | |
| 26 | use crate::api::Scope; |
| 27 | use crate::names::{NameError, RepoPath, is_owner}; |
| 28 | |
| 29 | /// Why a scope is not valid. |
| 30 | #[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] |
| 31 | pub enum ScopeError { |
| 32 | /// The `repo` of a scope is none of `owner/name`, `owner/*` and `*`. |
| 33 | #[error("{0:?} is not a repository pattern: expected \"owner/name\", \"owner/*\" or \"*\"")] |
| 34 | Repo(String), |
| 35 | /// A right that does not exist. |
| 36 | #[error( |
| 37 | "{0:?} is not a right: expected read, interact, write, admin, land:<ref glob> or verify:<ref glob>" |
| 38 | )] |
| 39 | Right(String), |
| 40 | /// A scope without rights. |
| 41 | #[error("the scope for {0:?} grants no right")] |
| 42 | NoRights(String), |
| 43 | } |
| 44 | |
| 45 | /// One right of a scope. More may come: a `match` on it ends with `_`. |
| 46 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] |
| 47 | #[non_exhaustive] |
| 48 | pub enum Right { |
| 49 | /// Every `GET` and `HEAD`, `lacks`, `missing` and the ref watch. |
| 50 | Read, |
| 51 | /// Stars, watching, following, issues, comments, reviews and forks, on |
| 52 | /// what the account may read. It gives no read of its own; `write` and |
| 53 | /// `admin` include it. |
| 54 | Interact, |
| 55 | /// Uploads, and `read`. |
| 56 | Write, |
| 57 | /// Settings, collaborators and deleting the repository, and `write`. |
| 58 | Admin, |
| 59 | /// Landing on the refs the glob matches (see |
| 60 | /// [`glob_matches`](crate::names::glob_matches)), with `write`. |
| 61 | Land(String), |
| 62 | /// Posting verdicts on the branches the glob matches (section 25), |
| 63 | /// where the account may write, on a token that holds nothing more |
| 64 | /// there than `read`. |
| 65 | Verify(String), |
| 66 | } |
| 67 | |
| 68 | /// The glob of a `land:` or `verify:` right: not empty, at most 4,096 |
| 69 | /// bytes, and without control characters. |
| 70 | fn glob(text: &str) -> Option<String> { |
| 71 | (!text.is_empty() && text.len() <= 4096 && !text.chars().any(char::is_control)) |
| 72 | .then(|| text.to_owned()) |
| 73 | } |
| 74 | |
| 75 | impl Right { |
| 76 | /// Reads `read`, `interact`, `write`, `admin`, `land:<glob>` or |
| 77 | /// `verify:<glob>`. A glob is not empty and holds no control character. |
| 78 | pub fn parse(text: &str) -> Result<Right, ScopeError> { |
| 79 | let refused = || ScopeError::Right(text.to_owned()); |
| 80 | match text { |
| 81 | "read" => Ok(Right::Read), |
| 82 | "interact" => Ok(Right::Interact), |
| 83 | "write" => Ok(Right::Write), |
| 84 | "admin" => Ok(Right::Admin), |
| 85 | _ => { |
| 86 | if let Some(rest) = text.strip_prefix("land:") { |
| 87 | glob(rest).map(Right::Land).ok_or_else(refused) |
| 88 | } else if let Some(rest) = text.strip_prefix("verify:") { |
| 89 | glob(rest).map(Right::Verify).ok_or_else(refused) |
| 90 | } else { |
| 91 | Err(refused()) |
| 92 | } |
| 93 | } |
| 94 | } |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | impl fmt::Display for Right { |
| 99 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 100 | match self { |
| 101 | Right::Read => f.write_str("read"), |
| 102 | Right::Interact => f.write_str("interact"), |
| 103 | Right::Write => f.write_str("write"), |
| 104 | Right::Admin => f.write_str("admin"), |
| 105 | Right::Land(glob) => write!(f, "land:{glob}"), |
| 106 | Right::Verify(glob) => write!(f, "verify:{glob}"), |
| 107 | } |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | /// The repositories a scope reaches. |
| 112 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] |
| 113 | pub enum ScopeRepo { |
| 114 | /// `*`: every repository. |
| 115 | All, |
| 116 | /// `owner/*`: every repository of one owner, lowercase. |
| 117 | Owner(String), |
| 118 | /// `owner/name`: one repository. |
| 119 | Repo(RepoPath), |
| 120 | } |
| 121 | |
| 122 | impl ScopeRepo { |
| 123 | /// Reads `*`, `owner/*` or `owner/name`. |
| 124 | pub fn parse(text: &str) -> Result<ScopeRepo, ScopeError> { |
| 125 | if text == "*" { |
| 126 | return Ok(ScopeRepo::All); |
| 127 | } |
| 128 | let invalid = || ScopeError::Repo(text.to_owned()); |
| 129 | match text.split_once('/') { |
| 130 | Some((owner, "*")) if is_owner(owner) => { |
| 131 | Ok(ScopeRepo::Owner(owner.to_ascii_lowercase())) |
| 132 | } |
| 133 | Some(_) => text |
| 134 | .parse::<RepoPath>() |
| 135 | .map(ScopeRepo::Repo) |
| 136 | .map_err(|_: NameError| invalid()), |
| 137 | None => Err(invalid()), |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | /// Whether the scope reaches `repo`. Owners and names are compared |
| 142 | /// without regard to case. |
| 143 | pub fn matches(&self, repo: &RepoPath) -> bool { |
| 144 | match self { |
| 145 | ScopeRepo::All => true, |
| 146 | ScopeRepo::Owner(owner) => owner.eq_ignore_ascii_case(&repo.owner), |
| 147 | ScopeRepo::Repo(path) => { |
| 148 | path.owner.eq_ignore_ascii_case(&repo.owner) |
| 149 | && path.name.eq_ignore_ascii_case(&repo.name) |
| 150 | } |
| 151 | } |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | impl fmt::Display for ScopeRepo { |
| 156 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 157 | match self { |
| 158 | ScopeRepo::All => f.write_str("*"), |
| 159 | ScopeRepo::Owner(owner) => write!(f, "{owner}/*"), |
| 160 | ScopeRepo::Repo(path) => write!(f, "{path}"), |
| 161 | } |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | /// A scope, read and checked. |
| 166 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 167 | pub struct ParsedScope { |
| 168 | /// The repositories it reaches. |
| 169 | pub repo: ScopeRepo, |
| 170 | /// What it allows there, at least one right. |
| 171 | pub rights: Vec<Right>, |
| 172 | } |
| 173 | |
| 174 | impl ParsedScope { |
| 175 | /// Checks a scope as it comes on the wire. |
| 176 | pub fn parse(scope: &Scope) -> Result<ParsedScope, ScopeError> { |
| 177 | let repo = ScopeRepo::parse(&scope.repo)?; |
| 178 | if scope.rights.is_empty() { |
| 179 | return Err(ScopeError::NoRights(scope.repo.clone())); |
| 180 | } |
| 181 | let rights = scope |
| 182 | .rights |
| 183 | .iter() |
| 184 | .map(|right| Right::parse(right)) |
| 185 | .collect::<Result<Vec<_>, _>>()?; |
| 186 | Ok(ParsedScope { repo, rights }) |
| 187 | } |
| 188 | |
| 189 | /// The scope as it goes on the wire, in canonical spelling. |
| 190 | pub fn to_scope(&self) -> Scope { |
| 191 | Scope { |
| 192 | repo: self.repo.to_string(), |
| 193 | rights: self.rights.iter().map(Right::to_string).collect(), |
| 194 | } |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | #[cfg(test)] |
| 199 | mod tests { |
| 200 | use super::*; |
| 201 | |
| 202 | #[test] |
| 203 | fn rights() { |
| 204 | for (text, right) in [ |
| 205 | ("read", Right::Read), |
| 206 | ("interact", Right::Interact), |
| 207 | ("write", Right::Write), |
| 208 | ("admin", Right::Admin), |
| 209 | ("land:*", Right::Land("*".into())), |
| 210 | ("land:release/*", Right::Land("release/*".into())), |
| 211 | ("verify:main", Right::Verify("main".into())), |
| 212 | ("verify:*", Right::Verify("*".into())), |
| 213 | ] { |
| 214 | assert_eq!(Right::parse(text), Ok(right.clone())); |
| 215 | assert_eq!(right.to_string(), text); |
| 216 | } |
| 217 | for bad in [ |
| 218 | "", |
| 219 | "READ", |
| 220 | "Interact", |
| 221 | "interact:*", |
| 222 | "land:", |
| 223 | "land", |
| 224 | "push", |
| 225 | "land:a\nb", |
| 226 | "verify:", |
| 227 | "verify", |
| 228 | "VERIFY:main", |
| 229 | "Verify:main", |
| 230 | "verify:a\nb", |
| 231 | ] { |
| 232 | assert_eq!( |
| 233 | Right::parse(bad), |
| 234 | Err(ScopeError::Right(bad.to_owned())), |
| 235 | "{bad:?}" |
| 236 | ); |
| 237 | } |
| 238 | let long = format!("verify:{}", "a".repeat(4096)); |
| 239 | assert!(Right::parse(&long).is_ok()); |
| 240 | assert!(Right::parse(&format!("{long}a")).is_err()); |
| 241 | // The error names every right there is. |
| 242 | let said = ScopeError::Right("push".into()).to_string(); |
| 243 | assert!( |
| 244 | said.contains("land:<ref glob>") && said.contains("verify:<ref glob>"), |
| 245 | "{said}" |
| 246 | ); |
| 247 | } |
| 248 | |
| 249 | #[test] |
| 250 | fn repositories() { |
| 251 | let demo: RepoPath = "ada/Demo".parse().unwrap(); |
| 252 | let other: RepoPath = "bob/demo".parse().unwrap(); |
| 253 | let all = ScopeRepo::parse("*").unwrap(); |
| 254 | let ada = ScopeRepo::parse("Ada/*").unwrap(); |
| 255 | let one = ScopeRepo::parse("ada/demo").unwrap(); |
| 256 | assert!(all.matches(&demo) && all.matches(&other)); |
| 257 | assert!(ada.matches(&demo) && !ada.matches(&other)); |
| 258 | assert!(one.matches(&demo) && !one.matches(&other)); |
| 259 | assert_eq!(ada.to_string(), "ada/*"); |
| 260 | for bad in [ |
| 261 | "", "ada", "ada/", "/demo", "ada/*/x", "a--b/*", "ada/.x", "**", |
| 262 | ] { |
| 263 | assert!(ScopeRepo::parse(bad).is_err(), "{bad:?}"); |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | #[test] |
| 268 | fn scopes() { |
| 269 | let scope = Scope { |
| 270 | repo: "ada/*".into(), |
| 271 | rights: vec!["read".into(), "land:main".into()], |
| 272 | }; |
| 273 | let parsed = ParsedScope::parse(&scope).unwrap(); |
| 274 | assert_eq!(parsed.rights, [Right::Read, Right::Land("main".into())]); |
| 275 | assert_eq!(parsed.to_scope(), scope); |
| 276 | let empty = Scope { |
| 277 | repo: "*".into(), |
| 278 | rights: Vec::new(), |
| 279 | }; |
| 280 | assert_eq!( |
| 281 | ParsedScope::parse(&empty), |
| 282 | Err(ScopeError::NoRights("*".into())) |
| 283 | ); |
| 284 | // The scope of a CI job's token: it reads, and posts verdicts. |
| 285 | let ci = Scope { |
| 286 | repo: "ada/demo".into(), |
| 287 | rights: vec!["read".into(), "verify:main".into()], |
| 288 | }; |
| 289 | let parsed = ParsedScope::parse(&ci).unwrap(); |
| 290 | assert_eq!(parsed.rights, [Right::Read, Right::Verify("main".into())]); |
| 291 | assert_eq!(parsed.to_scope(), ci); |
| 292 | // A right this crate cannot read refuses its scope whole. |
| 293 | let later = Scope { |
| 294 | repo: "ada/demo".into(), |
| 295 | rights: vec!["read".into(), "someday:main".into()], |
| 296 | }; |
| 297 | assert_eq!( |
| 298 | ParsedScope::parse(&later), |
| 299 | Err(ScopeError::Right("someday:main".into())) |
| 300 | ); |
| 301 | } |
| 302 | } |