steid

@jamesgill /

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