arks-server 1.3.11

Git server: upload-pack / receive-pack + smart/dumb HTTP + daemon (M11/M25)
Documentation
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
//! Host-advisory server unit tests (G15 is authoritative vs stock Git).

use super::*;
use arks_object::{Commit, ObjectKind, RawObject, Signature, Tree, TreeEntry, TreeMode};
use arks_repo::Repository;
use arks_store::{ObjectFormat, ObjectStore};
use std::sync::atomic::Ordering;
use std::thread;
use std::time::Duration;
use tempfile::TempDir;

fn seed_bare(root: &std::path::Path) -> (std::path::PathBuf, arks_oid::Oid) {
    let git = root.to_path_buf();
    std::fs::create_dir_all(git.join("objects")).unwrap();
    std::fs::create_dir_all(git.join("refs/heads")).unwrap();
    std::fs::write(git.join("HEAD"), b"ref: refs/heads/main\n").unwrap();
    let mut repo = Repository::open(&git).unwrap();
    let blob = RawObject::new(ObjectKind::Blob, b"hello server\n".to_vec());
    let blob_oid = repo.store_mut().put(ObjectFormat::Sha1, &blob).unwrap();
    let tree = Tree::new(vec![TreeEntry {
        mode: TreeMode::File,
        name: "hello.txt".into(),
        oid: blob_oid,
    }])
    .unwrap();
    let tree_obj = RawObject::new(ObjectKind::Tree, tree.encode().unwrap());
    let tree_oid = repo.store_mut().put(ObjectFormat::Sha1, &tree_obj).unwrap();
    let sig = Signature {
        name: "arks".into(),
        email: "arks@example.com".into(),
        timestamp: 1_700_000_000,
        timezone: "+0000".into(),
    };
    let commit = Commit {
        tree: tree_oid,
        parents: Vec::new(),
        author: sig.clone(),
        committer: sig,
        gpgsig: None,
        message: "initial\n".into(),
    };
    let commit_obj = RawObject::new(ObjectKind::Commit, commit.encode().unwrap());
    let commit_oid = repo
        .store_mut()
        .put(ObjectFormat::Sha1, &commit_obj)
        .unwrap();
    repo.refs_mut()
        .update("refs/heads/main", &commit_oid, None)
        .unwrap();
    (git, commit_oid)
}

#[test]
fn upload_advertisement_includes_main() {
    let dir = TempDir::new().unwrap();
    let (git, oid) = seed_bare(dir.path());
    let repo = Repository::open(&git).unwrap();
    let body = upload_advertisement(&repo).unwrap();
    let text = String::from_utf8_lossy(&body);
    assert!(text.contains("git-upload-pack"));
    assert!(text.contains(&oid.to_hex()));
    assert!(text.contains("refs/heads/main"));
    assert!(text.contains("side-band-64k"));
    assert!(!text.contains("agent=git/"));
}

#[test]
fn receive_advertises_delete_refs_and_report_status_v2() {
    let dir = TempDir::new().unwrap();
    let (git, _) = seed_bare(dir.path());
    let repo = Repository::open(&git).unwrap();
    let body = receive_advertisement(&repo).unwrap();
    let text = String::from_utf8_lossy(&body);
    assert!(text.contains("report-status"));
    assert!(text.contains("report-status-v2"));
    assert!(text.contains("delete-refs"));
    // O4: push-options advertised; FS2: proc-receive only when hook present.
    assert!(text.contains("push-options"));
    assert!(!text.contains("proc-receive"));
}

#[test]
fn receive_advertises_proc_receive_when_hook_present() {
    let dir = TempDir::new().unwrap();
    let (git, _) = seed_bare(dir.path());
    let hooks = git.join("hooks");
    std::fs::create_dir_all(&hooks).unwrap();
    let hook = hooks.join("proc-receive");
    std::fs::write(&hook, b"#!/bin/sh\nexit 0\n").unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = std::fs::metadata(&hook).unwrap().permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&hook, perms).unwrap();
    }
    let repo = Repository::open(&git).unwrap();
    let body = receive_advertisement(&repo).unwrap();
    let text = String::from_utf8_lossy(&body);
    assert!(
        text.contains("proc-receive"),
        "FS2 must advertise proc-receive when hook is runnable: {text}"
    );
}

