steid

@jamesgill /

steid/src/domain/repo.rs
Rust18.6 KBCode·Blame·History·Raw
1use std::{fmt, str::FromStr, time::SystemTime};
2
3use super::{DomainError, ImportSource, ImportState, OrgId, RepoId};
4
5/// Repository names that would collide with a route under `/{handle}/repos/`.
6///
7/// Only names directly under `repos/` can collide — `/{handle}/repos/{name}/settings`
8/// is deeper and safe. Reserve before the first repo exists; afterwards it is a
9/// breaking change for whoever holds the name.
10const RESERVED: &[&str] = &["import", "new", "search"];
11
12/// A repository name — the `{name}` in `/{handle}/repos/{name}`, and a path segment on
13/// disk at `{data_dir}/{handle}/{name}.git`.
14///
15/// **This value becomes a filesystem path**, so the rules below are a security boundary
16/// rather than a matter of taste. Anything that could escape the data directory has to
17/// be impossible here, in one place, rather than sanitised at each call site.
18///
19/// Follows [`OrgName`](super::OrgName) and additionally allows `.` and `_`, which
20/// repository names conventionally use (`.github`, `foo.js`, `my_repo`). Lowercased for
21/// the same reason handles are: so lookups, URLs, and directories all agree.
22#[derive(Debug, Clone, PartialEq, Eq, Hash)]
23pub struct RepoName(String);
24
25impl RepoName {
26 pub const MAX_LEN: usize = 100;
27
28 /// Validates and normalises user-supplied input.
29 pub fn new(value: impl Into<String>) -> Result<Self, DomainError> {
30 let value = value.into();
31 let trimmed = value.trim();
32
33 let invalid = |reason: &str| DomainError::validation("repository name", reason);
34
35 if trimmed.is_empty() {
36 return Err(invalid("must not be empty"));
37 }
38 if trimmed.chars().count() > Self::MAX_LEN {
39 return Err(invalid("must be at most 100 characters"));
40 }
41 if !trimmed
42 .chars()
43 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
44 {
45 return Err(invalid(
46 "may only contain letters, digits, hyphens, underscores, and dots",
47 ));
48 }
49 if trimmed.starts_with('-') || trimmed.ends_with('-') {
50 return Err(invalid("must not start or end with a hyphen"));
51 }
52
53 // `.` and `..` are directory references; a name of nothing but dots has no
54 // meaning as a repository and every meaning as a path. The character rule above
55 // already excludes `/`, so this closes the remaining traversal shape.
56 if trimmed.chars().all(|c| c == '.') {
57 return Err(invalid("must not consist only of dots"));
58 }
59
60 let normalised = trimmed.to_lowercase();
61
62 // A repo named `foo.git` would live at `foo.git.git` and make clone URLs
63 // ambiguous.
64 if normalised.ends_with(".git") {
65 return Err(invalid("must not end with .git"));
66 }
67 if RESERVED.contains(&normalised.as_str()) {
68 return Err(invalid("is reserved"));
69 }
70
71 Ok(Self(normalised))
72 }
73
74 /// Wraps a value already validated on the way into the database.
75 pub fn from_trusted(value: impl Into<String>) -> Self {
76 Self(value.into())
77 }
78
79 pub fn as_str(&self) -> &str {
80 &self.0
81 }
82}
83
84impl fmt::Display for RepoName {
85 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86 f.write_str(&self.0)
87 }
88}
89
90/// Who may see a repository.
91#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
92pub enum Visibility {
93 /// Anyone, signed in or not.
94 ///
95 /// The default: Steid is portfolio-first, so the ordinary case is showing your work.
96 #[default]
97 Public,
98 /// Members of the owning organisation only.
99 Private,
100}
101
102impl Visibility {
103 pub fn as_str(self) -> &'static str {
104 match self {
105 Self::Public => "public",
106 Self::Private => "private",
107 }
108 }
109
110 pub fn is_public(self) -> bool {
111 self == Self::Public
112 }
113}
114
115impl fmt::Display for Visibility {
116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 f.write_str(self.as_str())
118 }
119}
120
121/// Parsing returns `Result`, never `Option`. A silently-defaulted visibility would
122/// publish a private repository.
123impl FromStr for Visibility {
124 type Err = DomainError;
125
126 fn from_str(value: &str) -> Result<Self, Self::Err> {
127 match value {
128 "public" => Ok(Self::Public),
129 "private" => Ok(Self::Private),
130 other => Err(DomainError::validation(
131 "visibility",
132 format!("unknown visibility {other:?}"),
133 )),
134 }
135 }
136}
137
138/// A repository. Owned by an organisation, never directly by a user.
139#[derive(Debug, Clone, PartialEq, Eq)]
140pub struct Repository {
141 pub id: RepoId,
142 pub org_id: OrgId,
143 pub name: RepoName,
144 pub description: Option<String>,
145 pub visibility: Visibility,
146 /// When code last landed here — set at creation and moved when a push is
147 /// authorized. The profile orders by it, so it means "recently worked on", not
148 /// "row last written": editing a description does not move it.
149 pub updated_at: SystemTime,
150 /// Whether this is the one repository the owner leads their profile with.
151 ///
152 /// At most one per owner. Not a constructor argument: a repository becomes the lead
153 /// by a later, deliberate choice, never by being created.
154 pub pinned: bool,
155 /// Whether this repository is finished: still readable, no longer writable.
156 ///
157 /// Orthogonal to [`visibility`](Self::visibility) — archiving says "this is done",
158 /// not "this is hidden" — and, like [`pinned`](Self::pinned), never a constructor
159 /// argument: nothing is created already finished.
160 pub archived: bool,
161 /// How far an import has got, or `None` for an ordinary repository.
162 ///
163 /// `None` is the overwhelming case and the one every other feature assumes, which
164 /// is why it is the absence of a value rather than a `Ready` variant: a page that
165 /// forgets to think about importing gets the behaviour it already had.
166 ///
167 /// Not a constructor argument, for the same reason [`pinned`](Self::pinned) is not
168 /// — a repository is created, and *then* an import is attached to it.
169 pub import_state: Option<ImportState>,
170 /// Where the import is copying from. Set whenever [`import_state`](Self::import_state)
171 /// is, and kept afterwards: a repository that came from somewhere else stays a
172 /// repository that came from somewhere else.
173 pub import_source: Option<ImportSource>,
174 /// Why the import failed, in words a person can act on. Only ever set alongside
175 /// [`ImportState::Failed`].
176 pub import_error: Option<String>,
177}
178
179impl Repository {
180 /// Longest permitted description. A sentence, not a README.
181 pub const MAX_DESCRIPTION_LEN: usize = 300;
182
183 /// Creates a repository from user-supplied input.
184 ///
185 /// `now` is passed in rather than read here, following
186 /// [`PersonalAccessToken::new`](super::PersonalAccessToken::new): a domain type that
187 /// reads the clock cannot be tested against a fixed time.
188 pub fn new(
189 id: RepoId,
190 org_id: OrgId,
191 name: impl Into<String>,
192 description: Option<String>,
193 visibility: Visibility,
194 now: SystemTime,
195 ) -> Result<Self, DomainError> {
196 let description = normalise_optional(description);
197
198 if let Some(description) = &description
199 && description.chars().count() > Self::MAX_DESCRIPTION_LEN
200 {
201 return Err(DomainError::validation(
202 "description",
203 format!("must be at most {} characters", Self::MAX_DESCRIPTION_LEN),
204 ));
205 }
206
207 Ok(Self {
208 id,
209 org_id,
210 name: RepoName::new(name)?,
211 description,
212 visibility,
213 updated_at: now,
214 pinned: false,
215 archived: false,
216 import_state: None,
217 import_source: None,
218 import_error: None,
219 })
220 }
221
222 /// Reassembles a repository from storage, skipping validation.
223 #[allow(clippy::too_many_arguments)]
224 pub fn from_trusted(
225 id: RepoId,
226 org_id: OrgId,
227 name: RepoName,
228 description: Option<String>,
229 visibility: Visibility,
230 updated_at: SystemTime,
231 pinned: bool,
232 archived: bool,
233 ) -> Self {
234 Self {
235 id,
236 org_id,
237 name,
238 description,
239 visibility,
240 updated_at,
241 pinned,
242 archived,
243 import_state: None,
244 import_source: None,
245 import_error: None,
246 }
247 }
248
249 /// Attaches import state to a repository reassembled from storage.
250 ///
251 /// A separate builder rather than three more arguments to
252 /// [`from_trusted`](Self::from_trusted), which is already at the limit of what an
253 /// argument list can say without naming its values.
254 #[must_use]
255 pub fn with_import(
256 mut self,
257 state: Option<ImportState>,
258 source: Option<ImportSource>,
259 error: Option<String>,
260 ) -> Self {
261 self.import_state = state;
262 self.import_source = source;
263 self.import_error = error;
264 self
265 }
266
267 /// Marks a repository as being mirrored from `source`.
268 ///
269 /// The error is cleared as well as the state set, so a retry does not carry the
270 /// previous attempt's message on the page while it runs.
271 pub fn start_import(&mut self, source: ImportSource) {
272 self.import_state = Some(ImportState::Importing);
273 self.import_source = Some(source);
274 self.import_error = None;
275 }
276
277 /// Records that the mirror failed. The source is kept — it is what a retry needs.
278 pub fn fail_import(&mut self, reason: impl Into<String>) {
279 self.import_state = Some(ImportState::Failed);
280 self.import_error = Some(reason.into());
281 }
282
283 /// Records that the mirror finished. The repository becomes an ordinary one; only
284 /// [`import_source`](Self::import_source) remains, as provenance.
285 pub fn finish_import(&mut self) {
286 self.import_state = None;
287 self.import_error = None;
288 }
289
290 /// Whether the repository has no usable contents yet, or never will from this
291 /// attempt. Both states mean "do not read this with git".
292 pub fn is_importing(&self) -> bool {
293 self.import_state.is_some()
294 }
295}
296
297/// Trims, and treats blank as absent.
298fn normalise_optional(value: Option<String>) -> Option<String> {
299 value
300 .map(|value| value.trim().to_owned())
301 .filter(|value| !value.is_empty())
302}
303
304#[cfg(test)]
305mod tests {
306 use super::*;
307
308 #[test]
309 fn accepts_ordinary_repository_names() {
310 for input in [
311 "steid",
312 "my-repo",
313 "my_repo",
314 "foo.js",
315 ".github",
316 "v2",
317 "a",
318 "dot.separated.name",
319 "trailing.",
320 ] {
321 assert!(
322 RepoName::new(input).is_ok(),
323 "expected {input:?} to be accepted"
324 );
325 }
326 }
327
328 #[test]
329 fn normalises_case_and_whitespace() {
330 let name = RepoName::new(" MyRepo ").expect("should be valid");
331
332 assert_eq!(name.as_str(), "myrepo");
333 }
334
335 /// The security boundary. Each of these, if allowed through, becomes a path segment
336 /// that can leave `{data_dir}/{handle}/`.
337 #[test]
338 fn rejects_anything_that_could_escape_the_data_directory() {
339 for input in [
340 ".",
341 "..",
342 "...",
343 "../etc",
344 "..%2F..%2Fetc",
345 "foo/bar",
346 "foo\\bar",
347 "/absolute",
348 "~root",
349 "with space",
350 "new\nline",
351 "nul\0byte",
352 ] {
353 assert!(
354 RepoName::new(input).is_err(),
355 "expected {input:?} to be rejected: it could escape the data directory"
356 );
357 }
358 }
359
360 #[test]
361 fn rejects_malformed_names() {
362 for input in [
363 "",
364 " ",
365 "-leading",
366 "trailing-",
367 "emoji🦀",
368 &"a".repeat(101),
369 ] {
370 assert!(
371 RepoName::new(input).is_err(),
372 "expected {input:?} to be rejected"
373 );
374 }
375 }
376
377 #[test]
378 fn rejects_names_ending_in_dot_git() {
379 // Would live at `foo.git.git` on disk and make clone URLs ambiguous.
380 assert!(RepoName::new("foo.git").is_err());
381 assert!(RepoName::new("FOO.GIT").is_err());
382 // But `.git` inside the name is harmless.
383 assert!(RepoName::new("foo.github").is_ok());
384 }
385
386 #[test]
387 fn rejects_reserved_names() {
388 for reserved in RESERVED {
389 assert!(
390 RepoName::new(*reserved).is_err(),
391 "expected {reserved:?} to be reserved"
392 );
393 }
394 // Case-insensitively, since names normalise to lowercase.
395 assert!(RepoName::new("NEW").is_err());
396 }
397
398 #[test]
399 fn reservation_does_not_leak_into_substrings() {
400 for allowed in ["newton", "renew", "imports", "research"] {
401 assert!(
402 RepoName::new(allowed).is_ok(),
403 "expected {allowed:?} to be allowed"
404 );
405 }
406 }
407
408 #[test]
409 fn the_reserved_list_is_sorted_and_unique() {
410 let mut sorted = RESERVED.to_vec();
411 sorted.sort_unstable();
412 sorted.dedup();
413
414 assert_eq!(
415 sorted.as_slice(),
416 RESERVED,
417 "keep RESERVED sorted and unique"
418 );
419 }
420
421 #[test]
422 fn accepts_a_name_at_the_length_limit() {
423 assert!(RepoName::new("a".repeat(RepoName::MAX_LEN)).is_ok());
424 }
425
426 #[test]
427 fn repositories_default_to_public() {
428 assert_eq!(Visibility::default(), Visibility::Public);
429 assert!(Visibility::default().is_public());
430 }
431
432 #[test]
433 fn visibility_round_trips_through_strings() {
434 for visibility in [Visibility::Public, Visibility::Private] {
435 assert_eq!(
436 visibility
437 .as_str()
438 .parse::<Visibility>()
439 .expect("round trip"),
440 visibility
441 );
442 }
443 }
444
445 #[test]
446 fn unknown_visibility_is_an_error_not_a_default() {
447 // Defaulting here would publish a private repository.
448 assert!("internal".parse::<Visibility>().is_err());
449 assert!("Public".parse::<Visibility>().is_err());
450 }
451
452 fn repo(description: Option<&str>) -> Result<Repository, DomainError> {
453 Repository::new(
454 RepoId::generate(),
455 OrgId::generate(),
456 "steid",
457 description.map(str::to_owned),
458 Visibility::Public,
459 at(1_000),
460 )
461 }
462
463 fn at(seconds: u64) -> SystemTime {
464 SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(seconds)
465 }
466
467 #[test]
468 fn a_new_repository_is_stamped_with_the_time_it_was_created() {
469 let repo = Repository::new(
470 RepoId::generate(),
471 OrgId::generate(),
472 "steid",
473 None,
474 Visibility::Public,
475 at(1_700),
476 )
477 .expect("valid");
478
479 assert_eq!(repo.updated_at, at(1_700));
480 }
481
482 #[test]
483 fn a_new_repository_is_not_an_import() {
484 // Importing is attached afterwards, the way pinning is. A repository that
485 // defaulted to `Importing` would render every ordinary create as a spinner.
486 let repo = repo(None).expect("valid");
487
488 assert_eq!(repo.import_state, None);
489 assert_eq!(repo.import_source, None);
490 assert!(!repo.is_importing());
491 }
492
493 #[test]
494 fn an_import_runs_then_clears() {
495 let mut repo = repo(None).expect("valid");
496 let source = ImportSource::new("https://example.com/thing.git").expect("valid source");
497
498 repo.start_import(source.clone());
499 assert_eq!(repo.import_state, Some(ImportState::Importing));
500 assert!(repo.is_importing());
501
502 repo.finish_import();
503 assert_eq!(repo.import_state, None);
504 assert!(!repo.is_importing());
505 // Provenance survives: where it came from is still true afterwards.
506 assert_eq!(repo.import_source, Some(source));
507 }
508
509 #[test]
510 fn a_failed_import_keeps_its_source_and_its_reason() {
511 let mut repo = repo(None).expect("valid");
512 repo.start_import(ImportSource::new("https://example.com/thing.git").expect("valid"));
513 repo.fail_import("the remote hung up");
514
515 assert_eq!(repo.import_state, Some(ImportState::Failed));
516 assert_eq!(repo.import_error.as_deref(), Some("the remote hung up"));
517 // A retry needs the source, so failing must not throw it away.
518 assert!(repo.import_source.is_some());
519 }
520
521 #[test]
522 fn restarting_an_import_clears_the_previous_reason() {
523 let mut repo = repo(None).expect("valid");
524 repo.start_import(ImportSource::new("https://example.com/a.git").expect("valid"));
525 repo.fail_import("the remote hung up");
526 repo.start_import(ImportSource::new("https://example.com/b.git").expect("valid"));
527
528 assert_eq!(repo.import_error, None);
529 }
530
531 #[test]
532 fn a_new_repository_is_not_pinned() {
533 // Pinning is a later, deliberate choice; creating a repository is not a claim
534 // that it should lead the profile.
535 assert!(!repo(None).expect("valid").pinned);
536 }
537
538 #[test]
539 fn a_new_repository_is_not_archived() {
540 // Nothing is created already finished.
541 assert!(!repo(None).expect("valid").archived);
542 }
543
544 #[test]
545 fn a_repository_keeps_its_description() {
546 let repo = repo(Some("A personal-first gitforge.")).expect("valid");
547
548 assert_eq!(
549 repo.description.as_deref(),
550 Some("A personal-first gitforge.")
551 );
552 }
553
554 #[test]
555 fn a_blank_description_is_treated_as_unset() {
556 assert_eq!(repo(Some(" ")).expect("valid").description, None);
557 }
558
559 #[test]
560 fn rejects_an_over_long_description() {
561 let long = "a".repeat(Repository::MAX_DESCRIPTION_LEN + 1);
562
563 let error = repo(Some(&long)).expect_err("should reject");
564
565 assert!(matches!(error, DomainError::Validation { .. }));
566 }
567
568 #[test]
569 fn description_length_counts_characters_not_bytes() {
570 let accented = "é".repeat(Repository::MAX_DESCRIPTION_LEN);
571
572 assert!(repo(Some(&accented)).is_ok());
573 }
574
575 #[test]
576 fn an_invalid_name_rejects_the_whole_repository() {
577 let error = Repository::new(
578 RepoId::generate(),
579 OrgId::generate(),
580 "../escape",
581 None,
582 Visibility::Public,
583 at(1_000),
584 )
585 .expect_err("should reject");
586
587 assert!(matches!(error, DomainError::Validation { .. }));
588 }
589}