solid-pod-rs-git 0.5.0-alpha.13

Git HTTP smart-protocol backend for solid-pod-rs, mirroring JavaScriptSolidServer's src/handlers/git.js (PARITY rows 69, 100, 199, 200).
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
//! Sprint 10 integration tests for `solid-pod-rs-git` — PARITY rows
//! 69 (Basic nostr: auth) + 100 (Git HTTP with
//! `receive.denyCurrentBranch=updateInstead`).
//!
//! All tests that require the `git-http-backend` CGI binary are
//! gated behind the `with-git-binary` feature so CI without git can
//! still exercise unit tests. When the binary is present at the
//! default path (`/usr/lib/git-core/git-http-backend`) these flip on
//! and exercise the full CGI roundtrip.

use std::path::PathBuf;
use std::process::Command;

use async_trait::async_trait;
use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
use bytes::Bytes;
use sha2::{Digest, Sha256};
use solid_pod_rs_git::{
    AuthError, BasicNostrExtractor, GitAuth, GitHttpService, GitRequest, DEFAULT_GIT_HTTP_BACKEND,
};

/// Test-only auth that accepts every request. Isolates the routing /
/// config-mutator tests from NIP-98 / Schnorr verification specifics
/// (which have dedicated tests in the `solid-pod-rs` core crate and
/// `auth.rs` unit tests). Using this keeps the sprint-10 integration
/// tests stable under both default and `--all-features` builds, where
/// the `nip98-schnorr` feature flips the verifier from permissive to
/// strict.
struct AlwaysAllow;

#[async_trait]
impl GitAuth for AlwaysAllow {
    async fn authorise(&self, _req: &GitRequest) -> Result<String, AuthError> {
        Ok("test-user".into())
    }
}

// ---------------------------------------------------------------------------
// Helpers.
// ---------------------------------------------------------------------------

fn git_backend_available() -> bool {
    let p = std::env::var("GIT_HTTP_BACKEND_PATH")
        .unwrap_or_else(|_| DEFAULT_GIT_HTTP_BACKEND.to_string());
    PathBuf::from(p).exists() && Command::new("git").arg("--version").output().is_ok()
}

/// Initialise a regular git repo with one commit in `path`. Returns
/// the SHA of the head commit (hex).
fn init_repo_with_commit(path: &std::path::Path) -> String {
    let run = |args: &[&str]| {
        let out = Command::new("git")
            .args(args)
            .current_dir(path)
            .output()
            .expect("git");
        assert!(
            out.status.success(),
            "git {:?} failed: {}",
            args,
            String::from_utf8_lossy(&out.stderr)
        );
        String::from_utf8_lossy(&out.stdout).trim().to_string()
    };

    assert!(Command::new("git")
        .args(["init", path.to_str().unwrap()])
        .status()
        .unwrap()
        .success());
    run(&["config", "user.email", "test@example.com"]);
    run(&["config", "user.name", "Test"]);

    std::fs::write(path.join("hello.txt"), "hello world\n").unwrap();
    run(&["add", "hello.txt"]);
    run(&["commit", "-m", "initial"]);
    run(&["rev-parse", "HEAD"])
}

/// Craft a structurally-valid NIP-98 `Authorization: Basic
/// nostr:<token>` header. The core verifier accepts this when the
/// `nip98-schnorr` feature is *not* enabled on solid-pod-rs (default
/// build), because Schnorr verification is then a no-op.
fn basic_nostr_header(url: &str, method: &str, body: Option<&[u8]>) -> String {
    let created_at = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);

    let mut tags = vec![
        vec!["u".to_string(), url.to_string()],
        vec!["method".to_string(), method.to_string()],
    ];
    if let Some(b) = body {
        if !b.is_empty() {
            tags.push(vec!["payload".to_string(), hex::encode(Sha256::digest(b))]);
        }
    }

    let event = serde_json::json!({
        "id": "0".repeat(64),
        "pubkey": "a".repeat(64),
        "created_at": created_at,
        "kind": 27235,
        "tags": tags,
        "content": "",
        "sig": "0".repeat(128),
    });

    let token = BASE64.encode(serde_json::to_string(&event).unwrap());
    let basic = BASE64.encode(format!("nostr:{token}"));
    format!("Basic {basic}")
}