#[test]
fn smart_http_info_refs_upload() {
    let dir = TempDir::new().unwrap();
    let (git, _) = seed_bare(dir.path());
    let mut repo = Repository::open(&git).unwrap();
    let req = HttpRequest {
        method: "GET".into(),
        path: "/repo.git/info/refs".into(),
        query: "service=git-upload-pack".into(),
        body: Vec::new(),
        git_protocol: None,
        authorization: None,
        destination: None,
        lock_token: None,
        host: None,
        cookie: None,
        origin: None,
        sec_fetch_site: None,
        forwarded_proto: None,
        headers: Vec::new(),
    };
    let resp = handle_smart_http(&mut repo, &req).unwrap();
    assert_eq!(resp.status, 200);
    assert!(resp.content_type.contains("git-upload-pack-advertisement"));
}

#[test]
fn smart_http_basic_auth_challenge_and_accept() {
    let dir = TempDir::new().unwrap();
    let (git, _) = seed_bare(dir.path());
    let mut repo = Repository::open(&git).unwrap();
    let cfg = BasicAuthConfig::single("alice", "s3cret");
    let denied = HttpRequest {
        method: "GET".into(),
        path: "/info/refs".into(),
        query: "service=git-upload-pack".into(),
        body: Vec::new(),
        git_protocol: None,
        authorization: None,
        destination: None,
        lock_token: None,
        host: None,
        cookie: None,
        origin: None,
        sec_fetch_site: None,
        forwarded_proto: None,
        headers: Vec::new(),
    };
    let resp = handle_smart_http_auth(&mut repo, &denied, Some(&cfg)).unwrap();
    assert_eq!(resp.status, 401);
    assert_eq!(
        resp.www_authenticate.as_deref(),
        Some("Basic realm=\"arks\"")
    );

    let ok = HttpRequest {
        method: "GET".into(),
        path: "/info/refs".into(),
        query: "service=git-upload-pack".into(),
        body: Vec::new(),
        git_protocol: None,
        authorization: Some(basic_authorization_header("alice", "s3cret")),
        destination: None,
        lock_token: None,
        host: None,
        cookie: None,
        origin: None,
        sec_fetch_site: None,
        forwarded_proto: None,
        headers: Vec::new(),
    };
    let resp = handle_smart_http_auth(&mut repo, &ok, Some(&cfg)).unwrap();
    assert_eq!(resp.status, 200);
    assert!(resp.content_type.contains("git-upload-pack-advertisement"));
}

#[test]
fn loopback_serves_info_refs() {
    let dir = TempDir::new().unwrap();
    let (git, _) = seed_bare(dir.path());
    let (addr, stop, handle) = spawn_loopback(git).unwrap();
    thread::sleep(Duration::from_millis(50));
    let url = format!("http://{addr}/info/refs?service=git-upload-pack");
    let body = ureq_get(&url);
    stop.store(true, Ordering::SeqCst);
    let _ = handle.join();
    assert!(body.contains("refs/heads/main") || body.contains("# service=git-upload-pack"));
}

fn ureq_get(url: &str) -> String {
    // Avoid adding ureq to arks-server deps: raw TCP client for the smoke test.
    use std::io::{Read, Write};
    use std::net::TcpStream;
    let url = url.strip_prefix("http://").unwrap();
    let (hostport, path) = url.split_once('/').unwrap();
    let mut stream = TcpStream::connect(hostport).unwrap();
    let req = format!("GET /{path} HTTP/1.1\r\nHost: {hostport}\r\nConnection: close\r\n\r\n");
    stream.write_all(req.as_bytes()).unwrap();
    let mut buf = Vec::new();
    stream.read_to_end(&mut buf).unwrap();
    String::from_utf8_lossy(&buf).into_owned()
}

fn zero_oid() -> String {
    "0".repeat(40)
}

fn receive_create_branch_body(new_oid: &arks_oid::Oid, refname: &str) -> Vec<u8> {
    use arks_protocol::{Packet, encode_packet};
    let line = format!("{} {} {}\n", zero_oid(), new_oid.to_hex(), refname);
    let mut body = encode_packet(&Packet::Data(line.into_bytes())).unwrap();
    body.extend(encode_packet(&Packet::Flush).unwrap());
    body
}

