forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

route_tests.rs628 lines, 16.4 KiBHistoryRawDownload
1//! Route tests for the LFS API, driven through the public router.
2
3use std::path::PathBuf;
4
5use base64::prelude::{BASE64_STANDARD, Engine};
6use forge_core::lfs_token::{self, LfsOp};
7use forge_core::mirrors::{MirrorDirection, NewMirror};
8use forge_core::token::{generate_token, hash_token};
9use forge_core::{Store, Visibility};
10use sha2::{Digest, Sha256};
11use topcoat::router::request::Request;
12use topcoat::router::{Body, Router, to_bytes};
13
14use crate::test_support::{KEY, app_router, test_state};
15
16const OWNER: &str = "tahinli";
17const REPO: &str = "demo";
18
19struct Fixture {
20 router: Router,
21 store: Store,
22 repo_id: String,
23 token: String,
24 data: PathBuf,
25 _dir: tempfile::TempDir,
26}
27
28/// One user with a PAT, and one repo of the given visibility.
29async fn fixture(visibility: Visibility) -> Fixture {
30 let dir = tempfile::tempdir().unwrap();
31 let data = dir.path().to_path_buf();
32 let state = test_state(&data).await;
33 let store = state.store.clone();
34 let router = app_router(state);
35
36 let tahinli = store
37 .create_user(OWNER, None, "not-a-real-hash", false)
38 .await
39 .unwrap();
40 let token = generate_token();
41 store
42 .create_token(
43 &tahinli.id,
44 "test",
45 &hash_token(&token),
46 &["repo".to_owned()],
47 None,
48 )
49 .await
50 .unwrap();
51 let repo = store
52 .create_repo(&tahinli.id, REPO, "", visibility, "main")
53 .await
54 .unwrap();
55 Fixture {
56 router,
57 store,
58 repo_id: repo.id,
59 token,
60 data,
61 _dir: dir,
62 }
63}
64
65impl Fixture {
66 /// Rebuilds the router with a different LFS size limit, in MiB.
67 async fn with_max_mb(&mut self, max_object_mb: u64) {
68 let mut state = test_state(&self.data).await;
69 state.store = self.store.clone();
70 let mut config = (*state.config).clone();
71 config.lfs.max_object_mb = max_object_mb;
72 state.set_config(config);
73 self.router = app_router(state);
74 }
75}
76
77fn basic(user: &str, token: &str) -> String {
78 format!(
79 "Basic {}",
80 BASE64_STANDARD.encode(format!("{user}:{token}"))
81 )
82}
83
84fn oid_of(bytes: &[u8]) -> String {
85 hex::encode(Sha256::digest(bytes))
86}
87
88struct Reply {
89 status: u16,
90 headers: http::HeaderMap,
91 body: Vec<u8>,
92}
93
94impl Reply {
95 fn json(&self) -> serde_json::Value {
96 serde_json::from_slice(&self.body).unwrap()
97 }
98}
99
100async fn send(
101 router: &Router,
102 method: &str,
103 uri: &str,
104 headers: &[(&str, &str)],
105 body: Vec<u8>,
106) -> Reply {
107 let mut builder = Request::builder().method(method).uri(uri);
108 for (name, value) in headers {
109 builder = builder.header(*name, *value);
110 }
111 let req = builder.body(Body::from(body)).unwrap();
112 let res = router.handle(req).await;
113 let status = res.status().as_u16();
114 let headers = res.headers().clone();
115 let body = to_bytes(res.into_body(), usize::MAX)
116 .await
117 .unwrap()
118 .to_vec();
119 Reply {
120 status,
121 headers,
122 body,
123 }
124}
125
126fn objects_uri(suffix: &str) -> String {
127 format!("/{OWNER}/{REPO}.git/info/lfs/objects{suffix}")
128}
129
130fn batch_body(operation: &str, objects: &[(String, u64)]) -> Vec<u8> {
131 let objects: Vec<_> = objects
132 .iter()
133 .map(|(oid, size)| serde_json::json!({ "oid": oid, "size": size }))
134 .collect();
135 serde_json::to_vec(&serde_json::json!({
136 "operation": operation,
137 "transfers": ["basic"],
138 "objects": objects,
139 }))
140 .unwrap()
141}
142
143/// Uploads `bytes` with the PAT and asserts it was stored.
144async fn upload_with_pat(fx: &Fixture, bytes: &[u8]) -> String {
145 let oid = oid_of(bytes);
146 let auth = basic(OWNER, &fx.token);
147 let reply = send(
148 &fx.router,
149 "PUT",
150 &objects_uri(&format!("/{oid}")),
151 &[("authorization", &auth)],
152 bytes.to_vec(),
153 )
154 .await;
155 assert_eq!(
156 reply.status,
157 200,
158 "{}",
159 String::from_utf8_lossy(&reply.body)
160 );
161 oid
162}
163
164#[tokio::test]
165async fn batch_download_returns_action_for_stored_object() {
166 let fx = fixture(Visibility::Public).await;
167 let oid = upload_with_pat(&fx, b"hello lfs\n").await;
168 let missing = oid_of(b"never stored");
169
170 let reply = send(
171 &fx.router,
172 "POST",
173 &objects_uri("/batch"),
174 &[("content-type", "application/vnd.git-lfs+json")],
175 batch_body("download", &[(oid.clone(), 10), (missing.clone(), 5)]),
176 )
177 .await;
178
179 assert_eq!(reply.status, 200);
180 assert_eq!(
181 reply.headers["content-type"],
182 "application/vnd.git-lfs+json"
183 );
184 let body = reply.json();
185 assert_eq!(body["transfer"], "basic");
186 let found = &body["objects"][0];
187 assert_eq!(found["oid"], oid);
188 assert_eq!(found["size"], 10);
189 let action = &found["actions"]["download"];
190 assert_eq!(
191 action["href"],
192 format!("https://forge.test/{OWNER}/{REPO}.git/info/lfs/objects/{oid}")
193 );
194 let header = action["header"]["Authorization"].as_str().unwrap();
195 assert!(header.starts_with("RemoteAuth "));
196 assert!(lfs_token::verify(
197 &KEY,
198 header.trim_start_matches("RemoteAuth "),
199 &fx.repo_id,
200 LfsOp::Download,
201 now(),
202 ));
203 assert_eq!(body["objects"][1]["error"]["code"], 404);
204
205 // Same router: the batch path without the `.git` suffix also answers (second object, same repo).
206 let oid = upload_with_pat(&fx, b"bare path\n").await;
207 let reply = send(
208 &fx.router,
209 "POST",
210 &format!("/{OWNER}/{REPO}/info/lfs/objects/batch"),
211 &[],
212 batch_body("download", &[(oid.clone(), 9)]),
213 )
214 .await;
215 assert_eq!(reply.status, 200, "path without .git");
216 assert!(reply.json()["objects"][0]["actions"]["download"].is_object());
217}
218
219#[tokio::test]
220async fn public_reads_need_no_credentials_and_private_ones_get_the_challenge() {
221 let public = fixture(Visibility::Public).await;
222 let oid = upload_with_pat(&public, b"public\n").await;
223 let get = send(
224 &public.router,
225 "GET",
226 &objects_uri(&format!("/{oid}")),
227 &[],
228 Vec::new(),
229 )
230 .await;
231 assert_eq!(get.status, 200);
232 assert_eq!(get.body, b"public\n");
233
234 let private = fixture(Visibility::Private).await;
235 let oid = upload_with_pat(&private, b"secret\n").await;
236 let batch = send(
237 &private.router,
238 "POST",
239 &objects_uri("/batch"),
240 &[],
241 batch_body("download", &[(oid.clone(), 7)]),
242 )
243 .await;
244 assert_eq!(batch.status, 401);
245 assert_eq!(batch.headers["lfs-authenticate"], "Basic realm=\"forge\"");
246 let get = send(
247 &private.router,
248 "GET",
249 &objects_uri(&format!("/{oid}")),
250 &[],
251 Vec::new(),
252 )
253 .await;
254 assert_eq!(get.status, 401);
255}
256
257#[tokio::test]
258async fn upload_batch_needs_a_valid_pat() {
259 let fx = fixture(Visibility::Public).await;
260 let oid = oid_of(b"data");
261 let body = batch_body("upload", &[(oid.clone(), 4)]);
262
263 let anonymous = send(
264 &fx.router,
265 "POST",
266 &objects_uri("/batch"),
267 &[],
268 body.clone(),
269 )
270 .await;
271 assert_eq!(anonymous.status, 401);
272 assert_eq!(
273 anonymous.headers["lfs-authenticate"],
274 "Basic realm=\"forge\""
275 );
276
277 let wrong = basic(OWNER, "not-a-token");
278 let bad = send(
279 &fx.router,
280 "POST",
281 &objects_uri("/batch"),
282 &[("authorization", &wrong)],
283 body.clone(),
284 )
285 .await;
286 assert_eq!(bad.status, 401);
287
288 let auth = basic(OWNER, &fx.token);
289 let good = send(
290 &fx.router,
291 "POST",
292 &objects_uri("/batch"),
293 &[("authorization", &auth)],
294 body,
295 )
296 .await;
297 assert_eq!(good.status, 200);
298 let actions = &good.json()["objects"][0]["actions"];
299 assert!(actions["upload"]["href"].as_str().unwrap().ends_with(&oid));
300 assert!(
301 actions["verify"]["href"]
302 .as_str()
303 .unwrap()
304 .ends_with("/objects/verify")
305 );
306}
307
308#[tokio::test]
309async fn upload_batch_skips_objects_already_linked() {
310 let fx = fixture(Visibility::Public).await;
311 let oid = upload_with_pat(&fx, b"already here\n").await;
312 let auth = basic(OWNER, &fx.token);
313 let reply = send(
314 &fx.router,
315 "POST",
316 &objects_uri("/batch"),
317 &[("authorization", &auth)],
318 batch_body("upload", &[(oid, 13)]),
319 )
320 .await;
321 assert_eq!(reply.status, 200);
322 assert!(reply.json()["objects"][0].get("actions").is_none());
323}
324
325#[tokio::test]
326async fn oid_and_size_are_validated() {
327 let mut fx = fixture(Visibility::Public).await;
328 let auth = basic(OWNER, &fx.token);
329 let upper = oid_of(b"x").to_uppercase();
330 let reply = send(
331 &fx.router,
332 "POST",
333 &objects_uri("/batch"),
334 &[("authorization", &auth)],
335 batch_body("upload", &[(upper, 1)]),
336 )
337 .await;
338 assert_eq!(reply.status, 422);
339
340 let reply = send(
341 &fx.router,
342 "POST",
343 &objects_uri("/batch"),
344 &[("authorization", &auth)],
345 batch_body("upload", &[("abc".into(), 1)]),
346 )
347 .await;
348 assert_eq!(reply.status, 422);
349
350 let reply = send(
351 &fx.router,
352 "PUT",
353 &objects_uri("/not-an-oid"),
354 &[("authorization", &auth)],
355 b"x".to_vec(),
356 )
357 .await;
358 assert_eq!(reply.status, 422);
359
360 fx.with_max_mb(1).await;
361 let too_big = 1024 * 1024 + 1;
362 let reply = send(
363 &fx.router,
364 "POST",
365 &objects_uri("/batch"),
366 &[("authorization", &auth)],
367 batch_body("upload", &[(oid_of(b"big"), too_big)]),
368 )
369 .await;
370 assert_eq!(reply.status, 422);
371
372 let reply = send(
373 &fx.router,
374 "POST",
375 &objects_uri("/batch"),
376 &[("authorization", &auth)],
377 br#"{"operation":"sideways","objects":[]}"#.to_vec(),
378 )
379 .await;
380 assert_eq!(reply.status, 422);
381}
382
383#[tokio::test]
384async fn put_rejects_a_hash_mismatch_and_stores_nothing() {
385 let fx = fixture(Visibility::Public).await;
386 let auth = basic(OWNER, &fx.token);
387 let claimed = oid_of(b"the promised bytes");
388 let reply = send(
389 &fx.router,
390 "PUT",
391 &objects_uri(&format!("/{claimed}")),
392 &[("authorization", &auth)],
393 b"different bytes".to_vec(),
394 )
395 .await;
396 assert_eq!(reply.status, 422);
397 assert_eq!(
398 fx.store
399 .lfs_object_size(&fx.repo_id, &claimed)
400 .await
401 .unwrap(),
402 None
403 );
404 assert!(!object_file(&fx.data, &claimed).exists());
405 let temp_dir = fx.data.join("lfs").join("tmp");
406 let leftovers = std::fs::read_dir(&temp_dir).map(|d| d.count()).unwrap_or(0);
407 assert_eq!(leftovers, 0, "a failed upload leaves no temp file");
408}
409
410#[tokio::test]
411async fn put_then_get_round_trips_the_bytes() {
412 let fx = fixture(Visibility::Private).await;
413 let data = vec![0xAB_u8; 300_000];
414 let oid = upload_with_pat(&fx, &data).await;
415
416 assert!(object_file(&fx.data, &oid).exists());
417 assert_eq!(
418 fx.store.lfs_object_size(&fx.repo_id, &oid).await.unwrap(),
419 Some(300_000)
420 );
421
422 let auth = basic(OWNER, &fx.token);
423 let got = send(
424 &fx.router,
425 "GET",
426 &objects_uri(&format!("/{oid}")),
427 &[("authorization", &auth)],
428 Vec::new(),
429 )
430 .await;
431 assert_eq!(got.status, 200);
432 assert_eq!(got.headers["content-length"], "300000");
433 assert_eq!(got.body, data);
434}
435
436#[tokio::test]
437async fn remote_auth_tokens_are_scoped_to_their_operation() {
438 let fx = fixture(Visibility::Private).await;
439 let body = b"token upload\n";
440 let oid = oid_of(body);
441 let expires = now() + 600;
442 let upload = lfs_token::issue(&KEY, &fx.repo_id, LfsOp::Upload, expires);
443 let download = lfs_token::issue(&KEY, &fx.repo_id, LfsOp::Download, expires);
444 let upload_auth = format!("RemoteAuth {upload}");
445 let download_auth = format!("RemoteAuth {download}");
446
447 let refused = send(
448 &fx.router,
449 "PUT",
450 &objects_uri(&format!("/{oid}")),
451 &[("authorization", &download_auth)],
452 body.to_vec(),
453 )
454 .await;
455 assert_eq!(refused.status, 401);
456
457 let stored = send(
458 &fx.router,
459 "PUT",
460 &objects_uri(&format!("/{oid}")),
461 &[("authorization", &upload_auth)],
462 body.to_vec(),
463 )
464 .await;
465 assert_eq!(stored.status, 200);
466
467 let got = send(
468 &fx.router,
469 "GET",
470 &objects_uri(&format!("/{oid}")),
471 &[("authorization", &download_auth)],
472 Vec::new(),
473 )
474 .await;
475 assert_eq!(got.status, 200);
476 assert_eq!(got.body, body);
477
478 let wrong_repo = lfs_token::issue(&KEY, "some-other-repo", LfsOp::Download, expires);
479 let got = send(
480 &fx.router,
481 "GET",
482 &objects_uri(&format!("/{oid}")),
483 &[("authorization", &format!("RemoteAuth {wrong_repo}"))],
484 Vec::new(),
485 )
486 .await;
487 assert_eq!(got.status, 401);
488}
489
490#[tokio::test]
491async fn verify_checks_presence_and_size() {
492 let fx = fixture(Visibility::Public).await;
493 let oid = upload_with_pat(&fx, b"verify me\n").await;
494 let auth = basic(OWNER, &fx.token);
495 let verify = |oid: String, size: u64| {
496 let body = serde_json::to_vec(&serde_json::json!({ "oid": oid, "size": size })).unwrap();
497 (body, auth.clone())
498 };
499
500 let (body, auth_value) = verify(oid.clone(), 10);
501 let ok = send(
502 &fx.router,
503 "POST",
504 &objects_uri("/verify"),
505 &[("authorization", &auth_value)],
506 body,
507 )
508 .await;
509 assert_eq!(ok.status, 200);
510
511 let (body, auth_value) = verify(oid.clone(), 11);
512 let mismatch = send(
513 &fx.router,
514 "POST",
515 &objects_uri("/verify"),
516 &[("authorization", &auth_value)],
517 body,
518 )
519 .await;
520 assert_eq!(mismatch.status, 422);
521
522 let (body, auth_value) = verify(oid_of(b"absent"), 6);
523 let absent = send(
524 &fx.router,
525 "POST",
526 &objects_uri("/verify"),
527 &[("authorization", &auth_value)],
528 body,
529 )
530 .await;
531 assert_eq!(absent.status, 404);
532}
533
534#[tokio::test]
535async fn archived_and_pull_mirror_repos_refuse_uploads() {
536 let fx = fixture(Visibility::Public).await;
537 let oid = oid_of(b"frozen\n");
538 let auth = basic(OWNER, &fx.token);
539 let batch = batch_body("upload", &[(oid.clone(), 7)]);
540
541 fx.store.set_repo_archived(&fx.repo_id, true).await.unwrap();
542 let reply = send(
543 &fx.router,
544 "POST",
545 &objects_uri("/batch"),
546 &[("authorization", &auth)],
547 batch.clone(),
548 )
549 .await;
550 assert_eq!(reply.status, 403);
551 let reply = send(
552 &fx.router,
553 "PUT",
554 &objects_uri(&format!("/{oid}")),
555 &[("authorization", &auth)],
556 b"frozen\n".to_vec(),
557 )
558 .await;
559 assert_eq!(reply.status, 403);
560 fx.store
561 .set_repo_archived(&fx.repo_id, false)
562 .await
563 .unwrap();
564
565 fx.store
566 .create_mirror(&NewMirror {
567 repo_id: &fx.repo_id,
568 direction: MirrorDirection::Pull,
569 url: "https://example.com/upstream.git",
570 username: "",
571 secret: None,
572 interval_minutes: 0,
573 })
574 .await
575 .unwrap();
576 let reply = send(
577 &fx.router,
578 "PUT",
579 &objects_uri(&format!("/{oid}")),
580 &[("authorization", &auth)],
581 b"frozen\n".to_vec(),
582 )
583 .await;
584 assert_eq!(reply.status, 403);
585 let reply = send(
586 &fx.router,
587 "POST",
588 &objects_uri("/batch"),
589 &[("authorization", &auth)],
590 batch,
591 )
592 .await;
593 assert_eq!(reply.status, 403);
594}
595
596#[tokio::test]
597async fn lock_paths_are_not_implemented() {
598 let fx = fixture(Visibility::Public).await;
599 let auth = basic(OWNER, &fx.token);
600 for (method, suffix) in [
601 ("GET", "/info/lfs/locks"),
602 ("POST", "/info/lfs/locks"),
603 ("POST", "/info/lfs/locks/verify"),
604 ("POST", "/info/lfs/locks/abc/unlock"),
605 ] {
606 let uri = format!("/{OWNER}/{REPO}.git{suffix}");
607 let reply = send(
608 &fx.router,
609 method,
610 &uri,
611 &[("authorization", &auth)],
612 Vec::new(),
613 )
614 .await;
615 assert_eq!(reply.status, 404, "{method} {uri}");
616 }
617}
618
619fn object_file(data: &std::path::Path, oid: &str) -> PathBuf {
620 crate::lfs::object_path(data, oid)
621}
622
623fn now() -> i64 {
624 std::time::SystemTime::now()
625 .duration_since(std::time::UNIX_EPOCH)
626 .map(|d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX))
627 .unwrap_or(0)
628}