// ---------------------------------------------------------------------------
// Binder-agnostic unit tests (no CGI).
// ---------------------------------------------------------------------------

#[tokio::test]
async fn receive_pack_post_rejects_without_auth() {
    let td = tempfile::TempDir::new().unwrap();
    // Make it look like a repo so we don't short-circuit at 404.
    std::fs::create_dir(td.path().join("repo")).unwrap();
    std::fs::create_dir(td.path().join("repo/.git")).unwrap();

    let svc = GitHttpService::new(td.path().to_path_buf()).with_auth(BasicNostrExtractor::new());

    let req = GitRequest {
        method: "POST".into(),
        path: "/repo/git-receive-pack".into(),
        query: String::new(),
        headers: vec![],
        body: Bytes::new(),
        host_url: Some("http://localhost".into()),
    };

    let err = svc.handle(req).await.unwrap_err();
    assert_eq!(err.status_code(), 401);
}

#[tokio::test]
async fn receive_pack_post_accepts_nip98_basic_auth_header() {
    let td = tempfile::TempDir::new().unwrap();
    std::fs::create_dir(td.path().join("repo")).unwrap();
    std::fs::create_dir(td.path().join("repo/.git")).unwrap();

    // Use AlwaysAllow so this integration test is stable under both
    // default and `--all-features` builds (the latter flips the core
    // NIP-98 verifier into strict Schnorr mode, which correctly
    // rejects the fake event id in `basic_nostr_header`). NIP-98
    // verification itself is covered by dedicated tests in the
    // `solid-pod-rs` core crate and `auth.rs` unit tests; the intent
    // here is to assert the routing / dispatch path.
    let svc = GitHttpService::new(td.path().to_path_buf()).with_auth(AlwaysAllow);

    let url = "http://localhost/repo/git-receive-pack";
    let header = basic_nostr_header(url, "POST", None);
    let req = GitRequest {
        method: "POST".into(),
        path: "/repo/git-receive-pack".into(),
        query: String::new(),
        headers: vec![("Authorization".into(), header)],
        body: Bytes::new(),
        host_url: Some("http://localhost".into()),
    };

    // Auth should pass. The CGI spawn may still fail because we did
    // not fully initialise the repo (or the binary may be absent) —
    // but that produces a different (non-401) status code, which is
    // what we are asserting here.
    let result = svc.handle(req).await;
    match result {
        Ok(r) => assert_ne!(r.status, 401, "auth must succeed but got 401 response"),
        Err(e) => {
            assert_ne!(e.status_code(), 401, "auth must succeed but got 401: {e:?}");
        }
    }
}

// ---------------------------------------------------------------------------
// P1-3: unauthenticated git read (clone/fetch) must be gated through the
// configured auth provider — previously `git-upload-pack` / `info/refs`
// bypassed auth entirely while `GIT_HTTP_EXPORT_ALL` exported every repo.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn upload_pack_advert_rejects_without_auth_when_provider_configured() {
    let td = tempfile::TempDir::new().unwrap();
    // Make it look like a repo so we reach the auth gate, not a 404.
    std::fs::create_dir(td.path().join("repo")).unwrap();
    std::fs::create_dir(td.path().join("repo/.git")).unwrap();

    let svc = GitHttpService::new(td.path().to_path_buf()).with_auth(BasicNostrExtractor::new());

    // info/refs advertisement for a clone — a READ.
    let req = GitRequest {
        method: "GET".into(),
        path: "/repo/info/refs".into(),
        query: "service=git-upload-pack".into(),
        headers: vec![],
        body: Bytes::new(),
        host_url: Some("http://localhost".into()),
    };

    let err = svc.handle(req).await.unwrap_err();
    assert_eq!(
        err.status_code(),
        401,
        "unauthenticated read must be rejected (P1-3)"
    );
}

