steid

@jamesgill /

Rust21.8 KBCode·Blame·History·Raw
1//! Importing a repository from a public URL.
2//!
3//! Two halves, on purpose. [`import_repo`] is the part a person waits for: it
4//! authorizes, validates the address, and writes a row that says a copy is coming.
5//! [`run_import`] is the part that takes minutes and runs with nobody watching. The
6//! seam between them is the `importing` row — which is also what makes the failure
7//! modes tractable, because a process that dies leaves a fact behind rather than
8//! nothing.
9
10use std::time::SystemTime;
11
12use crate::domain::{
13 Actor, DomainError, ImportSource, OrgName, RepoId, Repository, Visibility,
14 repository::{MembershipRepository, OrgRepository, RepoRepository},
15};
16
17use super::{
18 authz::is_org_owner,
19 error::{Error, Result},
20 port::{GitImport, GitStorage},
21};
22
23/// What is recorded against a repository whose import was cut short by the process
24/// stopping. See [`sweep_interrupted_imports`].
25pub const INTERRUPTED: &str =
26 "The import was interrupted by a restart. Delete this repository and import it again.";
27
28/// Longest failure message kept on a repository.
29///
30/// git's stderr on a failed clone is usually two lines and occasionally hundreds; the
31/// column is rendered on a page, so it is bounded here rather than trusted.
32const MAX_ERROR_LEN: usize = 500;
33
34/// The repository a visitor is asking to copy in.
35///
36/// Raw input, like [`NewRepo`](super::NewRepo): both fields are whatever was typed, and
37/// validating them is [`ImportSource`] and [`Repository::new`]'s job.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct NewImport {
40 pub name: String,
41 pub source: String,
42}
43
44/// Records that a repository is being imported, and returns it.
45///
46/// Owner only — the same rule as [`create_repo`](super::create_repo), and for the same
47/// reason: a member's read access is not permission to add to someone's portfolio.
48///
49/// **Nothing is written to disk here.** Unlike `create_repo`, which inits a bare
50/// repository and compensates if the row fails to save, an import's directory is
51/// created by `git clone` itself in the background. So the row goes first and is the
52/// only write this function makes, which removes the two-writes problem from the
53/// request path entirely — at the cost of moving it into [`run_import`], where a
54/// failure has somewhere to be recorded.
55///
56/// The caller is expected to spawn [`run_import`] afterwards. It is deliberately not
57/// spawned here: the application layer has no business owning a runtime, and a use case
58/// that starts a task cannot be tested without waiting for one.
59pub async fn import_repo(
60 actor: &Actor,
61 handle: &OrgName,
62 spec: &NewImport,
63 orgs: &impl OrgRepository,
64 memberships: &impl MembershipRepository,
65 repos: &impl RepoRepository,
66) -> Result<Repository> {
67 let Some(org) = orgs.find_by_name(handle).await? else {
68 return Err(DomainError::NotFound {
69 entity: "repository owner",
70 }
71 .into());
72 };
73
74 if !is_org_owner(&org, actor, memberships).await? {
75 return Err(DomainError::Forbidden.into());
76 }
77
78 // The address before the name: a typo in the URL is the likelier mistake, and
79 // reporting it first means the form does not complain about the name it pre-filled
80 // from an address it has not accepted.
81 let source = ImportSource::new(spec.source.clone())?;
82
83 // A blank name means "call it what the source calls it". The form says so and
84 // offers no JavaScript to fill the box in as the URL is typed, so the fallback is
85 // the whole of that feature — and it lands here rather than in the page so that a
86 // future `/api` cannot answer differently.
87 let name = match spec.name.trim() {
88 "" => source.suggested_name().to_owned(),
89 typed => typed.to_owned(),
90 };
91
92 let mut repo = Repository::new(
93 RepoId::generate(),
94 org.id.clone(),
95 name,
96 None,
97 // Imported repositories are public, matching `Visibility::default()` and the
98 // form, which offers no choice. Making one private is one visit to its settings
99 // page — and the page exists the moment the row does, importing or not.
100 Visibility::Public,
101 SystemTime::now(),
102 )?;
103
104 if repos
105 .find_by_org_and_name(&org.id, &repo.name)
106 .await?
107 .is_some()
108 {
109 return Err(DomainError::AlreadyExists {
110 entity: "repository",
111 }
112 .into());
113 }
114
115 repo.start_import(source);
116 repos.save(&repo).await?;
117
118 Ok(repo)
119}
120
121/// Runs the mirror, then records how it went.
122///
123/// Long-running and spawned, so it takes owned handles rather than borrowing a request.
124/// It reports `Ok(())` for a *failed import* — the failure is data on the repository,
125/// not an error for the caller, which is a background task with nobody to tell. `Err`
126/// is reserved for not being able to record the outcome at all.
127///
128/// **The row is re-read after the clone.** Minutes have passed, and the repository may
129/// have been deleted meanwhile; writing back the copy loaded at the start would
130/// resurrect it as a row pointing at a directory that was removed underneath it.
131pub async fn run_import(
132 id: &RepoId,
133 handle: &OrgName,
134 repos: &impl RepoRepository,
135 importer: &impl GitImport,
136 storage: &impl GitStorage,
137) -> Result<()> {
138 let Some(repo) = repos.find_by_id(id).await? else {
139 return Ok(());
140 };
141
142 let Some(source) = repo.import_source.clone() else {
143 // Only ever reachable if something saved an `importing` row without a source.
144 return Err(DomainError::validation("import source", "is missing").into());
145 };
146
147 let outcome = importer.mirror(handle, &repo.name, &source).await;
148
149 let Some(mut repo) = repos.find_by_id(id).await? else {
150 // Deleted while the clone ran. `delete_repo` removed a directory that did not
151 // exist yet, so what the clone left behind is an orphan and this is the only
152 // code left that knows where it is.
153 let _ = storage.remove(handle, &repo.name).await;
154 return Ok(());
155 };
156
157 match outcome {
158 Ok(()) => {
159 repo.finish_import();
160 // The history landed now, whatever the dates inside it say. The profile
161 // orders by this, and an imported repository has genuinely just arrived.
162 repo.updated_at = SystemTime::now();
163 }
164 Err(error) => {
165 repo.fail_import(explain(error.message()));
166
167 // Whatever the clone left is unusable and must not be browsable: with the
168 // state set to `failed` the page would not read it, but the git transport
169 // and an archive request address the directory, not the row. Best effort —
170 // a directory that will not delete is not a reason to lose the message.
171 if let Err(removal) = storage.remove(handle, &repo.name).await {
172 eprintln!(
173 "steid: import of {handle}/{} failed, and its partial clone could not be removed: {removal}",
174 repo.name
175 );
176 }
177 }
178 }
179
180 repos.save(&repo).await?;
181
182 Ok(())
183}
184
185/// Fails every repository still marked `importing`, and reports how many.
186///
187/// **Called once on boot, before the first request is served.** An import lives in a
188/// background task, so a process that stops takes every running import with it and
189/// leaves rows that will never change again. Without this a restart during an import is
190/// a repository stuck showing "importing…" forever, with no way for its owner to tell
191/// that from one that is merely slow.
192///
193/// Safe precisely because of *when* it runs: nothing has been spawned yet, so there is
194/// no live import for it to mark as dead.
195pub async fn sweep_interrupted_imports(repos: &impl RepoRepository) -> Result<u64> {
196 Ok(repos.fail_interrupted_imports(INTERRUPTED).await?)
197}
198
199/// Turns git's own words into something the owner can act on.
200///
201/// One translation, and it earns its place because it is the **most likely failure
202/// there is**: a typo'd path or a private repository. GitHub answers both with a
203/// challenge rather than a 404, so with `GIT_TERMINAL_PROMPT=0` git reports "could not
204/// read Username", which describes Steid's configuration rather than the mistake.
205/// Every other message is git's, untranslated — inventing a friendlier wording for a
206/// failure nobody anticipated is how a real reason gets hidden.
207fn explain(message: &str) -> String {
208 const PROMPTED: &str = "could not read Username";
209 const AUTHENTICATION: &str = "Authentication failed";
210
211 if message.contains(PROMPTED) || message.contains(AUTHENTICATION) {
212 return "The repository could not be found. It may be private, or the URL may be \
213 wrong — Steid imports public repositories only, and never sends \
214 credentials."
215 .to_owned();
216 }
217
218 truncate(message, MAX_ERROR_LEN)
219}
220
221/// Cuts a message to `limit` bytes on a character boundary, marking that it was cut.
222fn truncate(message: &str, limit: usize) -> String {
223 let message = message.trim();
224
225 if message.len() <= limit {
226 return message.to_owned();
227 }
228
229 let mut cut = limit;
230 while cut > 0 && !message.is_char_boundary(cut) {
231 cut -= 1;
232 }
233
234 format!("{}…", &message[..cut])
235}
236
237/// Turns a use case failure into something the import form can say.
238///
239/// Here rather than in the page so that `/api` and the form cannot disagree about what
240/// a refused address sounds like.
241pub fn import_failure_message(error: &Error, typed_name: &str) -> Option<String> {
242 match error {
243 Error::Domain(DomainError::Validation { field, reason }) => {
244 Some(format!("That {field} is no good: {reason}."))
245 }
246 Error::Domain(DomainError::AlreadyExists { .. }) => Some(format!(
247 "You already have a repository called {}.",
248 typed_name.trim()
249 )),
250 _ => None,
251 }
252}
253
254#[cfg(test)]
255mod tests {
256 use super::*;
257 use crate::{
258 domain::{
259 ImportState, Membership, MembershipId, OrgId, Organization, RepoName, Role, UserId,
260 repository::RepoRepository,
261 },
262 infrastructure::{
263 git::{InMemoryGitImport, InMemoryGitStorage},
264 repository::{InMemoryMembershipRepo, InMemoryOrgRepo, InMemoryRepoRepo},
265 },
266 };
267
268 struct Fixture {
269 orgs: InMemoryOrgRepo,
270 memberships: InMemoryMembershipRepo,
271 repos: InMemoryRepoRepo,
272 storage: InMemoryGitStorage,
273 owner: Actor,
274 member: Actor,
275 stranger: Actor,
276 handle: OrgName,
277 }
278
279 async fn fixture() -> Fixture {
280 let orgs = InMemoryOrgRepo::new();
281 let memberships = InMemoryMembershipRepo::new();
282
283 let org = Organization::new(OrgId::generate(), "acme", None).expect("valid org");
284 orgs.save(&org).await.expect("save org");
285
286 let owner = UserId::generate();
287 let member = UserId::generate();
288
289 for (user, role) in [(&owner, Role::Owner), (&member, Role::Member)] {
290 memberships
291 .save(&Membership::new(
292 MembershipId::generate(),
293 org.id.clone(),
294 user.clone(),
295 role,
296 ))
297 .await
298 .expect("save membership");
299 }
300
301 Fixture {
302 orgs,
303 memberships,
304 repos: InMemoryRepoRepo::new(),
305 storage: InMemoryGitStorage::new(),
306 owner: Actor::User(owner),
307 member: Actor::User(member),
308 stranger: Actor::User(UserId::generate()),
309 handle: org.name,
310 }
311 }
312
313 impl Fixture {
314 async fn import(&self, actor: &Actor, name: &str, source: &str) -> Result<Repository> {
315 import_repo(
316 actor,
317 &self.handle,
318 &NewImport {
319 name: name.to_owned(),
320 source: source.to_owned(),
321 },
322 &self.orgs,
323 &self.memberships,
324 &self.repos,
325 )
326 .await
327 }
328
329 async fn run(&self, id: &RepoId, importer: &InMemoryGitImport) -> Result<()> {
330 run_import(id, &self.handle, &self.repos, importer, &self.storage).await
331 }
332
333 async fn reload(&self, id: &RepoId) -> Repository {
334 self.repos
335 .find_by_id(id)
336 .await
337 .expect("lookup")
338 .expect("still there")
339 }
340 }
341
342 const SOURCE: &str = "https://example.com/thing.git";
343
344 #[tokio::test]
345 async fn an_owner_starts_an_import_and_the_row_says_so() {
346 let fixture = fixture().await;
347
348 let repo = fixture
349 .import(&fixture.owner, "thing", SOURCE)
350 .await
351 .expect("should start");
352
353 assert_eq!(repo.import_state, Some(ImportState::Importing));
354 assert_eq!(
355 repo.import_source.as_ref().map(ImportSource::as_str),
356 Some(SOURCE)
357 );
358 assert_eq!(repo.import_error, None);
359 // The row is what the background task and the page both read, so it has to be
360 // saved before this returns rather than by the task that has not started.
361 assert!(
362 fixture
363 .repos
364 .find_by_id(&repo.id)
365 .await
366 .expect("lookup")
367 .is_some()
368 );
369 }
370
371 #[tokio::test]
372 async fn a_blank_name_is_taken_from_the_url() {
373 let fixture = fixture().await;
374
375 let repo = fixture
376 .import(
377 &fixture.owner,
378 " ",
379 "https://github.com/rust-lang/mdBook.git",
380 )
381 .await
382 .expect("should start");
383
384 // Lowercased on the way through `RepoName`, like any other name.
385 assert_eq!(repo.name.as_str(), "mdbook");
386 }
387
388 #[tokio::test]
389 async fn a_url_with_no_path_and_no_name_is_a_validation_failure() {
390 let fixture = fixture().await;
391
392 let error = fixture
393 .import(&fixture.owner, "", "https://example.com")
394 .await
395 .expect_err("nothing to call it");
396
397 assert!(matches!(
398 error,
399 Error::Domain(DomainError::Validation { .. })
400 ));
401 }
402
403 #[tokio::test]
404 async fn only_an_owner_may_import() {
405 let fixture = fixture().await;
406
407 for actor in [&fixture.member, &fixture.stranger, &Actor::Anonymous] {
408 let error = fixture
409 .import(actor, "thing", SOURCE)
410 .await
411 .expect_err("should refuse");
412
413 assert!(matches!(error, Error::Domain(DomainError::Forbidden)));
414 }
415
416 // Nothing was recorded for any of them.
417 assert!(
418 fixture
419 .repos
420 .find_by_org_and_name(
421 &fixture
422 .orgs
423 .find_by_name(&fixture.handle)
424 .await
425 .expect("lookup")
426 .expect("org")
427 .id,
428 &RepoName::new("thing").expect("valid"),
429 )
430 .await
431 .expect("lookup")
432 .is_none()
433 );
434 }
435
436 #[tokio::test]
437 async fn a_source_that_is_not_a_public_https_url_is_refused_before_anything_is_written() {
438 let fixture = fixture().await;
439
440 for source in [
441 "http://example.com/thing.git",
442 "file:///etc/passwd",
443 "https://127.0.0.1/thing.git",
444 "https://169.254.169.254/latest/meta-data",
445 "",
446 ] {
447 let error = fixture
448 .import(&fixture.owner, "thing", source)
449 .await
450 .expect_err("should refuse");
451
452 assert!(
453 matches!(error, Error::Domain(DomainError::Validation { .. })),
454 "expected {source:?} to be a validation failure"
455 );
456 }
457 }
458
459 #[tokio::test]
460 async fn an_import_cannot_take_a_name_that_is_already_used() {
461 let fixture = fixture().await;
462 fixture
463 .import(&fixture.owner, "thing", SOURCE)
464 .await
465 .expect("first");
466
467 let error = fixture
468 .import(&fixture.owner, "thing", SOURCE)
469 .await
470 .expect_err("should refuse");
471
472 assert!(matches!(
473 error,
474 Error::Domain(DomainError::AlreadyExists { .. })
475 ));
476 }
477
478 #[tokio::test]
479 async fn a_finished_import_becomes_an_ordinary_repository() {
480 let fixture = fixture().await;
481 let repo = fixture
482 .import(&fixture.owner, "thing", SOURCE)
483 .await
484 .expect("start");
485
486 let importer = InMemoryGitImport::new();
487 fixture.run(&repo.id, &importer).await.expect("run");
488
489 let after = fixture.reload(&repo.id).await;
490
491 assert_eq!(after.import_state, None);
492 assert!(!after.is_importing());
493 assert_eq!(after.import_error, None);
494 // Provenance survives; the repository is still one that came from elsewhere.
495 assert_eq!(
496 after.import_source.as_ref().map(ImportSource::as_str),
497 Some(SOURCE)
498 );
499 assert_eq!(
500 importer.requests(),
501 vec![(
502 fixture.handle.to_string(),
503 "thing".to_owned(),
504 SOURCE.to_owned()
505 )]
506 );
507 }
508
509 #[tokio::test]
510 async fn a_failed_import_records_the_reason_and_removes_what_it_left() {
511 let fixture = fixture().await;
512 let repo = fixture
513 .import(&fixture.owner, "thing", SOURCE)
514 .await
515 .expect("start");
516
517 // The clone would have created the directory itself, so the fake is seeded with
518 // it to prove the cleanup runs.
519 fixture
520 .storage
521 .init_bare(&fixture.handle, &repo.name)
522 .await
523 .expect("seed a partial clone");
524
525 let importer = InMemoryGitImport::failing("repository not found");
526 fixture.run(&repo.id, &importer).await.expect("run");
527
528 let after = fixture.reload(&repo.id).await;
529
530 assert_eq!(after.import_state, Some(ImportState::Failed));
531 assert_eq!(after.import_error.as_deref(), Some("repository not found"));
532 assert!(
533 !fixture.storage.contains(&fixture.handle, &repo.name),
534 "a half-clone must not stay browsable over the git transport"
535 );
536 }
537
538 #[tokio::test]
539 async fn a_repository_deleted_while_it_imported_is_not_resurrected() {
540 let fixture = fixture().await;
541 let repo = fixture
542 .import(&fixture.owner, "thing", SOURCE)
543 .await
544 .expect("start");
545
546 // What `delete_repo` does, mid-clone.
547 fixture.repos.delete(&repo.id).await.expect("delete");
548
549 let importer = InMemoryGitImport::new();
550 fixture.run(&repo.id, &importer).await.expect("run");
551
552 assert!(
553 fixture
554 .repos
555 .find_by_id(&repo.id)
556 .await
557 .expect("lookup")
558 .is_none(),
559 "saving the copy loaded before the clone would bring the row back"
560 );
561 }
562
563 #[tokio::test]
564 async fn the_boot_sweep_fails_a_running_import_and_leaves_everything_else() {
565 let fixture = fixture().await;
566 let running = fixture
567 .import(&fixture.owner, "running", SOURCE)
568 .await
569 .expect("start");
570 let done = fixture
571 .import(&fixture.owner, "done", SOURCE)
572 .await
573 .expect("start");
574
575 let importer = InMemoryGitImport::new();
576 fixture.run(&done.id, &importer).await.expect("run");
577
578 let swept = sweep_interrupted_imports(&fixture.repos)
579 .await
580 .expect("sweep");
581
582 assert_eq!(swept, 1);
583 assert_eq!(
584 fixture.reload(&running.id).await.import_state,
585 Some(ImportState::Failed)
586 );
587 assert_eq!(
588 fixture.reload(&running.id).await.import_error.as_deref(),
589 Some(INTERRUPTED)
590 );
591 assert_eq!(fixture.reload(&done.id).await.import_state, None);
592 }
593
594 #[test]
595 fn a_credential_challenge_is_explained_as_a_missing_repository() {
596 // What GitHub actually answers for a path that is not there, once terminal
597 // prompts are off. Left as git wrote it, it describes Steid's configuration
598 // rather than the mistake.
599 let explained = explain(
600 "fatal: could not read Username for 'https://github.com': terminal prompts disabled",
601 );
602
603 assert!(explained.contains("could not be found"), "{explained}");
604 assert!(
605 explained.contains("public repositories only"),
606 "{explained}"
607 );
608 }
609
610 #[test]
611 fn every_other_failure_keeps_gits_own_words() {
612 // Inventing a friendlier wording for a failure nobody anticipated is how a real
613 // reason gets hidden.
614 assert_eq!(
615 explain("fatal: unable to access 'https://example.com/': Could not resolve host"),
616 "fatal: unable to access 'https://example.com/': Could not resolve host"
617 );
618 }
619
620 #[test]
621 fn a_long_failure_message_is_cut_and_says_so() {
622 let long = "x".repeat(MAX_ERROR_LEN + 50);
623 let cut = truncate(&long, MAX_ERROR_LEN);
624
625 assert!(cut.len() <= MAX_ERROR_LEN + '…'.len_utf8());
626 assert!(cut.ends_with('…'));
627 }
628
629 #[test]
630 fn cutting_a_message_never_splits_a_character() {
631 // A multi-byte character straddling the limit would panic on a byte slice.
632 let long = "é".repeat(MAX_ERROR_LEN);
633
634 let cut = truncate(&long, MAX_ERROR_LEN);
635
636 assert!(cut.ends_with('…'));
637 }
638
639 #[test]
640 fn a_short_message_is_left_alone() {
641 assert_eq!(truncate(" not found ", MAX_ERROR_LEN), "not found");
642 }
643}