steid

@jamesgill /

steid/src/domain/repo.rs
Rust24.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 /// Whether the repository's state refuses a write of `kind`, and why.
297 ///
298 /// **The one place a repository says it is closed for writing.** Before this
299 /// existed, `serve_git` checked `archived`, checked `importing` beside it, and
300 /// `rename_repo` and `set_repo_archived` had neither — so a rename could move the
301 /// directory `git clone --mirror` was still writing into. A new write path that
302 /// forgets to ask is still possible, but it no longer has to reproduce the reasons
303 /// to ask correctly.
304 ///
305 /// The refusal is a [`DomainError`] rather than a bool because the reason is the
306 /// useful part: [`Archived`](DomainError::Archived) is a state the person hitting it
307 /// can lift, and [`Unavailable`](DomainError::Unavailable) is one that lifts itself
308 /// in a minute. A caller that turned both into "not permitted" would send someone
309 /// looking for a permissions problem that is not there.
310 ///
311 /// Archived is checked first, so a repository that is somehow both — impossible to
312 /// reach now that archiving is itself refused during an import, but reachable in a
313 /// row written before that — reports the durable reason rather than the transient
314 /// one.
315 pub fn refuse_writes(&self, kind: RepoWrite) -> Result<(), DomainError> {
316 if kind == RepoWrite::Contents && self.archived {
317 return Err(DomainError::Archived);
318 }
319
320 if self.is_importing() {
321 return Err(DomainError::Unavailable {
322 entity: "repository",
323 reason: IMPORT_IN_PROGRESS.to_owned(),
324 });
325 }
326
327 Ok(())
328 }
329}
330
331/// The sentence every refusal during an import carries.
332///
333/// One string because it reaches a `git push`'s terminal, a settings page and a future
334/// `/api` response, and three spellings of the same fact read as three different rules.
335const IMPORT_IN_PROGRESS: &str =
336 "it is still being imported. Wait for the import to finish, or delete it and start again.";
337
338/// What a write touches, which decides which of a repository's states refuse it.
339///
340/// The distinction is not decoration: an **archived** repository accepts no contents and
341/// yet must stay renameable — it is finished, not frozen, and its owner is the one person
342/// who might tidy the name. So archiving cannot be a blanket write refusal.
343#[derive(Debug, Clone, Copy, PartialEq, Eq)]
344pub enum RepoWrite {
345 /// git objects and refs: a push today, a merge or a web edit later.
346 Contents,
347 /// The repository's name or its archived flag.
348 ///
349 /// Refused during an import because both fight it: a rename moves the directory
350 /// `git clone --mirror` is writing into, and archiving declares finished something
351 /// that has not arrived. **Delete is deliberately absent** — deleting is how a stuck
352 /// import is cleaned up, and the failed panel says so.
353 Settings,
354}
355
356/// Trims, and treats blank as absent.
357fn normalise_optional(value: Option<String>) -> Option<String> {
358 value
359 .map(|value| value.trim().to_owned())
360 .filter(|value| !value.is_empty())
361}
362
363#[cfg(test)]
364mod tests {
365 use super::*;
366
367 #[test]
368 fn accepts_ordinary_repository_names() {
369 for input in [
370 "steid",
371 "my-repo",
372 "my_repo",
373 "foo.js",
374 ".github",
375 "v2",
376 "a",
377 "dot.separated.name",
378 "trailing.",
379 ] {
380 assert!(
381 RepoName::new(input).is_ok(),
382 "expected {input:?} to be accepted"
383 );
384 }
385 }
386
387 #[test]
388 fn normalises_case_and_whitespace() {
389 let name = RepoName::new(" MyRepo ").expect("should be valid");
390
391 assert_eq!(name.as_str(), "myrepo");
392 }
393
394 /// The security boundary. Each of these, if allowed through, becomes a path segment
395 /// that can leave `{data_dir}/{handle}/`.
396 #[test]
397 fn rejects_anything_that_could_escape_the_data_directory() {
398 for input in [
399 ".",
400 "..",
401 "...",
402 "../etc",
403 "..%2F..%2Fetc",
404 "foo/bar",
405 "foo\\bar",
406 "/absolute",
407 "~root",
408 "with space",
409 "new\nline",
410 "nul\0byte",
411 ] {
412 assert!(
413 RepoName::new(input).is_err(),
414 "expected {input:?} to be rejected: it could escape the data directory"
415 );
416 }
417 }
418
419 #[test]
420 fn rejects_malformed_names() {
421 for input in [
422 "",
423 " ",
424 "-leading",
425 "trailing-",
426 "emoji🦀",
427 &"a".repeat(101),
428 ] {
429 assert!(
430 RepoName::new(input).is_err(),
431 "expected {input:?} to be rejected"
432 );
433 }
434 }
435
436 #[test]
437 fn rejects_names_ending_in_dot_git() {
438 // Would live at `foo.git.git` on disk and make clone URLs ambiguous.
439 assert!(RepoName::new("foo.git").is_err());
440 assert!(RepoName::new("FOO.GIT").is_err());
441 // But `.git` inside the name is harmless.
442 assert!(RepoName::new("foo.github").is_ok());
443 }
444
445 #[test]
446 fn rejects_reserved_names() {
447 for reserved in RESERVED {
448 assert!(
449 RepoName::new(*reserved).is_err(),
450 "expected {reserved:?} to be reserved"
451 );
452 }
453 // Case-insensitively, since names normalise to lowercase.
454 assert!(RepoName::new("NEW").is_err());
455 }
456
457 #[test]
458 fn reservation_does_not_leak_into_substrings() {
459 for allowed in ["newton", "renew", "imports", "research"] {
460 assert!(
461 RepoName::new(allowed).is_ok(),
462 "expected {allowed:?} to be allowed"
463 );
464 }
465 }
466
467 #[test]
468 fn the_reserved_list_is_sorted_and_unique() {
469 let mut sorted = RESERVED.to_vec();
470 sorted.sort_unstable();
471 sorted.dedup();
472
473 assert_eq!(
474 sorted.as_slice(),
475 RESERVED,
476 "keep RESERVED sorted and unique"
477 );
478 }
479
480 #[test]
481 fn accepts_a_name_at_the_length_limit() {
482 assert!(RepoName::new("a".repeat(RepoName::MAX_LEN)).is_ok());
483 }
484
485 #[test]
486 fn repositories_default_to_public() {
487 assert_eq!(Visibility::default(), Visibility::Public);
488 assert!(Visibility::default().is_public());
489 }
490
491 #[test]
492 fn visibility_round_trips_through_strings() {
493 for visibility in [Visibility::Public, Visibility::Private] {
494 assert_eq!(
495 visibility
496 .as_str()
497 .parse::<Visibility>()
498 .expect("round trip"),
499 visibility
500 );
501 }
502 }
503
504 #[test]
505 fn unknown_visibility_is_an_error_not_a_default() {
506 // Defaulting here would publish a private repository.
507 assert!("internal".parse::<Visibility>().is_err());
508 assert!("Public".parse::<Visibility>().is_err());
509 }
510
511 fn repo(description: Option<&str>) -> Result<Repository, DomainError> {
512 Repository::new(
513 RepoId::generate(),
514 OrgId::generate(),
515 "steid",
516 description.map(str::to_owned),
517 Visibility::Public,
518 at(1_000),
519 )
520 }
521
522 fn at(seconds: u64) -> SystemTime {
523 SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(seconds)
524 }
525
526 #[test]
527 fn a_new_repository_is_stamped_with_the_time_it_was_created() {
528 let repo = Repository::new(
529 RepoId::generate(),
530 OrgId::generate(),
531 "steid",
532 None,
533 Visibility::Public,
534 at(1_700),
535 )
536 .expect("valid");
537
538 assert_eq!(repo.updated_at, at(1_700));
539 }
540
541 #[test]
542 fn a_new_repository_is_not_an_import() {
543 // Importing is attached afterwards, the way pinning is. A repository that
544 // defaulted to `Importing` would render every ordinary create as a spinner.
545 let repo = repo(None).expect("valid");
546
547 assert_eq!(repo.import_state, None);
548 assert_eq!(repo.import_source, None);
549 assert!(!repo.is_importing());
550 }
551
552 #[test]
553 fn an_import_runs_then_clears() {
554 let mut repo = repo(None).expect("valid");
555 let source = ImportSource::new("https://example.com/thing.git").expect("valid source");
556
557 repo.start_import(source.clone());
558 assert_eq!(repo.import_state, Some(ImportState::Importing));
559 assert!(repo.is_importing());
560
561 repo.finish_import();
562 assert_eq!(repo.import_state, None);
563 assert!(!repo.is_importing());
564 // Provenance survives: where it came from is still true afterwards.
565 assert_eq!(repo.import_source, Some(source));
566 }
567
568 #[test]
569 fn a_failed_import_keeps_its_source_and_its_reason() {
570 let mut repo = repo(None).expect("valid");
571 repo.start_import(ImportSource::new("https://example.com/thing.git").expect("valid"));
572 repo.fail_import("the remote hung up");
573
574 assert_eq!(repo.import_state, Some(ImportState::Failed));
575 assert_eq!(repo.import_error.as_deref(), Some("the remote hung up"));
576 // A retry needs the source, so failing must not throw it away.
577 assert!(repo.import_source.is_some());
578 }
579
580 #[test]
581 fn restarting_an_import_clears_the_previous_reason() {
582 let mut repo = repo(None).expect("valid");
583 repo.start_import(ImportSource::new("https://example.com/a.git").expect("valid"));
584 repo.fail_import("the remote hung up");
585 repo.start_import(ImportSource::new("https://example.com/b.git").expect("valid"));
586
587 assert_eq!(repo.import_error, None);
588 }
589
590 #[test]
591 fn a_new_repository_is_not_pinned() {
592 // Pinning is a later, deliberate choice; creating a repository is not a claim
593 // that it should lead the profile.
594 assert!(!repo(None).expect("valid").pinned);
595 }
596
597 #[test]
598 fn a_new_repository_is_not_archived() {
599 // Nothing is created already finished.
600 assert!(!repo(None).expect("valid").archived);
601 }
602
603 #[test]
604 fn a_repository_keeps_its_description() {
605 let repo = repo(Some("A personal-first gitforge.")).expect("valid");
606
607 assert_eq!(
608 repo.description.as_deref(),
609 Some("A personal-first gitforge.")
610 );
611 }
612
613 #[test]
614 fn a_blank_description_is_treated_as_unset() {
615 assert_eq!(repo(Some(" ")).expect("valid").description, None);
616 }
617
618 #[test]
619 fn rejects_an_over_long_description() {
620 let long = "a".repeat(Repository::MAX_DESCRIPTION_LEN + 1);
621
622 let error = repo(Some(&long)).expect_err("should reject");
623
624 assert!(matches!(error, DomainError::Validation { .. }));
625 }
626
627 #[test]
628 fn description_length_counts_characters_not_bytes() {
629 let accented = "é".repeat(Repository::MAX_DESCRIPTION_LEN);
630
631 assert!(repo(Some(&accented)).is_ok());
632 }
633
634 #[test]
635 fn an_invalid_name_rejects_the_whole_repository() {
636 let error = Repository::new(
637 RepoId::generate(),
638 OrgId::generate(),
639 "../escape",
640 None,
641 Visibility::Public,
642 at(1_000),
643 )
644 .expect_err("should reject");
645
646 assert!(matches!(error, DomainError::Validation { .. }));
647 }
648 // --- the write guard -------------------------------------------------------------
649
650 #[test]
651 fn an_ordinary_repository_refuses_nothing() {
652 let repo = repo(None).expect("valid");
653
654 assert!(repo.refuse_writes(RepoWrite::Contents).is_ok());
655 assert!(repo.refuse_writes(RepoWrite::Settings).is_ok());
656 }
657
658 #[test]
659 fn an_archived_repository_refuses_contents_and_still_allows_settings() {
660 // Archived says "finished", not "frozen": the owner may still rename it or
661 // unarchive it, and unarchiving would be unreachable if archived refused every
662 // write.
663 let mut repo = repo(None).expect("valid");
664 repo.archived = true;
665
666 assert!(matches!(
667 repo.refuse_writes(RepoWrite::Contents),
668 Err(DomainError::Archived)
669 ));
670 assert!(repo.refuse_writes(RepoWrite::Settings).is_ok());
671 }
672
673 #[test]
674 fn an_importing_repository_refuses_both() {
675 // A rename moves the directory the clone is writing into, and archiving declares
676 // finished something that has not arrived.
677 let mut repo = repo(None).expect("valid");
678 repo.start_import(ImportSource::new("https://example.com/a/b.git").expect("valid"));
679
680 for kind in [RepoWrite::Contents, RepoWrite::Settings] {
681 assert!(
682 matches!(
683 repo.refuse_writes(kind),
684 Err(DomainError::Unavailable {
685 entity: "repository",
686 ..
687 })
688 ),
689 "{kind:?} should be refused while importing"
690 );
691 }
692 }
693
694 #[test]
695 fn a_failed_import_still_refuses_writes() {
696 // The state is not `None`, so there is no usable directory yet — the answer is
697 // the same as while it was running, and the way out is Delete.
698 let mut repo = repo(None).expect("valid");
699 repo.start_import(ImportSource::new("https://example.com/a/b.git").expect("valid"));
700 repo.fail_import("could not read from remote");
701
702 assert!(repo.refuse_writes(RepoWrite::Contents).is_err());
703 assert!(repo.refuse_writes(RepoWrite::Settings).is_err());
704 }
705
706 #[test]
707 fn a_finished_import_refuses_nothing() {
708 let mut repo = repo(None).expect("valid");
709 repo.start_import(ImportSource::new("https://example.com/a/b.git").expect("valid"));
710 repo.finish_import();
711
712 assert!(repo.refuse_writes(RepoWrite::Contents).is_ok());
713 assert!(repo.refuse_writes(RepoWrite::Settings).is_ok());
714 }
715
716 #[test]
717 fn an_archived_repository_that_is_also_importing_reports_being_archived() {
718 // Unreachable through the use cases now that archiving is refused during an
719 // import, but reachable in a row written before that: the durable reason is the
720 // more useful one to state.
721 let mut repo = repo(None).expect("valid");
722 repo.archived = true;
723 repo.start_import(ImportSource::new("https://example.com/a/b.git").expect("valid"));
724
725 assert!(matches!(
726 repo.refuse_writes(RepoWrite::Contents),
727 Err(DomainError::Archived)
728 ));
729 }
730}