(* Copyright (c) 2024-2026 Thomas Gazagnaire Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) open Ssh_fixture (* gitprotocol-v2(5), "Initial Client Request", "SSH and File Transport": over SSH a client asks for v2 by setting GIT_PROTOCOL to version=2, which git's ssh passes in an env request (RFC 4254, 6.4) before the exec, and "the server may need to be configured to allow this environment variable to pass". A server that takes it answers with its capability advertisement, and the client lists the refs with the ls-refs command ("ls-refs") and fetches with fetch ("fetch"); one that does not, as sshd whose AcceptEnv does not name GIT_PROTOCOL, answers v0 (gitprotocol-pack(5), "Reference Discovery"), and the client reads the same refs and objects in v0. Each server must be asked, in order: ls-refs for a listing; ls-refs then fetch for a fetch of refs, and ls-refs alone for a second fetch of refs the client then holds, as git's fetch-pack sends no fetch when every wanted object is local; and nothing in v0. *) let test_ssh_protocol_v2 () = let main = ref None and topic = ref None in let srepo ~sw ~fs = let r = Test_helpers.init_bare ~sw ~fs (Fpath.v (Filename.temp_dir "gsv2" "")) in let commit msg = let blob = Git_eio.Repository.write_blob r (msg ^ " payload\n") in let tree = Git_eio.Repository.write_tree r (Git.Tree.v [ Git.Tree.entry ~perm:`Normal ~name:"F" blob ]) in let a = Git.User.v ~name:"n" ~email:"n@e" ~date:0L () in Git_eio.Repository.write_commit r (Git.Commit.v ~tree ~author:a ~committer:a (Some (msg ^ "\n"))) in let m = commit "main" and t = commit "topic" in Git_eio.Repository.write_ref r "refs/heads/main" m; Git_eio.Repository.write_ref r "refs/heads/topic" t; Git_eio.Repository.write_symbolic_ref r "HEAD" ~target:"refs/heads/main"; main := Some m; topic := Some t; r in let hex r = Git.Hash.to_hex (Option.get !r) in List.iter (fun (accept, listed, fetched) -> let what = if accept then "v2" else "v0" in let commands = ref [] in let session f = commands := []; let r = against ~on_request:(fun c -> commands := c :: !commands) ~accept_git_protocol:accept srepo f in (r, List.rev !commands) in let adv, seen = session @@ fun ~sw ~net ~mono ~fs:_ ~port -> Git_ssh.ls_refs ~authenticator:`No_authentication ~sw ~net ~mono ~port ~user:"git" (`Pubkey client_key) ~host:"127.0.0.1" "/srv" in (match adv with | Error (#Git_ssh.error as e) -> Alcotest.failf "%s ls_refs: %a" what Git_ssh.pp_error e | Ok adv -> Alcotest.(check (list (pair string string))) (what ^ ": every ref with its value") [ ("HEAD", hex main); ("refs/heads/main", hex main); ("refs/heads/topic", hex topic); ] (List.sort compare (List.map (fun (r : Git.Smart.Message.ref_entry) -> (r.name, Git.Hash.to_hex r.hash)) adv.refs)); Alcotest.(check bool) (what ^ ": HEAD's symref") true (List.mem "symref=HEAD:refs/heads/main" adv.capabilities)); Alcotest.(check (list string)) (what ^ ": ls_refs commands") listed seen; let got, seen = session @@ fun ~sw ~net ~mono ~fs ~port -> let dst = Git_eio.Repository.init ~sw ~fs (Fpath.v (Filename.temp_dir "gsv2d" "")) in let fetch () = Git_ssh.fetch_refs ~authenticator:`No_authentication ~sw ~net ~mono ~port ~user:"git" (`Pubkey client_key) ~host:"127.0.0.1" ~dst ~select:(fun r -> if String.starts_with ~prefix:"refs/heads/" r then Some ("refs/remotes/origin/" ^ String.sub r 11 (String.length r - 11)) else None) "/srv" in Result.bind (fetch ()) @@ fun got -> let held = List.for_all (fun (_, h) -> Git_eio.Repository.exists dst h) got in Result.map (fun again -> (got, held, again)) (fetch ()) in (match got with | Error (#Git_ssh.error as e) -> Alcotest.failf "%s fetch_refs: %a" what Git_ssh.pp_error e | Ok (got, held, again) -> Alcotest.(check (list (pair string string))) (what ^ ": the same refs, fetched again") (List.map (fun (r, h) -> (r, Git.Hash.to_hex h)) got) (List.map (fun (r, h) -> (r, Git.Hash.to_hex h)) again); Alcotest.(check (list (pair string string))) (what ^ ": each branch with its value") [ ("refs/remotes/origin/main", hex main); ("refs/remotes/origin/topic", hex topic); ] (List.sort compare (List.map (fun (r, h) -> (r, Git.Hash.to_hex h)) got)); Alcotest.(check bool) (what ^ ": the objects arrived") true held); Alcotest.(check (list string)) (what ^ ": fetch_refs commands") fetched seen) [ (true, [ "ls-refs" ], [ "ls-refs"; "fetch"; "ls-refs" ]); (false, [], []); ] (* [n] commits written into [r] on [parent], the i-th named [name ^ i] and dated [date + i], so two repositories given the same arguments hold the same commits; the last one, or [parent] when [n] is 0. *) let chain r ~name ~date ?parent n = let objects = ref [] in let add value = objects := value :: !objects; Git.Value.digest value in let rec go parent i = if i = n then parent else let msg = name ^ string_of_int i in let blob = add (Git.Value.Blob (Git.Blob.of_string (msg ^ "\n"))) in let tree = add (Git.Value.Tree (Git.Tree.v [ Git.Tree.entry ~perm:`Normal ~name:"F" blob ])) in let parents = Option.to_list parent in let a = Git.User.v ~name:"n" ~email:"n@e" ~date:(Int64.of_int (date + i)) () in go (Some (add (Git.Value.Commit (Git.Commit.v ~tree ~parents ~author:a ~committer:a (Some (msg ^ "\n")))))) (i + 1) in let tip = go parent 0 in let pack, _ = Test_helpers.or_fail "encode fixture history" (Git.Pack.encode_objects ~version:2 (List.rev !objects)) in ignore (Test_helpers.or_fail "store fixture history" (Git_eio.Repository.write_pack r pack)); tip (* gitprotocol-pack(5), "Packfile Negotiation", and git's default negotiator (fetch-pack.c): a client offers the commits it holds newest first, round after round, until the server has found the history they share, and the server then sends only what that history lacks. The client's one ref is [ahead] commits past the last commit both hold, more than any fixed depth of haves per tip, as a replica's notes run ahead of the copy it last pushed; the server's main is one commit past that shared commit. In v2 and in v0 the pack the fetch stores is that commit, its tree and its blob. *) let test_ssh_fetch_shared_history ahead () = let srepo ~sw ~fs = let r = Test_helpers.init_bare ~sw ~fs (Fpath.v (Filename.temp_dir "gsnh" "")) in let base = chain r ~name:"shared" ~date:0 5 in let main = chain r ~name:"new" ~date:1_000_000 ?parent:base 1 in Git_eio.Repository.write_ref r "refs/heads/main" (Option.get main); Git_eio.Repository.write_symbolic_ref r "HEAD" ~target:"refs/heads/main"; r in List.iter (fun accept -> let what = if accept then "v2" else "v0" in let stored = ref [] in let got = against ~accept_git_protocol:accept srepo @@ fun ~sw ~net ~mono ~fs ~port -> let dst = Git_eio.Repository.init ~sw ~fs (Fpath.v (Filename.temp_dir "gsnhd" "")) in let base = chain dst ~name:"shared" ~date:0 5 in let tip = chain dst ~name:"local" ~date:100 ?parent:base ahead in Git_eio.Repository.write_ref dst "refs/heads/local" (Option.get tip); Git_ssh.fetch_refs ~authenticator:`No_authentication ~sw ~net ~mono ~port ~user:"git" (`Pubkey client_key) ~host:"127.0.0.1" ~dst ~on_progress:(function | Git.Progress.Written n -> stored := n :: !stored | _ -> ()) ~select:(fun r -> if r = "refs/heads/main" then Some "refs/remotes/origin/main" else None) "/srv" in match got with | Error (#Git_ssh.error as e) -> Alcotest.failf "%s fetch_refs: %a" what Git_ssh.pp_error e | Ok got -> Alcotest.(check (list string)) (what ^ ": main fetched") [ "refs/remotes/origin/main" ] (List.map fst got); Alcotest.(check (list int)) (what ^ ": the pack holds the new commit, its tree and its blob") [ 3 ] !stored) [ true; false ] (* The single-ref fetch asks for protocol v2 as the others do, and a second fetch, after the server's main moved on, sends what it holds ("fetch", "have ") and is answered ready with the pack in the same response ("acknowledgments", "ready"). A server that takes GIT_PROTOCOL is asked ls-refs then fetch each time, one that does not answers v0 and is asked nothing; both give main's commit, FETCH_HEAD and origin/main. *) let test_ssh_fetch_v2 () = List.iter (fun (accept, expected) -> let what = if accept then "v2" else "v0" in let commands = ref [] and server = ref None in let srepo ~sw ~fs = let r = repo_with_blob 64 ~sw ~fs in server := Some r; r in let advance () = let r = Option.get !server in let parent = Option.get (ref_read r "refs/heads/main") in let blob = Git_eio.Repository.write_blob r "second\n" in let tree = Git_eio.Repository.write_tree r (Git.Tree.v [ Git.Tree.entry ~perm:`Normal ~name:"G" blob ]) in let a = Git.User.v ~name:"n" ~email:"n@e" ~date:0L () in let c = Git_eio.Repository.write_commit r (Git.Commit.v ~tree ~parents:[ parent ] ~author:a ~committer:a (Some "second\n")) in Git_eio.Repository.write_ref r "refs/heads/main" c in let got = against ~on_request:(fun c -> commands := c :: !commands) ~accept_git_protocol:accept srepo @@ fun ~sw ~net ~mono ~fs ~port -> let dst = Git_eio.Repository.init ~sw ~fs (Fpath.v (Filename.temp_dir "gsf2" "")) in let fetch () = Git_ssh.fetch ~authenticator:`No_authentication ~sw ~net ~mono ~port ~user:"git" (`Pubkey client_key) ~host:"127.0.0.1" ~dst ~ref_name:"main" "/srv" in let state h = ( Git.Hash.to_hex h, Option.map Git.Hash.to_hex (ref_read dst "FETCH_HEAD"), Option.map Git.Hash.to_hex (ref_read dst "refs/remotes/origin/main") ) in Result.bind (fetch ()) @@ fun first -> let before = state first in advance (); let main = Git.Hash.to_hex (Option.get (ref_read (Option.get !server) "refs/heads/main")) in Result.map (fun second -> (main, before, state second)) (fetch ()) in match got with | Error (#Git_ssh.error as e) -> Alcotest.failf "%s fetch: %a" what Git_ssh.pp_error e | Ok (main, (first, _, _), (h, fetch_head, tracking)) -> Alcotest.(check bool) (what ^ ": main moved") true (first <> main); Alcotest.(check string) (what ^ ": main") main h; Alcotest.(check (option string)) (what ^ ": FETCH_HEAD") (Some main) fetch_head; Alcotest.(check (option string)) (what ^ ": origin/main") (Some main) tracking; Alcotest.(check (list string)) (what ^ ": commands") expected (List.rev !commands)) [ (true, [ "ls-refs"; "fetch"; "ls-refs"; "fetch" ]); (false, []) ] (* What a peer can make a fetch spend is its budget, the bytes the session reads: at two sizes an order of magnitude apart, a pack past the budget is refused naming the budget, and the same pack within a budget of four times its size is fetched. *) let test_ssh_fetch_budget () = List.iter (fun size -> let fetch bytes = against (repo_with_blob size) @@ fun ~sw ~net ~mono ~fs ~port -> let dst = Git_eio.Repository.init ~sw ~fs (Fpath.v (Filename.temp_dir "gsbd" "")) in Git_ssh.fetch_refs ~budget:(budget bytes) ~authenticator:`No_authentication ~sw ~net ~mono ~port ~user:"git" (`Pubkey client_key) ~host:"127.0.0.1" ~dst ~select:(fun r -> if r = "refs/heads/main" then Some r else None) "/srv" in (match fetch (4 * size) with | Ok [ ("refs/heads/main", _) ] -> () | Ok _ -> Alcotest.failf "%d bytes: not main alone" size | Error (`Host_key e) -> Alcotest.failf "%a" Git_ssh.pp_host_key_error e | Error (`Auth e) -> Alcotest.failf "%a" Git_ssh.pp_auth_error e | Error (`Msg m) -> Alcotest.failf "%d bytes within budget: %s" size m); let bound = size / 2 in match fetch bound with | Ok _ -> Alcotest.failf "a %d-byte pack within %d bytes" size bound | Error (`Host_key e) -> Alcotest.failf "%a" Git_ssh.pp_host_key_error e | Error (`Auth e) -> Alcotest.failf "%a" Git_ssh.pp_auth_error e | Error (`Msg m) -> Alcotest.(check bool) (Fmt.str "names the bound: %s" m) true (contains ~sub:(Fmt.str "more than %d bytes" bound) m)) [ 16 * 1024; 160 * 1024 ] (* What a server sends for a listing: in v0 its advertisement, in v2 its capability advertisement and its answer to the ls-refs command the client sends (gitprotocol-v2(5), "ls-refs"). *) let listing_length ~v2 r = if not v2 then String.length (advertisement_of r) else let ls_refs = Git.Smart.Message.V2.request_to_string { command = "ls-refs"; capabilities = [ "object-format=sha1" ]; args = [ "symrefs"; "peel" ]; } in match Git_eio.Serve.v2_serve r (Bytesrw.Bytes.Reader.of_string ls_refs) with | Ok answer -> String.length (Git_eio.Serve.v2_advertise r) + String.length answer | Error (`Msg m) -> Alcotest.failf "ls-refs: %s" m (* [refs] branches at [hash], as the one packed-refs file git pack-refs writes (gitrepository-layout(5)): a ref transaction each was the case's whole cost, and how a server stores its refs is not what the budget bounds. *) let pack_branches ~fs r hash refs = let line k = Fmt.str "%s refs/heads/b%06d\n" (Git.Hash.to_hex hash) (k + 1) in let path = Fpath.(Git_eio.Repository.git_dir r / "packed-refs") in Eio.Path.save ~create:(`Or_truncate 0o644) Eio.Path.(fs / Fpath.to_string path) ("# pack-refs with: peeled fully-peeled sorted \n" ^ String.concat "" (List.init refs line)) (* The same for a listing: at two sizes an order of magnitude apart, from a server that answers v2 and from one that answers v0, ls_refs reads a listing of exactly its budget, and refuses one byte more, naming the bound. *) let test_ssh_ls_refs_budget () = List.iter (fun (v2, refs) -> let length = ref 0 in let srepo ~sw ~fs = let r = repo_with_blob 16 ~sw ~fs in let main = Option.get (ref_read r "refs/heads/main") in pack_branches ~fs r main refs; length := listing_length ~v2 r; r in let ls bytes = against ~accept_git_protocol:v2 srepo @@ fun ~sw ~net ~mono ~fs:_ ~port -> Git_ssh.ls_refs ~budget:(budget (bytes ())) ~authenticator:`No_authentication ~sw ~net ~mono ~port ~user:"git" (`Pubkey client_key) ~host:"127.0.0.1" "/srv" in (match ls (fun () -> !length) with | Ok adv -> Alcotest.(check int) "every ref" (refs + 2) (List.length adv.refs) | Error (`Host_key e) -> Alcotest.failf "%a" Git_ssh.pp_host_key_error e | Error (`Auth e) -> Alcotest.failf "%a" Git_ssh.pp_auth_error e | Error (`Msg m) -> Alcotest.failf "%d bytes within %d: %s" !length !length m); match ls (fun () -> !length - 1) with | Ok _ -> Alcotest.failf "%d bytes within %d" !length (!length - 1) | Error (`Host_key e) -> Alcotest.failf "%a" Git_ssh.pp_host_key_error e | Error (`Auth e) -> Alcotest.failf "%a" Git_ssh.pp_auth_error e | Error (`Msg m) -> Alcotest.(check bool) (Fmt.str "names the bound: %s" m) true (contains ~sub:(Fmt.str "more than %d bytes" (!length - 1)) m)) [ (true, 64); (true, 640); (false, 64); (false, 640) ] (* The same for a push: at two sizes an order of magnitude apart, a push whose receive-pack advertisement and status report fit its budget lands; one a byte short of the advertisement is refused before anything is sent, naming the bound, and the server's ref does not move; one that fits the advertisement alone is refused only after the request went out, which on_sent says, and the server took it. *) let test_ssh_push_budget () = List.iter (fun refs -> let length = ref 0 and server = ref None in let srepo ~sw ~fs = let r = repo_with_blob 16 ~sw ~fs in let main = Option.get (ref_read r "refs/heads/main") in pack_branches ~fs r main refs; length := String.length (advertisement_of ~receive:true r); server := Some r; r in let push bytes = against srepo @@ fun ~sw ~net ~mono ~fs ~port -> let src = repo_with_blob 32 ~sw ~fs in let value = ref_read src "refs/heads/main" in let sent = ref false in let r = Git_ssh.push_updates ~budget:(budget (bytes ())) ~on_sent:(fun () -> sent := true) ~authenticator:`No_authentication ~sw ~net ~mono ~port ~user:"git" (`Pubkey client_key) ~host:"127.0.0.1" ~src ~host_path:"/srv" [ { Git_eio.Push.dst_ref = "refs/heads/pushed"; value; expect = Lease None; }; ] in (r, !sent, ref_read (Option.get !server) "refs/heads/pushed") in let names bound m = Alcotest.(check bool) (Fmt.str "names the bound: %s" m) true (contains ~sub: (Fmt.str "git-receive-pack on 127.0.0.1 sent more than %d bytes" bound) m) in (* Past the bound before the advertisement is read, the remote is unreachable; after the request went out, it is the failure itself. *) let names_bound ~before bound = function | Error (`Unreachable m) when before -> names bound m | Error (`Msg m) when not before -> names bound m | Ok _ -> Alcotest.failf "%d bytes past %d" !length bound | Error _ -> Alcotest.fail "refused for another reason" in (match push (fun () -> 2 * !length) with | Ok _, sent, pushed -> Alcotest.(check bool) "sent" true sent; Alcotest.(check bool) "the ref is pushed" true (pushed <> None) | Error _, _, _ -> Alcotest.failf "%d bytes within %d" !length (2 * !length)); (let r, sent, pushed = push (fun () -> !length - 1) in names_bound ~before:true (!length - 1) r; Alcotest.(check bool) "nothing sent" false sent; Alcotest.(check bool) "the ref did not move" true (pushed = None)); let r, sent, pushed = push (fun () -> !length) in names_bound ~before:false !length r; Alcotest.(check bool) "sent before the status" true sent; Alcotest.(check bool) "the server took it" true (pushed <> None)) [ 64; 640 ] (* gitprotocol-http(5), "Smart Service git-upload-pack": each request stands alone and carries wants, common haves and the new have batch. *) let test_stateless_shared_history ahead () = Test_helpers.with_temp_repo @@ fun sw fs server_dir -> Test_helpers.with_temp_repo @@ fun _ _ dst_dir -> let server = Git_eio.Repository.init ~sw ~fs server_dir in let dst = Git_eio.Repository.init ~sw ~fs dst_dir in let base = chain server ~name:"shared" ~date:0 5 in let main = chain server ~name:"new" ~date:1_000_000 ?parent:base 1 in Git_eio.Repository.write_ref server "refs/heads/main" (Option.get main); let base = chain dst ~name:"shared" ~date:0 5 in let tip = chain dst ~name:"local" ~date:100 ?parent:base ahead in Git_eio.Repository.write_ref dst "refs/heads/local" (Option.get tip); let stored = ref [] in let send body = Result.map Bytesrw.Bytes.Reader.of_string (Git_eio.Serve.upload_pack server (Bytesrw.Bytes.Reader.of_string body)) in let client, adv = Test_helpers.or_fail "advertisement" (Git.Smart.Client.Fetch.advertisement Git.Smart.Client.Fetch.v (Bytesrw.Bytes.Reader.of_string (advertisement_of server))) in let got = Test_helpers.or_fail "stateless fetch" (Git_eio.Fetch.negotiate_refs ~client ~adv ~send dst ~on_progress:(function | Git.Progress.Written n -> stored := n :: !stored | _ -> ()) ~select:(fun r -> if r = "refs/heads/main" then Some r else None)) in Alcotest.(check (list string)) "main fetched" [ "refs/heads/main" ] (List.map fst got); (* A capped have walk packs the shared history again. *) Alcotest.(check (list int)) "only the new commit, tree and blob" [ 3 ] !stored let suite = ( "git_ssh_fetch", [ Alcotest.test_case "ssh fetch is bounded by its budget" `Slow test_ssh_fetch_budget; Alcotest.test_case "ssh ls-refs is bounded by its budget" `Slow test_ssh_ls_refs_budget; Alcotest.test_case "ssh speaks protocol v2 where the server offers it" `Slow test_ssh_protocol_v2; Alcotest.test_case "ssh fetch speaks protocol v2 where offered" `Slow test_ssh_fetch_v2; Alcotest.test_case "ssh push is bounded by its budget" `Slow test_ssh_push_budget; Alcotest.test_case "ssh fetch finds history shared 300 commits back" `Slow (test_ssh_fetch_shared_history 300); Alcotest.test_case "ssh fetch finds history shared 3000 commits back" `Slow (test_ssh_fetch_shared_history 3000); Alcotest.test_case "stateless fetch finds history shared 300 commits back" `Slow (test_stateless_shared_history 300); Alcotest.test_case "stateless fetch finds history shared 3000 commits back" `Slow (test_stateless_shared_history 3000); ] )