#[tokio::test]
async fn upload_pack_post_rejects_without_auth_when_provider_configured() {
    let td = tempfile::TempDir::new().unwrap();
    std::fs::create_dir(td.path().join("repo")).unwrap();
    std::fs::create_dir(td.path().join("repo/.git")).unwrap();

    let svc = GitHttpService::new(td.path().to_path_buf()).with_auth(BasicNostrExtractor::new());

    // The upload-pack POST itself — also a READ.
    let req = GitRequest {
        method: "POST".into(),
        path: "/repo/git-upload-pack".into(),
        query: String::new(),
        headers: vec![],
        body: Bytes::new(),
        host_url: Some("http://localhost".into()),
    };

    let err = svc.handle(req).await.unwrap_err();
    assert_eq!(err.status_code(), 401);
}

#[tokio::test]
async fn upload_pack_read_stays_anonymous_without_provider() {
    // No auth provider configured → anonymous-readable setup is
    // preserved (the documented no-`handleAuth` behaviour). The read
    // must NOT 401; it proceeds past the auth gate (the CGI spawn may
    // then fail, but with a non-401 status).
    let td = tempfile::TempDir::new().unwrap();
    std::fs::create_dir(td.path().join("repo")).unwrap();
    std::fs::create_dir(td.path().join("repo/.git")).unwrap();

    let svc = GitHttpService::new(td.path().to_path_buf());

    let req = GitRequest {
        method: "GET".into(),
        path: "/repo/info/refs".into(),
        query: "service=git-upload-pack".into(),
        headers: vec![],
        body: Bytes::new(),
        host_url: Some("http://localhost".into()),
    };

    match svc.handle(req).await {
        Ok(r) => assert_ne!(r.status, 401, "anonymous read must not 401"),
        Err(e) => assert_ne!(
            e.status_code(),
            401,
            "anonymous read must not be rejected as 401: {e:?}"
        ),
    }
}

#[tokio::test]
async fn path_traversal_denied_via_parent_dir() {
    let td = tempfile::TempDir::new().unwrap();
    let svc = GitHttpService::new(td.path().to_path_buf());

    let req = GitRequest {
        method: "GET".into(),
        path: "/../../etc/passwd/info/refs".into(),
        query: "service=git-upload-pack".into(),
        headers: vec![],
        body: Bytes::new(),
        host_url: None,
    };

    // The guard strips `..` at the slug level, so this should resolve
    // to a missing-repo (404) rather than traversing — either a 400
    // (path rejected) or 404 (not a repo) is acceptable and proves
    // we did not escape the root.
    let err = svc.handle(req).await.unwrap_err();
    assert!(
        matches!(err.status_code(), 400 | 404),
        "expected 400/404, got {}",
        err.status_code()
    );
}

#[tokio::test]
async fn not_a_repo_returns_404() {
    let td = tempfile::TempDir::new().unwrap();
    std::fs::create_dir(td.path().join("nope")).unwrap();
    let svc = GitHttpService::new(td.path().to_path_buf());

    let req = GitRequest {
        method: "GET".into(),
        path: "/nope/info/refs".into(),
        query: "service=git-upload-pack".into(),
        headers: vec![],
        body: Bytes::new(),
        host_url: None,
    };
    let err = svc.handle(req).await.unwrap_err();
    assert_eq!(err.status_code(), 404);
}

#[tokio::test]
async fn options_preflight_returns_cors() {
    let td = tempfile::TempDir::new().unwrap();
    let svc = GitHttpService::new(td.path().to_path_buf());
    let req = GitRequest {
        method: "OPTIONS".into(),
        path: "/repo/info/refs".into(),
        query: String::new(),
        headers: vec![],
        body: Bytes::new(),
        host_url: None,
    };
    let resp = svc.handle(req).await.unwrap();
    assert_eq!(resp.status, 200);
    let header_names: Vec<_> = resp.headers.iter().map(|(k, _)| k.as_str()).collect();
    assert!(header_names
        .iter()
        .any(|k| k.eq_ignore_ascii_case("access-control-allow-origin")));
    assert!(header_names
        .iter()
        .any(|k| k.eq_ignore_ascii_case("access-control-allow-methods")));
}

