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