steid

@jamesgill /

Rust12.9 KBCode·Blame·History·Raw
1use std::fmt;
2
3use super::{DomainError, OrgId};
4
5/// An organisation handle — the `{owner}` segment of every URL, and unique across the
6/// installation.
7///
8/// Rules follow GitHub's: 1–39 characters, ASCII alphanumeric or hyphen, no leading or
9/// trailing hyphen. Stored lowercase so lookups and URLs agree.
10#[derive(Debug, Clone, PartialEq, Eq, Hash)]
11pub struct OrgName(String);
12
13/// Handles that would collide with an application route.
14///
15/// Handles live at the root (`/{handle}`), so anything here would shadow a real route
16/// or be shadowed by one. Kept deliberately lean: routes are grouped under functional
17/// prefixes (`/auth/login`, not `/login`), so this grows per *area*, not per route.
18///
19/// **Reserve generously and early.** Adding an entry later is a breaking change for
20/// whoever already holds that handle — their account has to be renamed and their links
21/// break. Entries here cost nothing while unclaimed.
22///
23/// The test for adding one: could this ever be a *top-level* route? Under grouping,
24/// almost nothing is — a health check is `/api/health`, sign-up is `/auth/register` —
25/// so words that would live under a prefix do not belong here. GitHub reserves 590+
26/// because its namespace is flat; copying that list would import the cost without the
27/// cause.
28///
29/// Paths containing characters a handle cannot hold need no entry: `/_topcoat/`,
30/// `/.well-known/`, `robots.txt`, `favicon.ico` are all excluded by the rules above.
31const RESERVED: &[&str] = &[
32 "about",
33 "admin",
34 "api",
35 "assets",
36 "auth",
37 "dashboard",
38 "docs",
39 "explore",
40 "help",
41 "legal",
42 "notifications",
43 // Where the boot sweep parks a repository directory nothing claims
44 // (`GitStorage::quarantine`). A handle by this name would own a directory the sweep
45 // deliberately never looks inside, so its repositories could never be reconciled.
46 "orphaned",
47 "privacy",
48 "search",
49 "security",
50 "settings",
51 "static",
52 "status",
53 // The project's own name, so nobody can hold it and impersonate the software.
54 "steid",
55 "support",
56 "terms",
57];
58
59impl OrgName {
60 pub const MAX_LEN: usize = 39;
61
62 /// Validates and normalises user-supplied input.
63 pub fn new(value: impl Into<String>) -> Result<Self, DomainError> {
64 let value = value.into();
65 let trimmed = value.trim();
66
67 let invalid = |reason: &str| DomainError::validation("name", reason);
68
69 if trimmed.is_empty() {
70 return Err(invalid("must not be empty"));
71 }
72 if trimmed.chars().count() > Self::MAX_LEN {
73 return Err(invalid("must be at most 39 characters"));
74 }
75 if !trimmed
76 .chars()
77 .all(|c| c.is_ascii_alphanumeric() || c == '-')
78 {
79 return Err(invalid("may only contain letters, digits, and hyphens"));
80 }
81 if trimmed.starts_with('-') || trimmed.ends_with('-') {
82 return Err(invalid("must not start or end with a hyphen"));
83 }
84
85 let normalised = trimmed.to_lowercase();
86
87 // Checked against the normalised form: `API` and `api` are the same handle.
88 if RESERVED.contains(&normalised.as_str()) {
89 return Err(invalid("is reserved"));
90 }
91
92 Ok(Self(normalised))
93 }
94
95 /// Wraps a value already validated on the way into the database.
96 pub fn from_trusted(value: impl Into<String>) -> Self {
97 Self(value.into())
98 }
99
100 pub fn as_str(&self) -> &str {
101 &self.0
102 }
103}
104
105impl fmt::Display for OrgName {
106 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107 f.write_str(&self.0)
108 }
109}
110
111/// An organisation. Every user gets a personal one at registration, and repositories
112/// and content hang off organisations rather than users.
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub struct Organization {
115 pub id: OrgId,
116 pub name: OrgName,
117 /// Free-form label shown in the UI. Falls back to `name` when unset.
118 pub display_name: Option<String>,
119 /// Free-form profile text shown on the profile page.
120 pub bio: Option<String>,
121}
122
123impl Organization {
124 /// Longest permitted bio. Generous enough for a few sentences of introduction
125 /// without becoming a page of its own.
126 pub const MAX_BIO_LEN: usize = 500;
127
128 /// Creates an organisation from user-supplied input.
129 ///
130 /// Profile text is set afterwards with [`update_profile`](Self::update_profile) —
131 /// nothing creating an organisation has one to supply.
132 pub fn new(
133 id: OrgId,
134 name: impl Into<String>,
135 display_name: Option<String>,
136 ) -> Result<Self, DomainError> {
137 Ok(Self {
138 id,
139 name: OrgName::new(name)?,
140 display_name: normalise_optional(display_name),
141 bio: None,
142 })
143 }
144
145 /// Reassembles an organisation from storage, skipping validation.
146 pub fn from_trusted(
147 id: OrgId,
148 name: OrgName,
149 display_name: Option<String>,
150 bio: Option<String>,
151 ) -> Self {
152 Self {
153 id,
154 name,
155 display_name,
156 bio,
157 }
158 }
159
160 /// Applies edited profile fields, validating them.
161 ///
162 /// Blank input clears the field rather than storing whitespace, so "cleared" and
163 /// "never set" stay the same state and the page has one case to render.
164 pub fn update_profile(
165 &mut self,
166 display_name: Option<String>,
167 bio: Option<String>,
168 ) -> Result<(), DomainError> {
169 let bio = normalise_optional(bio);
170
171 if let Some(bio) = &bio
172 && bio.chars().count() > Self::MAX_BIO_LEN
173 {
174 return Err(DomainError::validation(
175 "bio",
176 format!("must be at most {} characters", Self::MAX_BIO_LEN),
177 ));
178 }
179
180 self.display_name = normalise_optional(display_name);
181 self.bio = bio;
182
183 Ok(())
184 }
185
186 /// The label to show in the UI.
187 pub fn label(&self) -> &str {
188 self.display_name
189 .as_deref()
190 .unwrap_or_else(|| self.name.as_str())
191 }
192}
193
194/// Trims, and treats blank as absent.
195fn normalise_optional(value: Option<String>) -> Option<String> {
196 value
197 .map(|value| value.trim().to_owned())
198 .filter(|value| !value.is_empty())
199}
200
201#[cfg(test)]
202mod tests {
203 use super::*;
204
205 #[test]
206 fn accepts_ordinary_handles() {
207 for input in ["james", "acme", "a", "my-org", "org2026", "a-b-c"] {
208 assert!(
209 OrgName::new(input).is_ok(),
210 "expected {input:?} to be accepted"
211 );
212 }
213 }
214
215 #[test]
216 fn normalises_case_and_whitespace() {
217 let name = OrgName::new(" JamesGill ").expect("should be valid");
218
219 assert_eq!(name.as_str(), "jamesgill");
220 }
221
222 #[test]
223 fn rejects_malformed_handles() {
224 for input in [
225 "",
226 " ",
227 "-leading",
228 "trailing-",
229 "has space",
230 "under_score",
231 "dot.dot",
232 "slash/slash",
233 "emoji🦀",
234 &"a".repeat(40),
235 ] {
236 assert!(
237 OrgName::new(input).is_err(),
238 "expected {input:?} to be rejected"
239 );
240 }
241 }
242
243 #[test]
244 fn accepts_a_handle_at_the_length_limit() {
245 assert!(OrgName::new("a".repeat(OrgName::MAX_LEN)).is_ok());
246 }
247
248 #[test]
249 fn rejects_reserved_handles() {
250 for reserved in RESERVED {
251 assert!(
252 OrgName::new(*reserved).is_err(),
253 "expected {reserved:?} to be reserved"
254 );
255 }
256 }
257
258 #[test]
259 fn reservation_ignores_case() {
260 // Handles normalise to lowercase, so a differently-cased reserved word is the
261 // same handle and must be refused too.
262 assert!(OrgName::new("API").is_err());
263 assert!(OrgName::new("Auth").is_err());
264 }
265
266 #[test]
267 fn reservation_does_not_leak_into_substrings() {
268 // Only whole handles are reserved. `apidocs` shadows nothing.
269 for allowed in [
270 "apidocs",
271 "authors",
272 "administrator",
273 "helpful",
274 "settings-app",
275 ] {
276 assert!(
277 OrgName::new(allowed).is_ok(),
278 "expected {allowed:?} to be allowed"
279 );
280 }
281 }
282
283 #[test]
284 fn the_reserved_list_is_sorted_and_unique() {
285 // Sorted so additions are easy to review; unique so a duplicate doesn't hide a
286 // typo'd entry that reserves nothing.
287 let mut sorted = RESERVED.to_vec();
288 sorted.sort_unstable();
289 sorted.dedup();
290
291 assert_eq!(
292 sorted.as_slice(),
293 RESERVED,
294 "keep RESERVED sorted and unique"
295 );
296 }
297
298 #[test]
299 fn reserved_entries_are_themselves_valid_handle_shapes() {
300 // A reserved word that could never be a handle anyway is dead weight and
301 // suggests a misunderstanding of what the list is for.
302 for reserved in RESERVED {
303 assert!(
304 !reserved.is_empty()
305 && reserved.len() <= OrgName::MAX_LEN
306 && reserved.chars().all(|c| c.is_ascii_lowercase())
307 && !reserved.starts_with('-')
308 && !reserved.ends_with('-'),
309 "{reserved:?} could never be a handle, so reserving it is pointless"
310 );
311 }
312 }
313
314 #[test]
315 fn label_falls_back_to_the_handle() {
316 let org = Organization::new(OrgId::generate(), "acme", None).expect("valid");
317
318 assert_eq!(org.label(), "acme");
319 }
320
321 #[test]
322 fn label_prefers_the_display_name() {
323 let org =
324 Organization::new(OrgId::generate(), "acme", Some("Acme".to_owned())).expect("valid");
325
326 assert_eq!(org.label(), "Acme");
327 }
328
329 #[test]
330 fn a_new_organisation_has_no_bio() {
331 let org = Organization::new(OrgId::generate(), "acme", None).expect("valid");
332
333 assert_eq!(org.bio, None);
334 }
335
336 #[test]
337 fn update_profile_sets_both_fields() {
338 let mut org = Organization::new(OrgId::generate(), "acme", None).expect("valid");
339
340 org.update_profile(
341 Some("Acme Inc".to_owned()),
342 Some("We make things.".to_owned()),
343 )
344 .expect("valid profile");
345
346 assert_eq!(org.label(), "Acme Inc");
347 assert_eq!(org.bio.as_deref(), Some("We make things."));
348 }
349
350 #[test]
351 fn update_profile_trims_and_clears_blank_input() {
352 let mut org = Organization::new(OrgId::generate(), "acme", None).expect("valid");
353 org.update_profile(Some("Acme".to_owned()), Some("Hello".to_owned()))
354 .expect("valid profile");
355
356 org.update_profile(Some(" ".to_owned()), Some(String::new()))
357 .expect("valid profile");
358
359 // Cleared and never-set are the same state, so the page renders one case.
360 assert_eq!(org.display_name, None);
361 assert_eq!(org.bio, None);
362 assert_eq!(org.label(), "acme");
363 }
364
365 #[test]
366 fn update_profile_trims_surrounding_whitespace() {
367 let mut org = Organization::new(OrgId::generate(), "acme", None).expect("valid");
368
369 org.update_profile(None, Some(" spaced ".to_owned()))
370 .expect("valid profile");
371
372 assert_eq!(org.bio.as_deref(), Some("spaced"));
373 }
374
375 #[test]
376 fn update_profile_accepts_a_bio_at_the_length_limit() {
377 let mut org = Organization::new(OrgId::generate(), "acme", None).expect("valid");
378
379 assert!(
380 org.update_profile(None, Some("a".repeat(Organization::MAX_BIO_LEN)))
381 .is_ok()
382 );
383 }
384
385 #[test]
386 fn update_profile_rejects_an_over_long_bio_and_changes_nothing() {
387 let mut org = Organization::new(OrgId::generate(), "acme", None).expect("valid");
388 org.update_profile(Some("Acme".to_owned()), Some("original".to_owned()))
389 .expect("valid profile");
390
391 let error = org
392 .update_profile(
393 Some("Changed".to_owned()),
394 Some("a".repeat(Organization::MAX_BIO_LEN + 1)),
395 )
396 .expect_err("should reject");
397
398 assert!(matches!(error, DomainError::Validation { .. }));
399 assert_eq!(
400 org.bio.as_deref(),
401 Some("original"),
402 "a rejected edit must not partially apply"
403 );
404 assert_eq!(org.label(), "Acme");
405 }
406
407 #[test]
408 fn bio_length_counts_characters_not_bytes() {
409 let mut org = Organization::new(OrgId::generate(), "acme", None).expect("valid");
410
411 // Multi-byte characters would trip a byte-length check well under the limit.
412 assert!(
413 org.update_profile(None, Some("é".repeat(Organization::MAX_BIO_LEN)))
414 .is_ok()
415 );
416 }
417
418 #[test]
419 fn blank_display_names_are_treated_as_unset() {
420 let org =
421 Organization::new(OrgId::generate(), "acme", Some(" ".to_owned())).expect("valid");
422
423 assert_eq!(org.display_name, None);
424 assert_eq!(org.label(), "acme");
425 }
426}