fn install_hook(git: &std::path::Path, name: &str, script: &str) {
    let hooks = git.join("hooks");
    std::fs::create_dir_all(&hooks).unwrap();
    let path = hooks.join(name);
    std::fs::write(&path, script).unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = std::fs::metadata(&path).unwrap().permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&path, perms).unwrap();
    }
}

#[test]
fn receive_pre_receive_hook_rejects_entire_push() {
    let dir = TempDir::new().unwrap();
    let (git, oid) = seed_bare(dir.path());
    install_hook(&git, "pre-receive", "#!/bin/sh\nexit 1\n");
    let mut repo = Repository::open(&git).unwrap();
    let body = receive_create_branch_body(&oid, "refs/heads/topic");
    let out = receive_pack(&mut repo, &body).unwrap();
    let text = String::from_utf8_lossy(&out);
    assert!(
        text.contains("pre-receive hook declined"),
        "expected decline in {text}"
    );
    assert!(repo.refs().resolve("refs/heads/topic").is_err());
}

#[test]
fn receive_update_hook_rejects_one_ref() {
    let dir = TempDir::new().unwrap();
    let (git, oid) = seed_bare(dir.path());
    install_hook(&git, "update", "#!/bin/sh\nexit 1\n");
    let mut repo = Repository::open(&git).unwrap();
    let body = receive_create_branch_body(&oid, "refs/heads/topic");
    let out = receive_pack(&mut repo, &body).unwrap();
    let text = String::from_utf8_lossy(&out);
    assert!(text.contains("hook declined"), "expected decline in {text}");
    assert!(repo.refs().resolve("refs/heads/topic").is_err());
}

#[test]
fn receive_post_receive_runs_after_success() {
    let dir = TempDir::new().unwrap();
    let (git, oid) = seed_bare(dir.path());
    let marker = git.join("post-receive-ran");
    // Isolate scratch under $GIT_DIR (per-push; no shared parallel scratch).
    install_hook(
        &git,
        "post-receive",
        "#!/bin/sh\ncat > \"$GIT_DIR/post-receive-ran\"\n",
    );
    let mut repo = Repository::open(&git).unwrap();
    let body = receive_create_branch_body(&oid, "refs/heads/topic");
    let out = receive_pack(&mut repo, &body).unwrap();
    let text = String::from_utf8_lossy(&out);
    assert!(
        text.contains("ok refs/heads/topic"),
        "expected ok in {text}"
    );
    assert_eq!(repo.refs().resolve("refs/heads/topic").unwrap(), oid);
    assert!(
        marker.is_file(),
        "post-receive should have written {}",
        marker.display()
    );
}

#[test]
fn v2_advertises_and_serves_bundle_uri() {
    let dir = TempDir::new().unwrap();
    let (git, _) = seed_bare(dir.path());
    std::fs::write(
        git.join("arks-bundle-uris"),
        "https://example.test/seed.bundle\n",
    )
    .unwrap();
    let lines = v2_capability_lines();
    assert!(
        lines.iter().any(|l| l == "bundle-uri"),
        "G3 must advertise bundle-uri: {lines:?}"
    );
    let repo = Repository::open(&git).unwrap();
    // command=bundle-uri + flush
    let mut body = arks_protocol::encode_text_line("command=bundle-uri").unwrap();
    body.extend(arks_protocol::encode_packet(&arks_protocol::Packet::Flush).unwrap());
    let out = handle_v2_request(&repo, &body, true).unwrap();
    let text = String::from_utf8_lossy(&out);
    assert!(text.contains("bundle.version=1"), "{text}");
    assert!(
        text.contains("bundle.seed1.uri=https://example.test/seed.bundle"),
        "{text}"
    );
}

