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