steid

@jamesgill /

Rust32.2 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 // A read never uses it; a write records it as the moment the push was authorized.
156 // Taken rather than read here so the transport's one notion of "now" is the one that
157 // lands in the row — see [`Clock`](super::port::Clock).
158 now: SystemTime,
159 orgs: &impl OrgRepository,
160 memberships: &impl MembershipRepository,
161 repos: &impl RepoRepository,
162 protocol: &impl GitProtocolServer,
163) -> Result<Option<GitResponse>> {
164 let Some(org) = orgs.find_by_name(handle).await? else {
165 return Ok(None);
166 };
167
168 let Some(repo) = repos.find_by_org_and_name(&org.id, name).await? else {
169 return Ok(None);
170 };
171
172 // Existence is settled before permission, so a push to a repository the actor may
173 // not even see answers "no such repository" rather than "not allowed" — the latter
174 // would confirm it exists.
175 if !repo.visibility.is_public() && !is_org_member(&org, actor, memberships).await? {
176 return Ok(None);
177 }
178
179 let writing = endpoint.service().operation() == GitOperation::Write;
180
181 if writing && !is_org_owner(&org, actor, memberships).await? {
182 return Err(DomainError::Forbidden.into());
183 }
184
185 // Every reason a repository refuses contents, asked in one place —
186 // [`Repository::refuse_writes`] holds both the reasons and their order, so this
187 // path and the settings ones cannot drift apart.
188 //
189 // **After the owner check, not before.** Otherwise a stranger probing a repository
190 // learns it is archived, or that one is being set up, which are facts about it they
191 // have no business being told; this way the only caller who ever sees a refusal is
192 // the one who could otherwise have pushed. A use-case rule rather than a handler
193 // check, so it holds for `/api` and any future transport the same way `Role::Owner`
194 // does.
195 //
196 // Reads are deliberately still allowed, archived or importing. Cloning a repository
197 // whose directory is half-written is not corruption — git either finds the refs or
198 // it does not — and a failed import's directory is removed, so there is nothing
199 // there to read.
200 if writing {
201 repo.refuse_writes(RepoWrite::Contents)?;
202 }
203
204 if writing {
205 // **Authorized write path only.** Every refusal above has already returned, and a
206 // read never reaches here, so nothing a clone does can move a repository up the
207 // profile.
208 //
209 // This records that a push was *authorized*, not that it succeeded: the pack may
210 // still be rejected by the backend, by a hook, or by the client hanging up. The
211 // honest alternative is to wait for the subprocess and inspect its exit — a far
212 // larger change (the response streams, so nothing here sees the end of it) for a
213 // small gain in accuracy on a timestamp that only orders a listing.
214 //
215 // A failure here must not fail the push, exactly as a directory that will not
216 // delete does not fail `delete_repo`: the push is the thing the user asked for,
217 // and a stale sort key is not worth refusing it over.
218 if let Err(error) = repos.touch(&repo.id, now).await {
219 eprintln!(
220 "steid: push to {}/{} authorized, but its updated_at could not be moved: {error}",
221 org.name, repo.name
222 );
223 }
224 }
225
226 let service = endpoint.service();
227 let path_info = format!("/{}/{}.git", org.name, repo.name);
228
229 // Built here from validated values rather than forwarded from the URL. `OrgName` and
230 // `RepoName` already made traversal impossible, so the backend cannot be pointed at
231 // a path this function did not agree to.
232 let (path_info, query) = match endpoint {
233 GitEndpoint::Advertisement(_) => (
234 format!("{path_info}/info/refs"),
235 format!("service={}", service.as_str()),
236 ),
237 GitEndpoint::Rpc(_) => (format!("{path_info}/{}", service.as_str()), String::new()),
238 };
239
240 let response = protocol
241 .serve(GitRequest {
242 method: endpoint.method(),
243 path_info,
244 query,
245 content_type: headers.content_type,
246 content_encoding: headers.content_encoding,
247 content_length: headers.content_length,
248 git_protocol: headers.git_protocol,
249 // Past the gate above, so this is only ever true for a write that was
250 // authorized. Left false for a read, which never needs it.
251 allow_receive_pack: writing,
252 remote_user: writing.then(|| pusher.unwrap_or("unknown").to_owned()),
253 body,
254 })
255 .await?;
256
257 Ok(Some(response))
258}
259
260#[cfg(test)]
261mod tests {
262 use std::time::Duration;
263
264 use super::*;
265 use crate::{
266 application::Error,
267 domain::{
268 ImportSource, Membership, MembershipId, OrgId, Organization, RepoId, Repository, Role,
269 UserId, Visibility,
270 },
271 infrastructure::{
272 git::InMemoryGitProtocol,
273 repository::{InMemoryMembershipRepo, InMemoryOrgRepo, InMemoryRepoRepo},
274 },
275 };
276
277 /// When the fixture's repositories were created. Fixed, so a test can tell a
278 /// timestamp that moved from one that never did without racing the clock.
279 const CREATED: SystemTime = SystemTime::UNIX_EPOCH;
280 /// The instant every test push is served at. Later than [`CREATED`], so a row that
281 /// moved is a row that says exactly this.
282 fn served() -> SystemTime {
283 SystemTime::UNIX_EPOCH + Duration::from_secs(1_000)
284 }
285
286 struct Fixture {
287 orgs: InMemoryOrgRepo,
288 memberships: InMemoryMembershipRepo,
289 repos: InMemoryRepoRepo,
290 protocol: InMemoryGitProtocol,
291 owner: Actor,
292 member: Actor,
293 stranger: Actor,
294 handle: OrgName,
295 }
296
297 async fn fixture() -> Fixture {
298 let orgs = InMemoryOrgRepo::new();
299 let memberships = InMemoryMembershipRepo::new();
300
301 let org = Organization::new(OrgId::generate(), "acme", None).expect("valid org");
302 orgs.save(&org).await.expect("save org");
303
304 let owner = UserId::generate();
305 let member = UserId::generate();
306
307 for (user, role) in [(&owner, Role::Owner), (&member, Role::Member)] {
308 memberships
309 .save(&Membership::new(
310 MembershipId::generate(),
311 org.id.clone(),
312 user.clone(),
313 role,
314 ))
315 .await
316 .expect("save membership");
317 }
318
319 let repos = InMemoryRepoRepo::new();
320 for (name, visibility) in [
321 ("steid", Visibility::Public),
322 ("secret", Visibility::Private),
323 ] {
324 repos
325 .save(
326 &Repository::new(
327 RepoId::generate(),
328 org.id.clone(),
329 name,
330 None,
331 visibility,
332 CREATED,
333 )
334 .expect("valid repo"),
335 )
336 .await
337 .expect("save repo");
338 }
339
340 Fixture {
341 orgs,
342 memberships,
343 repos,
344 protocol: InMemoryGitProtocol::new(),
345 owner: Actor::User(owner),
346 member: Actor::User(member),
347 stranger: Actor::User(UserId::generate()),
348 handle: org.name,
349 }
350 }
351
352 impl Fixture {
353 async fn serve(
354 &self,
355 actor: &Actor,
356 name: &str,
357 endpoint: GitEndpoint,
358 ) -> Result<Option<GitResponse>> {
359 self.serve_with(actor, name, endpoint, GitClientHeaders::default())
360 .await
361 }
362
363 async fn serve_with(
364 &self,
365 actor: &Actor,
366 name: &str,
367 endpoint: GitEndpoint,
368 headers: GitClientHeaders,
369 ) -> Result<Option<GitResponse>> {
370 serve_git(
371 &self.handle,
372 &RepoName::new(name).expect("valid name"),
373 endpoint,
374 headers,
375 Box::pin(tokio::io::empty()),
376 actor,
377 Some("ada"),
378 served(),
379 &self.orgs,
380 &self.memberships,
381 &self.repos,
382 &self.protocol,
383 )
384 .await
385 }
386 }
387
388 fn advertise_clone() -> GitEndpoint {
389 GitEndpoint::Advertisement(GitService::UploadPack)
390 }
391
392 fn advertise_push() -> GitEndpoint {
393 GitEndpoint::Advertisement(GitService::ReceivePack)
394 }
395
396 // --- what reaches the backend ----------------------------------------------
397
398 #[tokio::test]
399 async fn an_advertisement_is_addressed_to_the_repository_on_disk() {
400 // The URL says `/acme/repos/steid.git`; the disk says `acme/steid.git`. The use
401 // case builds the second from validated values rather than trusting the first.
402 let f = fixture().await;
403
404 f.serve(&Actor::Anonymous, "steid", advertise_clone())
405 .await
406 .expect("should serve")
407 .expect("should be visible");
408
409 let request = f.protocol.requests().pop().expect("backend was reached");
410 assert_eq!(request.path_info, "/acme/steid.git/info/refs");
411 assert_eq!(request.query, "service=git-upload-pack");
412 assert_eq!(request.method, GitMethod::Get);
413 }
414
415 #[tokio::test]
416 async fn an_rpc_posts_to_the_service_with_no_query() {
417 let f = fixture().await;
418
419 f.serve(
420 &Actor::Anonymous,
421 "steid",
422 GitEndpoint::Rpc(GitService::UploadPack),
423 )
424 .await
425 .expect("should serve")
426 .expect("should be visible");
427
428 let request = f.protocol.requests().pop().expect("backend was reached");
429 assert_eq!(request.path_info, "/acme/steid.git/git-upload-pack");
430 assert_eq!(request.query, "");
431 assert_eq!(request.method, GitMethod::Post);
432 }
433
434 #[tokio::test]
435 async fn the_headers_that_change_gits_behaviour_are_forwarded() {
436 // Both of these fail silently when dropped: one downgrades the protocol, the
437 // other hands git a compressed body it will not recognise.
438 let f = fixture().await;
439
440 f.serve_with(
441 &Actor::Anonymous,
442 "steid",
443 GitEndpoint::Rpc(GitService::UploadPack),
444 GitClientHeaders {
445 content_encoding: Some("gzip".to_owned()),
446 git_protocol: Some("version=2".to_owned()),
447 ..GitClientHeaders::default()
448 },
449 )
450 .await
451 .expect("should serve")
452 .expect("should be visible");
453
454 let request = f.protocol.requests().pop().expect("backend was reached");
455 assert_eq!(request.content_encoding.as_deref(), Some("gzip"));
456 assert_eq!(request.git_protocol.as_deref(), Some("version=2"));
457 }
458
459 // --- visibility --------------------------------------------------------------
460
461 #[tokio::test]
462 async fn a_public_repository_is_clonable_by_anyone() {
463 let f = fixture().await;
464
465 for actor in [&Actor::Anonymous, &f.stranger, &f.member, &f.owner] {
466 assert!(
467 f.serve(actor, "steid", advertise_clone())
468 .await
469 .expect("should serve")
470 .is_some(),
471 "{actor:?} should be able to clone a public repository"
472 );
473 }
474 }
475
476 #[tokio::test]
477 async fn a_private_repository_is_absent_for_outsiders_and_never_reaches_git() {
478 // `None`, not an error, and — the part worth testing — no bytes flow. A refusal
479 // that arrives after the backend is spawned is not a refusal.
480 let f = fixture().await;
481
482 for actor in [&Actor::Anonymous, &f.stranger] {
483 assert!(
484 f.serve(actor, "secret", advertise_clone())
485 .await
486 .expect("should serve")
487 .is_none(),
488 "{actor:?} should not see a private repository"
489 );
490 }
491
492 assert!(!f.protocol.was_called());
493 }
494
495 #[tokio::test]
496 async fn a_private_repository_is_clonable_by_any_member() {
497 let f = fixture().await;
498
499 for actor in [&f.member, &f.owner] {
500 assert!(
501 f.serve(actor, "secret", advertise_clone())
502 .await
503 .expect("should serve")
504 .is_some(),
505 "{actor:?} should be able to clone a private repository"
506 );
507 }
508 }
509
510 #[tokio::test]
511 async fn an_unknown_repository_is_absent() {
512 let f = fixture().await;
513
514 assert!(
515 f.serve(&f.owner, "nothing-here", advertise_clone())
516 .await
517 .expect("should serve")
518 .is_none()
519 );
520 assert!(!f.protocol.was_called());
521 }
522
523 #[tokio::test]
524 async fn an_unknown_handle_is_absent() {
525 let f = fixture().await;
526 let missing = OrgName::new("nobody").expect("valid handle");
527
528 let served = serve_git(
529 &missing,
530 &RepoName::new("steid").expect("valid"),
531 advertise_clone(),
532 GitClientHeaders::default(),
533 Box::pin(tokio::io::empty()),
534 &f.owner,
535 Some("ada"),
536 served(),
537 &f.orgs,
538 &f.memberships,
539 &f.repos,
540 &f.protocol,
541 )
542 .await
543 .expect("should serve");
544
545 assert!(served.is_none());
546 assert!(!f.protocol.was_called());
547 }
548
549 // --- writes ------------------------------------------------------------------
550
551 #[tokio::test]
552 async fn receive_pack_is_enabled_only_for_an_authorized_write() {
553 // The flag git keys off. A read must never turn it on, and a refused write must
554 // never reach the backend at all — so the only true is a push that passed.
555 let f = fixture().await;
556
557 f.serve(&Actor::Anonymous, "steid", advertise_clone())
558 .await
559 .expect("should serve")
560 .expect("visible");
561 assert!(!f.protocol.requests()[0].allow_receive_pack);
562
563 f.serve(&f.owner, "steid", advertise_push())
564 .await
565 .expect("should serve")
566 .expect("allowed");
567 assert!(f.protocol.requests()[1].allow_receive_pack);
568 }
569
570 #[tokio::test]
571 async fn the_owner_may_push() {
572 let f = fixture().await;
573
574 for endpoint in [advertise_push(), GitEndpoint::Rpc(GitService::ReceivePack)] {
575 f.serve(&f.owner, "steid", endpoint)
576 .await
577 .expect("should serve")
578 .expect("should be allowed");
579 }
580
581 assert_eq!(f.protocol.requests().len(), 2);
582 }
583
584 #[tokio::test]
585 async fn the_owner_may_push_to_a_private_repository() {
586 let f = fixture().await;
587
588 f.serve(&f.owner, "secret", advertise_push())
589 .await
590 .expect("should serve")
591 .expect("should be allowed");
592 }
593
594 #[tokio::test]
595 async fn a_member_who_is_not_the_owner_may_not_push() {
596 // Read access is not permission to rewrite history. The same rule as creating a
597 // repository, and the same rule attempt #2 shipped over SSH.
598 let f = fixture().await;
599
600 for endpoint in [advertise_push(), GitEndpoint::Rpc(GitService::ReceivePack)] {
601 let error = f
602 .serve(&f.member, "steid", endpoint)
603 .await
604 .expect_err("push should be refused");
605
606 assert!(
607 matches!(error, super::super::Error::Domain(DomainError::Forbidden)),
608 "a member on {endpoint:?} should be forbidden, got {error:?}"
609 );
610 }
611
612 assert!(!f.protocol.was_called());
613 }
614
615 #[tokio::test]
616 async fn strangers_and_anonymous_callers_may_not_push() {
617 let f = fixture().await;
618
619 for actor in [&Actor::Anonymous, &f.stranger] {
620 let error = f
621 .serve(actor, "steid", advertise_push())
622 .await
623 .expect_err("push should be refused");
624
625 assert!(
626 matches!(error, super::super::Error::Domain(DomainError::Forbidden)),
627 "{actor:?} should be forbidden"
628 );
629 }
630
631 assert!(!f.protocol.was_called());
632 }
633
634 #[tokio::test]
635 async fn a_refused_push_never_reaches_git() {
636 // The ordering that matters: once pack data is moving, refusing is not an option.
637 let f = fixture().await;
638
639 let _ = f.serve(&f.member, "steid", advertise_push()).await;
640
641 assert!(!f.protocol.was_called());
642 }
643
644 #[tokio::test]
645 async fn a_push_to_an_invisible_repository_is_absent_rather_than_forbidden() {
646 // Order matters: existence is settled before permission. Answering "forbidden"
647 // here would confirm that a private repository by that name exists.
648 let f = fixture().await;
649
650 let served = f
651 .serve(&Actor::Anonymous, "secret", advertise_push())
652 .await
653 .expect("should serve");
654
655 assert!(served.is_none());
656 }
657
658 // --- recency ------------------------------------------------------------------
659
660 impl Fixture {
661 async fn updated_at(&self, name: &str) -> SystemTime {
662 let org = self
663 .orgs
664 .find_by_name(&self.handle)
665 .await
666 .expect("lookup")
667 .expect("the handle exists");
668
669 self.repos
670 .find_by_org_and_name(&org.id, &RepoName::new(name).expect("valid name"))
671 .await
672 .expect("lookup")
673 .expect("the repository exists")
674 .updated_at
675 }
676 }
677
678 /// Marks a repository as mid-import, as `import_repo` would have.
679 async fn start_importing(f: &Fixture, name: &str) {
680 let org = f
681 .orgs
682 .find_by_name(&f.handle)
683 .await
684 .expect("lookup")
685 .expect("the handle exists");
686
687 let mut repo = f
688 .repos
689 .find_by_org_and_name(&org.id, &RepoName::new(name).expect("valid name"))
690 .await
691 .expect("lookup")
692 .expect("the repository exists");
693
694 repo.start_import(ImportSource::new("https://example.com/thing.git").expect("valid"));
695 f.repos.save(&repo).await.expect("save");
696 }
697
698 #[tokio::test]
699 async fn a_push_to_a_repository_still_importing_is_refused() {
700 // A mirror is writing into that directory, or it is not there yet. Receiving a
701 // pack into either is how two histories end up in one repository.
702 let f = fixture().await;
703 start_importing(&f, "steid").await;
704
705 let error = f
706 .serve(&f.owner, "steid", advertise_push())
707 .await
708 .expect_err("should refuse");
709
710 assert!(matches!(
711 error,
712 Error::Domain(DomainError::Unavailable { .. })
713 ));
714 assert!(!f.protocol.was_called(), "git must not have been spawned");
715 }
716
717 #[tokio::test]
718 async fn a_clone_of_a_repository_still_importing_is_allowed() {
719 // Not corruption: git either finds refs in the directory or it does not, and a
720 // failed import's directory is removed. Refusing would also mean a *public*
721 // repository answering differently while it imports, which is a leak of nothing
722 // useful and a special case in every reader.
723 let f = fixture().await;
724 start_importing(&f, "steid").await;
725
726 f.serve(&Actor::Anonymous, "steid", advertise_clone())
727 .await
728 .expect("should serve")
729 .expect("should be allowed");
730 }
731
732 #[tokio::test]
733 async fn an_import_does_not_change_what_a_stranger_is_told_about_a_push() {
734 // "Still importing" to somebody who may not push here would confirm that a
735 // repository is being set up. The permission check comes first for that reason.
736 let f = fixture().await;
737 start_importing(&f, "steid").await;
738
739 let error = f
740 .serve(&f.member, "steid", advertise_push())
741 .await
742 .expect_err("should refuse");
743
744 assert!(matches!(error, Error::Domain(DomainError::Forbidden)));
745 }
746
747 #[tokio::test]
748 async fn an_authorized_push_dates_the_repository() {
749 // What the profile orders by. Recorded when the push is *authorized*, so it is
750 // set before a byte of pack data moves.
751 let f = fixture().await;
752
753 f.serve(&f.owner, "steid", advertise_push())
754 .await
755 .expect("should serve")
756 .expect("should be allowed");
757
758 // The instant the caller handed down, not whatever the clock said inside.
759 assert_eq!(f.updated_at("steid").await, served());
760 }
761
762 #[tokio::test]
763 async fn a_clone_does_not_date_the_repository() {
764 // A portfolio ordered by who read it last would reorder itself under a crawler.
765 let f = fixture().await;
766
767 for actor in [&Actor::Anonymous, &f.stranger, &f.member, &f.owner] {
768 f.serve(actor, "steid", advertise_clone())
769 .await
770 .expect("should serve")
771 .expect("visible");
772 f.serve(actor, "steid", GitEndpoint::Rpc(GitService::UploadPack))
773 .await
774 .expect("should serve")
775 .expect("visible");
776 }
777
778 assert_eq!(f.updated_at("steid").await, CREATED);
779 }
780
781 #[tokio::test]
782 async fn a_refused_push_does_not_date_the_repository() {
783 // Otherwise anyone at all could reorder someone's profile by attempting a push.
784 let f = fixture().await;
785
786 for actor in [&Actor::Anonymous, &f.stranger, &f.member] {
787 let _ = f.serve(actor, "steid", advertise_push()).await;
788 }
789
790 assert_eq!(f.updated_at("steid").await, CREATED);
791 }
792
793 #[tokio::test]
794 async fn a_push_to_a_repository_the_actor_cannot_see_dates_nothing() {
795 // The visibility gate returns before the touch, so a stranger cannot even prove
796 // the private repository exists by watching the profile reorder.
797 let f = fixture().await;
798
799 assert!(
800 f.serve(&Actor::Anonymous, "secret", advertise_push())
801 .await
802 .expect("should serve")
803 .is_none()
804 );
805
806 assert_eq!(f.updated_at("secret").await, CREATED);
807 }
808
809 // --- archived ----------------------------------------------------------------
810
811 impl Fixture {
812 async fn archive(&self, name: &str) {
813 let org = self
814 .orgs
815 .find_by_name(&self.handle)
816 .await
817 .expect("lookup")
818 .expect("the handle exists");
819 let repo = self
820 .repos
821 .find_by_org_and_name(&org.id, &RepoName::new(name).expect("valid name"))
822 .await
823 .expect("lookup")
824 .expect("the repository exists");
825
826 self.repos
827 .save(&Repository {
828 archived: true,
829 ..repo
830 })
831 .await
832 .expect("save repo");
833 }
834 }
835
836 #[tokio::test]
837 async fn an_archived_repository_refuses_a_push_from_its_own_owner() {
838 // Archived is a state of the repository, not of the actor: the owner is refused
839 // too, and told why rather than told "not permitted".
840 let f = fixture().await;
841 f.archive("steid").await;
842
843 for endpoint in [advertise_push(), GitEndpoint::Rpc(GitService::ReceivePack)] {
844 let error = f
845 .serve(&f.owner, "steid", endpoint)
846 .await
847 .expect_err("push should be refused");
848
849 assert!(
850 matches!(error, super::super::Error::Domain(DomainError::Archived)),
851 "an owner pushing to an archived repository on {endpoint:?} should be told \
852 it is archived, got {error:?}"
853 );
854 }
855
856 assert!(!f.protocol.was_called());
857 }
858
859 #[tokio::test]
860 async fn an_archived_repository_is_still_clonable() {
861 // Everything that reads keeps working. That is the whole distinction between
862 // archiving and making something private.
863 let f = fixture().await;
864 f.archive("steid").await;
865
866 for endpoint in [advertise_clone(), GitEndpoint::Rpc(GitService::UploadPack)] {
867 f.serve(&Actor::Anonymous, "steid", endpoint)
868 .await
869 .expect("should serve")
870 .expect("should be visible");
871 }
872
873 assert_eq!(f.protocol.requests().len(), 2);
874 }
875
876 #[tokio::test]
877 async fn a_non_owner_never_learns_that_a_repository_is_archived() {
878 // The archive check sits after the owner check on purpose: `Forbidden` is what
879 // a member saw before, and it must stay what they see.
880 let f = fixture().await;
881 f.archive("steid").await;
882
883 let error = f
884 .serve(&f.member, "steid", advertise_push())
885 .await
886 .expect_err("push should be refused");
887
888 assert!(matches!(
889 error,
890 super::super::Error::Domain(DomainError::Forbidden)
891 ));
892 }
893
894 #[tokio::test]
895 async fn a_refused_push_to_an_archived_repository_does_not_date_it() {
896 let f = fixture().await;
897 f.archive("steid").await;
898
899 let _ = f.serve(&f.owner, "steid", advertise_push()).await;
900
901 assert_eq!(f.updated_at("steid").await, CREATED);
902 }
903
904 // --- service parsing ---------------------------------------------------------
905
906 #[tokio::test]
907 async fn a_service_round_trips_through_its_wire_name() {
908 for service in [GitService::UploadPack, GitService::ReceivePack] {
909 assert_eq!(
910 service
911 .as_str()
912 .parse::<GitService>()
913 .expect("known service"),
914 service
915 );
916 }
917 }
918
919 #[tokio::test]
920 async fn an_unknown_service_is_an_error_not_a_default() {
921 assert!("git-do-whatever".parse::<GitService>().is_err());
922 assert!("".parse::<GitService>().is_err());
923 }
924
925 #[tokio::test]
926 async fn only_upload_pack_reads() {
927 assert_eq!(GitService::UploadPack.operation(), GitOperation::Read);
928 assert_eq!(GitService::ReceivePack.operation(), GitOperation::Write);
929 }
930}