struct RefuseNamed(&'static str);

impl PushPolicy for RefuseNamed {
    fn check(&self, _: &Repository, pusher: &Pusher, updates: &[RefUpdate]) -> Vec<Option<String>> {
        assert_eq!(pusher.transport, "local");
        updates
            .iter()
            .map(|u| (u.name == self.0).then(|| format!("rule says no\nfor {}", u.name)))
            .collect()
    }
}

#[test]
fn receive_push_policy_refuses_one_ref_and_keeps_the_other() {
    use arks_protocol::{Packet, encode_packet};
    let dir = TempDir::new().unwrap();
    let (git, oid) = seed_bare(dir.path());
    let mut repo = Repository::open(&git).unwrap();
    let mut body = Vec::new();
    for name in ["refs/heads/a", "refs/heads/b"] {
        let line = format!("{} {} {name}\n", zero_oid(), oid.to_hex());
        body.extend(encode_packet(&Packet::Data(line.into_bytes())).unwrap());
    }
    body.extend(encode_packet(&Packet::Flush).unwrap());
    let policy = RefuseNamed("refs/heads/b");
    let out = receive_pack_with(&mut repo, &body, &Pusher::local(), Some(&policy)).unwrap();
    let text = String::from_utf8_lossy(&out);
    assert!(text.contains("ok refs/heads/a"), "{text}");
    // Reasons are single-line in report-status.
    assert!(
        text.contains("ng refs/heads/b rule says no for refs/heads/b\n"),
        "{text}"
    );
    assert_eq!(repo.refs().resolve("refs/heads/a").unwrap(), oid);
    assert!(repo.refs().resolve("refs/heads/b").is_err());
}

struct WrongArity;

impl PushPolicy for WrongArity {
    fn check(&self, _: &Repository, _: &Pusher, _: &[RefUpdate]) -> Vec<Option<String>> {
        Vec::new()
    }
}

#[test]
fn receive_push_policy_wrong_arity_fails_closed() {
    let dir = TempDir::new().unwrap();
    let (git, oid) = seed_bare(dir.path());
    let mut repo = Repository::open(&git).unwrap();
    let body = receive_create_branch_body(&oid, "refs/heads/topic");
    let out = receive_pack_with(&mut repo, &body, &Pusher::local(), Some(&WrongArity)).unwrap();
    let text = String::from_utf8_lossy(&out);
    assert!(
        text.contains("ng refs/heads/topic push policy error"),
        "{text}"
    );
    assert!(repo.refs().resolve("refs/heads/topic").is_err());
}

#[test]
fn basic_auth_reports_the_authorized_user() {
    let cfg = BasicAuthConfig::single("alice", "s3cret");
    let ok = basic_authorization_header("alice", "s3cret");
    assert_eq!(cfg.authorized_user(Some(&ok)).as_deref(), Some("alice"));
    let bad = basic_authorization_header("alice", "nope");
    assert_eq!(cfg.authorized_user(Some(&bad)), None);
}

/// Annotated tag object pointing at `target`, stored and referenced as `refs/tags/<name>`.
fn put_tag(repo: &mut Repository, name: &str, target: arks_oid::Oid) -> arks_oid::Oid {
    let body = format!(
        "object {}\ntype commit\ntag {name}\ntagger arks <arks@example.com> 1700000000 +0000\n\n{name}\n",
        target.to_hex()
    );
    let oid = repo
        .store_mut()
        .put(
            ObjectFormat::Sha1,
            &RawObject::new(ObjectKind::Tag, body.into_bytes()),
        )
        .unwrap();
    repo.refs_mut()
        .update(&format!("refs/tags/{name}"), &oid, None)
        .unwrap();
    oid
}

/// Object count from the PACK header of a raw (no side-band) upload-pack reply.
fn pack_object_count(reply: &[u8]) -> u32 {
    let at = reply
        .windows(4)
        .position(|w| w == b"PACK")
        .expect("PACK header in reply");
    u32::from_be_bytes(reply[at + 8..at + 12].try_into().unwrap())
}

fn want_request(oid: &arks_oid::Oid, caps: &str) -> Vec<u8> {
    use arks_protocol::{Packet, encode_packet};
    let mut body = encode_packet(&Packet::Data(
        format!("want {} {caps}\n", oid.to_hex()).into_bytes(),
    ))
    .unwrap();
    body.extend(encode_packet(&Packet::Flush).unwrap());
    body.extend(encode_packet(&Packet::Data(b"done\n".to_vec())).unwrap());
    body
}

#[test]
fn upload_pack_include_tag_adds_tags_pointing_into_the_pack() {
    let dir = TempDir::new().unwrap();
    let (git, commit) = seed_bare(dir.path());
    let mut repo = Repository::open(&git).unwrap();
    put_tag(&mut repo, "v1", commit);
    // A tag on an unrelated root commit must not ride along.
    let sig = Signature {
        name: "arks".into(),
        email: "arks@example.com".into(),
        timestamp: 1_700_000_001,
        timezone: "+0000".into(),
    };
    let tree = repo.get_object(&commit).unwrap();
    let tree_oid = Commit::decode(&tree.payload).unwrap().tree;
    let other = Commit {
        tree: tree_oid,
        parents: Vec::new(),
        author: sig.clone(),
        committer: sig,
        gpgsig: None,
        message: "unrelated\n".into(),
    };
    let other_oid = repo
        .store_mut()
        .put(
            ObjectFormat::Sha1,
            &RawObject::new(ObjectKind::Commit, other.encode().unwrap()),
        )
        .unwrap();
    put_tag(&mut repo, "elsewhere", other_oid);

    let advert = String::from_utf8_lossy(&upload_advertisement(&repo).unwrap()).to_string();
    assert!(advert.contains("include-tag"), "{advert}");
    let without = upload_pack_result(&repo, &want_request(&commit, "ofs-delta")).unwrap();
    assert_eq!(pack_object_count(&without), 3, "blob, tree, commit");
    let with = upload_pack_result(&repo, &want_request(&commit, "ofs-delta include-tag")).unwrap();
    assert_eq!(pack_object_count(&with), 4, "plus the v1 tag object only");
}

#[test]
fn transient_accept_error_classifies_emfile_and_aborted_without_exiting() {
    use std::io::{Error, ErrorKind};

    assert!(crate::serve::is_transient_accept_error(&Error::new(
        ErrorKind::WouldBlock,
        "would block"
    )));
    assert!(crate::serve::is_transient_accept_error(&Error::new(
        ErrorKind::Interrupted,
        "eintr"
    )));
    assert!(crate::serve::is_transient_accept_error(&Error::new(
        ErrorKind::ConnectionAborted,
        "aborted"
    )));
    assert!(crate::serve::is_transient_accept_error(&Error::new(
        ErrorKind::ConnectionReset,
        "reset"
    )));
    #[cfg(unix)]
    {
        // EMFILE (24) & ENFILE (23) must back off transiently instead of killing the server.
        assert!(crate::serve::is_transient_accept_error(
            &Error::from_raw_os_error(24)
        ));
        assert!(crate::serve::is_transient_accept_error(
            &Error::from_raw_os_error(23)
        ));
        // EBADF (9) is fatal (closed listener) and must not be treated as transient.
        assert!(!crate::serve::is_transient_accept_error(
            &Error::from_raw_os_error(9)
        ));
    }
    #[cfg(windows)]
    {
        assert!(crate::serve::is_transient_accept_error(
            &Error::from_raw_os_error(10024)
        ));
        assert!(!crate::serve::is_transient_accept_error(
            &Error::from_raw_os_error(10009)
        ));
    }
}

#[test]
fn slowloris_header_dribble_evicted_with_408_request_timeout() {
    use std::io::{Read, Write};
    use std::net::TcpStream;

    let dir = TempDir::new().unwrap();
    let (git, _) = seed_bare(dir.path());
    let opts = ServeHttpOptions {
        header_timeout: Some(Duration::from_millis(600)),
        ..ServeHttpOptions::default()
    };
    let (addr, stop, handle) = spawn_loopback_with_opts(git, opts).unwrap();

    let mut sock = TcpStream::connect(addr).unwrap();
    sock.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
    sock.write_all(b"GET /healthz HTTP/1.1\r\nHost: 127.0.0.1\r\nX-Slow: ")
        .unwrap();
    // Dribble bytes at 120ms intervals (each resetting a per-read timer) then await the 600ms
    // cumulative header deadline without writing past peer close (avoids Windows TCP RST).
    for _ in 0..3 {
        thread::sleep(Duration::from_millis(120));
        if sock.write_all(b"a").is_err() {
            break;
        }
    }
    let mut reply = Vec::new();
    let _ = sock.read_to_end(&mut reply);
    let reply_text = String::from_utf8_lossy(&reply);
    assert!(
        reply_text.starts_with("HTTP/1.1 408 Request Timeout"),
        "expected HTTP 408 Request Timeout on Slowloris dribble, got: {reply_text:?}"
    );
    assert!(
        reply_text.contains("Connection: close"),
        "408 response must close connection: {reply_text:?}"
    );

    stop.store(true, Ordering::SeqCst);
    handle.join().unwrap().unwrap();
}

#[test]
fn atomic_concurrency_slot_reservation_never_exceeds_limit() {
    use std::sync::atomic::AtomicUsize;
    use std::sync::{Arc, Barrier};

    let limit = 6usize;
    let base = crate::serve::active_http_connections();
    let cap = base + limit;
    let barrier = Arc::new(Barrier::new(24));
    let granted = Arc::new(AtomicUsize::new(0));
    let peak = Arc::new(AtomicUsize::new(0));

    let mut handles = Vec::new();
    for _ in 0..24 {
        let b = barrier.clone();
        let g = granted.clone();
        let p = peak.clone();
        handles.push(thread::spawn(move || {
            b.wait();
            if let Some(_guard) = crate::serve::try_reserve_http_slot_with_limit(cap) {
                let cur = crate::serve::active_http_connections();
                p.fetch_max(cur, Ordering::SeqCst);
                g.fetch_add(1, Ordering::SeqCst);
                thread::sleep(Duration::from_millis(80));
            }
        }));
    }
    for h in handles {
        h.join().unwrap();
    }
    assert!(
        granted.load(Ordering::SeqCst) <= limit,
        "granted {} > limit {limit}",
        granted.load(Ordering::SeqCst)
    );
    assert!(
        peak.load(Ordering::SeqCst) <= cap,
        "peak {} > cap {cap}",
        peak.load(Ordering::SeqCst)
    );
}

#[test]
fn forgestore_startup_gc_sweeps_dead_pid_temps_only() {
    let dir = TempDir::new().unwrap();
    let forge_dir = dir.path().join("arks-forge");
    std::fs::create_dir_all(&forge_dir).unwrap();

    let canonical = forge_dir.join("store.json");
    let dead1 = forge_dir.join(".store.json.999991.12.tmp");
    let dead2 = forge_dir.join(".store.json.999992.34.tmp");
    let live = forge_dir.join(".store.json.424242.7.tmp");
    let unrelated = forge_dir.join("other.tmp");

    std::fs::write(&canonical, b"{\"issues\":[]}").unwrap();
    std::fs::write(&dead1, b"partial-1").unwrap();
    std::fs::write(&dead2, b"partial-2").unwrap();
    std::fs::write(&live, b"in-flight").unwrap();
    std::fs::write(&unrelated, b"keep-me").unwrap();

    let removed =
        crate::web_ui::store::sweep_stale_temps_in_dir_with(&forge_dir, |pid, _| pid == 424_242);
    assert_eq!(
        removed, 2,
        "must remove exactly the two dead-PID temp files"
    );
    assert!(canonical.exists(), "canonical store.json must stay intact");
    assert!(!dead1.exists(), "dead1 temp file must be swept");
    assert!(!dead2.exists(), "dead2 temp file must be swept");
    assert!(live.exists(), "live PID temp file must NOT be removed");
    assert!(unrelated.exists(), "unrelated file must NOT be removed");
}

#[test]
fn forgestore_load_shared_reuses_arc_and_invalidates_on_commit() {
    use std::sync::Arc;

    let dir = TempDir::new().unwrap();
    let mut tx = crate::web_ui::store::ForgeStore::lock_mut(dir.path());
    tx.create_issue("First".into(), "body".into(), "alice".into(), vec![], None);
    tx.commit().unwrap();

    let s1 = crate::web_ui::store::ForgeStore::load_shared(dir.path());
    let s2 = crate::web_ui::store::ForgeStore::load_shared(dir.path());
    assert!(
        Arc::ptr_eq(&s1, &s2),
        "cached load_shared must share the same Arc without deep-cloning ForgeStore"
    );
    assert_eq!(s1.issues.len(), 1);

    let mut tx2 = crate::web_ui::store::ForgeStore::lock_mut(dir.path());
    tx2.create_issue("Second".into(), "body".into(), "bob".into(), vec![], None);
    tx2.commit().unwrap();

    let s3 = crate::web_ui::store::ForgeStore::load_shared(dir.path());
    assert!(
        !Arc::ptr_eq(&s1, &s3),
        "committing a new transaction must refresh the cached Arc snapshot"
    );
    assert_eq!(s3.issues.len(), 2);
}

#[test]
fn unified_api_get_and_non_api_routes_never_block_on_forgestore_write_lock() {
    use std::sync::mpsc;

    let dir = TempDir::new().unwrap();
    let (repo_dir, _head) = seed_bare(dir.path());

    // Seed store.json so the read cache is warm.
    {
        let mut tx = crate::web_ui::store::ForgeStore::lock_mut(&repo_dir);
        tx.create_issue("Warm".into(), "body".into(), "alice".into(), vec![], None);
        tx.commit().unwrap();
    }
    let _warm = crate::web_ui::store::ForgeStore::load_shared(&repo_dir);

    // Hold the exclusive per-repo write mutex on the main thread.
    let _held_write_lock = crate::web_ui::store::ForgeStore::lock_mut(&repo_dir);

    let repo_dir_bg = repo_dir.clone();
    let (tx_done, rx_done) = mpsc::channel();
    let handle = std::thread::spawn(move || {
        // Non-API Web UI GET (`/issues`) and REST API GET (`/api/v1/issues`)
        // must both complete without blocking on the write mutex.
        let r_web = crate::web_ui::handle_web_ui(
            &repo_dir_bg,
            &crate::http::HttpRequest::new("GET", "/issues", "", Vec::new()),
        )
        .expect("GET /issues must return a response");
        assert_eq!(r_web.status, 200);

        let r_api = crate::web_ui::handle_web_ui(
            &repo_dir_bg,
            &crate::http::HttpRequest::new("GET", "/api/v1/issues", "", Vec::new()),
        )
        .expect("GET /api/v1/issues must return a response");
        assert_eq!(r_api.status, 200);
        let parsed: serde_json::Value = serde_json::from_slice(&r_api.body).unwrap();
        assert_eq!(parsed.as_array().unwrap().len(), 1);
        let _ = tx_done.send(());
    });

    rx_done
        .recv_timeout(Duration::from_secs(2))
        .expect("GET /issues and GET /api/v1/issues deadlocked on ForgeStore write lock!");
    drop(_held_write_lock);
    handle.join().unwrap();
}

#[test]
fn http_request_smuggling_headers_rejected_with_400_and_server_stays_healthy() {
    use std::io::{Read, Write};
    use std::net::TcpStream;

    let dir = TempDir::new().unwrap();
    let (git, _) = seed_bare(dir.path());
    let (addr, stop, handle) = spawn_loopback_with_opts(git, ServeHttpOptions::default()).unwrap();

    let send_raw = |raw: &[u8]| -> String {
        let mut sock = TcpStream::connect(addr).unwrap();
        sock.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
        sock.write_all(raw).unwrap();
        let _ = sock.shutdown(std::net::Shutdown::Write);
        let mut buf = Vec::new();
        let _ = sock.read_to_end(&mut buf);
        String::from_utf8_lossy(&buf).into_owned()
    };

    // 1. Conflicting duplicate Content-Length headers (RFC 9112 ยง6.3)
    let resp_dup = send_raw(
        b"POST /healthz HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 4\r\nContent-Length: 8\r\nConnection: close\r\n\r\nbody",
    );
    assert!(
        resp_dup.starts_with("HTTP/1.1 400 "),
        "conflicting duplicate Content-Length must return 400, got: {resp_dup:?}"
    );

    // 2. Malformed non-numeric Content-Length header
    let resp_bad_cl = send_raw(
        b"POST /healthz HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 12abc\r\nConnection: close\r\n\r\n",
    );
    assert!(
        resp_bad_cl.starts_with("HTTP/1.1 400 "),
        "malformed Content-Length must return 400, got: {resp_bad_cl:?}"
    );

    // 3. Ambiguous Transfer-Encoding + Content-Length (CL.TE / TE.CL smuggling)
    let resp_te_cl = send_raw(
        b"POST /healthz HTTP/1.1\r\nHost: 127.0.0.1\r\nTransfer-Encoding: chunked\r\nContent-Length: 5\r\nConnection: close\r\n\r\n0\r\n\r\n",
    );
    assert!(
        resp_te_cl.starts_with("HTTP/1.1 400 "),
        "ambiguous Transfer-Encoding + Content-Length must return 400, got: {resp_te_cl:?}"
    );

    // 4. Subsequent valid request still succeeds cleanly.
    let resp_ok =
        send_raw(b"GET /healthz HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n");
    assert!(
        resp_ok.starts_with("HTTP/1.1 200 "),
        "server must remain healthy after rejecting smuggling probes, got: {resp_ok:?}"
    );

    stop.store(true, Ordering::Relaxed);
    let _ = handle.join();
}