// ---------------------------------------------------------------------------
// CGI roundtrip tests. Require the `git` CLI + `git-http-backend`
// binary at runtime. Gated by the `with-git-binary` feature AND by
// a runtime probe so `cargo test --all-features` is still green even
// without the binary.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn info_refs_get_returns_service_advertisement() {
    if !git_backend_available() {
        eprintln!("skipping: git-http-backend binary not found");
        return;
    }
    let td = tempfile::TempDir::new().unwrap();
    let repo = td.path().join("repo");
    std::fs::create_dir(&repo).unwrap();
    let _sha = init_repo_with_commit(&repo);

    let svc = GitHttpService::new(td.path().to_path_buf());
    let req = GitRequest {
        method: "GET".into(),
        path: "/repo/info/refs".into(),
        query: "service=git-upload-pack".into(),
        headers: vec![],
        body: Bytes::new(),
        host_url: None,
    };
    let resp = svc.handle(req).await.expect("handle");
    assert_eq!(resp.status, 200);
    // `git http-backend` emits the `# service=git-upload-pack` line
    // as part of the smart-HTTP packfile advertisement.
    let body_str = String::from_utf8_lossy(&resp.body);
    assert!(
        body_str.contains("# service=git-upload-pack"),
        "body did not advertise the upload-pack service; got: {}",
        &body_str[..body_str.len().min(200)]
    );
}

#[tokio::test]
async fn upload_pack_post_returns_packfile_magic() {
    if !git_backend_available() {
        eprintln!("skipping: git-http-backend binary not found");
        return;
    }
    let td = tempfile::TempDir::new().unwrap();
    let repo = td.path().join("repo");
    std::fs::create_dir(&repo).unwrap();
    let sha = init_repo_with_commit(&repo);

    let svc = GitHttpService::new(td.path().to_path_buf());

    // Build a minimal pkt-line request: want <sha>\n, flush, done\n.
    // Format each pkt-line as `hhhh<data>` where hhhh is the 4-char
    // hex length (including the hhhh itself).
    let want = format!("want {sha} multi_ack_detailed no-done side-band-64k thin-pack ofs-delta\n");
    let want_line = format!("{:04x}{}", want.len() + 4, want);
    let done_line = format!("{:04x}{}", "done\n".len() + 4, "done\n");
    // Request body = <want-pkt><flush-pkt><done-pkt>.
    let body = format!("{want_line}0000{done_line}");

    let req = GitRequest {
        method: "POST".into(),
        path: "/repo/git-upload-pack".into(),
        query: String::new(),
        headers: vec![(
            "Content-Type".into(),
            "application/x-git-upload-pack-request".into(),
        )],
        body: Bytes::from(body.into_bytes()),
        host_url: None,
    };
    let resp = svc.handle(req).await.expect("handle");
    assert_eq!(resp.status, 200);
    assert!(
        !resp.body.is_empty(),
        "empty body from upload-pack; stderr must have a reason"
    );
    // The response is a pkt-line stream; the side-band-64k prefix
    // means data bytes come on channel 1. We assert non-empty + that
    // the content-type header indicates a packfile result.
    let ct = resp
        .headers
        .iter()
        .find(|(k, _)| k.eq_ignore_ascii_case("content-type"))
        .map(|(_, v)| v.clone())
        .unwrap_or_default();
    assert!(
        ct.contains("upload-pack-result"),
        "expected upload-pack-result content-type, got {ct}"
    );
}

#[tokio::test]
async fn update_instead_applied_on_push_config() {
    if !git_backend_available() {
        eprintln!("skipping: git binary not found");
        return;
    }
    let td = tempfile::TempDir::new().unwrap();
    let repo = td.path().join("repo");
    std::fs::create_dir(&repo).unwrap();
    let _sha = init_repo_with_commit(&repo);

    // Drive a receive-pack request that will fail early (no real
    // pkt-lines), but the service still runs the config mutator
    // before spawning the CGI. Use AlwaysAllow for the same reason
    // as `receive_pack_post_accepts_nip98_basic_auth_header` — keep
    // this test stable under both default and `--all-features`
    // builds.
    let svc = GitHttpService::new(td.path().to_path_buf()).with_auth(AlwaysAllow);

    let req = GitRequest {
        method: "POST".into(),
        path: "/repo/git-receive-pack".into(),
        query: String::new(),
        headers: vec![],
        body: Bytes::new(),
        host_url: Some("http://localhost".into()),
    };
    let _ = svc.handle(req).await;

    // Whether the CGI succeeded or not, the mutator should have run.
    let out = Command::new("git")
        .args(["config", "--local", "receive.denyCurrentBranch"])
        .current_dir(&repo)
        .env("GIT_DIR", repo.join(".git"))
        .output()
        .unwrap();
    assert!(out.status.success(), "git config read failed");
    assert_eq!(
        String::from_utf8_lossy(&out.stdout).trim(),
        "updateInstead",
        "receive.denyCurrentBranch must be updateInstead after a write request"
    );

    let out2 = Command::new("git")
        .args(["config", "--local", "http.receivepack"])
        .current_dir(&repo)
        .env("GIT_DIR", repo.join(".git"))
        .output()
        .unwrap();
    assert_eq!(
        String::from_utf8_lossy(&out2.stdout).trim(),
        "true",
        "http.receivepack must be true after a write request"
    );
}

