steid

@jamesgill /

steid/src/domain/repo.rs
Rust25.1 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 Public,
95 /// Members of the owning organisation only.
96 ///
97 /// **The default, since 0.8.0.** A repository nobody chose for is private, because
98 /// the recoverable mistake is publishing something later and the unrecoverable one
99 /// is publishing it by accident —
100 /// [0010](../../plans/decisions/0010-single-tenant-vcs-not-portfolio.md) committed
101 /// to this and it is the whole of the change: existing repositories keep whatever
102 /// they were set to.
103 #[default]
104 Private,
105}
106
107impl Visibility {
108 pub fn as_str(self) -> &'static str {
109 match self {
110 Self::Public => "public",
111 Self::Private => "private",
112 }
113 }
114
115 pub fn is_public(self) -> bool {
116 self == Self::Public
117 }
118}
119
120impl fmt::Display for Visibility {
121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 f.write_str(self.as_str())
123 }
124}
125
126/// Parsing returns `Result`, never `Option`. A silently-defaulted visibility would
127/// publish a private repository.
128impl FromStr for Visibility {
129 type Err = DomainError;
130
131 fn from_str(value: &str) -> Result<Self, Self::Err> {
132 match value {
133 "public" => Ok(Self::Public),
134 "private" => Ok(Self::Private),
135 other => Err(DomainError::validation(
136 "visibility",
137 format!("unknown visibility {other:?}"),
138 )),
139 }
140 }
141}
142
143/// A repository. Owned by an organisation, never directly by a user.
144#[derive(Debug, Clone, PartialEq, Eq)]
145pub struct Repository {
146 pub id: RepoId,
147 pub org_id: OrgId,
148 pub name: RepoName,
149 pub description: Option<String>,
150 pub visibility: Visibility,
151 /// When code last landed here — set at creation and moved when a push is
152 /// authorized. The profile orders by it, so it means "recently worked on", not
153 /// "row last written": editing a description does not move it.
154 pub updated_at: SystemTime,
155 /// Whether this is the one repository the owner leads their profile with.
156 ///
157 /// At most one per owner. Not a constructor argument: a repository becomes the lead
158 /// by a later, deliberate choice, never by being created.
159 pub pinned: bool,
160 /// Whether this repository is finished: still readable, no longer writable.
161 ///
162 /// Orthogonal to [`visibility`](Self::visibility) — archiving says "this is done",
163 /// not "this is hidden" — and, like [`pinned`](Self::pinned), never a constructor
164 /// argument: nothing is created already finished.
165 pub archived: bool,
166 /// How far an import has got, or `None` for an ordinary repository.
167 ///
168 /// `None` is the overwhelming case and the one every other feature assumes, which
169 /// is why it is the absence of a value rather than a `Ready` variant: a page that
170 /// forgets to think about importing gets the behaviour it already had.
171 ///
172 /// Not a constructor argument, for the same reason [`pinned`](Self::pinned) is not
173 /// — a repository is created, and *then* an import is attached to it.
174 pub import_state: Option<ImportState>,
175 /// Where the import is copying from. Set whenever [`import_state`](Self::import_state)
176 /// is, and kept afterwards: a repository that came from somewhere else stays a
177 /// repository that came from somewhere else.
178 pub import_source: Option<ImportSource>,
179 /// Why the import failed, in words a person can act on. Only ever set alongside
180 /// [`ImportState::Failed`].
181 pub import_error: Option<String>,
182}
183
184impl Repository {
185 /// Longest permitted description. A sentence, not a README.
186 pub const MAX_DESCRIPTION_LEN: usize = 300;
187
188 /// Creates a repository from user-supplied input.
189 ///
190 /// `now` is passed in rather than read here, following
191 /// [`PersonalAccessToken::new`](super::PersonalAccessToken::new): a domain type that
192 /// reads the clock cannot be tested against a fixed time.
193 pub fn new(
194 id: RepoId,
195 org_id: OrgId,
196 name: impl Into<String>,
197 description: Option<String>,
198 visibility: Visibility,
199 now: SystemTime,
200 ) -> Result<Self, DomainError> {
201 let description = normalise_optional(description);
202
203 if let Some(description) = &description
204 && description.chars().count() > Self::MAX_DESCRIPTION_LEN
205 {
206 return Err(DomainError::validation(
207 "description",
208 format!("must be at most {} characters", Self::MAX_DESCRIPTION_LEN),
209 ));
210 }
211
212 Ok(Self {
213 id,
214 org_id,
215 name: RepoName::new(name)?,
216 description,
217 visibility,
218 updated_at: now,
219 pinned: false,
220 archived: false,
221 import_state: None,
222 import_source: None,
223 import_error: None,
224 })
225 }
226
227 /// Reassembles a repository from storage, skipping validation.
228 #[allow(clippy::too_many_arguments)]
229 pub fn from_trusted(
230 id: RepoId,
231 org_id: OrgId,
232 name: RepoName,
233 description: Option<String>,
234 visibility: Visibility,
235 updated_at: SystemTime,
236 pinned: bool,
237 archived: bool,
238 ) -> Self {
239 Self {
240 id,
241 org_id,
242 name,
243 description,
244 visibility,
245 updated_at,
246 pinned,
247 archived,
248 import_state: None,
249 import_source: None,
250 import_error: None,
251 }
252 }
253
254 /// Attaches import state to a repository reassembled from storage.
255 ///
256 /// A separate builder rather than three more arguments to
257 /// [`from_trusted`](Self::from_trusted), which is already at the limit of what an
258 /// argument list can say without naming its values.
259 #[must_use]
260 pub fn with_import(
261 mut self,
262 state: Option<ImportState>,
263 source: Option<ImportSource>,
264 error: Option<String>,
265 ) -> Self {
266 self.import_state = state;
267 self.import_source = source;
268 self.import_error = error;
269 self
270 }
271
272 /// Marks a repository as being mirrored from `source`.
273 ///
274 /// The error is cleared as well as the state set, so a retry does not carry the
275 /// previous attempt's message on the page while it runs.
276 pub fn start_import(&mut self, source: ImportSource) {
277 self.import_state = Some(ImportState::Importing);
278 self.import_source = Some(source);
279 self.import_error = None;
280 }
281
282 /// Records that the mirror failed. The source is kept — it is what a retry needs.
283 pub fn fail_import(&mut self, reason: impl Into<String>) {
284 self.import_state = Some(ImportState::Failed);
285 self.import_error = Some(reason.into());
286 }
287
288 /// Records that the mirror finished. The repository becomes an ordinary one; only
289 /// [`import_source`](Self::import_source) remains, as provenance.
290 pub fn finish_import(&mut self) {
291 self.import_state = None;
292 self.import_error = None;
293 }
294
295 /// Whether the repository has no usable contents yet, or never will from this
296 /// attempt. Both states mean "do not read this with git".
297 pub fn is_importing(&self) -> bool {
298 self.import_state.is_some()
299 }
300
301 /// Whether the repository's state refuses a write of `kind`, and why.
302 ///
303 /// **The one place a repository says it is closed for writing.** Before this
304 /// existed, `serve_git` checked `archived`, checked `importing` beside it, and
305 /// `rename_repo` and `set_repo_archived` had neither — so a rename could move the
306 /// directory `git clone --mirror` was still writing into. A new write path that
307 /// forgets to ask is still possible, but it no longer has to reproduce the reasons
308 /// to ask correctly.
309 ///
310 /// The refusal is a [`DomainError`] rather than a bool because the reason is the
311 /// useful part: [`Archived`](DomainError::Archived) is a state the person hitting it
312 /// can lift, and [`Unavailable`](DomainError::Unavailable) is one that lifts itself
313 /// in a minute. A caller that turned both into "not permitted" would send someone
314 /// looking for a permissions problem that is not there.
315 ///
316 /// Archived is checked first, so a repository that is somehow both — impossible to
317 /// reach now that archiving is itself refused during an import, but reachable in a
318 /// row written before that — reports the durable reason rather than the transient
319 /// one.
320 pub fn refuse_writes(&self, kind: RepoWrite) -> Result<(), DomainError> {
321 if kind == RepoWrite::Contents && self.archived {
322 return Err(DomainError::Archived);
323 }
324
325 if self.is_importing() {
326 return Err(DomainError::Unavailable {
327 entity: "repository",
328 reason: IMPORT_IN_PROGRESS.to_owned(),
329 });
330 }
331
332 Ok(())
333 }
334}
335
336/// The sentence every refusal during an import carries.
337///
338/// One string because it reaches a `git push`'s terminal, a settings page and a future
339/// `/api` response, and three spellings of the same fact read as three different rules.
340const IMPORT_IN_PROGRESS: &str =
341 "it is still being imported. Wait for the import to finish, or delete it and start again.";
342
343/// What a write touches, which decides which of a repository's states refuse it.
344///
345/// The distinction is not decoration: an **archived** repository accepts no contents and
346/// yet must stay renameable — it is finished, not frozen, and its owner is the one person
347/// who might tidy the name. So archiving cannot be a blanket write refusal.
348#[derive(Debug, Clone, Copy, PartialEq, Eq)]
349pub enum RepoWrite {
350 /// git objects and refs: a push today, a merge or a web edit later.
351 Contents,
352 /// The repository's name or its archived flag.
353 ///
354 /// Refused during an import because both fight it: a rename moves the directory
355 /// `git clone --mirror` is writing into, and archiving declares finished something
356 /// that has not arrived. **Delete is deliberately absent** — deleting is how a stuck
357 /// import is cleaned up, and the failed panel says so.
358 Settings,
359}
360
361/// Trims, and treats blank as absent.
362fn normalise_optional(value: Option<String>) -> Option<String> {
363 value
364 .map(|value| value.trim().to_owned())
365 .filter(|value| !value.is_empty())
366}
367
368#[cfg(test)]
369mod tests {
370 use super::*;
371
372 #[test]
373 fn accepts_ordinary_repository_names() {
374 for input in [
375 "steid",
376 "my-repo",
377 "my_repo",
378 "foo.js",
379 ".github",
380 "v2",
381 "a",
382 "dot.separated.name",
383 "trailing.",
384 ] {
385 assert!(
386 RepoName::new(input).is_ok(),
387 "expected {input:?} to be accepted"
388 );
389 }
390 }
391
392 #[test]
393 fn normalises_case_and_whitespace() {
394 let name = RepoName::new(" MyRepo ").expect("should be valid");
395
396 assert_eq!(name.as_str(), "myrepo");
397 }
398
399 /// The security boundary. Each of these, if allowed through, becomes a path segment
400 /// that can leave `{data_dir}/{handle}/`.
401 #[test]
402 fn rejects_anything_that_could_escape_the_data_directory() {
403 for input in [
404 ".",
405 "..",
406 "...",
407 "../etc",
408 "..%2F..%2Fetc",
409 "foo/bar",
410 "foo\\bar",
411 "/absolute",
412 "~root",
413 "with space",
414 "new\nline",
415 "nul\0byte",
416 ] {
417 assert!(
418 RepoName::new(input).is_err(),
419 "expected {input:?} to be rejected: it could escape the data directory"
420 );
421 }
422 }
423
424 #[test]
425 fn rejects_malformed_names() {
426 for input in [
427 "",
428 " ",
429 "-leading",
430 "trailing-",
431 "emoji🦀",
432 &"a".repeat(101),
433 ] {
434 assert!(
435 RepoName::new(input).is_err(),
436 "expected {input:?} to be rejected"
437 );
438 }
439 }
440
441 #[test]
442 fn rejects_names_ending_in_dot_git() {
443 // Would live at `foo.git.git` on disk and make clone URLs ambiguous.
444 assert!(RepoName::new("foo.git").is_err());
445 assert!(RepoName::new("FOO.GIT").is_err());
446 // But `.git` inside the name is harmless.
447 assert!(RepoName::new("foo.github").is_ok());
448 }
449
450 #[test]
451 fn rejects_reserved_names() {
452 for reserved in RESERVED {
453 assert!(
454 RepoName::new(*reserved).is_err(),
455 "expected {reserved:?} to be reserved"
456 );
457 }
458 // Case-insensitively, since names normalise to lowercase.
459 assert!(RepoName::new("NEW").is_err());
460 }
461
462 #[test]
463 fn reservation_does_not_leak_into_substrings() {
464 for allowed in ["newton", "renew", "imports", "research"] {
465 assert!(
466 RepoName::new(allowed).is_ok(),
467 "expected {allowed:?} to be allowed"
468 );
469 }
470 }
471
472 #[test]
473 fn the_reserved_list_is_sorted_and_unique() {
474 let mut sorted = RESERVED.to_vec();
475 sorted.sort_unstable();
476 sorted.dedup();
477
478 assert_eq!(
479 sorted.as_slice(),
480 RESERVED,
481 "keep RESERVED sorted and unique"
482 );
483 }
484
485 #[test]
486 fn accepts_a_name_at_the_length_limit() {
487 assert!(RepoName::new("a".repeat(RepoName::MAX_LEN)).is_ok());
488 }
489
490 #[test]
491 fn repositories_default_to_private() {
492 // Flipped in 0.8.0. The create form, the import form and `import_repo` all read
493 // this, so a change here is the whole change.
494 assert_eq!(Visibility::default(), Visibility::Private);
495 assert!(!Visibility::default().is_public());
496 }
497
498 #[test]
499 fn visibility_round_trips_through_strings() {
500 for visibility in [Visibility::Public, Visibility::Private] {
501 assert_eq!(
502 visibility
503 .as_str()
504 .parse::<Visibility>()
505 .expect("round trip"),
506 visibility
507 );
508 }
509 }
510
511 #[test]
512 fn unknown_visibility_is_an_error_not_a_default() {
513 // Defaulting here would publish a private repository.
514 assert!("internal".parse::<Visibility>().is_err());
515 assert!("Public".parse::<Visibility>().is_err());
516 }
517
518 fn repo(description: Option<&str>) -> Result<Repository, DomainError> {
519 Repository::new(
520 RepoId::generate(),
521 OrgId::generate(),
522 "steid",
523 description.map(str::to_owned),
524 Visibility::Public,
525 at(1_000),
526 )
527 }
528
529 fn at(seconds: u64) -> SystemTime {
530 SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(seconds)
531 }
532
533 #[test]
534 fn a_new_repository_is_stamped_with_the_time_it_was_created() {
535 let repo = Repository::new(
536 RepoId::generate(),
537 OrgId::generate(),
538 "steid",
539 None,
540 Visibility::Public,
541 at(1_700),
542 )
543 .expect("valid");
544
545 assert_eq!(repo.updated_at, at(1_700));
546 }
547
548 #[test]
549 fn a_new_repository_is_not_an_import() {
550 // Importing is attached afterwards, the way pinning is. A repository that
551 // defaulted to `Importing` would render every ordinary create as a spinner.
552 let repo = repo(None).expect("valid");
553
554 assert_eq!(repo.import_state, None);
555 assert_eq!(repo.import_source, None);
556 assert!(!repo.is_importing());
557 }
558
559 #[test]
560 fn an_import_runs_then_clears() {
561 let mut repo = repo(None).expect("valid");
562 let source = ImportSource::new("https://example.com/thing.git").expect("valid source");
563
564 repo.start_import(source.clone());
565 assert_eq!(repo.import_state, Some(ImportState::Importing));
566 assert!(repo.is_importing());
567
568 repo.finish_import();
569 assert_eq!(repo.import_state, None);
570 assert!(!repo.is_importing());
571 // Provenance survives: where it came from is still true afterwards.
572 assert_eq!(repo.import_source, Some(source));
573 }
574
575 #[test]
576 fn a_failed_import_keeps_its_source_and_its_reason() {
577 let mut repo = repo(None).expect("valid");
578 repo.start_import(ImportSource::new("https://example.com/thing.git").expect("valid"));
579 repo.fail_import("the remote hung up");
580
581 assert_eq!(repo.import_state, Some(ImportState::Failed));
582 assert_eq!(repo.import_error.as_deref(), Some("the remote hung up"));
583 // A retry needs the source, so failing must not throw it away.
584 assert!(repo.import_source.is_some());
585 }
586
587 #[test]
588 fn restarting_an_import_clears_the_previous_reason() {
589 let mut repo = repo(None).expect("valid");
590 repo.start_import(ImportSource::new("https://example.com/a.git").expect("valid"));
591 repo.fail_import("the remote hung up");
592 repo.start_import(ImportSource::new("https://example.com/b.git").expect("valid"));
593
594 assert_eq!(repo.import_error, None);
595 }
596
597 #[test]
598 fn a_new_repository_is_not_pinned() {
599 // Pinning is a later, deliberate choice; creating a repository is not a claim
600 // that it should lead the profile.
601 assert!(!repo(None).expect("valid").pinned);
602 }
603
604 #[test]
605 fn a_new_repository_is_not_archived() {
606 // Nothing is created already finished.
607 assert!(!repo(None).expect("valid").archived);
608 }
609
610 #[test]
611 fn a_repository_keeps_its_description() {
612 let repo = repo(Some("A single-tenant version control server.")).expect("valid");
613
614 assert_eq!(
615 repo.description.as_deref(),
616 Some("A single-tenant version control server.")
617 );
618 }
619
620 #[test]
621 fn a_blank_description_is_treated_as_unset() {
622 assert_eq!(repo(Some(" ")).expect("valid").description, None);
623 }
624
625 #[test]
626 fn rejects_an_over_long_description() {
627 let long = "a".repeat(Repository::MAX_DESCRIPTION_LEN + 1);
628
629 let error = repo(Some(&long)).expect_err("should reject");
630
631 assert!(matches!(error, DomainError::Validation { .. }));
632 }
633
634 #[test]
635 fn description_length_counts_characters_not_bytes() {
636 let accented = "é".repeat(Repository::MAX_DESCRIPTION_LEN);
637
638 assert!(repo(Some(&accented)).is_ok());
639 }
640
641 #[test]
642 fn an_invalid_name_rejects_the_whole_repository() {
643 let error = Repository::new(
644 RepoId::generate(),
645 OrgId::generate(),
646 "../escape",
647 None,
648 Visibility::Public,
649 at(1_000),
650 )
651 .expect_err("should reject");
652
653 assert!(matches!(error, DomainError::Validation { .. }));
654 }
655 // --- the write guard -------------------------------------------------------------
656
657 #[test]
658 fn an_ordinary_repository_refuses_nothing() {
659 let repo = repo(None).expect("valid");
660
661 assert!(repo.refuse_writes(RepoWrite::Contents).is_ok());
662 assert!(repo.refuse_writes(RepoWrite::Settings).is_ok());
663 }
664
665 #[test]
666 fn an_archived_repository_refuses_contents_and_still_allows_settings() {
667 // Archived says "finished", not "frozen": the owner may still rename it or
668 // unarchive it, and unarchiving would be unreachable if archived refused every
669 // write.
670 let mut repo = repo(None).expect("valid");
671 repo.archived = true;
672
673 assert!(matches!(
674 repo.refuse_writes(RepoWrite::Contents),
675 Err(DomainError::Archived)
676 ));
677 assert!(repo.refuse_writes(RepoWrite::Settings).is_ok());
678 }
679
680 #[test]
681 fn an_importing_repository_refuses_both() {
682 // A rename moves the directory the clone is writing into, and archiving declares
683 // finished something that has not arrived.
684 let mut repo = repo(None).expect("valid");
685 repo.start_import(ImportSource::new("https://example.com/a/b.git").expect("valid"));
686
687 for kind in [RepoWrite::Contents, RepoWrite::Settings] {
688 assert!(
689 matches!(
690 repo.refuse_writes(kind),
691 Err(DomainError::Unavailable {
692 entity: "repository",
693 ..
694 })
695 ),
696 "{kind:?} should be refused while importing"
697 );
698 }
699 }
700
701 #[test]
702 fn a_failed_import_still_refuses_writes() {
703 // The state is not `None`, so there is no usable directory yet — the answer is
704 // the same as while it was running, and the way out is Delete.
705 let mut repo = repo(None).expect("valid");
706 repo.start_import(ImportSource::new("https://example.com/a/b.git").expect("valid"));
707 repo.fail_import("could not read from remote");
708
709 assert!(repo.refuse_writes(RepoWrite::Contents).is_err());
710 assert!(repo.refuse_writes(RepoWrite::Settings).is_err());
711 }
712
713 #[test]
714 fn a_finished_import_refuses_nothing() {
715 let mut repo = repo(None).expect("valid");
716 repo.start_import(ImportSource::new("https://example.com/a/b.git").expect("valid"));
717 repo.finish_import();
718
719 assert!(repo.refuse_writes(RepoWrite::Contents).is_ok());
720 assert!(repo.refuse_writes(RepoWrite::Settings).is_ok());
721 }
722
723 #[test]
724 fn an_archived_repository_that_is_also_importing_reports_being_archived() {
725 // Unreachable through the use cases now that archiving is refused during an
726 // import, but reachable in a row written before that: the durable reason is the
727 // more useful one to state.
728 let mut repo = repo(None).expect("valid");
729 repo.archived = true;
730 repo.start_import(ImportSource::new("https://example.com/a/b.git").expect("valid"));
731
732 assert!(matches!(
733 repo.refuse_writes(RepoWrite::Contents),
734 Err(DomainError::Archived)
735 ));
736 }
737}