steid

@jamesgill /

Rust31.7 KBCode·Blame·History·Raw
1//! Serving the git smart-HTTP protocol.
2//!
3//! The protocol itself belongs to `git http-backend`. What belongs here is the part git
4//! cannot decide: whether this actor may do this to this repository, settled **before**
5//! the backend is spawned. Once pack data is moving, refusing is no longer an option.
6
7use std::time::SystemTime;
8
9use crate::domain::{
10 Actor, DomainError, OrgName, RepoName, RepoWrite,
11 repository::{MembershipRepository, OrgRepository, RepoRepository},
12};
13
14use super::{
15 authz::{is_org_member, is_org_owner},
16 error::Result,
17 port::{ByteStream, GitMethod, GitProtocolServer, GitRequest, GitResponse},
18};
19
20/// A git service, as named in the protocol.
21///
22/// The wire spelling and the enum are kept together because the two must not drift: the
23/// same value decides authorization and is handed to the backend.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum GitService {
26 /// Sends objects to a client. What `git clone` and `git fetch` use.
27 UploadPack,
28 /// Receives objects from a client. What `git push` uses.
29 ReceivePack,
30}
31
32impl GitService {
33 pub fn as_str(self) -> &'static str {
34 match self {
35 Self::UploadPack => "git-upload-pack",
36 Self::ReceivePack => "git-receive-pack",
37 }
38 }
39
40 /// What this service asks permission to do.
41 ///
42 /// The whole authorization surface of the git transport is this function. Adding a
43 /// service without deciding its operation is a compile error, which is the point of
44 /// matching exhaustively rather than defaulting.
45 pub fn operation(self) -> GitOperation {
46 match self {
47 Self::UploadPack => GitOperation::Read,
48 Self::ReceivePack => GitOperation::Write,
49 }
50 }
51}
52
53/// Parsing returns `Result`, never `Option`: an unrecognised service that silently
54/// defaulted to read would eventually default the wrong way.
55impl std::str::FromStr for GitService {
56 type Err = DomainError;
57
58 fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
59 match value {
60 "git-upload-pack" => Ok(Self::UploadPack),
61 "git-receive-pack" => Ok(Self::ReceivePack),
62 other => Err(DomainError::validation(
63 "service",
64 format!("unknown git service {other:?}"),
65 )),
66 }
67 }
68}
69
70/// What a git request wants to do to a repository.
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub enum GitOperation {
73 Read,
74 Write,
75}
76
77/// Which endpoint of the smart protocol is being asked for.
78///
79/// Named by the caller from the route it matched, never parsed out of a URL. Three
80/// routes, three literal values — so a path cannot be coaxed into meaning a different
81/// operation than the one that was authorized.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum GitEndpoint {
84 /// `GET {repo}.git/info/refs?service=…` — the ref advertisement that opens an
85 /// exchange. Carries the service of the operation it is opening, so a push
86 /// advertisement is a write before a single object moves.
87 Advertisement(GitService),
88 /// `POST {repo}.git/{service}` — the negotiation and the pack itself.
89 Rpc(GitService),
90}
91
92impl GitEndpoint {
93 fn service(self) -> GitService {
94 match self {
95 Self::Advertisement(service) | Self::Rpc(service) => service,
96 }
97 }
98
99 fn method(self) -> GitMethod {
100 match self {
101 Self::Advertisement(_) => GitMethod::Get,
102 Self::Rpc(_) => GitMethod::Post,
103 }
104 }
105}
106
107/// The request headers the backend needs to see.
108///
109/// Not every header — only the four that change what git does. Forwarding the rest
110/// would be handing a subprocess arbitrary client input for no benefit.
111#[derive(Debug, Default, Clone, PartialEq, Eq)]
112pub struct GitClientHeaders {
113 pub content_type: Option<String>,
114 /// Real clients gzip a request body once a repository has more than a handful of
115 /// refs. Dropping this makes clones of real repositories fail while a one-ref test
116 /// repository keeps passing.
117 pub content_encoding: Option<String>,
118 pub content_length: Option<String>,
119 /// `version=2` for any modern client. Dropping it downgrades to v0 silently.
120 pub git_protocol: Option<String>,
121}
122
123/// Serves one git protocol request against a repository the actor is allowed to reach.
124///
125/// `Ok(None)` covers **both** "no such repository" and "not allowed to see it", exactly
126/// as [`view_repo`](super::repo::view_repo) does, and the caller must render them
127/// identically — a private repository has to be absent, not merely unclonable.
128///
129/// Reading a public repository is open to anyone. Reading a private one needs any
130/// membership of the owning organisation — seeing is weaker than changing. **Writing
131/// needs `Role::Owner`**, matching every other mutation in Steid: a member's read access
132/// is not permission to rewrite someone's history.
133///
134/// **An archived repository refuses writes to everyone, its owner included.** That is
135/// checked after the owner check, so nobody who could not have pushed anyway learns
136/// that a repository is archived.
137///
138/// The refusal is made here rather than left to `git http-backend` disabling
139/// `receive-pack` by default. That default is configuration, and a default that
140/// helpfully changes is not a permission check.
141#[allow(clippy::too_many_arguments)]
142pub async fn serve_git(
143 handle: &OrgName,
144 name: &RepoName,
145 endpoint: GitEndpoint,
146 headers: GitClientHeaders,
147 body: ByteStream,
148 actor: &Actor,
149 // `pusher` is the handle to hand the backend as `REMOTE_USER`, so the repository's
150 // reflog names who moved a ref. Supplied by the caller rather than resolved here:
151 // the transport has already described the actor for its own purposes, and looking
152 // the same user up again would be two queries per push for a string used once.
153 // Attribution only — nothing is authorized on it, and a read ignores it.
154 pusher: Option<&str>,
155 orgs: &impl OrgRepository,
156 memberships: &impl MembershipRepository,
157 repos: &impl RepoRepository,
158 protocol: &impl GitProtocolServer,
159) -> Result<Option<GitResponse>> {
160 let Some(org) = orgs.find_by_name(handle).await? else {
161 return Ok(None);
162 };
163
164 let Some(repo) = repos.find_by_org_and_name(&org.id, name).await? else {
165 return Ok(None);
166 };
167
168 // Existence is settled before permission, so a push to a repository the actor may
169 // not even see answers "no such repository" rather than "not allowed" — the latter
170 // would confirm it exists.
171 if !repo.visibility.is_public() && !is_org_member(&org, actor, memberships).await? {
172 return Ok(None);
173 }
174
175 let writing = endpoint.service().operation() == GitOperation::Write;
176
177 if writing && !is_org_owner(&org, actor, memberships).await? {
178 return Err(DomainError::Forbidden.into());
179 }
180
181 // Every reason a repository refuses contents, asked in one place —
182 // [`Repository::refuse_writes`] holds both the reasons and their order, so this
183 // path and the settings ones cannot drift apart.
184 //
185 // **After the owner check, not before.** Otherwise a stranger probing a repository
186 // learns it is archived, or that one is being set up, which are facts about it they
187 // have no business being told; this way the only caller who ever sees a refusal is
188 // the one who could otherwise have pushed. A use-case rule rather than a handler
189 // check, so it holds for `/api` and any future transport the same way `Role::Owner`
190 // does.
191 //
192 // Reads are deliberately still allowed, archived or importing. Cloning a repository
193 // whose directory is half-written is not corruption — git either finds the refs or
194 // it does not — and a failed import's directory is removed, so there is nothing
195 // there to read.
196 if writing {
197 repo.refuse_writes(RepoWrite::Contents)?;
198 }
199
200 if writing {
201 // **Authorized write path only.** Every refusal above has already returned, and a
202 // read never reaches here, so nothing a clone does can move a repository up the
203 // profile.
204 //
205 // This records that a push was *authorized*, not that it succeeded: the pack may
206 // still be rejected by the backend, by a hook, or by the client hanging up. The
207 // honest alternative is to wait for the subprocess and inspect its exit — a far
208 // larger change (the response streams, so nothing here sees the end of it) for a
209 // small gain in accuracy on a timestamp that only orders a listing.
210 //
211 // A failure here must not fail the push, exactly as a directory that will not
212 // delete does not fail `delete_repo`: the push is the thing the user asked for,
213 // and a stale sort key is not worth refusing it over.
214 if let Err(error) = repos.touch(&repo.id, SystemTime::now()).await {
215 eprintln!(
216 "steid: push to {}/{} authorized, but its updated_at could not be moved: {error}",
217 org.name, repo.name
218 );
219 }
220 }
221
222 let service = endpoint.service();
223 let path_info = format!("/{}/{}.git", org.name, repo.name);
224
225 // Built here from validated values rather than forwarded from the URL. `OrgName` and
226 // `RepoName` already made traversal impossible, so the backend cannot be pointed at
227 // a path this function did not agree to.
228 let (path_info, query) = match endpoint {
229 GitEndpoint::Advertisement(_) => (
230 format!("{path_info}/info/refs"),
231 format!("service={}", service.as_str()),
232 ),
233 GitEndpoint::Rpc(_) => (format!("{path_info}/{}", service.as_str()), String::new()),
234 };
235
236 let response = protocol
237 .serve(GitRequest {
238 method: endpoint.method(),
239 path_info,
240 query,
241 content_type: headers.content_type,
242 content_encoding: headers.content_encoding,
243 content_length: headers.content_length,
244 git_protocol: headers.git_protocol,
245 // Past the gate above, so this is only ever true for a write that was
246 // authorized. Left false for a read, which never needs it.
247 allow_receive_pack: writing,
248 remote_user: writing.then(|| pusher.unwrap_or("unknown").to_owned()),
249 body,
250 })
251 .await?;
252
253 Ok(Some(response))
254}
255
256#[cfg(test)]
257mod tests {
258 use super::*;
259 use crate::{
260 application::Error,
261 domain::{
262 ImportSource, Membership, MembershipId, OrgId, Organization, RepoId, Repository, Role,
263 UserId, Visibility,
264 },
265 infrastructure::{
266 git::InMemoryGitProtocol,
267 repository::{InMemoryMembershipRepo, InMemoryOrgRepo, InMemoryRepoRepo},
268 },
269 };
270
271 /// When the fixture's repositories were created. Fixed, so a test can tell a
272 /// timestamp that moved from one that never did without racing the clock.
273 const CREATED: SystemTime = SystemTime::UNIX_EPOCH;
274
275 struct Fixture {
276 orgs: InMemoryOrgRepo,
277 memberships: InMemoryMembershipRepo,
278 repos: InMemoryRepoRepo,
279 protocol: InMemoryGitProtocol,
280 owner: Actor,
281 member: Actor,
282 stranger: Actor,
283 handle: OrgName,
284 }
285
286 async fn fixture() -> Fixture {
287 let orgs = InMemoryOrgRepo::new();
288 let memberships = InMemoryMembershipRepo::new();
289
290 let org = Organization::new(OrgId::generate(), "acme", None).expect("valid org");
291 orgs.save(&org).await.expect("save org");
292
293 let owner = UserId::generate();
294 let member = UserId::generate();
295
296 for (user, role) in [(&owner, Role::Owner), (&member, Role::Member)] {
297 memberships
298 .save(&Membership::new(
299 MembershipId::generate(),
300 org.id.clone(),
301 user.clone(),
302 role,
303 ))
304 .await
305 .expect("save membership");
306 }
307
308 let repos = InMemoryRepoRepo::new();
309 for (name, visibility) in [
310 ("steid", Visibility::Public),
311 ("secret", Visibility::Private),
312 ] {
313 repos
314 .save(
315 &Repository::new(
316 RepoId::generate(),
317 org.id.clone(),
318 name,
319 None,
320 visibility,
321 CREATED,
322 )
323 .expect("valid repo"),
324 )
325 .await
326 .expect("save repo");
327 }
328
329 Fixture {
330 orgs,
331 memberships,
332 repos,
333 protocol: InMemoryGitProtocol::new(),
334 owner: Actor::User(owner),
335 member: Actor::User(member),
336 stranger: Actor::User(UserId::generate()),
337 handle: org.name,
338 }
339 }
340
341 impl Fixture {
342 async fn serve(
343 &self,
344 actor: &Actor,
345 name: &str,
346 endpoint: GitEndpoint,
347 ) -> Result<Option<GitResponse>> {
348 self.serve_with(actor, name, endpoint, GitClientHeaders::default())
349 .await
350 }
351
352 async fn serve_with(
353 &self,
354 actor: &Actor,
355 name: &str,
356 endpoint: GitEndpoint,
357 headers: GitClientHeaders,
358 ) -> Result<Option<GitResponse>> {
359 serve_git(
360 &self.handle,
361 &RepoName::new(name).expect("valid name"),
362 endpoint,
363 headers,
364 Box::pin(tokio::io::empty()),
365 actor,
366 Some("ada"),
367 &self.orgs,
368 &self.memberships,
369 &self.repos,
370 &self.protocol,
371 )
372 .await
373 }
374 }
375
376 fn advertise_clone() -> GitEndpoint {
377 GitEndpoint::Advertisement(GitService::UploadPack)
378 }
379
380 fn advertise_push() -> GitEndpoint {
381 GitEndpoint::Advertisement(GitService::ReceivePack)
382 }
383
384 // --- what reaches the backend ----------------------------------------------
385
386 #[tokio::test]
387 async fn an_advertisement_is_addressed_to_the_repository_on_disk() {
388 // The URL says `/acme/repos/steid.git`; the disk says `acme/steid.git`. The use
389 // case builds the second from validated values rather than trusting the first.
390 let f = fixture().await;
391
392 f.serve(&Actor::Anonymous, "steid", advertise_clone())
393 .await
394 .expect("should serve")
395 .expect("should be visible");
396
397 let request = f.protocol.requests().pop().expect("backend was reached");
398 assert_eq!(request.path_info, "/acme/steid.git/info/refs");
399 assert_eq!(request.query, "service=git-upload-pack");
400 assert_eq!(request.method, GitMethod::Get);
401 }
402
403 #[tokio::test]
404 async fn an_rpc_posts_to_the_service_with_no_query() {
405 let f = fixture().await;
406
407 f.serve(
408 &Actor::Anonymous,
409 "steid",
410 GitEndpoint::Rpc(GitService::UploadPack),
411 )
412 .await
413 .expect("should serve")
414 .expect("should be visible");
415
416 let request = f.protocol.requests().pop().expect("backend was reached");
417 assert_eq!(request.path_info, "/acme/steid.git/git-upload-pack");
418 assert_eq!(request.query, "");
419 assert_eq!(request.method, GitMethod::Post);
420 }
421
422 #[tokio::test]
423 async fn the_headers_that_change_gits_behaviour_are_forwarded() {
424 // Both of these fail silently when dropped: one downgrades the protocol, the
425 // other hands git a compressed body it will not recognise.
426 let f = fixture().await;
427
428 f.serve_with(
429 &Actor::Anonymous,
430 "steid",
431 GitEndpoint::Rpc(GitService::UploadPack),
432 GitClientHeaders {
433 content_encoding: Some("gzip".to_owned()),
434 git_protocol: Some("version=2".to_owned()),
435 ..GitClientHeaders::default()
436 },
437 )
438 .await
439 .expect("should serve")
440 .expect("should be visible");
441
442 let request = f.protocol.requests().pop().expect("backend was reached");
443 assert_eq!(request.content_encoding.as_deref(), Some("gzip"));
444 assert_eq!(request.git_protocol.as_deref(), Some("version=2"));
445 }
446
447 // --- visibility --------------------------------------------------------------
448
449 #[tokio::test]
450 async fn a_public_repository_is_clonable_by_anyone() {
451 let f = fixture().await;
452
453 for actor in [&Actor::Anonymous, &f.stranger, &f.member, &f.owner] {
454 assert!(
455 f.serve(actor, "steid", advertise_clone())
456 .await
457 .expect("should serve")
458 .is_some(),
459 "{actor:?} should be able to clone a public repository"
460 );
461 }
462 }
463
464 #[tokio::test]
465 async fn a_private_repository_is_absent_for_outsiders_and_never_reaches_git() {
466 // `None`, not an error, and — the part worth testing — no bytes flow. A refusal
467 // that arrives after the backend is spawned is not a refusal.
468 let f = fixture().await;
469
470 for actor in [&Actor::Anonymous, &f.stranger] {
471 assert!(
472 f.serve(actor, "secret", advertise_clone())
473 .await
474 .expect("should serve")
475 .is_none(),
476 "{actor:?} should not see a private repository"
477 );
478 }
479
480 assert!(!f.protocol.was_called());
481 }
482
483 #[tokio::test]
484 async fn a_private_repository_is_clonable_by_any_member() {
485 let f = fixture().await;
486
487 for actor in [&f.member, &f.owner] {
488 assert!(
489 f.serve(actor, "secret", advertise_clone())
490 .await
491 .expect("should serve")
492 .is_some(),
493 "{actor:?} should be able to clone a private repository"
494 );
495 }
496 }
497
498 #[tokio::test]
499 async fn an_unknown_repository_is_absent() {
500 let f = fixture().await;
501
502 assert!(
503 f.serve(&f.owner, "nothing-here", advertise_clone())
504 .await
505 .expect("should serve")
506 .is_none()
507 );
508 assert!(!f.protocol.was_called());
509 }
510
511 #[tokio::test]
512 async fn an_unknown_handle_is_absent() {
513 let f = fixture().await;
514 let missing = OrgName::new("nobody").expect("valid handle");
515
516 let served = serve_git(
517 &missing,
518 &RepoName::new("steid").expect("valid"),
519 advertise_clone(),
520 GitClientHeaders::default(),
521 Box::pin(tokio::io::empty()),
522 &f.owner,
523 Some("ada"),
524 &f.orgs,
525 &f.memberships,
526 &f.repos,
527 &f.protocol,
528 )
529 .await
530 .expect("should serve");
531
532 assert!(served.is_none());
533 assert!(!f.protocol.was_called());
534 }
535
536 // --- writes ------------------------------------------------------------------
537
538 #[tokio::test]
539 async fn receive_pack_is_enabled_only_for_an_authorized_write() {
540 // The flag git keys off. A read must never turn it on, and a refused write must
541 // never reach the backend at all — so the only true is a push that passed.
542 let f = fixture().await;
543
544 f.serve(&Actor::Anonymous, "steid", advertise_clone())
545 .await
546 .expect("should serve")
547 .expect("visible");
548 assert!(!f.protocol.requests()[0].allow_receive_pack);
549
550 f.serve(&f.owner, "steid", advertise_push())
551 .await
552 .expect("should serve")
553 .expect("allowed");
554 assert!(f.protocol.requests()[1].allow_receive_pack);
555 }
556
557 #[tokio::test]
558 async fn the_owner_may_push() {
559 let f = fixture().await;
560
561 for endpoint in [advertise_push(), GitEndpoint::Rpc(GitService::ReceivePack)] {
562 f.serve(&f.owner, "steid", endpoint)
563 .await
564 .expect("should serve")
565 .expect("should be allowed");
566 }
567
568 assert_eq!(f.protocol.requests().len(), 2);
569 }
570
571 #[tokio::test]
572 async fn the_owner_may_push_to_a_private_repository() {
573 let f = fixture().await;
574
575 f.serve(&f.owner, "secret", advertise_push())
576 .await
577 .expect("should serve")
578 .expect("should be allowed");
579 }
580
581 #[tokio::test]
582 async fn a_member_who_is_not_the_owner_may_not_push() {
583 // Read access is not permission to rewrite history. The same rule as creating a
584 // repository, and the same rule attempt #2 shipped over SSH.
585 let f = fixture().await;
586
587 for endpoint in [advertise_push(), GitEndpoint::Rpc(GitService::ReceivePack)] {
588 let error = f
589 .serve(&f.member, "steid", endpoint)
590 .await
591 .expect_err("push should be refused");
592
593 assert!(
594 matches!(error, super::super::Error::Domain(DomainError::Forbidden)),
595 "a member on {endpoint:?} should be forbidden, got {error:?}"
596 );
597 }
598
599 assert!(!f.protocol.was_called());
600 }
601
602 #[tokio::test]
603 async fn strangers_and_anonymous_callers_may_not_push() {
604 let f = fixture().await;
605
606 for actor in [&Actor::Anonymous, &f.stranger] {
607 let error = f
608 .serve(actor, "steid", advertise_push())
609 .await
610 .expect_err("push should be refused");
611
612 assert!(
613 matches!(error, super::super::Error::Domain(DomainError::Forbidden)),
614 "{actor:?} should be forbidden"
615 );
616 }
617
618 assert!(!f.protocol.was_called());
619 }
620
621 #[tokio::test]
622 async fn a_refused_push_never_reaches_git() {
623 // The ordering that matters: once pack data is moving, refusing is not an option.
624 let f = fixture().await;
625
626 let _ = f.serve(&f.member, "steid", advertise_push()).await;
627
628 assert!(!f.protocol.was_called());
629 }
630
631 #[tokio::test]
632 async fn a_push_to_an_invisible_repository_is_absent_rather_than_forbidden() {
633 // Order matters: existence is settled before permission. Answering "forbidden"
634 // here would confirm that a private repository by that name exists.
635 let f = fixture().await;
636
637 let served = f
638 .serve(&Actor::Anonymous, "secret", advertise_push())
639 .await
640 .expect("should serve");
641
642 assert!(served.is_none());
643 }
644
645 // --- recency ------------------------------------------------------------------
646
647 impl Fixture {
648 async fn updated_at(&self, name: &str) -> SystemTime {
649 let org = self
650 .orgs
651 .find_by_name(&self.handle)
652 .await
653 .expect("lookup")
654 .expect("the handle exists");
655
656 self.repos
657 .find_by_org_and_name(&org.id, &RepoName::new(name).expect("valid name"))
658 .await
659 .expect("lookup")
660 .expect("the repository exists")
661 .updated_at
662 }
663 }
664
665 /// Marks a repository as mid-import, as `import_repo` would have.
666 async fn start_importing(f: &Fixture, name: &str) {
667 let org = f
668 .orgs
669 .find_by_name(&f.handle)
670 .await
671 .expect("lookup")
672 .expect("the handle exists");
673
674 let mut repo = f
675 .repos
676 .find_by_org_and_name(&org.id, &RepoName::new(name).expect("valid name"))
677 .await
678 .expect("lookup")
679 .expect("the repository exists");
680
681 repo.start_import(ImportSource::new("https://example.com/thing.git").expect("valid"));
682 f.repos.save(&repo).await.expect("save");
683 }
684
685 #[tokio::test]
686 async fn a_push_to_a_repository_still_importing_is_refused() {
687 // A mirror is writing into that directory, or it is not there yet. Receiving a
688 // pack into either is how two histories end up in one repository.
689 let f = fixture().await;
690 start_importing(&f, "steid").await;
691
692 let error = f
693 .serve(&f.owner, "steid", advertise_push())
694 .await
695 .expect_err("should refuse");
696
697 assert!(matches!(
698 error,
699 Error::Domain(DomainError::Unavailable { .. })
700 ));
701 assert!(!f.protocol.was_called(), "git must not have been spawned");
702 }
703
704 #[tokio::test]
705 async fn a_clone_of_a_repository_still_importing_is_allowed() {
706 // Not corruption: git either finds refs in the directory or it does not, and a
707 // failed import's directory is removed. Refusing would also mean a *public*
708 // repository answering differently while it imports, which is a leak of nothing
709 // useful and a special case in every reader.
710 let f = fixture().await;
711 start_importing(&f, "steid").await;
712
713 f.serve(&Actor::Anonymous, "steid", advertise_clone())
714 .await
715 .expect("should serve")
716 .expect("should be allowed");
717 }
718
719 #[tokio::test]
720 async fn an_import_does_not_change_what_a_stranger_is_told_about_a_push() {
721 // "Still importing" to somebody who may not push here would confirm that a
722 // repository is being set up. The permission check comes first for that reason.
723 let f = fixture().await;
724 start_importing(&f, "steid").await;
725
726 let error = f
727 .serve(&f.member, "steid", advertise_push())
728 .await
729 .expect_err("should refuse");
730
731 assert!(matches!(error, Error::Domain(DomainError::Forbidden)));
732 }
733
734 #[tokio::test]
735 async fn an_authorized_push_dates_the_repository() {
736 // What the profile orders by. Recorded when the push is *authorized*, so it is
737 // set before a byte of pack data moves.
738 let f = fixture().await;
739 let before = SystemTime::now();
740
741 f.serve(&f.owner, "steid", advertise_push())
742 .await
743 .expect("should serve")
744 .expect("should be allowed");
745
746 let updated = f.updated_at("steid").await;
747 assert!(updated > CREATED, "the timestamp should have moved");
748 assert!(updated >= before && updated <= SystemTime::now());
749 }
750
751 #[tokio::test]
752 async fn a_clone_does_not_date_the_repository() {
753 // A portfolio ordered by who read it last would reorder itself under a crawler.
754 let f = fixture().await;
755
756 for actor in [&Actor::Anonymous, &f.stranger, &f.member, &f.owner] {
757 f.serve(actor, "steid", advertise_clone())
758 .await
759 .expect("should serve")
760 .expect("visible");
761 f.serve(actor, "steid", GitEndpoint::Rpc(GitService::UploadPack))
762 .await
763 .expect("should serve")
764 .expect("visible");
765 }
766
767 assert_eq!(f.updated_at("steid").await, CREATED);
768 }
769
770 #[tokio::test]
771 async fn a_refused_push_does_not_date_the_repository() {
772 // Otherwise anyone at all could reorder someone's profile by attempting a push.
773 let f = fixture().await;
774
775 for actor in [&Actor::Anonymous, &f.stranger, &f.member] {
776 let _ = f.serve(actor, "steid", advertise_push()).await;
777 }
778
779 assert_eq!(f.updated_at("steid").await, CREATED);
780 }
781
782 #[tokio::test]
783 async fn a_push_to_a_repository_the_actor_cannot_see_dates_nothing() {
784 // The visibility gate returns before the touch, so a stranger cannot even prove
785 // the private repository exists by watching the profile reorder.
786 let f = fixture().await;
787
788 assert!(
789 f.serve(&Actor::Anonymous, "secret", advertise_push())
790 .await
791 .expect("should serve")
792 .is_none()
793 );
794
795 assert_eq!(f.updated_at("secret").await, CREATED);
796 }
797
798 // --- archived ----------------------------------------------------------------
799
800 impl Fixture {
801 async fn archive(&self, name: &str) {
802 let org = self
803 .orgs
804 .find_by_name(&self.handle)
805 .await
806 .expect("lookup")
807 .expect("the handle exists");
808 let repo = self
809 .repos
810 .find_by_org_and_name(&org.id, &RepoName::new(name).expect("valid name"))
811 .await
812 .expect("lookup")
813 .expect("the repository exists");
814
815 self.repos
816 .save(&Repository {
817 archived: true,
818 ..repo
819 })
820 .await
821 .expect("save repo");
822 }
823 }
824
825 #[tokio::test]
826 async fn an_archived_repository_refuses_a_push_from_its_own_owner() {
827 // Archived is a state of the repository, not of the actor: the owner is refused
828 // too, and told why rather than told "not permitted".
829 let f = fixture().await;
830 f.archive("steid").await;
831
832 for endpoint in [advertise_push(), GitEndpoint::Rpc(GitService::ReceivePack)] {
833 let error = f
834 .serve(&f.owner, "steid", endpoint)
835 .await
836 .expect_err("push should be refused");
837
838 assert!(
839 matches!(error, super::super::Error::Domain(DomainError::Archived)),
840 "an owner pushing to an archived repository on {endpoint:?} should be told \
841 it is archived, got {error:?}"
842 );
843 }
844
845 assert!(!f.protocol.was_called());
846 }
847
848 #[tokio::test]
849 async fn an_archived_repository_is_still_clonable() {
850 // Everything that reads keeps working. That is the whole distinction between
851 // archiving and making something private.
852 let f = fixture().await;
853 f.archive("steid").await;
854
855 for endpoint in [advertise_clone(), GitEndpoint::Rpc(GitService::UploadPack)] {
856 f.serve(&Actor::Anonymous, "steid", endpoint)
857 .await
858 .expect("should serve")
859 .expect("should be visible");
860 }
861
862 assert_eq!(f.protocol.requests().len(), 2);
863 }
864
865 #[tokio::test]
866 async fn a_non_owner_never_learns_that_a_repository_is_archived() {
867 // The archive check sits after the owner check on purpose: `Forbidden` is what
868 // a member saw before, and it must stay what they see.
869 let f = fixture().await;
870 f.archive("steid").await;
871
872 let error = f
873 .serve(&f.member, "steid", advertise_push())
874 .await
875 .expect_err("push should be refused");
876
877 assert!(matches!(
878 error,
879 super::super::Error::Domain(DomainError::Forbidden)
880 ));
881 }
882
883 #[tokio::test]
884 async fn a_refused_push_to_an_archived_repository_does_not_date_it() {
885 let f = fixture().await;
886 f.archive("steid").await;
887
888 let _ = f.serve(&f.owner, "steid", advertise_push()).await;
889
890 assert_eq!(f.updated_at("steid").await, CREATED);
891 }
892
893 // --- service parsing ---------------------------------------------------------
894
895 #[tokio::test]
896 async fn a_service_round_trips_through_its_wire_name() {
897 for service in [GitService::UploadPack, GitService::ReceivePack] {
898 assert_eq!(
899 service
900 .as_str()
901 .parse::<GitService>()
902 .expect("known service"),
903 service
904 );
905 }
906 }
907
908 #[tokio::test]
909 async fn an_unknown_service_is_an_error_not_a_default() {
910 assert!("git-do-whatever".parse::<GitService>().is_err());
911 assert!("".parse::<GitService>().is_err());
912 }
913
914 #[tokio::test]
915 async fn only_upload_pack_reads() {
916 assert_eq!(GitService::UploadPack.operation(), GitOperation::Read);
917 assert_eq!(GitService::ReceivePack.operation(), GitOperation::Write);
918 }
919}