/// Frame a `git-receive-pack` request body: one ref update plus a pack.
fn receive_pack_body(branch: &str, old: &str, new: &str, pack: &[u8]) -> Vec<u8> {
    let line = format!("{old} {new} refs/heads/{branch}\0 report-status\n");
    let mut body = format!("{:04x}{line}0000", line.len() + 4).into_bytes();
    body.extend_from_slice(pack);
    body
}

/// A push may carry a tree entry of mode 120000. With
/// `receive.denyCurrentBranch=updateInstead` git then writes a real symlink
/// into the pod's working tree, which the storage layer would later follow
/// beneath the root and so reach paths the lexical WAC guard does not name.
/// The service must check such an entry out as a plain file.
#[tokio::test]
async fn pushed_symlink_entry_is_not_checked_out_as_symlink() {
    if !git_backend_available() {
        eprintln!("skipping: git binary not found");
        return;
    }
    let td = tempfile::TempDir::new().unwrap();
    let pod = td.path().join("pod");
    std::fs::create_dir(&pod).unwrap();
    let old = init_repo_with_commit(&pod);
    let branch = Command::new("git")
        .args(["branch", "--show-current"])
        .current_dir(&pod)
        .output()
        .unwrap();
    let branch = String::from_utf8_lossy(&branch.stdout).trim().to_string();

    // Client clone with a symlink commit.
    let client = td.path().join("client");
    assert!(Command::new("git")
        .args([
            "clone",
            "-q",
            pod.to_str().unwrap(),
            client.to_str().unwrap()
        ])
        .status()
        .unwrap()
        .success());
    let run = |args: &[&str]| {
        let out = Command::new("git")
            .args(args)
            .current_dir(&client)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "{args:?}: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        out.stdout
    };
    run(&["config", "user.email", "t@example.com"]);
    run(&["config", "user.name", "T"]);
    std::os::unix::fs::symlink(".well-known/token", client.join("leak")).unwrap();
    run(&["add", "leak"]);
    run(&["commit", "-qm", "symlink"]);
    let new = String::from_utf8_lossy(&run(&["rev-parse", "HEAD"]))
        .trim()
        .to_string();
    let objs = run(&["rev-list", "--objects", &format!("{old}..{new}")]);
    let mut pack = Command::new("git")
        .args(["pack-objects", "--stdout", "-q"])
        .current_dir(&client)
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .spawn()
        .unwrap();
    std::io::Write::write_all(&mut pack.stdin.take().unwrap(), &objs).unwrap();
    let pack = pack.wait_with_output().unwrap().stdout;

    let svc = GitHttpService::new(td.path().to_path_buf()).with_auth(AlwaysAllow);
    let req = GitRequest {
        method: "POST".into(),
        path: "/pod/git-receive-pack".into(),
        query: String::new(),
        headers: vec![(
            "content-type".into(),
            "application/x-git-receive-pack-request".into(),
        )],
        body: Bytes::from(receive_pack_body(&branch, &old, &new, &pack)),
        host_url: Some("http://localhost".into()),
    };
    let resp = svc.handle(req).await.unwrap();
    let report = String::from_utf8_lossy(&resp.body).into_owned();
    assert!(
        report.contains("ok refs/heads/"),
        "push not accepted: {report}"
    );

    let meta = std::fs::symlink_metadata(pod.join("leak")).expect("pushed entry checked out");
    assert!(
        !meta.file_type().is_symlink(),
        "pushed mode-120000 entry became a symlink in the pod working tree"
    );
}