1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
|
//! HTTP Git Servers for Testing
//!
//! This module provides two git server implementations for integration tests:
//!
//! ## `SimpleGitServer` (Dumb HTTP Protocol)
//!
//! Serves static files from a bare git repository using Git's "dumb HTTP" protocol.
//! This is lightweight but does NOT support shallow fetches (`git fetch --depth=1`).
//!
//! ## `SmartGitServer` (Smart HTTP Protocol)
//!
//! Implements the Git Smart HTTP protocol by spawning `git upload-pack` subprocesses.
//! This supports all git fetch operations including shallow fetches.
//!
//! # Usage
//!
//! ```ignore
//! use common::{SimpleGitServer, SmartGitServer};
//!
//! #[tokio::test]
//! async fn test_git_fetch() {
//! // Create a test repo
//! let temp_dir = tempfile::tempdir().unwrap();
//! create_test_repo_with_commit(temp_dir.path(), CommitVariant::StateTest).unwrap();
//!
//! // Use SmartGitServer for full protocol support (including shallow fetches)
//! let server = SmartGitServer::start(temp_dir.path()).await;
//!
//! // Git operations work against server.url()
//! let output = Command::new("git")
//! .args(["clone", "--depth=1", server.url(), "/tmp/clone"])
//! .output()
//! .unwrap();
//! assert!(output.status.success());
//!
//! // Server cleans up on drop
//! server.stop().await;
//! }
//! ```
//!
//! # When to Use Which
//!
//! - **SimpleGitServer**: Fast, lightweight, good for basic `git fetch` without depth limits
//! - **SmartGitServer**: Full protocol support, required for `--depth=1` shallow fetches
//!
//! The purgatory sync system uses `git fetch --depth=1`, so tests involving purgatory
//! sync should use `SmartGitServer`.
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;
use http_body_util::Full;
use hyper::body::Bytes;
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper::{Request, Response, StatusCode};
use hyper_util::rt::TokioIo;
use tokio::net::TcpListener;
use tokio::sync::oneshot;
/// Simple HTTP server for serving git repositories.
///
/// Creates a bare clone of a source repository and serves it over HTTP
/// using git's "dumb HTTP" protocol. Useful for testing git fetch operations
/// without needing a full git HTTP backend.
pub struct SimpleGitServer {
/// Shutdown signal sender
shutdown_tx: Option<oneshot::Sender<()>>,
/// Server task handle
handle: Option<tokio::task::JoinHandle<()>>,
/// Server URL (http://127.0.0.1:<port>)
url: String,
/// Server port
#[allow(dead_code)]
port: u16,
/// Temporary directory containing the bare repository
/// Kept alive for the lifetime of the server
_temp_dir: tempfile::TempDir,
}
impl SimpleGitServer {
/// Start a simple HTTP git server serving the given repository.
///
/// Creates a bare clone of the source repository, runs `git update-server-info`,
/// and starts an HTTP server to serve the repository files.
///
/// # Arguments
/// * `source_repo` - Path to the source git repository (can be non-bare)
///
/// # Returns
/// A `SimpleGitServer` instance with the server running
///
/// # Panics
/// Panics if the git operations fail or the server cannot start
pub async fn start(source_repo: &Path) -> Self {
// 1. Create temp directory for bare repo
let temp_dir = tempfile::tempdir().expect("Failed to create temp dir for git server");
let bare_repo_path = temp_dir.path().join("repo.git");
// 2. Create bare clone
let output = Command::new("git")
.args(["clone", "--bare"])
.arg(source_repo)
.arg(&bare_repo_path)
.output()
.expect("Failed to run git clone --bare");
if !output.status.success() {
panic!(
"git clone --bare failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
// 3. Run git update-server-info to generate info/refs and objects/info/packs
let output = Command::new("git")
.args(["update-server-info"])
.current_dir(&bare_repo_path)
.output()
.expect("Failed to run git update-server-info");
if !output.status.success() {
panic!(
"git update-server-info failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
// 4. Find a free port
let port = find_free_port();
let addr: SocketAddr = ([127, 0, 0, 1], port).into();
// 5. Create shutdown channel
let (shutdown_tx, mut shutdown_rx) = oneshot::channel::<()>();
// 6. Start the HTTP server
let repo_path = Arc::new(bare_repo_path);
let listener = TcpListener::bind(addr)
.await
.expect("Failed to bind to address");
let handle = tokio::spawn(async move {
println!("[SmartGitServer] Server loop started on port {}", port);
eprintln!("[SmartGitServer] Server loop started on port {}", port);
loop {
tokio::select! {
accept_result = listener.accept() => {
match accept_result {
Ok((stream, addr)) => {
eprintln!("[SmartGitServer] Accepted connection from {}", addr);
let repo_path = Arc::clone(&repo_path);
let io = TokioIo::new(stream);
tokio::spawn(async move {
let service = service_fn(move |req| {
let repo_path = Arc::clone(&repo_path);
async move { handle_request(req, &repo_path).await }
});
if let Err(e) = http1::Builder::new()
.serve_connection(io, service)
.await
{
// Connection errors are expected when client disconnects
if !e.to_string().contains("connection") {
eprintln!("SimpleGitServer connection error: {}", e);
}
}
});
}
Err(e) => {
eprintln!("SimpleGitServer accept error: {}", e);
}
}
}
_ = &mut shutdown_rx => {
// Shutdown signal received
break;
}
}
}
});
let url = format!("http://127.0.0.1:{}", port);
// 7. Wait for server to be ready
wait_for_server_ready(port).await;
Self {
shutdown_tx: Some(shutdown_tx),
handle: Some(handle),
url,
port,
_temp_dir: temp_dir,
}
}
/// Get the server URL.
///
/// Returns the HTTP URL where the git repository is served.
/// Can be used directly with `git clone`, `git fetch`, or `git ls-remote`.
pub fn url(&self) -> &str {
&self.url
}
/// Stop the server.
///
/// Sends a shutdown signal and waits for the server to stop.
/// The temporary directory is cleaned up when the server is dropped.
pub async fn stop(mut self) {
// Send shutdown signal
if let Some(tx) = self.shutdown_tx.take() {
let _ = tx.send(());
}
// Wait for server task to complete
if let Some(handle) = self.handle.take() {
let _ = handle.await;
}
}
}
impl Drop for SimpleGitServer {
fn drop(&mut self) {
// Send shutdown signal if not already sent
if let Some(tx) = self.shutdown_tx.take() {
let _ = tx.send(());
}
// Note: We can't await the handle in drop, but the temp_dir cleanup
// will happen automatically when _temp_dir is dropped
}
}
/// Handle an HTTP request by serving files from the git repository.
async fn handle_request(
req: Request<hyper::body::Incoming>,
repo_path: &Path,
) -> Result<Response<Full<Bytes>>, hyper::Error> {
let path = req.uri().path();
// Remove leading slash and construct file path
let relative_path = path.trim_start_matches('/');
let file_path = repo_path.join(relative_path);
// Security: ensure the path doesn't escape the repo directory
if !is_safe_path(&file_path, repo_path) {
return Ok(Response::builder()
.status(StatusCode::FORBIDDEN)
.body(Full::new(Bytes::from("Forbidden")))
.unwrap());
}
// Try to read the file
match tokio::fs::read(&file_path).await {
Ok(contents) => {
let content_type = guess_content_type(&file_path);
Ok(Response::builder()
.status(StatusCode::OK)
.header("Content-Type", content_type)
.body(Full::new(Bytes::from(contents)))
.unwrap())
}
Err(_) => Ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Full::new(Bytes::from("Not Found")))
.unwrap()),
}
}
/// Check if a path is safe (doesn't escape the repository directory).
fn is_safe_path(path: &Path, repo_path: &Path) -> bool {
match path.canonicalize() {
Ok(canonical) => canonical.starts_with(repo_path),
Err(_) => {
// If canonicalize fails, check if the path would escape
// by looking for .. components
!path.to_string_lossy().contains("..")
}
}
}
/// Guess the content type for a git-related file.
fn guess_content_type(path: &PathBuf) -> &'static str {
let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
if filename == "info/refs" || filename == "refs" {
"text/plain; charset=utf-8"
} else if filename.ends_with(".pack") {
"application/x-git-packed-objects"
} else if filename.ends_with(".idx") {
"application/x-git-packed-objects-toc"
} else {
"application/octet-stream"
}
}
/// Find a free port to use for the server.
fn find_free_port() -> u16 {
use std::net::TcpListener;
let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind to random port");
let port = listener
.local_addr()
.expect("Failed to get local addr")
.port();
drop(listener);
port
}
/// Wait for the server to be ready to accept connections.
async fn wait_for_server_ready(port: u16) {
let max_attempts = 50; // 5 seconds total
let delay = std::time::Duration::from_millis(100);
for attempt in 0..max_attempts {
match tokio::net::TcpStream::connect(format!("127.0.0.1:{}", port)).await {
Ok(_) => {
// Connection successful, server is ready
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
return;
}
Err(_) => {
if attempt == max_attempts - 1 {
panic!(
"SimpleGitServer failed to start after {} attempts",
max_attempts
);
}
tokio::time::sleep(delay).await;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::common::purgatory_helpers::{create_test_repo_with_commit, CommitVariant};
#[tokio::test]
async fn test_simple_git_server_starts_and_stops() {
// Create a test repo
let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
create_test_repo_with_commit(temp_dir.path(), CommitVariant::StateTest)
.expect("Failed to create test repo");
// Start server
let server = SimpleGitServer::start(temp_dir.path()).await;
// Verify URL is set
assert!(server.url().starts_with("http://127.0.0.1:"));
// Stop server
server.stop().await;
}
#[tokio::test]
async fn test_simple_git_server_serves_git_info_refs() {
// Create a test repo
let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
create_test_repo_with_commit(temp_dir.path(), CommitVariant::StateTest)
.expect("Failed to create test repo");
// Start server
let server = SimpleGitServer::start(temp_dir.path()).await;
// Fetch info/refs
let info_refs_url = format!("{}/info/refs", server.url());
let response = reqwest::get(&info_refs_url)
.await
.expect("Failed to fetch info/refs");
assert!(
response.status().is_success(),
"info/refs should be accessible"
);
let body = response.text().await.expect("Failed to read response body");
// Should contain at least one ref (HEAD or refs/heads/main)
assert!(
body.contains("refs/heads/main") || body.contains("HEAD"),
"info/refs should contain refs, got: {}",
body
);
server.stop().await;
}
#[tokio::test]
async fn test_git_ls_remote_from_simple_server() {
// Create a test repo
let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
let commit_hash = create_test_repo_with_commit(temp_dir.path(), CommitVariant::StateTest)
.expect("Failed to create test repo");
// Start server
let server = SimpleGitServer::start(temp_dir.path()).await;
// Run git ls-remote against the server (using tokio::process::Command)
let output = tokio::process::Command::new("git")
.args(["ls-remote", server.url()])
.output()
.await
.expect("Failed to run git ls-remote");
assert!(
output.status.success(),
"git ls-remote should succeed: {}",
String::from_utf8_lossy(&output.stderr)
);
let stdout = String::from_utf8_lossy(&output.stdout);
// Should list the main branch with the correct commit
assert!(
stdout.contains(&commit_hash),
"ls-remote output should contain commit {}, got: {}",
commit_hash,
stdout
);
assert!(
stdout.contains("refs/heads/main"),
"ls-remote output should contain refs/heads/main, got: {}",
stdout
);
server.stop().await;
}
#[tokio::test]
async fn test_git_fetch_from_simple_server() {
// Create a source repo with a commit
let source_dir = tempfile::tempdir().expect("Failed to create source dir");
let commit_hash = create_test_repo_with_commit(source_dir.path(), CommitVariant::StateTest)
.expect("Failed to create test repo");
// Start server serving the source repo
let server = SimpleGitServer::start(source_dir.path()).await;
// Create a destination repo to fetch into
let dest_dir = tempfile::tempdir().expect("Failed to create dest dir");
// Initialize empty repo (using tokio::process::Command)
let output = tokio::process::Command::new("git")
.args(["init"])
.current_dir(dest_dir.path())
.output()
.await
.expect("Failed to init dest repo");
assert!(output.status.success());
// Add the server as a remote
let output = tokio::process::Command::new("git")
.args(["remote", "add", "origin", server.url()])
.current_dir(dest_dir.path())
.output()
.await
.expect("Failed to add remote");
assert!(output.status.success());
// Fetch from the server
let output = tokio::process::Command::new("git")
.args(["fetch", "origin"])
.current_dir(dest_dir.path())
.output()
.await
.expect("Failed to fetch");
assert!(
output.status.success(),
"git fetch should succeed: {}",
String::from_utf8_lossy(&output.stderr)
);
// Verify the commit was fetched
let output = tokio::process::Command::new("git")
.args(["rev-parse", "origin/main"])
.current_dir(dest_dir.path())
.output()
.await
.expect("Failed to rev-parse");
assert!(output.status.success());
let fetched_commit = String::from_utf8_lossy(&output.stdout).trim().to_string();
assert_eq!(
fetched_commit, commit_hash,
"Fetched commit should match source commit"
);
server.stop().await;
}
#[test]
fn test_is_safe_path_blocks_traversal() {
let repo_path = Path::new("/tmp/repo");
// Safe paths
assert!(is_safe_path(Path::new("/tmp/repo/info/refs"), repo_path));
assert!(is_safe_path(
Path::new("/tmp/repo/objects/pack/file.pack"),
repo_path
));
// Unsafe paths (path traversal)
assert!(!is_safe_path(
Path::new("/tmp/repo/../etc/passwd"),
repo_path
));
assert!(!is_safe_path(
Path::new("/tmp/repo/../../etc/passwd"),
repo_path
));
}
}
// =============================================================================
// SmartGitServer - Git Smart HTTP Protocol Server
// =============================================================================
/// Smart HTTP server for serving git repositories with full protocol support.
///
/// Unlike `SimpleGitServer` which uses the "dumb HTTP" protocol (static files),
/// this server implements the Git Smart HTTP protocol by spawning `git upload-pack`
/// subprocesses. This enables:
///
/// - Shallow clones (`git clone --depth=1`)
/// - Shallow fetches (`git fetch --depth=1`)
/// - Full protocol negotiation
///
/// This is required for testing purgatory sync, which uses `git fetch --depth=1`.
pub struct SmartGitServer {
/// Shutdown signal sender
shutdown_tx: Option<oneshot::Sender<()>>,
/// Server task handle
handle: Option<tokio::task::JoinHandle<()>>,
/// Server URL (http://127.0.0.1:<port>)
url: String,
/// Server port
#[allow(dead_code)]
port: u16,
/// Temporary directory containing the bare repository
/// Kept alive for the lifetime of the server
_temp_dir: tempfile::TempDir,
}
impl SmartGitServer {
/// Start a smart HTTP git server serving the given repository.
///
/// Creates a bare clone of the source repository and starts an HTTP server
/// that implements the Git Smart HTTP protocol.
///
/// # Arguments
/// * `source_repo` - Path to the source git repository (can be non-bare)
///
/// # Returns
/// A `SmartGitServer` instance with the server running
///
/// # Panics
/// Panics if the git operations fail or the server cannot start
pub async fn start(source_repo: &Path) -> Self {
// 1. Create temp directory for bare repo
let temp_dir = tempfile::tempdir().expect("Failed to create temp dir for git server");
let bare_repo_path = temp_dir.path().join("repo.git");
// 2. Create bare clone
let output = Command::new("git")
.args(["clone", "--bare"])
.arg(source_repo)
.arg(&bare_repo_path)
.output()
.expect("Failed to run git clone --bare");
if !output.status.success() {
panic!(
"git clone --bare failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
// 3. Create and bind listener (eliminates port race condition)
let std_listener =
std::net::TcpListener::bind("127.0.0.1:0").expect("Failed to bind to random port");
let port = std_listener
.local_addr()
.expect("Failed to get local addr")
.port();
// Convert to tokio listener (keeps port bound)
std_listener
.set_nonblocking(true)
.expect("Failed to set non-blocking");
let listener =
TcpListener::from_std(std_listener).expect("Failed to convert to tokio listener");
// 4. Create shutdown channel
let (shutdown_tx, mut shutdown_rx) = oneshot::channel::<()>();
// 5. Start the HTTP server
let repo_path = Arc::new(bare_repo_path);
let handle = tokio::spawn(async move {
loop {
tokio::select! {
accept_result = listener.accept() => {
match accept_result {
Ok((stream, _addr)) => {
let repo_path = Arc::clone(&repo_path);
let io = TokioIo::new(stream);
tokio::spawn(async move {
let service = service_fn(move |req| {
let repo_path = Arc::clone(&repo_path);
async move { handle_smart_request(req, &repo_path).await }
});
if let Err(e) = http1::Builder::new()
.serve_connection(io, service)
.await
{
// Connection errors are expected when client disconnects
if !e.to_string().contains("connection") {
eprintln!("SmartGitServer connection error: {}", e);
}
}
});
}
Err(e) => {
eprintln!("SmartGitServer accept error: {}", e);
}
}
}
_ = &mut shutdown_rx => {
// Shutdown signal received
break;
}
}
}
});
let url = format!("http://127.0.0.1:{}", port);
// 6. Wait for server to be ready
wait_for_server_ready(port).await;
Self {
shutdown_tx: Some(shutdown_tx),
handle: Some(handle),
url,
port,
_temp_dir: temp_dir,
}
}
/// Get the server URL.
///
/// Returns the HTTP URL where the git repository is served.
/// Can be used directly with `git clone`, `git fetch`, or `git ls-remote`.
pub fn url(&self) -> &str {
&self.url
}
/// Stop the server.
///
/// Sends a shutdown signal and waits for the server to stop.
/// The temporary directory is cleaned up when the server is dropped.
pub async fn stop(mut self) {
// Send shutdown signal
if let Some(tx) = self.shutdown_tx.take() {
let _ = tx.send(());
}
// Wait for server task to complete
if let Some(handle) = self.handle.take() {
let _ = handle.await;
}
}
}
impl Drop for SmartGitServer {
fn drop(&mut self) {
// Send shutdown signal if not already sent
if let Some(tx) = self.shutdown_tx.take() {
let _ = tx.send(());
}
// Note: We can't await the handle in drop, but the temp_dir cleanup
// will happen automatically when _temp_dir is dropped
}
}
/// Handle an HTTP request using the Git Smart HTTP protocol.
async fn handle_smart_request(
req: Request<hyper::body::Incoming>,
repo_path: &Path,
) -> Result<Response<Full<Bytes>>, hyper::Error> {
let path = req.uri().path();
let query = req.uri().query().unwrap_or("");
let method = req.method();
// Extract Git-Protocol header (for protocol version 2)
// We need to clone it to avoid borrowing issues when moving req
let git_protocol = req
.headers()
.get("Git-Protocol")
.and_then(|v| v.to_str().ok())
.map(|s| s.to_string());
// Route: GET /info/refs?service=git-upload-pack
if method == hyper::Method::GET && path.ends_with("/info/refs") {
// Parse service from query string
let service = query.split('&').find_map(|param| {
let mut parts = param.splitn(2, '=');
match (parts.next(), parts.next()) {
(Some("service"), Some(svc)) => Some(svc),
_ => None,
}
});
match service {
Some("git-upload-pack") => {
return handle_info_refs_upload_pack(repo_path, git_protocol.as_deref()).await;
}
Some("git-receive-pack") => {
// We only support upload-pack for testing (fetch/clone)
return Ok(Response::builder()
.status(StatusCode::FORBIDDEN)
.body(Full::new(Bytes::from("receive-pack not supported")))
.unwrap());
}
_ => {
return Ok(Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(Full::new(Bytes::from(
"Missing or invalid service parameter",
)))
.unwrap());
}
}
}
// Route: POST /git-upload-pack
if method == hyper::Method::POST && path.ends_with("/git-upload-pack") {
return handle_upload_pack(req, repo_path, git_protocol.as_deref()).await;
}
// Not found
Ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Full::new(Bytes::from("Not Found")))
.unwrap())
}
/// Handle GET /info/refs?service=git-upload-pack
///
/// This advertises the repository's refs to the client using the smart protocol.
async fn handle_info_refs_upload_pack(
repo_path: &Path,
git_protocol_version: Option<&str>,
) -> Result<Response<Full<Bytes>>, hyper::Error> {
use std::process::Stdio;
use tokio::io::AsyncReadExt;
use tokio::process::Command as TokioCommand;
// Spawn git upload-pack --advertise-refs
let mut cmd = TokioCommand::new("git");
cmd.arg("-c")
.arg("uploadpack.allowReachableSHA1InWant=true")
.arg("-c")
.arg("uploadpack.allowTipSHA1InWant=true")
.arg("upload-pack")
.arg("--advertise-refs")
.arg("--stateless-rpc");
// Set GIT_PROTOCOL environment variable if version 2 is requested
if let Some(version) = git_protocol_version {
cmd.env("GIT_PROTOCOL", version);
}
cmd.arg(repo_path)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = match cmd.spawn() {
Ok(child) => child,
Err(e) => {
eprintln!("Failed to spawn git upload-pack: {}", e);
return Ok(Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(Full::new(Bytes::from("Failed to spawn git process")))
.unwrap());
}
};
// Read stdout
let mut output = Vec::new();
if let Some(mut stdout) = child.stdout.take() {
if let Err(e) = stdout.read_to_end(&mut output).await {
eprintln!("Failed to read git output: {}", e);
}
}
// Wait for process
let status = child.wait().await;
if let Ok(s) = &status {
if !s.success() {
eprintln!("git upload-pack --advertise-refs failed");
}
}
// Build response with pkt-line header
// Format: pkt-line("# service=git-upload-pack\n") + flush + git output
let mut response_body = Vec::new();
// First line: service advertisement
let service_line = "# service=git-upload-pack\n";
let len = service_line.len() + 4;
response_body.extend_from_slice(format!("{:04x}", len).as_bytes());
response_body.extend_from_slice(service_line.as_bytes());
// Flush packet
response_body.extend_from_slice(b"0000");
// Then the git output
response_body.extend_from_slice(&output);
Ok(Response::builder()
.status(StatusCode::OK)
.header(
"Content-Type",
"application/x-git-upload-pack-advertisement",
)
.header("Cache-Control", "no-cache")
.body(Full::new(Bytes::from(response_body)))
.unwrap())
}
/// Handle POST /git-upload-pack
///
/// This handles the actual fetch negotiation and pack data transfer.
async fn handle_upload_pack(
req: Request<hyper::body::Incoming>,
repo_path: &Path,
git_protocol_version: Option<&str>,
) -> Result<Response<Full<Bytes>>, hyper::Error> {
use http_body_util::BodyExt;
use std::process::Stdio;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::process::Command as TokioCommand;
// Read request body
let body_bytes = req.collect().await?.to_bytes();
// Spawn git upload-pack
let mut cmd = TokioCommand::new("git");
cmd.arg("-c")
.arg("uploadpack.allowReachableSHA1InWant=true")
.arg("-c")
.arg("uploadpack.allowTipSHA1InWant=true")
.arg("upload-pack")
.arg("--stateless-rpc");
// Set GIT_PROTOCOL environment variable if version 2 is requested
if let Some(version) = git_protocol_version {
cmd.env("GIT_PROTOCOL", version);
}
cmd.arg(repo_path)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = match cmd.spawn() {
Ok(child) => child,
Err(e) => {
eprintln!("Failed to spawn git upload-pack: {}", e);
return Ok(Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(Full::new(Bytes::from("Failed to spawn git process")))
.unwrap());
}
};
// Write request body to stdin
if let Some(mut stdin) = child.stdin.take() {
if let Err(e) = stdin.write_all(&body_bytes).await {
eprintln!("Failed to write to git stdin: {}", e);
}
// Close stdin to signal end of input
drop(stdin);
}
// Read stdout
let mut output = Vec::new();
if let Some(mut stdout) = child.stdout.take() {
if let Err(e) = stdout.read_to_end(&mut output).await {
eprintln!("Failed to read git output: {}", e);
}
}
// Read stderr for debugging
let mut stderr_output = Vec::new();
if let Some(mut stderr) = child.stderr.take() {
let _ = stderr.read_to_end(&mut stderr_output).await;
}
// Wait for process
let status = child.wait().await;
if let Ok(s) = &status {
if !s.success() {
let stderr_str = String::from_utf8_lossy(&stderr_output);
eprintln!("git upload-pack failed: {}", stderr_str);
}
}
Ok(Response::builder()
.status(StatusCode::OK)
.header("Content-Type", "application/x-git-upload-pack-result")
.header("Cache-Control", "no-cache")
.body(Full::new(Bytes::from(output)))
.unwrap())
}
#[cfg(test)]
mod smart_git_server_tests {
use super::*;
use crate::common::purgatory_helpers::{create_test_repo_with_commit, CommitVariant};
#[tokio::test]
async fn test_smart_git_server_starts_and_stops() {
// Create a test repo
let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
create_test_repo_with_commit(temp_dir.path(), CommitVariant::StateTest)
.expect("Failed to create test repo");
// Start server
let server = SmartGitServer::start(temp_dir.path()).await;
// Verify URL is set
assert!(server.url().starts_with("http://127.0.0.1:"));
// Stop server
server.stop().await;
}
#[tokio::test]
async fn test_smart_git_server_info_refs() {
// Create a test repo
let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
create_test_repo_with_commit(temp_dir.path(), CommitVariant::StateTest)
.expect("Failed to create test repo");
// Start server
let server = SmartGitServer::start(temp_dir.path()).await;
// Fetch info/refs with service parameter
let info_refs_url = format!("{}/info/refs?service=git-upload-pack", server.url());
let response = reqwest::get(&info_refs_url)
.await
.expect("Failed to fetch info/refs");
assert!(
response.status().is_success(),
"info/refs should be accessible"
);
// Check content type
let content_type = response
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("");
assert!(
content_type.contains("application/x-git-upload-pack-advertisement"),
"Content-Type should be git-upload-pack-advertisement, got: {}",
content_type
);
let body = response
.bytes()
.await
.expect("Failed to read response body");
// Should start with service advertisement pkt-line
let body_str = String::from_utf8_lossy(&body);
assert!(
body_str.contains("# service=git-upload-pack"),
"Response should contain service advertisement, got: {}",
body_str
);
server.stop().await;
}
#[tokio::test]
async fn test_smart_git_server_ls_remote() {
// Create a test repo
let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
let commit_hash = create_test_repo_with_commit(temp_dir.path(), CommitVariant::StateTest)
.expect("Failed to create test repo");
// Start server
let server = SmartGitServer::start(temp_dir.path()).await;
// Run git ls-remote against the server (using tokio::process::Command)
let output = tokio::process::Command::new("git")
.args(["ls-remote", server.url()])
.output()
.await
.expect("Failed to run git ls-remote");
assert!(
output.status.success(),
"git ls-remote should succeed: {}",
String::from_utf8_lossy(&output.stderr)
);
let stdout = String::from_utf8_lossy(&output.stdout);
// Should list the main branch with the correct commit
assert!(
stdout.contains(&commit_hash),
"ls-remote output should contain commit {}, got: {}",
commit_hash,
stdout
);
assert!(
stdout.contains("refs/heads/main"),
"ls-remote output should contain refs/heads/main, got: {}",
stdout
);
server.stop().await;
}
#[tokio::test]
async fn test_smart_git_server_fetch() {
// Create a source repo with a commit
let source_dir = tempfile::tempdir().expect("Failed to create source dir");
let commit_hash = create_test_repo_with_commit(source_dir.path(), CommitVariant::StateTest)
.expect("Failed to create test repo");
// Start server serving the source repo
let server = SmartGitServer::start(source_dir.path()).await;
// Create a destination repo to fetch into
let dest_dir = tempfile::tempdir().expect("Failed to create dest dir");
// Initialize empty repo
let output = tokio::process::Command::new("git")
.args(["init"])
.current_dir(dest_dir.path())
.output()
.await
.expect("Failed to init dest repo");
assert!(output.status.success());
// Add the server as a remote
let output = tokio::process::Command::new("git")
.args(["remote", "add", "origin", server.url()])
.current_dir(dest_dir.path())
.output()
.await
.expect("Failed to add remote");
assert!(output.status.success());
// Fetch from the server
let output = tokio::process::Command::new("git")
.args(["fetch", "origin"])
.current_dir(dest_dir.path())
.output()
.await
.expect("Failed to fetch");
assert!(
output.status.success(),
"git fetch should succeed: {}",
String::from_utf8_lossy(&output.stderr)
);
// Verify the commit was fetched
let output = tokio::process::Command::new("git")
.args(["rev-parse", "origin/main"])
.current_dir(dest_dir.path())
.output()
.await
.expect("Failed to rev-parse");
assert!(output.status.success());
let fetched_commit = String::from_utf8_lossy(&output.stdout).trim().to_string();
assert_eq!(
fetched_commit, commit_hash,
"Fetched commit should match source commit"
);
server.stop().await;
}
#[tokio::test]
async fn test_smart_git_server_shallow_fetch() {
// This is the KEY test - shallow fetch requires smart HTTP protocol
// Create a source repo with a commit
let source_dir = tempfile::tempdir().expect("Failed to create source dir");
let commit_hash = create_test_repo_with_commit(source_dir.path(), CommitVariant::StateTest)
.expect("Failed to create test repo");
// Start server serving the source repo
let server = SmartGitServer::start(source_dir.path()).await;
// Create a destination repo to fetch into
let dest_dir = tempfile::tempdir().expect("Failed to create dest dir");
// Initialize empty repo
let output = tokio::process::Command::new("git")
.args(["init"])
.current_dir(dest_dir.path())
.output()
.await
.expect("Failed to init dest repo");
assert!(output.status.success());
// Add the server as a remote
let output = tokio::process::Command::new("git")
.args(["remote", "add", "origin", server.url()])
.current_dir(dest_dir.path())
.output()
.await
.expect("Failed to add remote");
assert!(output.status.success());
// Shallow fetch from the server - THIS IS WHAT PURGATORY SYNC USES
let output = tokio::process::Command::new("git")
.args(["fetch", "--depth=1", "origin", &commit_hash])
.current_dir(dest_dir.path())
.output()
.await
.expect("Failed to fetch");
assert!(
output.status.success(),
"git fetch --depth=1 should succeed with smart HTTP: {}",
String::from_utf8_lossy(&output.stderr)
);
// Verify the commit was fetched
let output = tokio::process::Command::new("git")
.args(["cat-file", "-t", &commit_hash])
.current_dir(dest_dir.path())
.output()
.await
.expect("Failed to cat-file");
assert!(
output.status.success(),
"Commit should exist after shallow fetch"
);
let object_type = String::from_utf8_lossy(&output.stdout).trim().to_string();
assert_eq!(object_type, "commit", "Object should be a commit");
server.stop().await;
}
}
|