steid

@jamesgill /

Rust88.6 KBCode·Blame·History·Raw
1use std::time::SystemTime;
2
3use crate::domain::{
4 Actor, DomainError, ImportSource, ImportState, OrgName, RefName, RepoId, RepoName, Repository,
5 Visibility,
6 repository::{MembershipRepository, OrgRepository, RepoRepository},
7};
8
9use super::{
10 authz::{is_org_member, is_org_owner},
11 error::{Error, Result},
12 port::{GitQuery, GitStorage, GitStorageError},
13};
14
15/// The repository a visitor is asking to create.
16///
17/// Raw input: `name` is whatever was typed, and normalising it is
18/// [`Repository::new`]'s job, not the caller's.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct NewRepo {
21 pub name: String,
22 pub description: Option<String>,
23 pub visibility: Visibility,
24}
25
26/// Creates a repository as a record and as a bare repo on disk.
27///
28/// Owner only. A member's read access is not permission to add to someone's portfolio.
29///
30/// Returns the created [`Repository`] rather than `()` because the name normalises on
31/// the way in — someone who typed `MyRepo` has to be redirected to `myrepo`, and only
32/// the returned value knows that.
33///
34/// **The two writes cannot share a transaction.** The bare repo is created first and
35/// removed again if the record fails to save, per
36/// `plans/architecture.md#db-plus-filesystem-writes`. If the process dies between them
37/// the directory is orphaned; that hole is known and unclosed.
38pub async fn create_repo(
39 actor: &Actor,
40 handle: &OrgName,
41 spec: &NewRepo,
42 orgs: &impl OrgRepository,
43 memberships: &impl MembershipRepository,
44 repos: &impl RepoRepository,
45 storage: &impl GitStorage,
46) -> Result<Repository> {
47 let Some(org) = orgs.find_by_name(handle).await? else {
48 return Err(DomainError::NotFound {
49 entity: "repository owner",
50 }
51 .into());
52 };
53
54 if !is_org_owner(&org, actor, memberships).await? {
55 return Err(DomainError::Forbidden.into());
56 }
57
58 // Validated before anything is written, so a bad name leaves neither a row nor a
59 // directory behind.
60 let repo = Repository::new(
61 RepoId::generate(),
62 org.id.clone(),
63 spec.name.clone(),
64 spec.description.clone(),
65 spec.visibility,
66 // Read here rather than taken as an argument, unlike `touch`: nothing needs to
67 // create a repository *as of* a stated time, and a parameter no caller ever
68 // varies is a parameter every caller has to think about. Revisit if a clock port
69 // appears.
70 SystemTime::now(),
71 )?;
72
73 if repos
74 .find_by_org_and_name(&org.id, &repo.name)
75 .await?
76 .is_some()
77 {
78 return Err(taken());
79 }
80
81 storage
82 .init_bare(handle, &repo.name)
83 .await
84 .map_err(|error| {
85 match error {
86 // No record, but something is already on disk: an orphan from a create that
87 // died between the two writes. The name really is unavailable, so this is
88 // what the visitor is told — at the cost of an orphan being
89 // indistinguishable from a duplicate from the outside. The durable fix is
90 // the reconciliation sweep noted in architecture.md.
91 GitStorageError::AlreadyExists => taken(),
92 other => Error::GitStorage(other),
93 }
94 })?;
95
96 if let Err(error) = repos.save(&repo).await {
97 // Compensation. Safe to delete by path because `init_bare` just proved nothing
98 // was there — this can never remove a repository that won a race, because the
99 // loser of that race never gets past `init_bare`.
100 //
101 // Best effort: if the removal also fails the caller still needs the error that
102 // started this, and an orphaned directory is the documented failure mode.
103 let _ = storage.remove(handle, &repo.name).await;
104 return Err(error.into());
105 }
106
107 Ok(repo)
108}
109
110/// A repository as a viewer is allowed to see it.
111#[derive(Debug, Clone, PartialEq, Eq)]
112pub struct RepoView {
113 /// The owning handle, carried so a page can build links without a second lookup.
114 pub handle: OrgName,
115 pub name: RepoName,
116 pub description: Option<String>,
117 pub visibility: Visibility,
118 /// When code last landed here. The repository page dates itself from this rather
119 /// than asking git, which costs a fork.
120 pub updated_at: SystemTime,
121 /// Whether this repository leads the owner's profile. Here as well as on
122 /// [`RepoSummary`] because the settings page renders the pin control from this view
123 /// and would otherwise have to read the row a second time to know the box's state.
124 pub pinned: bool,
125 /// Whether the repository is archived: readable, not writable. Every repository
126 /// page renders the badge from this, so it travels with the view rather than being
127 /// looked up again per page.
128 pub archived: bool,
129 /// Whether the viewer may change this repository. Decided here so a page and
130 /// `/api` cannot disagree about who sees a management control.
131 pub viewer_is_owner: bool,
132 /// How far an import has got, or `None` for an ordinary repository.
133 ///
134 /// Carried on the view rather than looked up separately because **every page that
135 /// reads a repository has to check it**: the contents are not there yet, and asking
136 /// git for them costs five processes to be told the directory is empty.
137 pub import: Option<ImportStatus>,
138}
139
140/// An import, as a page renders it.
141///
142/// The state, the address and the reason travel together because no page wants one
143/// without the others: the importing panel names the source, and the failed panel names
144/// the source and the reason.
145#[derive(Debug, Clone, PartialEq, Eq)]
146pub struct ImportStatus {
147 pub state: ImportState,
148 pub source: Option<ImportSource>,
149 pub error: Option<String>,
150}
151
152impl ImportStatus {
153 /// Reads the import off a repository, or `None` for an ordinary one.
154 fn of(repo: &Repository) -> Option<Self> {
155 Some(Self {
156 state: repo.import_state?,
157 source: repo.import_source.clone(),
158 error: repo.import_error.clone(),
159 })
160 }
161
162 pub fn is_running(&self) -> bool {
163 self.state == ImportState::Importing
164 }
165}
166
167/// Resolves a handle and name into a repository the viewer may see.
168///
169/// `Ok(None)` covers **both** "no such repository" and "not allowed to see it", and
170/// the caller must render them identically. Distinguishing them would confirm that a
171/// private repository exists and reveal its name, which is the thing being protected —
172/// a private repo has to be absent, not merely unlinked.
173///
174/// Private repositories are visible to any member of the owning organisation, not only
175/// its owner: seeing is weaker than changing.
176pub async fn view_repo(
177 handle: &OrgName,
178 name: &RepoName,
179 actor: &Actor,
180 orgs: &impl OrgRepository,
181 memberships: &impl MembershipRepository,
182 repos: &impl RepoRepository,
183) -> Result<Option<RepoView>> {
184 let Some(org) = orgs.find_by_name(handle).await? else {
185 return Ok(None);
186 };
187
188 let Some(repo) = repos.find_by_org_and_name(&org.id, name).await? else {
189 return Ok(None);
190 };
191
192 if !repo.visibility.is_public() && !is_org_member(&org, actor, memberships).await? {
193 return Ok(None);
194 }
195
196 Ok(Some(RepoView {
197 handle: org.name.clone(),
198 import: ImportStatus::of(&repo),
199 name: repo.name,
200 description: repo.description,
201 visibility: repo.visibility,
202 updated_at: repo.updated_at,
203 pinned: repo.pinned,
204 archived: repo.archived,
205 viewer_is_owner: is_org_owner(&org, actor, memberships).await?,
206 }))
207}
208
209/// A repository as it appears in a listing.
210///
211/// Leaner than [`RepoView`] on purpose: the owning handle and whether the viewer owns
212/// it are constant across a listing and already known to whatever is rendering it.
213#[derive(Debug, Clone, PartialEq, Eq)]
214pub struct RepoSummary {
215 pub name: RepoName,
216 pub description: Option<String>,
217 pub visibility: Visibility,
218 pub updated_at: SystemTime,
219 /// Whether this is the owner's lead repository. Carried in the listing because the
220 /// profile picks the lead *out of* the listing rather than fetching it separately —
221 /// one query, and no chance of the lead and the list disagreeing.
222 pub pinned: bool,
223 /// Whether the repository is archived. Carried for the same reason `pinned` is: the
224 /// profile's badge comes out of the listing rather than a row read per repository.
225 pub archived: bool,
226 /// How far an import has got, or `None` for an ordinary repository.
227 ///
228 /// The state rather than the whole [`ImportStatus`]: a listing row needs to tell
229 /// "still copying" from "did not copy" — a badge saying "Importing" on a row that
230 /// failed an hour ago is a lie — but the address and the reason belong on the page
231 /// that has room for them.
232 pub import_state: Option<ImportState>,
233}
234
235/// Every repository under a handle that the viewer is allowed to see, most recently
236/// updated first — the order [`RepoRepository::list_by_org`] defines.
237///
238/// `Ok(None)` means no such handle — distinct from `Ok(Some(vec![]))`, which means the
239/// handle exists and the viewer can see nothing under it. A caller serving `/api` needs
240/// that difference to answer 404 rather than an empty list.
241///
242/// **The filtering happens here, not in the port.** `list_by_org` deliberately returns
243/// everything, so that the page and `/api` cannot end up applying different rules.
244/// A viewer who may see nothing gets an empty list, never a count or a hint — that
245/// would leak both the existence and the number of private repositories.
246pub async fn list_repos(
247 handle: &OrgName,
248 actor: &Actor,
249 orgs: &impl OrgRepository,
250 memberships: &impl MembershipRepository,
251 repos: &impl RepoRepository,
252) -> Result<Option<Vec<RepoSummary>>> {
253 let Some(org) = orgs.find_by_name(handle).await? else {
254 return Ok(None);
255 };
256
257 // Resolved once rather than per row: membership cannot change mid-listing, and
258 // asking per repository would be a query per repository.
259 let is_member = is_org_member(&org, actor, memberships).await?;
260
261 Ok(Some(
262 repos
263 .list_by_org(&org.id)
264 .await?
265 .into_iter()
266 .filter(|repo| repo.visibility.is_public() || is_member)
267 .map(|repo| RepoSummary {
268 import_state: repo.import_state,
269 name: repo.name,
270 description: repo.description,
271 visibility: repo.visibility,
272 updated_at: repo.updated_at,
273 pinned: repo.pinned,
274 archived: repo.archived,
275 })
276 .collect(),
277 ))
278}
279
280/// Resolves a repository the actor is allowed to **change**.
281///
282/// Two different answers, on purpose, and the split matters:
283///
284/// - A repository the actor may not *see* is [`DomainError::NotFound`], exactly as
285/// [`view_repo`] returns `None` for it. Saying "forbidden" instead would confirm that
286/// a private repository by that name exists, which is the thing being protected.
287/// - A repository the actor *can* see but does not own is [`DomainError::Forbidden`],
288/// matching [`create_repo`]: the resource is public anyway, so pretending it is
289/// missing would be theatre.
290///
291/// A caller that wants to collapse both into a 404 — the settings page does — can; a
292/// caller that wants to explain the difference has the information to.
293pub(crate) async fn changeable_repo(
294 actor: &Actor,
295 handle: &OrgName,
296 name: &RepoName,
297 orgs: &impl OrgRepository,
298 memberships: &impl MembershipRepository,
299 repos: &impl RepoRepository,
300) -> Result<Repository> {
301 let missing = || {
302 Error::Domain(DomainError::NotFound {
303 entity: "repository",
304 })
305 };
306
307 let Some(org) = orgs.find_by_name(handle).await? else {
308 return Err(missing());
309 };
310
311 let Some(repo) = repos.find_by_org_and_name(&org.id, name).await? else {
312 return Err(missing());
313 };
314
315 if !repo.visibility.is_public() && !is_org_member(&org, actor, memberships).await? {
316 return Err(missing());
317 }
318
319 if !is_org_owner(&org, actor, memberships).await? {
320 return Err(DomainError::Forbidden.into());
321 }
322
323 Ok(repo)
324}
325
326/// The changes an owner is asking to make to a repository.
327///
328/// Grouped like [`NewRepo`] rather than passed loose, so that adding a settable field
329/// later does not change every call site — and so the argument list stays readable.
330///
331/// **No `name`.** See [`update_repo`].
332#[derive(Debug, Clone, PartialEq, Eq)]
333pub struct RepoEdit {
334 pub description: Option<String>,
335 pub visibility: Visibility,
336 /// Whether this repository should lead the owner's profile. Setting it unpins
337 /// whichever repository held the spot — see [`update_repo`].
338 pub pinned: bool,
339}
340
341/// Changes a repository's description and visibility.
342///
343/// Owner only. Seeing a private repository is not permission to change it.
344///
345/// **The name is deliberately not changeable here.** A rename is not a column update:
346/// the bare repo lives at `{data_dir}/{handle}/{name}.git`, so renaming means moving a
347/// directory while clones, pushes and in-flight requests point at the old path, and it
348/// needs its own use case with its own answer for the two-writes problem in
349/// `plans/architecture.md#db-plus-filesystem-writes`. Half-doing it — updating the row
350/// and leaving the directory — would break every existing clone silently.
351///
352/// Returns the saved [`Repository`] so a caller can re-render from what was actually
353/// stored rather than from what was submitted; the description normalises on the way in.
354pub async fn update_repo(
355 actor: &Actor,
356 handle: &OrgName,
357 name: &RepoName,
358 edit: &RepoEdit,
359 orgs: &impl OrgRepository,
360 memberships: &impl MembershipRepository,
361 repos: &impl RepoRepository,
362) -> Result<Repository> {
363 let existing = changeable_repo(actor, handle, name, orgs, memberships, repos).await?;
364
365 // Rebuilt through `new` rather than assigned field by field, so the description
366 // length rule lives in exactly one place. The stored name goes back through
367 // validation as a side effect — acceptable because it was validated on the way in
368 // and has not changed, and the alternative is a second copy of the rule here.
369 let mut updated = Repository::new(
370 existing.id,
371 existing.org_id.clone(),
372 existing.name.as_str(),
373 edit.description.clone(),
374 edit.visibility,
375 // The existing timestamp, not the current time. `updated_at` means "code last
376 // landed here" and orders a portfolio by what is being worked on; rewording a
377 // description is not work on the repository and must not jump it to the top.
378 existing.updated_at,
379 )?;
380 updated.pinned = edit.pinned;
381 // Carried, not edited. Archiving is its own use case with its own control; a
382 // description save must not quietly un-archive a repository.
383 updated.archived = existing.archived;
384
385 // **At most one pinned repository per owner**, enforced here rather than in storage.
386 // The rule is not "refuse a second pin" but "pinning this unpins that", and a
387 // constraint — a partial unique index would express the shape exactly — can only
388 // refuse. Enforcing it in the use case also keeps the two `RepoRepository`
389 // implementations from having to agree on a behaviour neither of them is asked for.
390 //
391 // The two writes are not one transaction, so a crash between them can leave nothing
392 // pinned. That is the harmless direction: no lead section, rather than two.
393 if updated.pinned {
394 for other in repos.list_by_org(&existing.org_id).await? {
395 if other.pinned && other.id != updated.id {
396 repos
397 .save(&Repository {
398 pinned: false,
399 ..other
400 })
401 .await?;
402 }
403 }
404 }
405
406 repos.save(&updated).await?;
407
408 Ok(updated)
409}
410
411/// Renames a repository: its record, and the bare repo on disk.
412///
413/// Owner only, and the second of Steid's two writes that cannot share a transaction.
414/// **The directory moves first, then the row**, which is the opposite order from
415/// [`delete_repo`] and the same one as [`create_repo`], for the same reason: a move is
416/// reversible and a delete is not, so the filesystem write can be undone if the record
417/// write fails. If the process dies between them the repository is on disk under its
418/// new name while the row still says the old one, and every page 404s until it is moved
419/// back by hand — the same class of hole `create_repo` documents, and closed by the same
420/// reconciliation sweep in `plans/architecture.md#db-plus-filesystem-writes`.
421///
422/// **Nothing redirects from the old name.** Steid is single tenant and the owner holds
423/// the clones; a permanent alias table would outlive its usefulness on the first repo
424/// that is renamed twice. Existing remotes have to be updated, and the form says so.
425///
426/// Renaming to the name it already has is a no-op rather than an error: the name
427/// normalises on the way in, so `MyRepo` submitted for `myrepo` is somebody confirming
428/// what is already true, not a collision with itself.
429#[allow(clippy::too_many_arguments)]
430pub async fn rename_repo(
431 actor: &Actor,
432 handle: &OrgName,
433 name: &RepoName,
434 new_name: &str,
435 orgs: &impl OrgRepository,
436 memberships: &impl MembershipRepository,
437 repos: &impl RepoRepository,
438 storage: &impl GitStorage,
439) -> Result<Repository> {
440 let existing = changeable_repo(actor, handle, name, orgs, memberships, repos).await?;
441
442 // Rebuilt through `new` rather than assigning a `RepoName`, so the reserved list and
443 // the traversal rules are applied to the new name exactly as they were to the old.
444 // Validated before anything moves, so a bad name leaves the repository untouched.
445 let mut renamed = Repository::new(
446 existing.id.clone(),
447 existing.org_id.clone(),
448 new_name,
449 existing.description.clone(),
450 existing.visibility,
451 // `updated_at` means "code last landed here". A rename is not a push.
452 existing.updated_at,
453 )?;
454 renamed.pinned = existing.pinned;
455 renamed.archived = existing.archived;
456
457 if renamed.name == existing.name {
458 return Ok(existing);
459 }
460
461 if repos
462 .find_by_org_and_name(&existing.org_id, &renamed.name)
463 .await?
464 .is_some()
465 {
466 return Err(taken());
467 }
468
469 storage
470 .rename(handle, &existing.name, &renamed.name)
471 .await
472 .map_err(|error| match error {
473 // Something is already at the destination with no record to match — an
474 // orphan, exactly as in `create_repo`. The name is genuinely unavailable.
475 GitStorageError::AlreadyExists => taken(),
476 other => Error::GitStorage(other),
477 })?;
478
479 if let Err(error) = repos.save(&renamed).await {
480 // Compensation. Safe because the move above proved the destination was empty,
481 // and the source is the path this repository's own row still names.
482 let _ = storage.rename(handle, &renamed.name, &existing.name).await;
483 return Err(error.into());
484 }
485
486 Ok(renamed)
487}
488
489/// Points the repository's `HEAD` at a different branch.
490///
491/// Owner only. **Nothing is stored in the database**: git already holds the answer, and
492/// every read of it goes through [`GitQuery::default_branch`], so a column would be a
493/// second answer that can drift from the first — see
494/// [`GitStorage::set_default_branch`].
495///
496/// The branch has to exist, and is checked against the repository's own branch list
497/// rather than trusted: `symbolic-ref` will happily point `HEAD` at a branch that is
498/// not there, which is precisely the state an empty repository is in, and doing it to a
499/// repository with commits makes every page say "nothing pushed yet".
500///
501/// **One `git` process to check, one to write.** An empty repository has no branches to
502/// choose from, so the caller does not offer the control at all.
503#[allow(clippy::too_many_arguments)]
504pub async fn set_default_branch(
505 actor: &Actor,
506 handle: &OrgName,
507 name: &RepoName,
508 branch: &str,
509 orgs: &impl OrgRepository,
510 memberships: &impl MembershipRepository,
511 repos: &impl RepoRepository,
512 queries: &impl GitQuery,
513 storage: &impl GitStorage,
514) -> Result<RefName> {
515 let repo = changeable_repo(actor, handle, name, orgs, memberships, repos).await?;
516
517 // Validated before it reaches git, the same way a revision from a URL is: this
518 // value ends up as an argument to the binary.
519 let branch = RefName::new(branch)?;
520
521 let exists = queries
522 .branches(handle, &repo.name)
523 .await?
524 .iter()
525 .any(|row| row.name == branch);
526
527 if !exists {
528 return Err(DomainError::NotFound { entity: "branch" }.into());
529 }
530
531 storage
532 .set_default_branch(handle, &repo.name, &branch)
533 .await?;
534
535 Ok(branch)
536}
537
538/// Archives or unarchives a repository.
539///
540/// Owner only. An archived repository is **finished, not hidden**: everything that
541/// reads keeps working — browsing, cloning, search, archive download — and only writing
542/// stops. The refusal itself lives in [`serve_git`](super::git::serve_git), beside the
543/// `Role::Owner` check, so it applies to every transport rather than to one handler.
544///
545/// Separate from [`update_repo`] rather than a field on [`RepoEdit`], because it is a
546/// state change with its own consequence and its own control: bundling it into the
547/// description form would let a mistyped save silently reopen a repository for writing.
548///
549/// Idempotent. Archiving an archived repository is what a double-clicked button does.
550pub async fn set_repo_archived(
551 actor: &Actor,
552 handle: &OrgName,
553 name: &RepoName,
554 archived: bool,
555 orgs: &impl OrgRepository,
556 memberships: &impl MembershipRepository,
557 repos: &impl RepoRepository,
558) -> Result<Repository> {
559 let existing = changeable_repo(actor, handle, name, orgs, memberships, repos).await?;
560
561 // `updated_at` is untouched: archiving is not code landing, and a portfolio ordered
562 // by recency must not float a finished repository to the top on the day it is
563 // declared finished.
564 let updated = Repository {
565 archived,
566 ..existing
567 };
568
569 repos.save(&updated).await?;
570
571 Ok(updated)
572}
573
574/// Deletes a repository: its record, and the bare repo on disk.
575///
576/// Owner only, and irreversible — the git history goes with it.
577///
578/// **The row goes first, then the directory.** The two writes cannot share a
579/// transaction, so one of the two orphans is possible, and this picks the less harmful
580/// one deliberately. An orphaned *directory* only blocks reusing that name, and is
581/// already the documented failure mode of [`create_repo`]'s compensation path. An
582/// orphaned *row* is worse and visible: a repository that still lists on the profile and
583/// 404s the moment anyone clicks it.
584///
585/// If the directory cannot be removed this still reports success, because as far as
586/// Steid is concerned the repository genuinely is gone — there is nothing the caller
587/// could usefully do about it, and failing here would leave the visitor thinking the
588/// delete had not happened when the record is already destroyed. The failure is logged.
589pub async fn delete_repo(
590 actor: &Actor,
591 handle: &OrgName,
592 name: &RepoName,
593 orgs: &impl OrgRepository,
594 memberships: &impl MembershipRepository,
595 repos: &impl RepoRepository,
596 storage: &impl GitStorage,
597) -> Result<()> {
598 let repo = changeable_repo(actor, handle, name, orgs, memberships, repos).await?;
599
600 repos.delete(&repo.id).await?;
601
602 if let Err(error) = storage.remove(handle, &repo.name).await {
603 eprintln!(
604 "steid: repository {handle}/{} deleted, but its directory could not be removed: {error}",
605 repo.name
606 );
607 }
608
609 Ok(())
610}
611
612fn taken() -> Error {
613 DomainError::AlreadyExists {
614 entity: "repository",
615 }
616 .into()
617}
618
619#[cfg(test)]
620mod tests {
621 use super::*;
622 use crate::{
623 domain::{
624 Membership, MembershipId, OrgId, Organization, RepoName, Role, UserId,
625 repository::{RepositoryError, RepositoryResult},
626 },
627 infrastructure::{
628 git::{DiskGitStorage, InMemoryGitQuery, InMemoryGitStorage},
629 repository::{InMemoryMembershipRepo, InMemoryOrgRepo, InMemoryRepoRepo},
630 },
631 };
632
633 fn at(seconds: u64) -> SystemTime {
634 SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(seconds)
635 }
636
637 /// A `RepoRepository` whose `save` always fails, for exercising compensation.
638 ///
639 /// Test-local on purpose: fault injection does not belong in the shared fake, where
640 /// every other test would have to know about it.
641 #[derive(Debug, Default)]
642 struct FailingRepoRepo;
643
644 impl RepoRepository for FailingRepoRepo {
645 async fn find_by_id(&self, _id: &RepoId) -> RepositoryResult<Option<Repository>> {
646 Ok(None)
647 }
648
649 async fn find_by_org_and_name(
650 &self,
651 _org_id: &OrgId,
652 _name: &RepoName,
653 ) -> RepositoryResult<Option<Repository>> {
654 Ok(None)
655 }
656
657 async fn list_by_org(&self, _org_id: &OrgId) -> RepositoryResult<Vec<Repository>> {
658 Ok(Vec::new())
659 }
660
661 async fn save(&self, _repo: &Repository) -> RepositoryResult<()> {
662 Err(RepositoryError::backend("save failed on purpose"))
663 }
664
665 async fn touch(&self, _id: &RepoId, _now: SystemTime) -> RepositoryResult<()> {
666 Ok(())
667 }
668
669 async fn fail_interrupted_imports(&self, _reason: &str) -> RepositoryResult<u64> {
670 Ok(0)
671 }
672
673 async fn delete(&self, _id: &RepoId) -> RepositoryResult<()> {
674 Ok(())
675 }
676 }
677
678 struct Fixture {
679 orgs: InMemoryOrgRepo,
680 memberships: InMemoryMembershipRepo,
681 repos: InMemoryRepoRepo,
682 storage: InMemoryGitStorage,
683 owner: Actor,
684 member: Actor,
685 stranger: Actor,
686 handle: OrgName,
687 }
688
689 async fn fixture() -> Fixture {
690 let orgs = InMemoryOrgRepo::new();
691 let memberships = InMemoryMembershipRepo::new();
692
693 let org = Organization::new(OrgId::generate(), "acme", None).expect("valid org");
694 orgs.save(&org).await.expect("save org");
695
696 let owner = UserId::generate();
697 let member = UserId::generate();
698
699 for (user, role) in [(&owner, Role::Owner), (&member, Role::Member)] {
700 memberships
701 .save(&Membership::new(
702 MembershipId::generate(),
703 org.id.clone(),
704 user.clone(),
705 role,
706 ))
707 .await
708 .expect("save membership");
709 }
710
711 Fixture {
712 orgs,
713 memberships,
714 repos: InMemoryRepoRepo::new(),
715 storage: InMemoryGitStorage::new(),
716 owner: Actor::User(owner),
717 member: Actor::User(member),
718 stranger: Actor::User(UserId::generate()),
719 handle: org.name,
720 }
721 }
722
723 fn spec(name: &str) -> NewRepo {
724 NewRepo {
725 name: name.to_owned(),
726 description: None,
727 visibility: Visibility::Public,
728 }
729 }
730
731 impl Fixture {
732 async fn create(&self, actor: &Actor, spec: &NewRepo) -> Result<Repository> {
733 create_repo(
734 actor,
735 &self.handle,
736 spec,
737 &self.orgs,
738 &self.memberships,
739 &self.repos,
740 &self.storage,
741 )
742 .await
743 }
744 }
745
746 #[tokio::test]
747 async fn the_owner_creates_a_record_and_a_bare_repo() {
748 let f = fixture().await;
749
750 let repo = f
751 .create(&f.owner, &spec("steid"))
752 .await
753 .expect("should create");
754
755 assert_eq!(repo.name.as_str(), "steid");
756 assert!(
757 f.repos
758 .find_by_org_and_name(&repo.org_id, &repo.name)
759 .await
760 .expect("lookup")
761 .is_some()
762 );
763 assert!(f.storage.contains(&f.handle, &repo.name));
764 }
765
766 #[tokio::test]
767 async fn an_anonymous_visitor_is_refused() {
768 let f = fixture().await;
769
770 let error = f
771 .create(&Actor::Anonymous, &spec("steid"))
772 .await
773 .expect_err("should refuse");
774
775 assert!(matches!(error, Error::Domain(DomainError::Forbidden)));
776 assert!(f.storage.is_empty());
777 }
778
779 #[tokio::test]
780 async fn a_signed_in_stranger_is_refused() {
781 // Signed in is not the same as allowed.
782 let f = fixture().await;
783
784 let error = f
785 .create(&f.stranger, &spec("steid"))
786 .await
787 .expect_err("should refuse");
788
789 assert!(matches!(error, Error::Domain(DomainError::Forbidden)));
790 assert!(f.storage.is_empty());
791 }
792
793 #[tokio::test]
794 async fn a_non_owner_member_is_refused() {
795 // Membership is read access, not permission to add to someone's portfolio.
796 let f = fixture().await;
797
798 let error = f
799 .create(&f.member, &spec("steid"))
800 .await
801 .expect_err("should refuse");
802
803 assert!(matches!(error, Error::Domain(DomainError::Forbidden)));
804 assert!(f.storage.is_empty());
805 }
806
807 #[tokio::test]
808 async fn an_unknown_handle_is_not_found() {
809 let f = fixture().await;
810 let missing = OrgName::new("nobody").expect("valid handle");
811
812 let error = create_repo(
813 &f.owner,
814 &missing,
815 &spec("steid"),
816 &f.orgs,
817 &f.memberships,
818 &f.repos,
819 &f.storage,
820 )
821 .await
822 .expect_err("should not find");
823
824 assert!(matches!(
825 error,
826 Error::Domain(DomainError::NotFound {
827 entity: "repository owner"
828 })
829 ));
830 }
831
832 #[tokio::test]
833 async fn an_invalid_name_writes_nothing() {
834 // Validation precedes both side effects, so a rejected name leaves no trace.
835 let f = fixture().await;
836
837 let error = f
838 .create(&f.owner, &spec("../escape"))
839 .await
840 .expect_err("should reject");
841
842 assert!(matches!(
843 error,
844 Error::Domain(DomainError::Validation { .. })
845 ));
846 assert!(f.storage.is_empty());
847 }
848
849 #[tokio::test]
850 async fn a_duplicate_name_is_refused_and_changes_nothing() {
851 let f = fixture().await;
852 let first = f
853 .create(&f.owner, &spec("steid"))
854 .await
855 .expect("should create");
856
857 let error = f
858 .create(&f.owner, &spec("steid"))
859 .await
860 .expect_err("should refuse");
861
862 assert!(matches!(
863 error,
864 Error::Domain(DomainError::AlreadyExists {
865 entity: "repository"
866 })
867 ));
868 assert_eq!(f.storage.len(), 1, "the existing repo should be untouched");
869 assert_eq!(
870 f.repos
871 .find_by_org_and_name(&first.org_id, &first.name)
872 .await
873 .expect("lookup")
874 .expect("still there")
875 .id,
876 first.id
877 );
878 }
879
880 #[tokio::test]
881 async fn a_duplicate_is_caught_case_insensitively() {
882 // The name normalises, so `Steid` and `steid` are the same repository.
883 let f = fixture().await;
884 f.create(&f.owner, &spec("steid"))
885 .await
886 .expect("should create");
887
888 let error = f
889 .create(&f.owner, &spec("Steid"))
890 .await
891 .expect_err("should refuse");
892
893 assert!(matches!(
894 error,
895 Error::Domain(DomainError::AlreadyExists {
896 entity: "repository"
897 })
898 ));
899 }
900
901 #[tokio::test]
902 async fn an_orphaned_directory_reads_as_a_taken_name() {
903 // No record, but the path is occupied — a create that died between the writes.
904 // The visitor is told the name is taken, because from outside it is.
905 let f = fixture().await;
906 let name = RepoName::new("steid").expect("valid");
907 f.storage
908 .init_bare(&f.handle, &name)
909 .await
910 .expect("orphan the directory");
911
912 let error = f
913 .create(&f.owner, &spec("steid"))
914 .await
915 .expect_err("should refuse");
916
917 assert!(matches!(
918 error,
919 Error::Domain(DomainError::AlreadyExists {
920 entity: "repository"
921 })
922 ));
923 }
924
925 #[tokio::test]
926 async fn the_name_is_normalised_in_what_comes_back() {
927 // The caller redirects using this, so it has to be the stored form.
928 let f = fixture().await;
929
930 let repo = f
931 .create(&f.owner, &spec(" MyRepo "))
932 .await
933 .expect("should create");
934
935 assert_eq!(repo.name.as_str(), "myrepo");
936 assert!(f.storage.contains(&f.handle, &repo.name));
937 }
938
939 #[tokio::test]
940 async fn visibility_and_description_are_carried_through() {
941 let f = fixture().await;
942
943 let repo = f
944 .create(
945 &f.owner,
946 &NewRepo {
947 name: "steid".to_owned(),
948 description: Some(" A gitforge. ".to_owned()),
949 visibility: Visibility::Private,
950 },
951 )
952 .await
953 .expect("should create");
954
955 assert_eq!(repo.visibility, Visibility::Private);
956 assert_eq!(repo.description.as_deref(), Some("A gitforge."));
957 }
958
959 #[tokio::test]
960 async fn a_blank_description_is_stored_as_unset() {
961 let f = fixture().await;
962
963 let repo = f
964 .create(
965 &f.owner,
966 &NewRepo {
967 name: "steid".to_owned(),
968 description: Some(" ".to_owned()),
969 visibility: Visibility::Public,
970 },
971 )
972 .await
973 .expect("should create");
974
975 assert_eq!(repo.description, None);
976 }
977
978 #[tokio::test]
979 async fn a_failed_save_removes_the_bare_repo() {
980 // The compensating transaction. Without it every failed insert leaks a
981 // directory that then blocks the name forever.
982 let f = fixture().await;
983
984 let error = create_repo(
985 &f.owner,
986 &f.handle,
987 &spec("steid"),
988 &f.orgs,
989 &f.memberships,
990 &FailingRepoRepo,
991 &f.storage,
992 )
993 .await
994 .expect_err("should fail");
995
996 assert!(matches!(error, Error::Repository(_)));
997 assert!(
998 f.storage.is_empty(),
999 "the bare repo should have been compensated away"
1000 );
1001 }
1002
1003 #[tokio::test]
1004 async fn a_successful_save_keeps_the_bare_repo() {
1005 // The other half of the above: compensation must not fire on the happy path.
1006 let f = fixture().await;
1007
1008 let repo = f
1009 .create(&f.owner, &spec("steid"))
1010 .await
1011 .expect("should create");
1012
1013 assert!(f.storage.contains(&f.handle, &repo.name));
1014 }
1015
1016 #[tokio::test]
1017 async fn a_compensated_name_can_be_created_again() {
1018 let f = fixture().await;
1019 let _ = create_repo(
1020 &f.owner,
1021 &f.handle,
1022 &spec("steid"),
1023 &f.orgs,
1024 &f.memberships,
1025 &FailingRepoRepo,
1026 &f.storage,
1027 )
1028 .await;
1029
1030 f.create(&f.owner, &spec("steid"))
1031 .await
1032 .expect("the name should be free again");
1033 }
1034
1035 /// The one test that runs the real adapter. Everything above proves the use case's
1036 /// logic against a fake; this proves the record and the directory actually both
1037 /// appear when it is wired to disk.
1038 #[tokio::test]
1039 async fn against_real_disk_storage_both_the_row_and_the_repo_appear() {
1040 let f = fixture().await;
1041 let dir = tempfile::TempDir::new().expect("temp dir");
1042 let storage = DiskGitStorage::new(dir.path());
1043
1044 let repo = create_repo(
1045 &f.owner,
1046 &f.handle,
1047 &spec("steid"),
1048 &f.orgs,
1049 &f.memberships,
1050 &f.repos,
1051 &storage,
1052 )
1053 .await
1054 .expect("should create");
1055
1056 assert!(
1057 f.repos
1058 .find_by_id(&repo.id)
1059 .await
1060 .expect("lookup")
1061 .is_some()
1062 );
1063 assert!(dir.path().join("acme").join("steid.git").is_dir());
1064 }
1065
1066 // --- view_repo -------------------------------------------------------------
1067
1068 impl Fixture {
1069 async fn view(&self, actor: &Actor, name: &str) -> Option<RepoView> {
1070 view_repo(
1071 &self.handle,
1072 &RepoName::new(name).expect("valid name"),
1073 actor,
1074 &self.orgs,
1075 &self.memberships,
1076 &self.repos,
1077 )
1078 .await
1079 .expect("lookup should not error")
1080 }
1081
1082 /// Creates a repository and dates it, so an ordering test states its own times
1083 /// rather than depending on how fast it runs.
1084 async fn create_dated(&self, name: &str, seconds: u64) -> Repository {
1085 let repo = self.create_with(Visibility::Public, name).await;
1086 self.repos
1087 .touch(&repo.id, at(seconds))
1088 .await
1089 .expect("touch");
1090 Repository {
1091 updated_at: at(seconds),
1092 ..repo
1093 }
1094 }
1095
1096 async fn create_with(&self, visibility: Visibility, name: &str) -> Repository {
1097 self.create(
1098 &self.owner,
1099 &NewRepo {
1100 name: name.to_owned(),
1101 description: None,
1102 visibility,
1103 },
1104 )
1105 .await
1106 .expect("should create")
1107 }
1108 }
1109
1110 #[tokio::test]
1111 async fn a_public_repository_is_visible_to_anyone() {
1112 let f = fixture().await;
1113 f.create_with(Visibility::Public, "steid").await;
1114
1115 for actor in [&Actor::Anonymous, &f.stranger, &f.member, &f.owner] {
1116 assert!(
1117 f.view(actor, "steid").await.is_some(),
1118 "public repo should be visible to {actor:?}"
1119 );
1120 }
1121 }
1122
1123 #[tokio::test]
1124 async fn a_private_repository_is_absent_for_outsiders() {
1125 // `None`, not an error: distinguishing "forbidden" from "missing" would confirm
1126 // the repository exists and reveal its name.
1127 let f = fixture().await;
1128 f.create_with(Visibility::Private, "secret").await;
1129
1130 assert!(f.view(&Actor::Anonymous, "secret").await.is_none());
1131 assert!(f.view(&f.stranger, "secret").await.is_none());
1132 }
1133
1134 #[tokio::test]
1135 async fn a_private_repository_is_visible_to_any_member() {
1136 // Seeing is weaker than changing: a member who may not create repositories may
1137 // still read the private ones.
1138 let f = fixture().await;
1139 f.create_with(Visibility::Private, "secret").await;
1140
1141 assert!(f.view(&f.member, "secret").await.is_some());
1142 assert!(f.view(&f.owner, "secret").await.is_some());
1143 }
1144
1145 #[tokio::test]
1146 async fn viewer_is_owner_tracks_the_actor() {
1147 let f = fixture().await;
1148 f.create_with(Visibility::Public, "steid").await;
1149
1150 assert!(
1151 f.view(&f.owner, "steid")
1152 .await
1153 .expect("visible")
1154 .viewer_is_owner
1155 );
1156 for actor in [&Actor::Anonymous, &f.stranger, &f.member] {
1157 assert!(
1158 !f.view(actor, "steid")
1159 .await
1160 .expect("visible")
1161 .viewer_is_owner,
1162 "{actor:?} should not be treated as owner"
1163 );
1164 }
1165 }
1166
1167 #[tokio::test]
1168 async fn an_unknown_repository_is_absent() {
1169 let f = fixture().await;
1170 f.create_with(Visibility::Public, "steid").await;
1171
1172 assert!(f.view(&f.owner, "nothing-here").await.is_none());
1173 }
1174
1175 #[tokio::test]
1176 async fn an_unknown_handle_is_absent() {
1177 let f = fixture().await;
1178 let missing = OrgName::new("nobody").expect("valid handle");
1179
1180 let found = view_repo(
1181 &missing,
1182 &RepoName::new("steid").expect("valid"),
1183 &f.owner,
1184 &f.orgs,
1185 &f.memberships,
1186 &f.repos,
1187 )
1188 .await
1189 .expect("lookup should not error");
1190
1191 assert!(found.is_none());
1192 }
1193
1194 #[tokio::test]
1195 async fn the_view_carries_what_a_page_needs() {
1196 let f = fixture().await;
1197 f.create(
1198 &f.owner,
1199 &NewRepo {
1200 name: "steid".to_owned(),
1201 description: Some("A gitforge.".to_owned()),
1202 visibility: Visibility::Private,
1203 },
1204 )
1205 .await
1206 .expect("should create");
1207
1208 let view = f.view(&f.owner, "steid").await.expect("visible");
1209
1210 assert_eq!(view.handle.as_str(), "acme");
1211 assert_eq!(view.name.as_str(), "steid");
1212 assert_eq!(view.description.as_deref(), Some("A gitforge."));
1213 assert_eq!(view.visibility, Visibility::Private);
1214 }
1215
1216 #[tokio::test]
1217 async fn lookup_is_case_insensitive_through_the_name_type() {
1218 let f = fixture().await;
1219 f.create_with(Visibility::Public, "MyRepo").await;
1220
1221 assert!(f.view(&Actor::Anonymous, "myrepo").await.is_some());
1222 }
1223
1224 // --- list_repos ------------------------------------------------------------
1225
1226 impl Fixture {
1227 async fn list(&self, actor: &Actor) -> Vec<RepoSummary> {
1228 list_repos(
1229 &self.handle,
1230 actor,
1231 &self.orgs,
1232 &self.memberships,
1233 &self.repos,
1234 )
1235 .await
1236 .expect("listing should not error")
1237 .expect("the handle exists")
1238 }
1239
1240 fn names(summaries: &[RepoSummary]) -> Vec<&str> {
1241 summaries.iter().map(|repo| repo.name.as_str()).collect()
1242 }
1243 }
1244
1245 /// Two public and one private, dated so that recency and the alphabet disagree.
1246 ///
1247 /// `zebra` is the most recent and `alpha` the oldest, so a listing that came back
1248 /// alphabetical would be visibly wrong rather than accidentally right.
1249 async fn mixed() -> Fixture {
1250 let f = fixture().await;
1251 f.create_dated("zebra", 3_000).await;
1252 f.repos
1253 .save(&Repository {
1254 updated_at: at(2_000),
1255 ..f.create_with(Visibility::Private, "secret").await
1256 })
1257 .await
1258 .expect("date the private repo");
1259 f.create_dated("alpha", 1_000).await;
1260 f
1261 }
1262
1263 #[tokio::test]
1264 async fn outsiders_see_only_public_repositories() {
1265 let f = mixed().await;
1266
1267 for actor in [&Actor::Anonymous, &f.stranger] {
1268 let listed = f.list(actor).await;
1269 assert_eq!(
1270 Fixture::names(&listed),
1271 vec!["zebra", "alpha"],
1272 "{actor:?} should see only the public repositories"
1273 );
1274 }
1275 }
1276
1277 #[tokio::test]
1278 async fn members_and_owners_see_private_repositories_too() {
1279 let f = mixed().await;
1280
1281 for actor in [&f.member, &f.owner] {
1282 let listed = f.list(actor).await;
1283 assert_eq!(
1284 Fixture::names(&listed),
1285 vec!["zebra", "secret", "alpha"],
1286 "{actor:?} should see everything"
1287 );
1288 }
1289 }
1290
1291 #[tokio::test]
1292 async fn listings_are_ordered_by_recency_not_by_name() {
1293 // Changed deliberately from alphabetical: the profile is a portfolio, and
1294 // alphabetical is a filing rule that puts `dotfiles` above the thing being built.
1295 let f = mixed().await;
1296
1297 assert_eq!(
1298 Fixture::names(&f.list(&f.owner).await),
1299 vec!["zebra", "secret", "alpha"]
1300 );
1301 }
1302
1303 #[tokio::test]
1304 async fn repositories_updated_in_the_same_second_are_ordered_by_name() {
1305 // Every repository that predates `updated_at` shares one timestamp, so without a
1306 // tiebreak a profile would reshuffle itself between page loads.
1307 let f = fixture().await;
1308 for name in ["zebra", "alpha", "middle"] {
1309 f.create_dated(name, 1_000).await;
1310 }
1311
1312 assert_eq!(
1313 Fixture::names(&f.list(&f.owner).await),
1314 vec!["alpha", "middle", "zebra"]
1315 );
1316 }
1317
1318 #[tokio::test]
1319 async fn a_new_repository_is_dated_when_it_was_created() {
1320 let f = fixture().await;
1321 let before = SystemTime::now();
1322
1323 let repo = f.create_with(Visibility::Public, "steid").await;
1324
1325 assert!(repo.updated_at >= before);
1326 assert!(repo.updated_at <= SystemTime::now());
1327 assert!(!repo.pinned, "nothing leads a profile by being created");
1328 }
1329
1330 #[tokio::test]
1331 async fn a_viewer_who_may_see_nothing_gets_an_empty_list() {
1332 // Not a count, not a hint. Either would leak that private repositories exist
1333 // and how many.
1334 let f = fixture().await;
1335 f.create_with(Visibility::Private, "secret").await;
1336 f.create_with(Visibility::Private, "other").await;
1337
1338 assert!(f.list(&Actor::Anonymous).await.is_empty());
1339 }
1340
1341 #[tokio::test]
1342 async fn a_handle_with_no_repositories_lists_nothing() {
1343 let f = fixture().await;
1344
1345 assert!(f.list(&f.owner).await.is_empty());
1346 }
1347
1348 #[tokio::test]
1349 async fn an_unknown_handle_is_none_not_an_empty_list() {
1350 // `/api` has to answer 404 for a handle that does not exist rather than `[]`.
1351 let f = fixture().await;
1352 let missing = OrgName::new("nobody").expect("valid handle");
1353
1354 let listed = list_repos(&missing, &f.owner, &f.orgs, &f.memberships, &f.repos)
1355 .await
1356 .expect("listing should not error");
1357
1358 assert!(listed.is_none());
1359 }
1360
1361 #[tokio::test]
1362 async fn a_summary_carries_what_a_listing_renders() {
1363 let f = fixture().await;
1364 f.create(
1365 &f.owner,
1366 &NewRepo {
1367 name: "steid".to_owned(),
1368 description: Some("A gitforge.".to_owned()),
1369 visibility: Visibility::Private,
1370 },
1371 )
1372 .await
1373 .expect("should create");
1374
1375 let listed = f.list(&f.owner).await;
1376 let summary = listed.first().expect("one repository");
1377
1378 assert_eq!(summary.name.as_str(), "steid");
1379 assert_eq!(summary.description.as_deref(), Some("A gitforge."));
1380 assert_eq!(summary.visibility, Visibility::Private);
1381 // The profile dates each row and picks its lead out of the listing, so both
1382 // travel with the summary rather than costing a second lookup.
1383 assert!(!summary.pinned);
1384 assert!(summary.updated_at <= SystemTime::now());
1385 }
1386
1387 #[tokio::test]
1388 async fn listing_only_covers_the_handle_asked_for() {
1389 let f = fixture().await;
1390 f.create_with(Visibility::Public, "mine").await;
1391
1392 let other = Organization::new(OrgId::generate(), "other-org", None).expect("valid org");
1393 f.orgs.save(&other).await.expect("save org");
1394 f.repos
1395 .save(
1396 &Repository::new(
1397 RepoId::generate(),
1398 other.id.clone(),
1399 "theirs",
1400 None,
1401 Visibility::Public,
1402 SystemTime::now(),
1403 )
1404 .expect("valid repo"),
1405 )
1406 .await
1407 .expect("save repo");
1408
1409 assert_eq!(
1410 Fixture::names(&f.list(&Actor::Anonymous).await),
1411 vec!["mine"]
1412 );
1413 }
1414 // --- update_repo -----------------------------------------------------------
1415
1416 impl Fixture {
1417 async fn update(
1418 &self,
1419 actor: &Actor,
1420 name: &str,
1421 description: Option<&str>,
1422 visibility: Visibility,
1423 ) -> Result<Repository> {
1424 update_repo(
1425 actor,
1426 &self.handle,
1427 &RepoName::new(name).expect("valid name"),
1428 &RepoEdit {
1429 description: description.map(str::to_owned),
1430 visibility,
1431 pinned: false,
1432 },
1433 &self.orgs,
1434 &self.memberships,
1435 &self.repos,
1436 )
1437 .await
1438 }
1439
1440 async fn stored(&self, name: &str) -> Option<Repository> {
1441 let org = self
1442 .orgs
1443 .find_by_name(&self.handle)
1444 .await
1445 .expect("lookup")
1446 .expect("the handle exists");
1447
1448 self.repos
1449 .find_by_org_and_name(&org.id, &RepoName::new(name).expect("valid name"))
1450 .await
1451 .expect("lookup")
1452 }
1453 }
1454
1455 #[tokio::test]
1456 async fn the_owner_changes_the_description_and_the_visibility() {
1457 let f = fixture().await;
1458 f.create_with(Visibility::Public, "steid").await;
1459
1460 let updated = f
1461 .update(
1462 &f.owner,
1463 "steid",
1464 Some(" A gitforge. "),
1465 Visibility::Private,
1466 )
1467 .await
1468 .expect("should update");
1469
1470 assert_eq!(updated.description.as_deref(), Some("A gitforge."));
1471 assert_eq!(updated.visibility, Visibility::Private);
1472
1473 let stored = f.stored("steid").await.expect("still there");
1474 assert_eq!(stored.description.as_deref(), Some("A gitforge."));
1475 assert_eq!(stored.visibility, Visibility::Private);
1476 }
1477
1478 #[tokio::test]
1479 async fn a_description_can_be_cleared() {
1480 let f = fixture().await;
1481 f.create(
1482 &f.owner,
1483 &NewRepo {
1484 name: "steid".to_owned(),
1485 description: Some("A gitforge.".to_owned()),
1486 visibility: Visibility::Public,
1487 },
1488 )
1489 .await
1490 .expect("should create");
1491
1492 f.update(&f.owner, "steid", None, Visibility::Public)
1493 .await
1494 .expect("should update");
1495
1496 assert_eq!(
1497 f.stored("steid").await.expect("still there").description,
1498 None
1499 );
1500 }
1501
1502 #[tokio::test]
1503 async fn an_update_never_touches_the_name_or_the_directory() {
1504 // Renaming is a directory move, not a column update, so it is deliberately not
1505 // offered here — and an update must not disturb what is on disk.
1506 let f = fixture().await;
1507 let created = f.create_with(Visibility::Public, "steid").await;
1508
1509 let updated = f
1510 .update(&f.owner, "steid", Some("changed"), Visibility::Private)
1511 .await
1512 .expect("should update");
1513
1514 assert_eq!(updated.name, created.name);
1515 assert_eq!(updated.id, created.id);
1516 assert!(f.storage.contains(&f.handle, &created.name));
1517 assert_eq!(f.storage.len(), 1);
1518 }
1519
1520 #[tokio::test]
1521 async fn a_member_who_is_not_the_owner_cannot_change_a_repository() {
1522 // The repository is public, so the member can see it; seeing is not changing.
1523 let f = fixture().await;
1524 f.create_with(Visibility::Public, "steid").await;
1525
1526 let error = f
1527 .update(&f.member, "steid", Some("mine now"), Visibility::Private)
1528 .await
1529 .expect_err("should refuse");
1530
1531 assert!(matches!(error, Error::Domain(DomainError::Forbidden)));
1532 assert_eq!(
1533 f.stored("steid").await.expect("untouched").visibility,
1534 Visibility::Public
1535 );
1536 }
1537
1538 #[tokio::test]
1539 async fn a_stranger_and_an_anonymous_visitor_cannot_change_a_repository() {
1540 let f = fixture().await;
1541 f.create_with(Visibility::Public, "steid").await;
1542
1543 for actor in [&Actor::Anonymous, &f.stranger] {
1544 let error = f
1545 .update(actor, "steid", Some("mine now"), Visibility::Private)
1546 .await
1547 .expect_err("should refuse");
1548
1549 assert!(
1550 matches!(error, Error::Domain(DomainError::Forbidden)),
1551 "{actor:?} should be refused"
1552 );
1553 }
1554
1555 assert_eq!(
1556 f.stored("steid").await.expect("untouched").description,
1557 None
1558 );
1559 }
1560
1561 #[tokio::test]
1562 async fn a_private_repository_is_not_found_rather_than_forbidden_for_an_outsider() {
1563 // The established rule: "forbidden" would confirm that a private repository by
1564 // that name exists, which is exactly what private is protecting.
1565 let f = fixture().await;
1566 f.create_with(Visibility::Private, "secret").await;
1567
1568 for actor in [&Actor::Anonymous, &f.stranger] {
1569 let error = f
1570 .update(actor, "secret", None, Visibility::Public)
1571 .await
1572 .expect_err("should refuse");
1573
1574 assert!(
1575 matches!(
1576 error,
1577 Error::Domain(DomainError::NotFound {
1578 entity: "repository"
1579 })
1580 ),
1581 "{actor:?} should be told it does not exist"
1582 );
1583 }
1584
1585 assert_eq!(
1586 f.stored("secret").await.expect("untouched").visibility,
1587 Visibility::Private
1588 );
1589 }
1590
1591 #[tokio::test]
1592 async fn an_unknown_repository_or_handle_is_not_found() {
1593 let f = fixture().await;
1594
1595 let error = f
1596 .update(&f.owner, "nothing-here", None, Visibility::Public)
1597 .await
1598 .expect_err("should refuse");
1599
1600 assert!(matches!(
1601 error,
1602 Error::Domain(DomainError::NotFound {
1603 entity: "repository"
1604 })
1605 ));
1606
1607 let missing = OrgName::new("nobody").expect("valid handle");
1608 let error = update_repo(
1609 &f.owner,
1610 &missing,
1611 &RepoName::new("steid").expect("valid"),
1612 &RepoEdit {
1613 description: None,
1614 visibility: Visibility::Public,
1615 pinned: false,
1616 },
1617 &f.orgs,
1618 &f.memberships,
1619 &f.repos,
1620 )
1621 .await
1622 .expect_err("should refuse");
1623
1624 assert!(matches!(
1625 error,
1626 Error::Domain(DomainError::NotFound {
1627 entity: "repository"
1628 })
1629 ));
1630 }
1631
1632 #[tokio::test]
1633 async fn an_over_long_description_is_rejected_and_changes_nothing() {
1634 let f = fixture().await;
1635 f.create_with(Visibility::Public, "steid").await;
1636 let long = "a".repeat(Repository::MAX_DESCRIPTION_LEN + 1);
1637
1638 let error = f
1639 .update(&f.owner, "steid", Some(&long), Visibility::Private)
1640 .await
1641 .expect_err("should reject");
1642
1643 assert!(matches!(
1644 error,
1645 Error::Domain(DomainError::Validation { .. })
1646 ));
1647 let stored = f.stored("steid").await.expect("untouched");
1648 assert_eq!(stored.description, None);
1649 assert_eq!(stored.visibility, Visibility::Public);
1650 }
1651
1652 #[tokio::test]
1653 async fn making_a_public_repository_private_hides_it_from_outsiders() {
1654 // The hole this closes: someone who published by accident can un-publish.
1655 let f = fixture().await;
1656 f.create_with(Visibility::Public, "oops").await;
1657 assert!(f.view(&Actor::Anonymous, "oops").await.is_some());
1658
1659 f.update(&f.owner, "oops", None, Visibility::Private)
1660 .await
1661 .expect("should update");
1662
1663 assert!(
1664 f.view(&Actor::Anonymous, "oops").await.is_none(),
1665 "it should be absent, not merely unlinked"
1666 );
1667 assert!(f.list(&Actor::Anonymous).await.is_empty());
1668 assert!(f.view(&f.owner, "oops").await.is_some());
1669 }
1670
1671 #[tokio::test]
1672 async fn making_a_private_repository_public_reveals_it() {
1673 let f = fixture().await;
1674 f.create_with(Visibility::Private, "secret").await;
1675
1676 f.update(&f.owner, "secret", None, Visibility::Public)
1677 .await
1678 .expect("should update");
1679
1680 assert!(f.view(&Actor::Anonymous, "secret").await.is_some());
1681 assert_eq!(
1682 Fixture::names(&f.list(&Actor::Anonymous).await),
1683 vec!["secret"]
1684 );
1685 }
1686
1687 // --- pinning ---------------------------------------------------------------
1688
1689 impl Fixture {
1690 /// Sets the pin, leaving everything else as stored.
1691 async fn set_pin(&self, actor: &Actor, name: &str, pinned: bool) -> Result<Repository> {
1692 let existing = self.stored(name).await.expect("the repository exists");
1693
1694 update_repo(
1695 actor,
1696 &self.handle,
1697 &existing.name,
1698 &RepoEdit {
1699 description: existing.description.clone(),
1700 visibility: existing.visibility,
1701 pinned,
1702 },
1703 &self.orgs,
1704 &self.memberships,
1705 &self.repos,
1706 )
1707 .await
1708 }
1709
1710 async fn pinned_names(&self) -> Vec<String> {
1711 self.list(&self.owner)
1712 .await
1713 .into_iter()
1714 .filter(|summary| summary.pinned)
1715 .map(|summary| summary.name.to_string())
1716 .collect()
1717 }
1718 }
1719
1720 #[tokio::test]
1721 async fn the_owner_pins_a_repository() {
1722 let f = fixture().await;
1723 f.create_with(Visibility::Public, "steid").await;
1724
1725 let pinned = f
1726 .set_pin(&f.owner, "steid", true)
1727 .await
1728 .expect("should pin");
1729
1730 assert!(pinned.pinned);
1731 assert_eq!(f.pinned_names().await, vec!["steid".to_owned()]);
1732 }
1733
1734 #[tokio::test]
1735 async fn pinning_a_second_repository_unpins_the_first() {
1736 // At most one lead per owner. Two would leave the profile with no rule for
1737 // choosing between them.
1738 let f = fixture().await;
1739 f.create_with(Visibility::Public, "steid").await;
1740 f.create_with(Visibility::Public, "dotfiles").await;
1741 f.set_pin(&f.owner, "steid", true)
1742 .await
1743 .expect("should pin");
1744
1745 f.set_pin(&f.owner, "dotfiles", true)
1746 .await
1747 .expect("should pin");
1748
1749 assert_eq!(f.pinned_names().await, vec!["dotfiles".to_owned()]);
1750 }
1751
1752 #[tokio::test]
1753 async fn re_pinning_the_same_repository_leaves_it_pinned() {
1754 // The unpin sweep skips the repository being saved; getting that wrong would
1755 // make a second save of an unchanged form silently clear the pin.
1756 let f = fixture().await;
1757 f.create_with(Visibility::Public, "steid").await;
1758 f.set_pin(&f.owner, "steid", true)
1759 .await
1760 .expect("should pin");
1761
1762 f.set_pin(&f.owner, "steid", true)
1763 .await
1764 .expect("should pin");
1765
1766 assert_eq!(f.pinned_names().await, vec!["steid".to_owned()]);
1767 }
1768
1769 #[tokio::test]
1770 async fn unpinning_leaves_nothing_pinned() {
1771 let f = fixture().await;
1772 f.create_with(Visibility::Public, "steid").await;
1773 f.set_pin(&f.owner, "steid", true)
1774 .await
1775 .expect("should pin");
1776
1777 f.set_pin(&f.owner, "steid", false)
1778 .await
1779 .expect("should unpin");
1780
1781 assert!(f.pinned_names().await.is_empty());
1782 }
1783
1784 #[tokio::test]
1785 async fn pinning_only_reaches_the_owners_own_repositories() {
1786 // The sweep is scoped to the org. Another owner's lead is not this owner's to
1787 // clear.
1788 let f = fixture().await;
1789 f.create_with(Visibility::Public, "steid").await;
1790
1791 let other = Organization::new(OrgId::generate(), "other-org", None).expect("valid org");
1792 f.orgs.save(&other).await.expect("save org");
1793 let mut theirs = Repository::new(
1794 RepoId::generate(),
1795 other.id.clone(),
1796 "theirs",
1797 None,
1798 Visibility::Public,
1799 SystemTime::now(),
1800 )
1801 .expect("valid repo");
1802 theirs.pinned = true;
1803 f.repos.save(&theirs).await.expect("save repo");
1804
1805 f.set_pin(&f.owner, "steid", true)
1806 .await
1807 .expect("should pin");
1808
1809 assert!(
1810 f.repos
1811 .find_by_id(&theirs.id)
1812 .await
1813 .expect("lookup")
1814 .expect("still there")
1815 .pinned,
1816 "another owner's lead should be untouched"
1817 );
1818 }
1819
1820 #[tokio::test]
1821 async fn a_member_who_is_not_the_owner_cannot_pin() {
1822 // Pinning is a mutation, and every repository mutation is owner-only.
1823 let f = fixture().await;
1824 f.create_with(Visibility::Public, "steid").await;
1825
1826 for actor in [&f.member, &f.stranger, &Actor::Anonymous] {
1827 let error = f
1828 .set_pin(actor, "steid", true)
1829 .await
1830 .expect_err("should refuse");
1831
1832 assert!(
1833 matches!(error, Error::Domain(DomainError::Forbidden)),
1834 "{actor:?} should be forbidden, got {error:?}"
1835 );
1836 }
1837
1838 assert!(f.pinned_names().await.is_empty());
1839 }
1840
1841 #[tokio::test]
1842 async fn editing_a_repository_does_not_move_its_place_in_the_listing() {
1843 // `updated_at` means "code last landed here". Rewording a description must not
1844 // jump a dormant repository to the top of a portfolio.
1845 let f = fixture().await;
1846 let repo = f.create_dated("steid", 1_000).await;
1847
1848 let updated = f
1849 .update(&f.owner, "steid", Some("A gitforge."), Visibility::Public)
1850 .await
1851 .expect("should update");
1852
1853 assert_eq!(updated.updated_at, repo.updated_at);
1854 }
1855
1856 // --- delete_repo -----------------------------------------------------------
1857
1858 /// Git storage whose `remove` always fails, for the best-effort path.
1859 #[derive(Debug, Default)]
1860 struct FailingRemoveStorage;
1861
1862 impl GitStorage for FailingRemoveStorage {
1863 async fn init_bare(
1864 &self,
1865 _handle: &OrgName,
1866 _name: &RepoName,
1867 ) -> std::result::Result<(), GitStorageError> {
1868 Ok(())
1869 }
1870
1871 async fn remove(
1872 &self,
1873 _handle: &OrgName,
1874 _name: &RepoName,
1875 ) -> std::result::Result<(), GitStorageError> {
1876 Err(GitStorageError::backend("remove failed on purpose"))
1877 }
1878
1879 async fn rename(
1880 &self,
1881 _handle: &OrgName,
1882 _from: &RepoName,
1883 _to: &RepoName,
1884 ) -> std::result::Result<(), GitStorageError> {
1885 Ok(())
1886 }
1887
1888 async fn set_default_branch(
1889 &self,
1890 _handle: &OrgName,
1891 _name: &RepoName,
1892 _branch: &RefName,
1893 ) -> std::result::Result<(), GitStorageError> {
1894 Ok(())
1895 }
1896
1897 fn repo_path(&self, handle: &OrgName, name: &RepoName) -> std::path::PathBuf {
1898 std::path::PathBuf::from(format!("{handle}/{name}.git"))
1899 }
1900 }
1901
1902 impl Fixture {
1903 async fn delete(&self, actor: &Actor, name: &str) -> Result<()> {
1904 delete_repo(
1905 actor,
1906 &self.handle,
1907 &RepoName::new(name).expect("valid name"),
1908 &self.orgs,
1909 &self.memberships,
1910 &self.repos,
1911 &self.storage,
1912 )
1913 .await
1914 }
1915 }
1916
1917 #[tokio::test]
1918 async fn the_owner_deletes_the_record_and_the_bare_repo() {
1919 let f = fixture().await;
1920 f.create_with(Visibility::Public, "steid").await;
1921
1922 f.delete(&f.owner, "steid").await.expect("should delete");
1923
1924 assert!(f.stored("steid").await.is_none());
1925 assert!(f.storage.is_empty(), "the directory should be gone too");
1926 assert!(f.view(&f.owner, "steid").await.is_none());
1927 assert!(f.list(&f.owner).await.is_empty());
1928 }
1929
1930 #[tokio::test]
1931 async fn a_non_owner_deletes_neither_the_record_nor_the_directory() {
1932 let f = fixture().await;
1933 let repo = f.create_with(Visibility::Public, "steid").await;
1934
1935 for actor in [&Actor::Anonymous, &f.stranger, &f.member] {
1936 let error = f.delete(actor, "steid").await.expect_err("should refuse");
1937
1938 assert!(
1939 matches!(error, Error::Domain(DomainError::Forbidden)),
1940 "{actor:?} should be refused"
1941 );
1942 }
1943
1944 assert!(f.stored("steid").await.is_some());
1945 assert!(f.storage.contains(&f.handle, &repo.name));
1946 }
1947
1948 #[tokio::test]
1949 async fn a_private_repository_is_not_found_for_an_outsider_asking_to_delete_it() {
1950 let f = fixture().await;
1951 let repo = f.create_with(Visibility::Private, "secret").await;
1952
1953 let error = f
1954 .delete(&f.stranger, "secret")
1955 .await
1956 .expect_err("should refuse");
1957
1958 assert!(matches!(
1959 error,
1960 Error::Domain(DomainError::NotFound {
1961 entity: "repository"
1962 })
1963 ));
1964 assert!(f.stored("secret").await.is_some());
1965 assert!(f.storage.contains(&f.handle, &repo.name));
1966 }
1967
1968 #[tokio::test]
1969 async fn deleting_a_repository_that_does_not_exist_is_not_found() {
1970 let f = fixture().await;
1971
1972 let error = f
1973 .delete(&f.owner, "nothing-here")
1974 .await
1975 .expect_err("should refuse");
1976
1977 assert!(matches!(
1978 error,
1979 Error::Domain(DomainError::NotFound {
1980 entity: "repository"
1981 })
1982 ));
1983 }
1984
1985 #[tokio::test]
1986 async fn deleting_one_repository_leaves_the_others_alone() {
1987 let f = fixture().await;
1988 f.create_with(Visibility::Public, "keep").await;
1989 f.create_with(Visibility::Public, "drop").await;
1990
1991 f.delete(&f.owner, "drop").await.expect("should delete");
1992
1993 assert_eq!(Fixture::names(&f.list(&f.owner).await), vec!["keep"]);
1994 assert_eq!(f.storage.len(), 1);
1995 }
1996
1997 #[tokio::test]
1998 async fn a_name_freed_by_deletion_can_be_created_again() {
1999 let f = fixture().await;
2000 f.create_with(Visibility::Public, "steid").await;
2001 f.delete(&f.owner, "steid").await.expect("should delete");
2002
2003 let recreated = f
2004 .create(&f.owner, &spec("steid"))
2005 .await
2006 .expect("the name should be free again");
2007
2008 assert!(f.storage.contains(&f.handle, &recreated.name));
2009 }
2010
2011 #[tokio::test]
2012 async fn a_directory_that_will_not_delete_still_reports_success() {
2013 // The row goes first and is already gone; as far as Steid is concerned the
2014 // repository is deleted, and there is nothing the caller could do about the
2015 // leftover directory. The failure is logged, not returned.
2016 let f = fixture().await;
2017 f.create_with(Visibility::Public, "steid").await;
2018
2019 delete_repo(
2020 &f.owner,
2021 &f.handle,
2022 &RepoName::new("steid").expect("valid"),
2023 &f.orgs,
2024 &f.memberships,
2025 &f.repos,
2026 &FailingRemoveStorage,
2027 )
2028 .await
2029 .expect("should still report success");
2030
2031 assert!(f.stored("steid").await.is_none());
2032 }
2033
2034 /// The real adapter, so that "the directory is gone" is more than a fake's opinion.
2035 #[tokio::test]
2036 async fn against_real_disk_storage_delete_removes_the_directory() {
2037 let f = fixture().await;
2038 let dir = tempfile::TempDir::new().expect("temp dir");
2039 let storage = DiskGitStorage::new(dir.path());
2040
2041 create_repo(
2042 &f.owner,
2043 &f.handle,
2044 &spec("steid"),
2045 &f.orgs,
2046 &f.memberships,
2047 &f.repos,
2048 &storage,
2049 )
2050 .await
2051 .expect("should create");
2052 assert!(dir.path().join("acme").join("steid.git").is_dir());
2053
2054 delete_repo(
2055 &f.owner,
2056 &f.handle,
2057 &RepoName::new("steid").expect("valid"),
2058 &f.orgs,
2059 &f.memberships,
2060 &f.repos,
2061 &storage,
2062 )
2063 .await
2064 .expect("should delete");
2065
2066 assert!(!dir.path().join("acme").join("steid.git").exists());
2067 assert!(f.stored("steid").await.is_none());
2068 }
2069
2070 // --- rename_repo -----------------------------------------------------------
2071
2072 /// An in-memory repository whose `save` fails once armed, for the compensation path.
2073 ///
2074 /// Delegates the rest, unlike [`FailingRepoRepo`], because a rename has to *find*
2075 /// the repository before it can fail to save it.
2076 #[derive(Debug, Default)]
2077 struct SaveFailsRepoRepo {
2078 inner: InMemoryRepoRepo,
2079 armed: std::sync::atomic::AtomicBool,
2080 }
2081
2082 impl RepoRepository for SaveFailsRepoRepo {
2083 async fn find_by_id(&self, id: &RepoId) -> RepositoryResult<Option<Repository>> {
2084 self.inner.find_by_id(id).await
2085 }
2086
2087 async fn find_by_org_and_name(
2088 &self,
2089 org_id: &OrgId,
2090 name: &RepoName,
2091 ) -> RepositoryResult<Option<Repository>> {
2092 self.inner.find_by_org_and_name(org_id, name).await
2093 }
2094
2095 async fn list_by_org(&self, org_id: &OrgId) -> RepositoryResult<Vec<Repository>> {
2096 self.inner.list_by_org(org_id).await
2097 }
2098
2099 async fn save(&self, repo: &Repository) -> RepositoryResult<()> {
2100 if self.armed.load(std::sync::atomic::Ordering::SeqCst) {
2101 return Err(RepositoryError::backend("save failed on purpose"));
2102 }
2103 self.inner.save(repo).await
2104 }
2105
2106 async fn touch(&self, id: &RepoId, now: SystemTime) -> RepositoryResult<()> {
2107 self.inner.touch(id, now).await
2108 }
2109
2110 async fn delete(&self, id: &RepoId) -> RepositoryResult<()> {
2111 self.inner.delete(id).await
2112 }
2113
2114 async fn fail_interrupted_imports(&self, reason: &str) -> RepositoryResult<u64> {
2115 self.inner.fail_interrupted_imports(reason).await
2116 }
2117 }
2118
2119 impl Fixture {
2120 async fn rename(&self, actor: &Actor, name: &str, to: &str) -> Result<Repository> {
2121 rename_repo(
2122 actor,
2123 &self.handle,
2124 &RepoName::new(name).expect("valid name"),
2125 to,
2126 &self.orgs,
2127 &self.memberships,
2128 &self.repos,
2129 &self.storage,
2130 )
2131 .await
2132 }
2133 }
2134
2135 #[tokio::test]
2136 async fn the_owner_renames_the_record_and_the_directory() {
2137 let f = fixture().await;
2138 f.create_with(Visibility::Public, "steid").await;
2139
2140 let renamed = f
2141 .rename(&f.owner, "steid", "forge")
2142 .await
2143 .expect("should rename");
2144
2145 assert_eq!(renamed.name.as_str(), "forge");
2146 assert!(f.stored("forge").await.is_some());
2147 assert!(f.stored("steid").await.is_none());
2148 assert!(f.storage.contains(&f.handle, &renamed.name));
2149 assert!(
2150 !f.storage
2151 .contains(&f.handle, &RepoName::from_trusted("steid"))
2152 );
2153 }
2154
2155 #[tokio::test]
2156 async fn a_rename_keeps_everything_except_the_name() {
2157 // Including `updated_at`: renaming is not code landing, so a portfolio must not
2158 // reorder itself because somebody tidied a name.
2159 let f = fixture().await;
2160 let before = f.create_dated("steid", 1_000).await;
2161 f.set_pin(&f.owner, "steid", true)
2162 .await
2163 .expect("should pin");
2164
2165 let renamed = f
2166 .rename(&f.owner, "steid", "forge")
2167 .await
2168 .expect("should rename");
2169
2170 assert_eq!(renamed.id, before.id);
2171 assert_eq!(renamed.updated_at, at(1_000));
2172 assert_eq!(renamed.visibility, before.visibility);
2173 assert!(renamed.pinned, "a pinned repository stays the lead");
2174 }
2175
2176 #[tokio::test]
2177 async fn renaming_normalises_the_new_name() {
2178 let f = fixture().await;
2179 f.create_with(Visibility::Public, "steid").await;
2180
2181 let renamed = f
2182 .rename(&f.owner, "steid", " MyForge ")
2183 .await
2184 .expect("should rename");
2185
2186 assert_eq!(renamed.name.as_str(), "myforge");
2187 }
2188
2189 #[tokio::test]
2190 async fn renaming_to_the_same_name_changes_nothing() {
2191 // The name normalises, so `Steid` submitted for `steid` is a confirmation, not
2192 // a collision with itself.
2193 let f = fixture().await;
2194 f.create_with(Visibility::Public, "steid").await;
2195
2196 let renamed = f
2197 .rename(&f.owner, "steid", "Steid")
2198 .await
2199 .expect("should be a no-op");
2200
2201 assert_eq!(renamed.name.as_str(), "steid");
2202 assert!(f.storage.contains(&f.handle, &renamed.name));
2203 }
2204
2205 #[tokio::test]
2206 async fn renaming_onto_an_existing_repository_is_refused_and_moves_nothing() {
2207 let f = fixture().await;
2208 f.create_with(Visibility::Public, "steid").await;
2209 f.create_with(Visibility::Public, "forge").await;
2210
2211 let error = f
2212 .rename(&f.owner, "steid", "forge")
2213 .await
2214 .expect_err("should refuse");
2215
2216 assert!(matches!(
2217 error,
2218 Error::Domain(DomainError::AlreadyExists { .. })
2219 ));
2220 assert!(f.stored("steid").await.is_some());
2221 assert!(
2222 f.storage
2223 .contains(&f.handle, &RepoName::from_trusted("steid"))
2224 );
2225 }
2226
2227 #[tokio::test]
2228 async fn an_invalid_new_name_is_rejected_before_anything_moves() {
2229 let f = fixture().await;
2230 f.create_with(Visibility::Public, "steid").await;
2231
2232 for bad in ["../escape", "", "new", "forge.git"] {
2233 let error = f
2234 .rename(&f.owner, "steid", bad)
2235 .await
2236 .expect_err("should reject");
2237
2238 assert!(
2239 matches!(error, Error::Domain(DomainError::Validation { .. })),
2240 "expected {bad:?} to be rejected"
2241 );
2242 }
2243
2244 assert!(f.stored("steid").await.is_some());
2245 assert!(
2246 f.storage
2247 .contains(&f.handle, &RepoName::from_trusted("steid"))
2248 );
2249 }
2250
2251 #[tokio::test]
2252 async fn only_the_owner_can_rename() {
2253 let f = fixture().await;
2254 f.create_with(Visibility::Public, "steid").await;
2255
2256 for actor in [&Actor::Anonymous, &f.stranger, &f.member] {
2257 let error = f
2258 .rename(actor, "steid", "forge")
2259 .await
2260 .expect_err("should refuse");
2261
2262 assert!(
2263 matches!(error, Error::Domain(DomainError::Forbidden)),
2264 "{actor:?} should be forbidden, got {error:?}"
2265 );
2266 }
2267
2268 assert!(f.stored("steid").await.is_some());
2269 }
2270
2271 #[tokio::test]
2272 async fn a_private_repository_is_not_found_rather_than_forbidden_for_an_outsider_renaming_it() {
2273 let f = fixture().await;
2274 f.create_with(Visibility::Private, "secret").await;
2275
2276 for actor in [&Actor::Anonymous, &f.stranger] {
2277 let error = f
2278 .rename(actor, "secret", "forge")
2279 .await
2280 .expect_err("should refuse");
2281
2282 assert!(
2283 matches!(error, Error::Domain(DomainError::NotFound { .. })),
2284 "{actor:?} should see a 404, got {error:?}"
2285 );
2286 }
2287 }
2288
2289 #[tokio::test]
2290 async fn a_failed_record_write_moves_the_directory_back() {
2291 // The compensation. Without it the repository is on disk under a name no row
2292 // names, and every page 404s.
2293 let f = fixture().await;
2294 let repos = SaveFailsRepoRepo::default();
2295 let storage = InMemoryGitStorage::new();
2296
2297 create_repo(
2298 &f.owner,
2299 &f.handle,
2300 &spec("steid"),
2301 &f.orgs,
2302 &f.memberships,
2303 &repos,
2304 &storage,
2305 )
2306 .await
2307 .expect("should create");
2308
2309 repos.armed.store(true, std::sync::atomic::Ordering::SeqCst);
2310
2311 let error = rename_repo(
2312 &f.owner,
2313 &f.handle,
2314 &RepoName::new("steid").expect("valid"),
2315 "forge",
2316 &f.orgs,
2317 &f.memberships,
2318 &repos,
2319 &storage,
2320 )
2321 .await
2322 .expect_err("the save should fail");
2323
2324 assert!(matches!(error, Error::Repository(_)));
2325 assert!(
2326 storage.contains(&f.handle, &RepoName::from_trusted("steid")),
2327 "the directory should be back where the row still says it is"
2328 );
2329 assert!(!storage.contains(&f.handle, &RepoName::from_trusted("forge")));
2330 }
2331
2332 #[tokio::test]
2333 async fn a_name_freed_by_a_rename_can_be_used_again() {
2334 let f = fixture().await;
2335 f.create_with(Visibility::Public, "steid").await;
2336
2337 f.rename(&f.owner, "steid", "forge")
2338 .await
2339 .expect("should rename");
2340
2341 f.create(&f.owner, &spec("steid"))
2342 .await
2343 .expect("the old name is free again");
2344 }
2345
2346 #[tokio::test]
2347 async fn against_real_disk_storage_rename_moves_the_directory() {
2348 let f = fixture().await;
2349 let dir = tempfile::tempdir().expect("tempdir");
2350 let storage = DiskGitStorage::new(dir.path());
2351
2352 create_repo(
2353 &f.owner,
2354 &f.handle,
2355 &spec("steid"),
2356 &f.orgs,
2357 &f.memberships,
2358 &f.repos,
2359 &storage,
2360 )
2361 .await
2362 .expect("should create");
2363
2364 rename_repo(
2365 &f.owner,
2366 &f.handle,
2367 &RepoName::new("steid").expect("valid"),
2368 "forge",
2369 &f.orgs,
2370 &f.memberships,
2371 &f.repos,
2372 &storage,
2373 )
2374 .await
2375 .expect("should rename");
2376
2377 assert!(
2378 dir.path()
2379 .join("acme")
2380 .join("forge.git")
2381 .join("HEAD")
2382 .is_file()
2383 );
2384 assert!(!dir.path().join("acme").join("steid.git").exists());
2385 }
2386
2387 // --- set_default_branch ------------------------------------------------------
2388
2389 impl Fixture {
2390 async fn set_head(
2391 &self,
2392 actor: &Actor,
2393 name: &str,
2394 branch: &str,
2395 queries: &InMemoryGitQuery,
2396 ) -> Result<RefName> {
2397 set_default_branch(
2398 actor,
2399 &self.handle,
2400 &RepoName::new(name).expect("valid name"),
2401 branch,
2402 &self.orgs,
2403 &self.memberships,
2404 &self.repos,
2405 queries,
2406 &self.storage,
2407 )
2408 .await
2409 }
2410 }
2411
2412 /// A repository with two branches, `main` being the default.
2413 fn two_branches() -> InMemoryGitQuery {
2414 InMemoryGitQuery::new()
2415 .with_branch_row("main", true, at(2_000))
2416 .with_branch_row("develop", false, at(3_000))
2417 }
2418
2419 #[tokio::test]
2420 async fn the_owner_points_head_at_another_branch() {
2421 let f = fixture().await;
2422 f.create_with(Visibility::Public, "steid").await;
2423
2424 let branch = f
2425 .set_head(&f.owner, "steid", "develop", &two_branches())
2426 .await
2427 .expect("should set");
2428
2429 assert_eq!(branch.as_str(), "develop");
2430 assert_eq!(
2431 f.storage.head(&f.handle, &RepoName::from_trusted("steid")),
2432 Some(RefName::from_trusted("develop"))
2433 );
2434 }
2435
2436 #[tokio::test]
2437 async fn a_branch_the_repository_does_not_have_is_not_found() {
2438 // `symbolic-ref` would accept it and leave every page saying "nothing pushed
2439 // yet", which is why this is checked rather than trusted.
2440 let f = fixture().await;
2441 f.create_with(Visibility::Public, "steid").await;
2442
2443 let error = f
2444 .set_head(&f.owner, "steid", "nothing-here", &two_branches())
2445 .await
2446 .expect_err("should refuse");
2447
2448 assert!(matches!(
2449 error,
2450 Error::Domain(DomainError::NotFound { entity: "branch" })
2451 ));
2452 assert!(
2453 f.storage
2454 .head(&f.handle, &RepoName::from_trusted("steid"))
2455 .is_none()
2456 );
2457 }
2458
2459 #[tokio::test]
2460 async fn a_tag_is_not_a_branch() {
2461 // `branches()` is the list checked against, so a tag of the same shape cannot
2462 // be smuggled into `refs/heads/`.
2463 let f = fixture().await;
2464 f.create_with(Visibility::Public, "steid").await;
2465 let queries = two_branches().with_tag_row("v0.1.0", true, at(4_000));
2466
2467 let error = f
2468 .set_head(&f.owner, "steid", "v0.1.0", &queries)
2469 .await
2470 .expect_err("should refuse");
2471
2472 assert!(matches!(
2473 error,
2474 Error::Domain(DomainError::NotFound { entity: "branch" })
2475 ));
2476 }
2477
2478 #[tokio::test]
2479 async fn an_empty_repository_has_no_branch_to_choose() {
2480 let f = fixture().await;
2481 f.create_with(Visibility::Public, "steid").await;
2482
2483 let error = f
2484 .set_head(&f.owner, "steid", "main", &InMemoryGitQuery::empty())
2485 .await
2486 .expect_err("should refuse");
2487
2488 assert!(matches!(
2489 error,
2490 Error::Domain(DomainError::NotFound { entity: "branch" })
2491 ));
2492 }
2493
2494 #[tokio::test]
2495 async fn a_malformed_branch_name_never_reaches_git() {
2496 let f = fixture().await;
2497 f.create_with(Visibility::Public, "steid").await;
2498
2499 for bad in ["-flag", "main..develop", "with space", ""] {
2500 let error = f
2501 .set_head(&f.owner, "steid", bad, &two_branches())
2502 .await
2503 .expect_err("should reject");
2504
2505 assert!(
2506 matches!(error, Error::Domain(DomainError::Validation { .. })),
2507 "expected {bad:?} to be rejected, got {error:?}"
2508 );
2509 }
2510
2511 assert!(
2512 f.storage
2513 .head(&f.handle, &RepoName::from_trusted("steid"))
2514 .is_none()
2515 );
2516 }
2517
2518 #[tokio::test]
2519 async fn only_the_owner_can_move_head() {
2520 let f = fixture().await;
2521 f.create_with(Visibility::Public, "steid").await;
2522
2523 for actor in [&Actor::Anonymous, &f.stranger, &f.member] {
2524 let error = f
2525 .set_head(actor, "steid", "develop", &two_branches())
2526 .await
2527 .expect_err("should refuse");
2528
2529 assert!(
2530 matches!(error, Error::Domain(DomainError::Forbidden)),
2531 "{actor:?} should be forbidden, got {error:?}"
2532 );
2533 }
2534
2535 assert!(
2536 f.storage
2537 .head(&f.handle, &RepoName::from_trusted("steid"))
2538 .is_none()
2539 );
2540 }
2541
2542 #[tokio::test]
2543 async fn a_private_repository_is_absent_rather_than_forbidden_when_an_outsider_moves_head() {
2544 let f = fixture().await;
2545 f.create_with(Visibility::Private, "secret").await;
2546
2547 for actor in [&Actor::Anonymous, &f.stranger] {
2548 let error = f
2549 .set_head(actor, "secret", "develop", &two_branches())
2550 .await
2551 .expect_err("should refuse");
2552
2553 assert!(
2554 matches!(error, Error::Domain(DomainError::NotFound { .. })),
2555 "{actor:?} should see a 404, got {error:?}"
2556 );
2557 }
2558 }
2559
2560 // --- archiving ---------------------------------------------------------------
2561
2562 impl Fixture {
2563 async fn set_archived(
2564 &self,
2565 actor: &Actor,
2566 name: &str,
2567 archived: bool,
2568 ) -> Result<Repository> {
2569 set_repo_archived(
2570 actor,
2571 &self.handle,
2572 &RepoName::new(name).expect("valid name"),
2573 archived,
2574 &self.orgs,
2575 &self.memberships,
2576 &self.repos,
2577 )
2578 .await
2579 }
2580 }
2581
2582 #[tokio::test]
2583 async fn the_owner_archives_and_unarchives() {
2584 let f = fixture().await;
2585 f.create_with(Visibility::Public, "steid").await;
2586
2587 assert!(
2588 f.set_archived(&f.owner, "steid", true)
2589 .await
2590 .expect("should archive")
2591 .archived
2592 );
2593 assert!(f.stored("steid").await.expect("stored").archived);
2594
2595 assert!(
2596 !f.set_archived(&f.owner, "steid", false)
2597 .await
2598 .expect("should unarchive")
2599 .archived
2600 );
2601 assert!(!f.stored("steid").await.expect("stored").archived);
2602 }
2603
2604 #[tokio::test]
2605 async fn archiving_twice_is_not_an_error() {
2606 // What a double-clicked button does.
2607 let f = fixture().await;
2608 f.create_with(Visibility::Public, "steid").await;
2609
2610 f.set_archived(&f.owner, "steid", true)
2611 .await
2612 .expect("should archive");
2613 f.set_archived(&f.owner, "steid", true)
2614 .await
2615 .expect("should still be fine");
2616
2617 assert!(f.stored("steid").await.expect("stored").archived);
2618 }
2619
2620 #[tokio::test]
2621 async fn archiving_does_not_move_a_repository_up_the_listing() {
2622 // `updated_at` means "code last landed here". Declaring something finished is
2623 // not work on it, and must not float it to the top of a portfolio.
2624 let f = fixture().await;
2625 f.create_dated("steid", 1_000).await;
2626
2627 let archived = f
2628 .set_archived(&f.owner, "steid", true)
2629 .await
2630 .expect("should archive");
2631
2632 assert_eq!(archived.updated_at, at(1_000));
2633 }
2634
2635 #[tokio::test]
2636 async fn archiving_is_orthogonal_to_visibility_and_pinning() {
2637 // Archived says "finished", not "hidden": a private pinned repository keeps both
2638 // when it is archived, and stays visible to the people who could already see it.
2639 let f = fixture().await;
2640 f.create_with(Visibility::Private, "secret").await;
2641 f.set_pin(&f.owner, "secret", true)
2642 .await
2643 .expect("should pin");
2644
2645 let archived = f
2646 .set_archived(&f.owner, "secret", true)
2647 .await
2648 .expect("should archive");
2649
2650 assert_eq!(archived.visibility, Visibility::Private);
2651 assert!(archived.pinned);
2652 assert!(
2653 f.view(&f.member, "secret").await.is_some(),
2654 "a member still sees an archived private repository"
2655 );
2656 }
2657
2658 #[tokio::test]
2659 async fn editing_or_renaming_an_archived_repository_leaves_it_archived() {
2660 // The description form does not carry this field, so it must not clear it.
2661 let f = fixture().await;
2662 f.create_with(Visibility::Public, "steid").await;
2663 f.set_archived(&f.owner, "steid", true)
2664 .await
2665 .expect("should archive");
2666
2667 f.update(&f.owner, "steid", Some("Finished."), Visibility::Public)
2668 .await
2669 .expect("should update");
2670 assert!(f.stored("steid").await.expect("stored").archived);
2671
2672 let renamed = f
2673 .rename(&f.owner, "steid", "forge")
2674 .await
2675 .expect("should rename");
2676 assert!(renamed.archived);
2677 }
2678
2679 #[tokio::test]
2680 async fn only_the_owner_can_archive() {
2681 let f = fixture().await;
2682 f.create_with(Visibility::Public, "steid").await;
2683
2684 for actor in [&Actor::Anonymous, &f.stranger, &f.member] {
2685 let error = f
2686 .set_archived(actor, "steid", true)
2687 .await
2688 .expect_err("should refuse");
2689
2690 assert!(
2691 matches!(error, Error::Domain(DomainError::Forbidden)),
2692 "{actor:?} should be forbidden, got {error:?}"
2693 );
2694 }
2695
2696 assert!(!f.stored("steid").await.expect("stored").archived);
2697 }
2698
2699 #[tokio::test]
2700 async fn a_private_repository_is_absent_rather_than_forbidden_when_an_outsider_archives_it() {
2701 let f = fixture().await;
2702 f.create_with(Visibility::Private, "secret").await;
2703
2704 for actor in [&Actor::Anonymous, &f.stranger] {
2705 let error = f
2706 .set_archived(actor, "secret", true)
2707 .await
2708 .expect_err("should refuse");
2709
2710 assert!(
2711 matches!(error, Error::Domain(DomainError::NotFound { .. })),
2712 "{actor:?} should see a 404, got {error:?}"
2713 );
2714 }
2715 }
2716
2717 #[tokio::test]
2718 async fn a_view_and_a_listing_both_report_archived() {
2719 // Both carry it because both render the badge, and a page that had to read the
2720 // row again per repository would cost a query per row.
2721 let f = fixture().await;
2722 f.create_with(Visibility::Public, "steid").await;
2723 f.set_archived(&f.owner, "steid", true)
2724 .await
2725 .expect("should archive");
2726
2727 assert!(
2728 f.view(&Actor::Anonymous, "steid")
2729 .await
2730 .expect("visible")
2731 .archived
2732 );
2733 assert!(
2734 f.list(&Actor::Anonymous)
2735 .await
2736 .iter()
2737 .any(|repo| repo.name.as_str() == "steid" && repo.archived)
2738 );
2739 }
2740}