(* 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 (** Tests for {!Git_ssh}. A full SSH clone needs a live server and credentials, so the round-trip is an opt-in live test ([GIT_SSH_LIVE]). The hermetic test drives the transport against an unreachable port and asserts the error path: dialing, connecting, and failure wrapping all run without a server. *) (* In-process SSH round-trip: the nox-git SSH server ({!Git_ssh.serve}) backed by a real repo, cloned by the nox-git SSH client ({!Git_ssh.fetch}). Proves both sides of the SSH transport against each other end-to-end. *) (* A client must not connect to an unverified host: an unknown host (no known_hosts entry) is refused unless the caller explicitly opts into skipping verification, which then downgrades to accepting any key. *) let test_host_authenticator_fails_closed () = let pinned = `Sha256 "pinned-key-hash" in (match Git_ssh.host_authenticator ~insecure:false ~host:"h" (Some pinned) with | Ok (`Sha256 s) -> Alcotest.(check string) "known host keeps its pinned key" "pinned-key-hash" s | Ok _ -> Alcotest.fail "known host: wrong authenticator" | Error (`Msg m) -> Alcotest.failf "known host rejected: %s" m); (match Git_ssh.host_authenticator ~insecure:false ~host:"h" None with | Error (`Msg _) -> () | Ok _ -> Alcotest.fail "unknown host must fail closed without --insecure"); match Git_ssh.host_authenticator ~insecure:true ~host:"h" None with | Ok `No_authentication -> () | Ok _ -> Alcotest.fail "insecure must be explicit No_authentication" | Error (`Msg m) -> Alcotest.failf "insecure path rejected: %s" m let test_ssh_clone () = Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let net = Eio_net_mem.v ~sw () in let mono = Eio.Stdenv.mono_clock env in let fs = Eio.Stdenv.fs env in let clock = Eio.Stdenv.clock env in (* Server repo: one commit on refs/heads/main. *) let srepo = Git_eio.Repository.init ~sw ~fs (Fpath.v (Filename.temp_dir "gss" "")) in let blob = Git_eio.Repository.write_blob srepo "ssh payload\n" in let tree = Git_eio.Repository.write_tree srepo (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 let chash = Git_eio.Repository.write_commit srepo (Git.Commit.v ~tree ~author:a ~committer:a (Some "c\n")) in Git_eio.Repository.write_ref srepo "refs/heads/main" chash; let authenticate user = function | Ssh.Server.Pubkey p -> Ssh.Server.is_pubkey_query p || Ssh.Server.verify_pubkeyauth ~user p | Ssh.Server.Authnone -> false | Ssh.Server.Password _ -> true in let dst = Git_eio.Repository.init ~sw ~fs (Fpath.v (Filename.temp_dir "gsc" "")) in (* Run the server until the client finishes (Fiber.first cancels it). *) let result = ref (Error (`Msg "client did not run")) in let ready, announce = Eio.Promise.create () in Eio.Fiber.first (fun () -> Eio.Switch.run @@ fun ssw -> Git_ssh.serve ~max_connections:64 ~sw:ssw ~on_listen:(Eio.Promise.resolve announce) ~net ~mono ~host_key ~authenticate ~addr:(`Tcp (Eio.Net.Ipaddr.V4.loopback, 0)) srepo) (fun () -> let port = Test_helpers.announced_port ~clock ready in result := 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"); match !result with | Error (#Git_ssh.error as e) -> Alcotest.failf "ssh clone: %a" Git_ssh.pp_error e | Ok target -> Alcotest.(check bool) "right commit" true (Git.Hash.equal target chash); Alcotest.(check bool) "object present" true (Git_eio.Repository.exists dst target) (* git ls-remote over SSH (gitprotocol-pack(5), "Reference Discovery"): the advertisement alone, every ref with its value and HEAD's symref, and the session ends with the client's flush-pkt, nothing fetched. *) let test_ssh_ls_refs () = Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let net = Eio_net_mem.v ~sw () in let mono = Eio.Stdenv.mono_clock env in let fs = Eio.Stdenv.fs env in let clock = Eio.Stdenv.clock env in let srepo = Test_helpers.init_bare ~sw ~fs (Fpath.v (Filename.temp_dir "gsls" "")) in let commit msg = let blob = Git_eio.Repository.write_blob srepo (msg ^ " payload\n") in let tree = Git_eio.Repository.write_tree srepo (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 srepo (Git.Commit.v ~tree ~author:a ~committer:a (Some (msg ^ "\n"))) in let main = commit "main" and topic = commit "topic" in Git_eio.Repository.write_ref srepo "refs/heads/main" main; Git_eio.Repository.write_ref srepo "refs/heads/topic" topic; Git_eio.Repository.write_symbolic_ref srepo "HEAD" ~target:"refs/heads/main"; let authenticate user = function | Ssh.Server.Pubkey p -> Ssh.Server.is_pubkey_query p || Ssh.Server.verify_pubkeyauth ~user p | Ssh.Server.Authnone -> false | Ssh.Server.Password _ -> false in let result = ref (Error (`Msg "client did not run")) in let ready, announce = Eio.Promise.create () in Eio.Fiber.first (fun () -> Eio.Switch.run @@ fun ssw -> Git_ssh.serve ~max_connections:64 ~sw:ssw ~on_listen:(Eio.Promise.resolve announce) ~net ~mono ~host_key ~authenticate ~addr:(`Tcp (Eio.Net.Ipaddr.V4.loopback, 0)) srepo) (fun () -> let port = Test_helpers.announced_port ~clock ready in result := Git_ssh.ls_refs ~authenticator:`No_authentication ~sw ~net ~mono ~port ~user:"git" (`Pubkey client_key) ~host:"127.0.0.1" "/srv"); match !result with | Error (#Git_ssh.error as e) -> Alcotest.failf "ssh ls-refs: %a" Git_ssh.pp_error e | Ok adv -> let refs = List.map (fun (r : Git.Smart.Message.ref_entry) -> (r.name, Git.Hash.to_hex r.hash)) adv.refs |> List.sort compare in Alcotest.(check (list (pair string string))) "every ref with its value" [ ("HEAD", Git.Hash.to_hex main); ("refs/heads/main", Git.Hash.to_hex main); ("refs/heads/topic", Git.Hash.to_hex topic); ] refs; Alcotest.(check bool) "HEAD's symref" true (List.mem "symref=HEAD:refs/heads/main" adv.capabilities) (* [k] times as many peers as a server's bound of four connections connect, read its identification string and send nothing, the handshake never begun. The server holds four of them and sheds the others, then sheds one more for a client that lists the refs, and answers it. *) let test_silent_peers k () = let n = 4 in Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let net = Eio_net_mem.v ~sw () in let mono = Eio.Stdenv.mono_clock env in let fs = Eio.Stdenv.fs env in let clock = Eio.Stdenv.clock env in let srepo = Test_helpers.init_bare ~sw ~fs (Fpath.v (Filename.temp_dir "gsilent" "")) in let blob = Git_eio.Repository.write_blob srepo "payload\n" in let tree = Git_eio.Repository.write_tree srepo (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 let main = Git_eio.Repository.write_commit srepo (Git.Commit.v ~tree ~author:a ~committer:a (Some "main\n")) in Git_eio.Repository.write_ref srepo "refs/heads/main" main; let authenticate user = function | Ssh.Server.Pubkey p -> Ssh.Server.is_pubkey_query p || Ssh.Server.verify_pubkeyauth ~user p | Ssh.Server.Authnone -> false | Ssh.Server.Password _ -> false in let ready, announce = Eio.Promise.create () in Eio.Fiber.first (fun () -> Eio.Switch.run @@ fun ssw -> Git_ssh.serve ~max_connections:n ~sw:ssw ~on_listen:(Eio.Promise.resolve announce) ~net ~mono ~host_key ~authenticate ~addr:(`Tcp (Eio.Net.Ipaddr.V4.loopback, 0)) srepo) (fun () -> let port = Test_helpers.announced_port ~clock ready in let ended = Test_helpers.silent_peers ~sw ~net (`Tcp (Eio.Net.Ipaddr.V4.loopback, port)) (k * n) in Test_helpers.settle (10 * k * n); Alcotest.(check int) "the server holds its bound and sheds the rest" ((k - 1) * n) !ended; match Git_ssh.ls_refs ~authenticator:`No_authentication ~sw ~net ~mono ~port ~user:"git" (`Pubkey client_key) ~host:"127.0.0.1" "/srv" with | Error (#Git_ssh.error as e) -> Alcotest.failf "ssh ls-refs: %a" Git_ssh.pp_error e | Ok adv -> Alcotest.(check (list string)) "a client is answered" [ "HEAD"; "refs/heads/main" ] (List.map (fun (r : Git.Smart.Message.ref_entry) -> r.name) adv.refs); Alcotest.(check int) "one more is shed for it" (((k - 1) * n) + 1) !ended) (* RFC 5656 end to end: a server whose host key is ecdsa-sha2-nistp256, a client that authenticates with an ecdsa-sha2-nistp384 key and pins the server's key, as a known_hosts line for it does. *) let test_ssh_ecdsa () = Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let net = Eio_net_mem.v ~sw () in let mono = Eio.Stdenv.mono_clock env in let fs = Eio.Stdenv.fs env in let clock = Eio.Stdenv.clock env in let host_key = Ssh.Hostkey.P256_priv (fst (Crypto_ec.P256.Dsa.generate ())) in let user_key = Ssh.Hostkey.P384_priv (fst (Crypto_ec.P384.Dsa.generate ())) in let user_pub = Ssh.Hostkey.pub_of_priv user_key in let srepo = Test_helpers.init_bare ~sw ~fs (Fpath.v (Filename.temp_dir "gsec" "")) in let blob = Git_eio.Repository.write_blob srepo "ecdsa payload\n" in let tree = Git_eio.Repository.write_tree srepo (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 let main = Git_eio.Repository.write_commit srepo (Git.Commit.v ~tree ~author:a ~committer:a (Some "c\n")) in Git_eio.Repository.write_ref srepo "refs/heads/main" main; let authenticate user = function | Ssh.Server.Pubkey p -> Ssh.Hostkey.pub_eq (Ssh.Server.pubkey_of_pubkeyauth p) user_pub && (Ssh.Server.is_pubkey_query p || Ssh.Server.verify_pubkeyauth ~user p) | Ssh.Server.Authnone -> false | Ssh.Server.Password _ -> false in let result = ref (Error (`Msg "client did not run")) in let ready, announce = Eio.Promise.create () in Eio.Fiber.first (fun () -> Eio.Switch.run @@ fun ssw -> Git_ssh.serve ~max_connections:64 ~sw:ssw ~on_listen:(Eio.Promise.resolve announce) ~net ~mono ~host_key ~authenticate ~addr:(`Tcp (Eio.Net.Ipaddr.V4.loopback, 0)) srepo) (fun () -> let port = Test_helpers.announced_port ~clock ready in result := Git_ssh.ls_refs ~authenticator:(`Key (Ssh.Hostkey.pub_of_priv host_key)) ~sw ~net ~mono ~port ~user:"git" (`Pubkey user_key) ~host:"127.0.0.1" "/srv"); match !result with | Error (#Git_ssh.error as e) -> Alcotest.failf "ssh over ECDSA: %a" Git_ssh.pp_error e | Ok adv -> Alcotest.(check (option string)) "main" (Some (Git.Hash.to_hex main)) (Option.map Git.Hash.to_hex (Git.Smart.Message.Advertisement.find_ref adv "refs/heads/main")) (* The repository path in the command a client runs, quoted as Git's sq_quote_buf quotes it (quote.c): in single quotes, each ' as '\'' and each ! as '\!'. The server receives exactly that, and a POSIX shell, which runs it on the server's side, reads the path back as one argument. *) let test_ssh_quoted_path () = Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let net = Eio_net_mem.v ~sw () in let mono = Eio.Stdenv.mono_clock env in let fs = Eio.Stdenv.fs env in let clock = Eio.Stdenv.clock env in let srepo = Test_helpers.init_bare ~sw ~fs (Fpath.v (Filename.temp_dir "gsq" "")) in let authenticate user = function | Ssh.Server.Pubkey p -> Ssh.Server.is_pubkey_query p || Ssh.Server.verify_pubkeyauth ~user p | Ssh.Server.Authnone -> false | Ssh.Server.Password _ -> false in let received = ref [] in let on_exec cmd = received := cmd :: !received in let paths = [ "/srv/it's"; "/srv/a!b"; "/srv/'!'" ] in let ready, announce = Eio.Promise.create () in Eio.Fiber.first (fun () -> Eio.Switch.run @@ fun ssw -> Git_ssh.serve ~max_connections:64 ~sw:ssw ~on_listen:(Eio.Promise.resolve announce) ~on_exec ~net ~mono ~host_key ~authenticate ~addr:(`Tcp (Eio.Net.Ipaddr.V4.loopback, 0)) srepo) (fun () -> let port = Test_helpers.announced_port ~clock ready in List.iter (fun path -> (* Only the command the server is sent is checked: the session may end either way on an empty repository. *) (match Git_ssh.ls_refs ~authenticator:`No_authentication ~sw ~net ~mono ~port ~user:"git" (`Pubkey client_key) ~host:"127.0.0.1" path with | Ok _ | Error _ -> ()); match Git_ssh.push_updates ~authenticator:`No_authentication ~sw ~net ~mono ~port ~user:"git" (`Pubkey client_key) ~host:"127.0.0.1" ~src:srepo ~host_path:path [] with | Ok _ | Error _ -> ()) paths); Alcotest.(check (list string)) "the commands the server received" [ {|git-upload-pack '/srv/it'\''s'|}; {|git-receive-pack '/srv/it'\''s'|}; {|git-upload-pack '/srv/a'\!'b'|}; {|git-receive-pack '/srv/a'\!'b'|}; {|git-upload-pack '/srv/'\'''\!''\'''|}; {|git-receive-pack '/srv/'\'''\!''\'''|}; ] (List.rev !received); List.iter2 (fun path cmd -> let arg = match String.index_opt cmd ' ' with | Some i -> String.sub cmd (i + 1) (String.length cmd - i - 1) | None -> Alcotest.failf "%s names no path" cmd in let ic = Unix.open_process_args_in "/bin/sh" [| "/bin/sh"; "-c"; "set -- " ^ arg ^ "; printf '%s|%d' \"$1\" $#" |] in let out = In_channel.input_all ic in ignore (Unix.close_process_in ic); Alcotest.(check string) ("one argument: " ^ cmd) (path ^ "|1") out) (List.concat_map (fun p -> [ p; p ]) paths) (List.rev !received) (* The dual of {!test_ssh_clone}: the client pushes its one commit into an empty server repo over SSH, and we assert the server's ref now points at it. *) let test_ssh_push () = Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let net = Eio_net_mem.v ~sw () in let mono = Eio.Stdenv.mono_clock env in let fs = Eio.Stdenv.fs env in let clock = Eio.Stdenv.clock env in let srepo = Test_helpers.init_bare ~sw ~fs (Fpath.v (Filename.temp_dir "gsps" "")) in let crepo = Git_eio.Repository.init ~sw ~fs (Fpath.v (Filename.temp_dir "gspc" "")) in let blob = Git_eio.Repository.write_blob crepo "ssh push payload\n" in let tree = Git_eio.Repository.write_tree crepo (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 let chash = Git_eio.Repository.write_commit crepo (Git.Commit.v ~tree ~author:a ~committer:a (Some "c\n")) in Git_eio.Repository.write_ref crepo "refs/heads/main" chash; let authenticate user = function | Ssh.Server.Pubkey p -> Ssh.Server.is_pubkey_query p || Ssh.Server.verify_pubkeyauth ~user p | Ssh.Server.Authnone -> false | Ssh.Server.Password _ -> true in let result = ref (Error (`Msg "client did not run")) in let ready, announce = Eio.Promise.create () in Eio.Fiber.first (fun () -> Eio.Switch.run @@ fun ssw -> Git_ssh.serve ~max_connections:64 ~sw:ssw ~on_listen:(Eio.Promise.resolve announce) ~net ~mono ~host_key ~authenticate ~addr:(`Tcp (Eio.Net.Ipaddr.V4.loopback, 0)) srepo) (fun () -> let port = Test_helpers.announced_port ~clock ready in result := Git_ssh.push ~authenticator:`No_authentication ~sw ~net ~mono ~port ~user:"git" (`Pubkey client_key) ~host:"127.0.0.1" ~src:crepo ~src_hash:"refs/heads/main" ~dst_ref:"refs/heads/main" ~force:false ~host_path:"/srv" ()); match !result with | Error (#Git_ssh.error as e) -> Alcotest.failf "ssh push: %a" Git_ssh.pp_error e | Error (`Rejected (r, _, _)) -> Alcotest.failf "ssh push: %s rejected" r | Error (`Declined why) -> Alcotest.failf "ssh push: declined: %s" why | Ok (pushed, _) -> Alcotest.(check bool) "pushed the right commit" true (Git.Hash.equal pushed chash); Alcotest.(check bool) "server ref updated" true (match ref_read srepo "refs/heads/main" with | Some h -> Git.Hash.equal h chash | None -> false) (* {1 Sessions} One connection carries every command a session runs, each on its own channel (RFC 4254 section 5), as OpenSSH's ControlMaster gives git. *) (* The connections a server accepts, and the commands they run, counted by an accept loop of its own around {!Git_ssh.serve_connection}. *) let counting_server ~sw ~net ~mono repo = let connections = ref 0 and execs = ref 0 in let sock = Eio.Net.listen ~sw ~backlog:8 ~reuse_addr:true net (`Tcp (Eio.Net.Ipaddr.V4.loopback, 22)) in let authenticate user = function | Ssh.Server.Pubkey p -> Ssh.Server.is_pubkey_query p || Ssh.Server.verify_pubkeyauth ~user p | Ssh.Server.Authnone | Ssh.Server.Password _ -> false in Eio.Fiber.fork_daemon ~sw (fun () -> let rec loop () = Eio.Net.accept_fork ~sw sock ~on_error:raise (fun flow _ -> incr connections; Git_ssh.serve_connection ~on_exec:(fun _ -> incr execs) ~mono ~host_key ~authenticate repo flow); loop () in loop ()); (connections, execs) (* Ten pushes at once on one session: one connection, ten commands, and each ref at the commit pushed. A session that connected per command counts ten connections. *) let test_session_carries_ten_pushes () = Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let net = Eio_net_mem.v ~sw () in let mono = Eio.Stdenv.mono_clock env in let fs = Eio.Stdenv.fs env in let clock = Eio.Stdenv.clock env in let srepo = Test_helpers.init_bare ~sw ~fs (Fpath.v (Filename.temp_dir "gsss" "")) in let crepo = Git_eio.Repository.init ~sw ~fs (Fpath.v (Filename.temp_dir "gssc" "")) in let blob = Git_eio.Repository.write_blob crepo "session payload\n" in let tree = Git_eio.Repository.write_tree crepo (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 let chash = Git_eio.Repository.write_commit crepo (Git.Commit.v ~tree ~author:a ~committer:a (Some "c\n")) in Git_eio.Repository.write_ref crepo "refs/heads/main" chash; let connections, execs = counting_server ~sw ~net ~mono srepo in let refs = List.init 10 (Fmt.str "refs/heads/r%d") in Eio.Time.with_timeout_exn clock 8. (fun () -> match Git_ssh.Session.connect ~sw ~net ~mono ~authenticator:`No_authentication ~user:"git" (`Pubkey client_key) ~host:"127.0.0.1" () with | Error e -> Alcotest.failf "connect: %a" Git_ssh.pp_error e | Ok s -> Eio.Fiber.List.iter (fun dst_ref -> match Git_ssh.Session.push s ~src:crepo ~src_hash:"refs/heads/main" ~dst_ref ~force:false ~host_path:"/srv" () with | Ok (pushed, _) -> Alcotest.check Test_helpers.hash dst_ref chash pushed | Error (#Git_ssh.error as e) -> Alcotest.failf "%s: %a" dst_ref Git_ssh.pp_error e | Error (`Rejected (r, _, _)) -> Alcotest.failf "%s rejected" r | Error (`Declined why) -> Alcotest.failf "declined: %s" why) refs; Alcotest.(check bool) "the session is open" true (Git_ssh.Session.is_open s); Git_ssh.Session.close s); Alcotest.(check (list (option string))) "each ref at the commit pushed" (List.map (fun _ -> Some (Git.Hash.to_hex chash)) refs) (List.map (fun r -> Option.map Git.Hash.to_hex (ref_read srepo r)) refs); Alcotest.(check int) "commands run" 10 !execs; Alcotest.(check int) "connections made" 1 !connections let string_contains_sub ~sub s = let sub_len = String.length sub and len = String.length s in let rec loop i = i + sub_len <= len && (String.equal (String.sub s i sub_len) sub || loop (i + 1)) in sub_len = 0 || loop 0 let test_ssh_push_large_pack_keeps_reading () = Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let net = Eio_net_mem.v ~sw () in let mono = Eio.Stdenv.mono_clock env in let fs = Eio.Stdenv.fs env in let clock = Eio.Stdenv.clock env in let srepo = Test_helpers.init_bare ~sw ~fs (Fpath.v (Filename.temp_dir "gspls" "")) in let crepo = Git_eio.Repository.init ~sw ~fs (Fpath.v (Filename.temp_dir "gsplc" "")) in let payload = pseudo_random_payload ((2 * Int32.to_int Ssh.Message.channel_win_len) + 4096) in let blob = Git_eio.Repository.write_blob crepo payload in let tree = Git_eio.Repository.write_tree crepo (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 let chash = Git_eio.Repository.write_commit crepo (Git.Commit.v ~tree ~author:a ~committer:a (Some "large\n")) in Git_eio.Repository.write_ref crepo "refs/heads/main" chash; let authenticate user = function | Ssh.Server.Pubkey p -> Ssh.Server.is_pubkey_query p || Ssh.Server.verify_pubkeyauth ~user p | Ssh.Server.Authnone -> false | Ssh.Server.Password _ -> true in let result = ref (Error (`Msg "client did not run")) in let ready, announce = Eio.Promise.create () in Eio.Fiber.first (fun () -> Eio.Switch.run @@ fun ssw -> Git_ssh.serve ~max_connections:64 ~sw:ssw ~on_listen:(Eio.Promise.resolve announce) ~net ~mono ~host_key ~authenticate ~addr:(`Tcp (Eio.Net.Ipaddr.V4.loopback, 0)) srepo) (fun () -> let port = Test_helpers.announced_port ~clock ready in result := try Eio.Time.with_timeout_exn clock 15.0 (fun () -> Git_ssh.push ~authenticator:`No_authentication ~sw ~net ~mono ~port ~user:"git" (`Pubkey client_key) ~host:"127.0.0.1" ~src:crepo ~src_hash:"refs/heads/main" ~dst_ref:"refs/heads/main" ~force:false ~host_path:"/srv" ()) with Eio.Time.Timeout -> Error (`Msg "ssh push timed out while sending a large pack")); match !result with | Error (#Git_ssh.error as e) -> Alcotest.failf "ssh large push: %a" Git_ssh.pp_error e | Error (`Rejected (r, _, _)) -> Alcotest.failf "ssh large push: %s rejected" r | Error (`Declined why) -> Alcotest.failf "ssh large push: declined: %s" why | Ok (pushed, _) -> Alcotest.(check bool) "pushed the right commit" true (Git.Hash.equal pushed chash); Alcotest.(check bool) "server ref updated" true (match ref_read srepo "refs/heads/main" with | Some h -> Git.Hash.equal h chash | None -> false) let serve_push_without_channel_close ~mono ~host_key ~authenticate repo flow = let chans = Hashtbl.create 1 in let on_event t = function | Ssh.Server.Channel_exec (chan, cmd) when String.starts_with ~prefix:"git-receive-pack" (String.trim cmd) -> Ssh_eio.Server.send t chan (advertisement_of repo); Hashtbl.replace chans chan (Buffer.create 256) | Ssh.Server.Channel_data (chan, data) -> ( match Hashtbl.find_opt chans chan with | Some b -> Buffer.add_string b data | None -> ()) | Ssh.Server.Channel_eof chan -> ( match Hashtbl.find_opt chans chan with | None -> () | Some b -> ( match Git_eio.Serve.receive_pack repo (Bytesrw.Bytes.Reader.of_string (Buffer.contents b)) with | Ok response -> Ssh_eio.Server.send t chan response; Hashtbl.remove chans chan | Error (`Msg msg) -> Alcotest.failf "receive-pack: %s" msg)) | _ -> () in Ssh_eio.Server.serve ~mono flow ~host_key ~authenticate ~on_event let serve_push_repo_not_found ?(stderr = "repo not found\n") ~mono ~host_key ~authenticate flow = let on_event t = function | Ssh.Server.Channel_exec (chan, cmd) when String.starts_with ~prefix:"git-receive-pack" (String.trim cmd) -> Ssh_eio.Server.stderr t chan stderr; Ssh_eio.Server.eof t chan; Ssh_eio.Server.exit_status t chan 1l; Ssh_eio.Server.close t chan | _ -> () in Ssh_eio.Server.serve ~mono flow ~host_key ~authenticate ~on_event (* A push to a remote whose receive-pack writes [stderr] and exits 1 before its advertisement, and the error the push ends with. *) let push_to_missing ?stderr () = Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let net = Eio_net_mem.v ~sw () in let mono = Eio.Stdenv.mono_clock env in let fs = Eio.Stdenv.fs env in let crepo = Git_eio.Repository.init ~sw ~fs (Fpath.v (Filename.temp_dir "gsperr" "")) in let blob = Git_eio.Repository.write_blob crepo "ssh push missing remote\n" in let tree = Git_eio.Repository.write_tree crepo (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 let chash = Git_eio.Repository.write_commit crepo (Git.Commit.v ~tree ~author:a ~committer:a (Some "c\n")) in Git_eio.Repository.write_ref crepo "refs/heads/main" chash; let authenticate user = function | Ssh.Server.Pubkey p -> Ssh.Server.is_pubkey_query p || Ssh.Server.verify_pubkeyauth ~user p | Ssh.Server.Authnone -> false | Ssh.Server.Password _ -> true in let result = ref (Ok (chash, Git_eio.Push.Up_to_date)) in let sock = Eio.Net.listen ~sw ~backlog:1 ~reuse_addr:true net (`Tcp (Eio.Net.Ipaddr.V4.loopback, 0)) in let port = match Eio.Net.listening_addr sock with | `Tcp (_, port) -> port | `Unix _ -> Alcotest.fail "a TCP listener has a TCP address" in Eio.Fiber.first (fun () -> Eio.Switch.run @@ fun ssw -> Eio.Net.accept_fork ~sw:ssw sock ~on_error:raise (fun flow _addr -> serve_push_repo_not_found ?stderr ~mono ~host_key ~authenticate flow); Eio.Fiber.await_cancel ()) (fun () -> result := Git_ssh.push ~authenticator:`No_authentication ~sw ~net ~mono ~port ~user:"git" (`Pubkey client_key) ~host:"127.0.0.1" ~src:crepo ~src_hash:"refs/heads/main" ~dst_ref:"refs/heads/main" ~force:false ~host_path:"/missing" ()); match !result with | Ok _ -> Alcotest.fail "expected push to fail before advertisement" | Error (`Rejected (r, _, _)) -> Alcotest.failf "%s rejected" r | 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 (`Declined why) -> Alcotest.failf "declined: %s" why | Error (`Msg msg) -> msg let test_ssh_push_reports_remote_stderr_before_advertisement () = let msg = push_to_missing () in Alcotest.(check bool) "remote error is preserved" true (string_contains_sub ~sub:"repo not found" msg); Alcotest.(check bool) "not parser eof" false (String.equal msg "eof") (* A receive-pack that takes [limit] bytes of the request, then writes its refusal to stderr, exits 1 and closes the channel while the client is still sending, as GitHub's does to a pack past its size limit. Each of [progress] goes out first on side-band 2 of the channel's stdout (gitprotocol-pack(5), "Packfile Data"), as git's receive-pack relays index-pack's stderr (receive-pack.c, copy_to_sideband). *) let serve_push_cut_off ?(progress = []) ?(stderr = "") ~limit ~mono ~host_key ~authenticate repo flow = let taken = Hashtbl.create 1 in let on_event t = function | Ssh.Server.Channel_exec (chan, cmd) when String.starts_with ~prefix:"git-receive-pack" (String.trim cmd) -> Ssh_eio.Server.send t chan (advertisement_of repo); Hashtbl.replace taken chan 0 | Ssh.Server.Channel_data (chan, data) -> ( match Hashtbl.find_opt taken chan with | None -> () | Some n -> let n = n + String.length data in if n < limit then Hashtbl.replace taken chan n else begin Hashtbl.remove taken chan; List.iter (fun line -> Ssh_eio.Server.send t chan Git.Smart.Packet.(to_string (Data ("\002" ^ line ^ "\n")))) progress; if stderr <> "" then Ssh_eio.Server.stderr t chan stderr; Ssh_eio.Server.exit_status t chan 1l; Ssh_eio.Server.eof t chan; Ssh_eio.Server.close t chan end) | _ -> () in Ssh_eio.Server.serve ~mono flow ~host_key ~authenticate ~on_event (* A push whose remote sends [progress] on side-band 2, writes [stderr] and closes the channel partway through the pack, and the error the push ends with. *) let push_cut_off ?progress ?stderr () = Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let net = Eio_net_mem.v ~sw () in let mono = Eio.Stdenv.mono_clock env in let fs = Eio.Stdenv.fs env in let clock = Eio.Stdenv.clock env in let srepo = Test_helpers.init_bare ~sw ~fs (Fpath.v (Filename.temp_dir "gspcs" "")) in let crepo = Git_eio.Repository.init ~sw ~fs (Fpath.v (Filename.temp_dir "gspcc" "")) in let win = Int32.to_int Ssh.Message.channel_win_len in let blob = Git_eio.Repository.write_blob crepo (pseudo_random_payload (2 * win)) in let tree = Git_eio.Repository.write_tree crepo (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 let chash = Git_eio.Repository.write_commit crepo (Git.Commit.v ~tree ~author:a ~committer:a (Some "large\n")) in Git_eio.Repository.write_ref crepo "refs/heads/main" chash; let authenticate user = function | Ssh.Server.Pubkey p -> Ssh.Server.is_pubkey_query p || Ssh.Server.verify_pubkeyauth ~user p | Ssh.Server.Authnone -> false | Ssh.Server.Password _ -> true in let sock = Eio.Net.listen ~sw ~backlog:1 ~reuse_addr:true net (`Tcp (Eio.Net.Ipaddr.V4.loopback, 0)) in let port = match Eio.Net.listening_addr sock with | `Tcp (_, port) -> port | `Unix _ -> Alcotest.fail "a TCP listener has a TCP address" in let result = ref (Ok (chash, Git_eio.Push.Up_to_date)) in Eio.Fiber.first (fun () -> Eio.Switch.run @@ fun ssw -> Eio.Net.accept_fork ~sw:ssw sock ~on_error:raise (fun flow _addr -> serve_push_cut_off ?progress ?stderr ~limit:(win / 4) ~mono ~host_key ~authenticate srepo flow); Eio.Fiber.await_cancel ()) (fun () -> result := try Eio.Time.with_timeout_exn clock 15.0 (fun () -> Eio.Switch.run @@ fun push_sw -> Git_ssh.push ~authenticator:`No_authentication ~sw:push_sw ~net ~mono ~port ~user:"git" (`Pubkey client_key) ~host:"127.0.0.1" ~src:crepo ~src_hash:"refs/heads/main" ~dst_ref:"refs/heads/main" ~force:false ~host_path:"/srv" ()) with Eio.Time.Timeout -> Error (`Msg "ssh push timed out after the remote closed")); match !result with | Ok _ -> Alcotest.fail "a push the remote cut off succeeded" | Error (`Rejected (r, _, _)) -> Alcotest.failf "%s rejected" r | 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 (`Declined why) -> Alcotest.failf "declined: %s" why | Error (`Msg msg) -> msg (* A push whose remote refuses the pack partway through it: the error is the remote's stderr, not the client's next write on the channel the remote closed, which a client that drops the stderr reports as "no such channel". *) let test_ssh_push_cut_off_reports_remote () = let refusal = "fatal: pack exceeds maximum allowed size (2.00 GiB)" in Alcotest.(check string) "the remote's refusal" ("remote: " ^ refusal) (push_cut_off ~stderr:(refusal ^ "\n") ()) (* git's receive-pack, past receive.maxInputSize, relays index-pack's refusal on side-band 2 and ends the request while the client is still sending, with nothing on stderr. The error is that refusal; a client that discards the channel's stdout once a write fails reports its own write on the closed channel. *) let test_ssh_push_cut_off_reports_sideband () = let refusal = "fatal: pack exceeds maximum allowed size" in Alcotest.(check string) "the remote's side-band refusal" ("remote: " ^ refusal) (push_cut_off ~progress:[ refusal ] ()) (* Run [f] with every log line captured, and return what was logged. *) let logged f = let buf = Buffer.create 256 in let ppf = Fmt.with_buffer buf in let report _src _level ~over k msgf = let k' _ = over (); k () in msgf (fun ?header:_ ?tags:_ fmt -> Fmt.kpf k' ppf (fmt ^^ "@.")) in let saved_reporter = Logs.reporter () and saved_level = Logs.level () in Logs.set_reporter { Logs.report }; Logs.set_level (Some Logs.Info); let r = Fun.protect ~finally:(fun () -> Logs.set_reporter saved_reporter; Logs.set_level saved_level) f in (r, Buffer.contents buf) (* RFC 4251 sec 9.2: the remote's stderr is display text from a peer the host key names but does not vouch for. An OSC 52 that writes the clipboard, its BEL, a CSI in its 8-bit C1 form and a CR that rewrites the line reach the log line and the error as their escapes. *) let test_ssh_remote_stderr_is_display_text () = let hostile = "repo \x1b]52;c;cGF5\x07not found\rall good \xc2\x9b2J\x9b31m\n" in let msg, log = logged (fun () -> push_to_missing ~stderr:hostile ()) in let raw = [ ('\x1b', "ESC"); ('\x07', "BEL"); ('\x9b', "C1"); ('\r', "CR") ] in List.iter (fun (what, text) -> List.iter (fun (c, name) -> Alcotest.(check bool) (Fmt.str "no raw %s in the %s" name what) false (String.contains text c)) raw; List.iter (fun sub -> Alcotest.(check bool) (Fmt.str "%s shows %s" what sub) true (string_contains_sub ~sub text)) [ {|\x1b]52|}; {|\x07|}; {|\x0d|}; {|\xc2\x9b2J|}; {|\x9b31m|} ]) [ ("error", msg); ("log", log) ] let test_ssh_push_closes_channel_after_status () = Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let net = Eio_net_mem.v ~sw () in let mono = Eio.Stdenv.mono_clock env in let fs = Eio.Stdenv.fs env in let clock = Eio.Stdenv.clock env in let srepo = Test_helpers.init_bare ~sw ~fs (Fpath.v (Filename.temp_dir "gspns" "")) in let crepo = Git_eio.Repository.init ~sw ~fs (Fpath.v (Filename.temp_dir "gspnc" "")) in let blob = Git_eio.Repository.write_blob crepo "ssh push no-close\n" in let tree = Git_eio.Repository.write_tree crepo (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 let chash = Git_eio.Repository.write_commit crepo (Git.Commit.v ~tree ~author:a ~committer:a (Some "c\n")) in Git_eio.Repository.write_ref crepo "refs/heads/main" chash; let authenticate user = function | Ssh.Server.Pubkey p -> Ssh.Server.is_pubkey_query p || Ssh.Server.verify_pubkeyauth ~user p | Ssh.Server.Authnone -> false | Ssh.Server.Password _ -> true in let result = ref (Error (`Msg "client did not run")) in let sock = Eio.Net.listen ~sw ~backlog:1 ~reuse_addr:true net (`Tcp (Eio.Net.Ipaddr.V4.loopback, 0)) in let port = match Eio.Net.listening_addr sock with | `Tcp (_, port) -> port | `Unix _ -> Alcotest.fail "a TCP listener has a TCP address" in Eio.Fiber.first (fun () -> Eio.Switch.run @@ fun ssw -> Eio.Net.accept_fork ~sw:ssw sock ~on_error:raise (fun flow _addr -> serve_push_without_channel_close ~mono ~host_key ~authenticate srepo flow); Eio.Fiber.await_cancel ()) (fun () -> result := try Eio.Time.with_timeout_exn clock 2.0 (fun () -> Eio.Switch.run @@ fun push_sw -> Git_ssh.push ~authenticator:`No_authentication ~sw:push_sw ~net ~mono ~port ~user:"git" (`Pubkey client_key) ~host:"127.0.0.1" ~src:crepo ~src_hash:"refs/heads/main" ~dst_ref:"refs/heads/main" ~force:false ~host_path:"/srv" ()) with Eio.Time.Timeout -> Error (`Msg "ssh push timed out after receive-pack status")); match !result with | Error (#Git_ssh.error as e) -> Alcotest.failf "ssh push no-close: %a" Git_ssh.pp_error e | Error (`Rejected (r, _, _)) -> Alcotest.failf "ssh push no-close: %s rejected" r | Error (`Declined why) -> Alcotest.failf "ssh push no-close: declined: %s" why | Ok (pushed, _) -> Alcotest.(check bool) "pushed the right commit" true (Git.Hash.equal pushed chash); Alcotest.(check bool) "server ref updated" true (match ref_read srepo "refs/heads/main" with | Some h -> Git.Hash.equal h chash | None -> false) let test_unreachable () = Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let net = Eio.Stdenv.net env in let mono = Eio.Stdenv.mono_clock env in let fs = Eio.Stdenv.fs env in let tmp = Fpath.v (Filename.temp_dir "git_ssh_test" "") in let dst = Git_eio.Repository.init ~sw ~fs tmp in (* Port 1 is reserved (tcpmux) and not listening: connect must fail and the transport must surface it as [`Msg], not raise, in OpenSSH's words (sshconnect.c, ssh_connect_direct): the host, the port and strerror(3)'s reason. *) let refused = "ssh: connect to host 127.0.0.1 port 1: connection refused" in match Git_ssh.fetch ~authenticator:`No_authentication ~sw ~net ~mono ~port:1 ~user:"git" (`Password "x") ~host:"127.0.0.1" ~dst ~ref_name:"main" "/some/repo.git" with | Ok _ -> Alcotest.fail "expected a transport error against a closed port" | 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 string) "a fetch names the host and port" refused m; (* A push that cannot connect sent nothing: the remote is unreachable. *) match Git_ssh.push_updates ~authenticator:`No_authentication ~sw ~net ~mono ~port:1 ~user:"git" (`Password "x") ~host:"127.0.0.1" ~src:dst ~host_path:"/some/repo.git" [] with | Error (`Unreachable m) -> Alcotest.(check string) "a push names the host and port" refused m | Ok _ -> Alcotest.fail "pushed to a closed port" | Error _ -> Alcotest.fail "a push that cannot connect is refused") (* A server that reads the client's identification string and resets the connection (SO_LINGER zero, then close): the transport names the host and port that reset it, as OpenSSH's "Connection reset by H port P" does (packet.c, sshpkt_vfatal). *) let test_reset () = Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let net = Eio.Stdenv.net env in let mono = Eio.Stdenv.mono_clock env in let fs = Eio.Stdenv.fs env in let dst = Git_eio.Repository.init ~sw ~fs (Fpath.v (Filename.temp_dir "gsr" "")) in let sock = Eio.Net.listen ~sw ~backlog:1 ~reuse_addr:true net (`Tcp (Eio.Net.Ipaddr.V4.loopback, 0)) in let port = match Eio.Net.listening_addr sock with | `Tcp (_, port) -> port | `Unix _ -> Alcotest.fail "a TCP listener has a TCP address" in let result = ref None in Eio.Fiber.both (fun () -> Eio.Switch.run @@ fun ssw -> let flow, _ = Eio.Net.accept ~sw:ssw sock in ignore (Eio.Flow.single_read flow (Cstruct.create 256) : int); (match Eio_unix.Resource.fd_opt flow with | None -> Alcotest.fail "an accepted socket has a file descriptor" | Some fd -> Eio_unix.Fd.use_exn "linger" fd (fun fd -> Unix.setsockopt_optint fd Unix.SO_LINGER (Some 0))); Eio.Resource.close flow) (fun () -> result := Some (Git_ssh.fetch ~authenticator:`No_authentication ~sw ~net ~mono ~port ~user:"git" (`Password "x") ~host:"127.0.0.1" ~dst ~ref_name:"main" "/some/repo.git")); match !result with | None | Some (Ok _) -> Alcotest.fail "a reset connection fetches nothing" | Some (Error e) -> Alcotest.(check string) "the host and port that reset it" (Fmt.str "ssh: connection reset by 127.0.0.1 port %d" port) (Fmt.str "%a" Git_ssh.pp_error e) (* A peer that accepts the connection and never sends its identification string: ConnectTimeout ends the session as OpenSSH's banner exchange does (sshconnect.c, kex_exchange_identification), at two bounds an order of magnitude apart, and a push that ends so sent nothing. *) let test_silent_peer_times_out () = List.iter (fun n -> Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let net = Eio.Stdenv.net env in let mono = Eio.Stdenv.mono_clock env in let fs = Eio.Stdenv.fs env in let dst = Git_eio.Repository.init ~sw ~fs (Fpath.v (Filename.temp_dir "gsq" "")) in let sock = Eio.Net.listen ~sw ~backlog:4 ~reuse_addr:true net (`Tcp (Eio.Net.Ipaddr.V4.loopback, 0)) in let port = match Eio.Net.listening_addr sock with | `Tcp (_, port) -> port | `Unix _ -> Alcotest.fail "a TCP listener has a TCP address" in Eio.Fiber.fork_daemon ~sw (fun () -> while true do ignore (Eio.Net.accept ~sw sock) done; `Stop_daemon); let connect_timeout = Mtime.Span.(n * ms) in let said = "ssh: Connection timed out during banner exchange" in (match Git_ssh.ls_refs ~connect_timeout ~authenticator:`No_authentication ~sw ~net ~mono ~port ~user:"git" (`Password "x") ~host:"127.0.0.1" "/some/repo.git" with | Ok _ -> Alcotest.fail "a silent peer advertised refs" | Error e -> Alcotest.(check string) (Fmt.str "ls-refs at %dms" n) said (Fmt.str "%a" Git_ssh.pp_error e)); ignore dst; match Git_ssh.push_updates ~connect_timeout ~authenticator:`No_authentication ~sw ~net ~mono ~port ~user:"git" (`Password "x") ~host:"127.0.0.1" ~src:dst ~host_path:"/some/repo.git" [] with | Error (`Unreachable m) -> Alcotest.(check string) (Fmt.str "push at %dms" n) said m | Ok _ -> Alcotest.fail "pushed to a silent peer" | Error _ -> Alcotest.fail "a push to a silent peer is unreachable") [ 100; 1000 ] (* [on_listen] announces an address a client can reach at once: inside the announcement a connection to it is accepted, so the bind is done, and on port 0 the port it carries is the one the system chose, from which ls_refs reads the advertisement. *) let test_ssh_serve_announces_listener () = Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let net = Eio.Stdenv.net env in let mono = Eio.Stdenv.mono_clock env in let fs = Eio.Stdenv.fs env in let clock = Eio.Stdenv.clock env in let srepo = Test_helpers.init_bare ~sw ~fs (Fpath.v (Filename.temp_dir "gsann" "")) in let tree = Git_eio.Repository.write_tree srepo (Git.Tree.v []) in let a = Git.User.v ~name:"n" ~email:"n@e" ~date:0L () in let main = Git_eio.Repository.write_commit srepo (Git.Commit.v ~tree ~author:a ~committer:a (Some "announce\n")) in Git_eio.Repository.write_ref srepo "refs/heads/main" main; let ready, announce = Eio.Promise.create () in let on_listen addr = (try Eio.Switch.run @@ fun csw -> ignore (Eio.Net.connect ~sw:csw net addr) with Eio.Io _ as e -> Alcotest.failf "the announced %a refused a connection: %a" Eio.Net.Sockaddr.pp addr Eio.Exn.pp e); Eio.Promise.resolve announce addr in let result = ref (Error (`Msg "client did not run")) in Eio.Fiber.first (fun () -> Eio.Switch.run @@ fun ssw -> Git_ssh.serve ~max_connections:64 ~sw:ssw ~on_listen ~net ~mono ~host_key ~authenticate:(fun user -> function | Ssh.Server.Pubkey p -> Ssh.Server.is_pubkey_query p || Ssh.Server.verify_pubkeyauth ~user p | Ssh.Server.Authnone -> false | Ssh.Server.Password _ -> false) ~addr:(`Tcp (Eio.Net.Ipaddr.V4.loopback, 0)) srepo) (fun () -> let port = Test_helpers.announced_port ~clock ready in result := Git_ssh.ls_refs ~authenticator:`No_authentication ~sw ~net ~mono ~port ~user:"git" (`Pubkey client_key) ~host:"127.0.0.1" "/srv"); match !result with | Error e -> Alcotest.failf "ssh ls-refs: %a" Git_ssh.pp_error e | Ok adv -> Alcotest.(check (option string)) "main, as the announced server advertises it" (Some (Git.Hash.to_hex main)) (List.find_map (fun (r : Git.Smart.Message.ref_entry) -> if r.name = "refs/heads/main" then Some (Git.Hash.to_hex r.hash) else None) adv.refs) let test_live () = match Sys.getenv_opt "GIT_SSH_LIVE" with | None -> () | Some _ -> ( (* GIT_SSH_HOST, GIT_SSH_PATH, GIT_SSH_USER, GIT_SSH_KEY (ed25519:), GIT_SSH_REF drive a real clone. *) let getenv k = Option.value ~default:"" (Sys.getenv_opt k) in Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let net = Eio.Stdenv.net env in let mono = Eio.Stdenv.mono_clock env in let fs = Eio.Stdenv.fs env in let tmp = Fpath.v (Filename.temp_dir "git_ssh_live" "") in let dst = Git_eio.Repository.init ~sw ~fs tmp in let cred = match Ssh.Keys.of_string (getenv "GIT_SSH_KEY") with | Ok k -> `Pubkey k | Error (`Msg m) -> Alcotest.failf "bad GIT_SSH_KEY: %s" m in let ref_name = match getenv "GIT_SSH_REF" with "" -> "main" | r -> r in match Git_ssh.fetch ~authenticator:`No_authentication ~sw ~net ~mono ~user:(getenv "GIT_SSH_USER") cred ~host:(getenv "GIT_SSH_HOST") ~dst ~ref_name (getenv "GIT_SSH_PATH") with | Error (#Git_ssh.error as e) -> Alcotest.failf "ssh fetch: %a" Git_ssh.pp_error e | Ok target -> Alcotest.(check bool) "tip present" true (Git_eio.Repository.exists dst target)) (* A passing run proves client and server multi_ack drivers interleave correctly. *) let test_ssh_incremental () = Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let net = Eio.Stdenv.net env in let mono = Eio.Stdenv.mono_clock env in let fs = Eio.Stdenv.fs env in let clock = Eio.Stdenv.clock env in let a = Git.User.v ~name:"n" ~email:"n@e" ~date:0L () in (* c1 is built identically in both repos, so it has the same hash and the destination genuinely already holds it. *) let entry name h = Git.Tree.entry ~perm:`Normal ~name h in let build_c1 repo = let b1 = Git_eio.Repository.write_blob repo "v1\n" in let t1 = Git_eio.Repository.write_tree repo (Git.Tree.v [ entry "F" b1 ]) in ( b1, Git_eio.Repository.write_commit repo (Git.Commit.v ~tree:t1 ~author:a ~committer:a (Some "c1\n")) ) in let srepo = Git_eio.Repository.init ~sw ~fs (Fpath.v (Filename.temp_dir "gsi-s" "")) in let sb1, c1 = build_c1 srepo in let b2 = Git_eio.Repository.write_blob srepo "v2\n" in let t2 = Git_eio.Repository.write_tree srepo (Git.Tree.v [ entry "F" sb1; entry "G" b2 ]) in let c2 = Git_eio.Repository.write_commit srepo (Git.Commit.v ~tree:t2 ~author:a ~committer:a ~parents:[ c1 ] (Some "c2\n")) in Git_eio.Repository.write_ref srepo "refs/heads/main" c2; (* Destination already has c1 (on main), so [local_haves] offers it. *) let dst = Git_eio.Repository.init ~sw ~fs (Fpath.v (Filename.temp_dir "gsi-d" "")) in let _, c1' = build_c1 dst in Alcotest.(check bool) "c1 reproduced" true (Git.Hash.equal c1 c1'); Git_eio.Repository.write_ref dst "refs/heads/main" c1; let authenticate user = function | Ssh.Server.Pubkey p -> Ssh.Server.is_pubkey_query p || Ssh.Server.verify_pubkeyauth ~user p | Ssh.Server.Authnone -> false | Ssh.Server.Password _ -> true in let result = ref (Error (`Msg "client did not run")) in let ready, announce = Eio.Promise.create () in Eio.Fiber.first (fun () -> Eio.Switch.run @@ fun ssw -> Git_ssh.serve ~max_connections:64 ~sw:ssw ~on_listen:(Eio.Promise.resolve announce) ~net ~mono ~host_key ~authenticate ~addr:(`Tcp (Eio.Net.Ipaddr.V4.loopback, 0)) srepo) (fun () -> let port = Test_helpers.announced_port ~clock ready in result := 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"); match !result with | Error (#Git_ssh.error as e) -> Alcotest.failf "ssh incremental fetch: %a" Git_ssh.pp_error e | Ok target -> Alcotest.(check bool) "fetched c2" true (Git.Hash.equal target c2); Alcotest.(check bool) "c2 present" true (Git_eio.Repository.exists dst c2); Alcotest.(check bool) "c1 still present (reused, not re-fetched)" true (Git_eio.Repository.exists dst c1) (* A fixture HOME whose [.ssh/known_hosts] is [known_hosts] (a directory when [None], which is there but cannot be read as a file). *) let with_home known_hosts f = let home = Filename.temp_dir "git-ssh-home" "" in let ssh = Filename.concat home ".ssh" in Unix.mkdir ssh 0o700; let path = Filename.concat ssh "known_hosts" in (match known_hosts with | None -> Unix.mkdir path 0o700 | Some content -> Out_channel.with_open_bin path (fun oc -> output_string oc content)); let saved = Sys.getenv_opt "HOME" in Unix.putenv "HOME" home; Fun.protect ~finally:(fun () -> Unix.putenv "HOME" (Option.value saved ~default:"")) (fun () -> Eio_main.run @@ fun env -> f ~fs:(Eio.Stdenv.fs env) ~path) let github_ed25519 = "AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl" (* GitHub's published ed25519 and ecdsa keys after a line for another host, the shape OpenSSH's UpdateHostKeys leaves. *) let github_known_hosts = "gitlab.com ssh-ed25519 \ AAAAC3NzaC1lZDI1NTE5AAAAIAfuCHKVTjquxvt6CM6tdG4SLp1Btn/nOeHHE5UOzRdf\n\ github.com ssh-ed25519 " ^ github_ed25519 ^ "\n\ github.com ecdsa-sha2-nistp256 \ AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEmKSENjQEezOmxkZMy7opKgwFB9nkt5YRrYMjNuG5N87uRgg6CLrbo5wAdT/y6v0mKV0U2w0WZ2YB/++Tpockg=\n" let test_known_hosts_github () = with_home (Some github_known_hosts) @@ fun ~fs ~path:_ -> match Git_ssh.known_hosts_authenticator ~fs ~host:"github.com" () with | Error (`Msg m) -> Alcotest.failf "known_hosts: %s" m | Ok None -> Alcotest.fail "github.com is not found in ~/.ssh/known_hosts" | Ok (Some auth) -> ( match Ssh.Hostkey.pubkey_of_blob (Base64.decode_exn github_ed25519) with | Error m -> Alcotest.failf "fixture key: %s" m | Ok pub -> Alcotest.(check bool) "github.com's ed25519 key authenticates" true (Ssh.Keys.hostkey_matches auth pub)) (* A known_hosts that is there but cannot be read is named, never reported as a host missing from it. *) let test_known_hosts_unreadable () = with_home None @@ fun ~fs ~path -> match Git_ssh.known_hosts_authenticator ~fs ~host:"github.com" () with | Error (`Msg m) -> Alcotest.(check bool) ("names " ^ path ^ ": " ^ m) true (contains ~sub:path m) | Ok _ -> Alcotest.fail "an unreadable known_hosts must be an error" (* A server that answers git-upload-pack with bytes that are no pkt-line and keeps the channel open. *) let serve_garbage ~mono ~host_key ~authenticate flow = let on_event t = function | Ssh.Server.Channel_exec (chan, _) -> Ssh_eio.Server.send t chan "zzzz" | _ -> () in Ssh_eio.Server.serve ~mono flow ~host_key ~authenticate ~on_event (* A session that ends in an error it returns, not one it raises, also leaves nothing running: ls_refs refuses the garbage and its caller's switch ends within ten seconds, while the server still holds the channel open. *) let test_ssh_error_ends_session () = Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let net = Eio_net_mem.v ~sw () in let mono = Eio.Stdenv.mono_clock env in let clock = Eio.Stdenv.clock env in let result = ref None in let sock = Eio.Net.listen ~sw ~backlog:1 ~reuse_addr:true net (`Tcp (Eio.Net.Ipaddr.V4.loopback, 0)) in let port = match Eio.Net.listening_addr sock with | `Tcp (_, port) -> port | `Unix _ -> Alcotest.fail "a TCP listener has a TCP address" in Eio.Fiber.first (fun () -> Eio.Switch.run @@ fun ssw -> Eio.Net.accept_fork ~sw:ssw sock ~on_error:raise (fun flow _addr -> serve_garbage ~mono ~host_key ~authenticate:allow flow); Eio.Fiber.await_cancel ()) (fun () -> result := Some (Eio.Time.with_timeout_exn clock 10. (fun () -> Eio.Switch.run @@ fun sw -> Git_ssh.ls_refs ~authenticator:`No_authentication ~sw ~net ~mono ~port ~user:"git" (`Pubkey client_key) ~host:"127.0.0.1" "/srv"))); match Option.get !result with | Ok _ -> Alcotest.fail "garbage is no advertisement" | 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 _) -> () (* git-upload-pack advertises HEAD, then every ref sorted by name in byte order, whether it is packed or loose (gitprotocol-pack(5), "Reference Discovery"; refs.c iterates refs in that order). The repository is the one traces/layout describes, its refs made in that order and stored as it says; traces/upload-pack.pkt is what git-upload-pack advertised for it (scripts/generate.sh). The server advertises the same names in the same order. *) let test_ssh_advertisement_order () = Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let net = Eio_net_mem.v ~sw () in let mono = Eio.Stdenv.mono_clock env in let fs = Eio.Stdenv.fs env in let clock = Eio.Stdenv.clock env in let dir = Filename.temp_dir "gsorder" "" in let srepo = Test_helpers.init_bare ~sw ~fs (Fpath.v dir) in let tree = Git_eio.Repository.write_tree srepo (Git.Tree.v []) in let a = Git.User.v ~name:"n" ~email:"n@e" ~date:0L () in let c = Git_eio.Repository.write_commit srepo (Git.Commit.v ~tree ~author:a ~committer:a (Some "advertise\n")) in let layout = String.split_on_char '\n' (read_file "traces/layout") |> List.filter_map (fun l -> match String.split_on_char ' ' l with | [ "packed"; r ] -> Some (`Packed, r) | [ "loose"; r ] -> Some (`Loose, r) | [ "" ] -> None | _ -> Alcotest.failf "traces/layout: %S" l) in let packed = List.filter_map (function `Packed, r -> Some r | `Loose, _ -> None) layout in Out_channel.with_open_bin (Filename.concat (Filename.concat dir ".git") "packed-refs") (fun oc -> output_string oc "# pack-refs with: peeled fully-peeled sorted \n"; List.iter (fun r -> output_string oc (Fmt.str "%s %s\n" (Git.Hash.to_hex c) r)) (List.sort String.compare packed)); List.iter (function | `Loose, r -> Git_eio.Repository.write_ref srepo r c | `Packed, _ -> ()) layout; Git_eio.Repository.write_symbolic_ref srepo "HEAD" ~target:"refs/heads/main"; let git = match Git.Smart.Message.Advertisement.of_string (read_file "traces/upload-pack.pkt") with | Ok adv -> adv | Error (`Msg m) -> Alcotest.failf "traces/upload-pack.pkt: %s" m in let result = ref (Error (`Msg "client did not run")) in let ready, announce = Eio.Promise.create () in Eio.Fiber.first (fun () -> Eio.Switch.run @@ fun ssw -> Git_ssh.serve ~max_connections:64 ~sw:ssw ~on_listen:(Eio.Promise.resolve announce) ~net ~mono ~host_key ~authenticate:allow ~addr:(`Tcp (Eio.Net.Ipaddr.V4.loopback, 0)) srepo) (fun () -> let port = Test_helpers.announced_port ~clock ready in result := Git_ssh.ls_refs ~authenticator:`No_authentication ~sw ~net ~mono ~port ~user:"git" (`Pubkey client_key) ~host:"127.0.0.1" "/srv"); let names (adv : Git.Smart.Message.Advertisement.t) = List.map (fun (r : Git.Smart.Message.ref_entry) -> r.name) adv.refs in match !result with | Error e -> Alcotest.failf "ssh ls-refs: %a" Git_ssh.pp_error e | Ok adv -> Alcotest.(check (list string)) "git-upload-pack's order" (names git) (names adv) (* git push writes its request and reads the report with its stream open: over SSH its channel ends only when ssh's standard input does, which pack-objects holds, and a deletion alone runs no pack-objects (send-pack.c). receive-pack answers once the request is whole: the commands to their flush-pkt, then the pack unless every command is a delete (gitprotocol-pack(5), "Reference Update Request and Packfile Transfer"). A client here pushes a branch, then deletes it, each on a channel it does not end; each report must come while it stays open. *) let push_open ~sw ~net ~mono ~port ~src updates = let flow = Eio.Net.connect ~sw net (`Tcp (Eio.Net.Ipaddr.V4.loopback, port)) in let client = Ssh_eio.Client.connect ~sw ~mono flow ~authenticator:`No_authentication ~user:"git" (`Pubkey client_key) in let id = Ssh_eio.Client.open_channel client in Ssh_eio.Client.exec client ~id "git-receive-pack '/srv'"; let reader, _ = Ssh_eio.Client.channel_reader ~sw client ~id in match Git.Smart.Client.Push.advertisement Git.Smart.Client.Push.v reader with | Error (`Msg m) -> Alcotest.fail m | Ok (push, adv) -> ( let send body = Ssh_eio.Client.write client ~id (Bytesrw.Bytes.Reader.to_string body); Ssh_eio.Client.flush client; Ok reader in match Git_eio.Push.negotiate_updates ~client:push ~adv ~src ~send updates with | Ok refs -> refs | Error (`Msg m | `Declined m) -> Alcotest.fail m | Error (`Stale (r, _) | `Non_fast_forward r) -> Alcotest.failf "refused %s" r) let test_ssh_receive_open () = let srepo ~sw ~fs = Test_helpers.init_bare ~sw ~fs (Fpath.v (Filename.temp_dir "gsro" "")) in against srepo @@ fun ~sw ~net ~mono ~fs ~port -> let src = Git_eio.Repository.init ~sw ~fs (Fpath.v (Filename.temp_dir "gsrc" "")) in let blob = Git_eio.Repository.write_blob src "pushed open\n" in let tree = Git_eio.Repository.write_tree src (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 let c = Git_eio.Repository.write_commit src (Git.Commit.v ~tree ~author:a ~committer:a (Some "c\n")) in let update value expect = { Git_eio.Push.dst_ref = "refs/heads/topic"; value; expect } in Alcotest.(check (list string)) "topic created" [ "refs/heads/topic" ] (push_open ~sw ~net ~mono ~port ~src [ update (Some c) (Lease None) ]); Alcotest.(check (list string)) "topic deleted" [ "refs/heads/topic" ] (push_open ~sw ~net ~mono ~port ~src [ update None (Lease (Some c)) ]) (* A client that leaves with its push request half sent leaves nothing of its session running: serve_connection returns once the connection ends. *) let test_ssh_receive_abandoned () = Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let net = Eio_net_mem.v ~sw () in let mono = Eio.Stdenv.mono_clock env and clock = Eio.Stdenv.clock env in let fs = Eio.Stdenv.fs env in let repo = Test_helpers.init_bare ~sw ~fs (Fpath.v (Filename.temp_dir "gsra" "")) in let sock = Eio.Net.listen ~sw ~backlog:1 ~reuse_addr:true net (`Tcp (Eio.Net.Ipaddr.V4.loopback, 0)) in let port = match Eio.Net.listening_addr sock with | `Tcp (_, port) -> port | `Unix _ -> Alcotest.fail "a TCP listener has a TCP address" in let server () = Eio.Switch.run @@ fun sw -> let flow, _ = Eio.Net.accept ~sw sock in Git_ssh.serve_connection ~mono ~host_key ~authenticate:allow repo flow in let client () = Eio.Switch.run @@ fun sw -> let flow = Eio.Net.connect ~sw net (`Tcp (Eio.Net.Ipaddr.V4.loopback, port)) in let client = Ssh_eio.Client.connect ~sw ~mono flow ~authenticator:`No_authentication ~user:"git" (`Pubkey client_key) in let id = Ssh_eio.Client.open_channel client in Ssh_eio.Client.exec client ~id "git-receive-pack '/srv'"; let reader, _ = Ssh_eio.Client.channel_reader ~sw client ~id in (match Git.Smart.Client.Push.advertisement Git.Smart.Client.Push.v reader with | Ok _ -> () | Error (`Msg m) -> Alcotest.fail m); Ssh_eio.Client.write client ~id "00b4"; Ssh_eio.Client.flush client; Eio.Flow.close flow in Eio.Time.with_timeout_exn clock 10. (fun () -> Eio.Fiber.both server client) (* The traces of git push over a stand-in for ssh (scripts/ssh_relay.ml): for a branch, git ends its channel once it has the advertisement, the pack sent; for a deletion alone, only once it has the whole report. *) let advertisement_length s = let r = Bytesrw.Bytes.Reader.of_string s in let rec go () = match Git.Smart.Packet.of_reader r with | Ok Git.Smart.Packet.Flush -> Bytesrw.Bytes.Reader.pos r | Ok _ -> go () | Error (`Msg m) -> Alcotest.fail m in go () let ended name = int_of_string (String.trim (read_file ("traces/" ^ name ^ ".eof"))) let test_git_push_over_ssh () = let server = read_file "traces/push-ssh.server" in Alcotest.(check int) "a push ends its channel after the advertisement" (advertisement_length server) (ended "push-ssh"); Alcotest.(check int) "a deletion ends its channel after the report" (String.length (read_file "traces/delete-ssh.server")) (ended "delete-ssh") (* git's deletion request is whole at its flush-pkt, with no pack after it, read from a stream that fails past it. *) let test_git_delete_framed () = let request = read_file "traces/delete-ssh.client" in let r = Bytesrw.Bytes.Reader.of_string request in let open_stream = Bytesrw.Bytes.Reader.make (fun () -> let s = Bytesrw.Bytes.Reader.read r in if Bytesrw.Bytes.Slice.is_eod s then Alcotest.fail "read past the request, while git waits" else s) in match Git.Smart.Message.Receive_pack.read_framed open_stream with | Ok got -> Alcotest.(check string) "the request" request got | Error (`Msg m) -> Alcotest.fail m (* git fetch of one ref over ssh, in protocol v0, keeps its channel open until it has the pack (transport.c, fetch_refs_via_pack closes its descriptors once fetch_pack returns). A session of nox-git's, given upload-pack's recorded answer a byte at a time, ends its side at the same byte. *) let test_git_fetch_over_ssh () = let server = read_file "traces/fetch-ssh.server" in Alcotest.(check int) "a fetch ends its channel after the pack" (String.length server) (ended "fetch-ssh"); let reader = Bytesrw.Bytes.Reader.of_string ~slice_length:1 server in let ended_at = ref None in let channel = { Git_eio.Fetch.write = ignore; reader; eof = (fun () -> ended_at := Some (Bytesrw.Bytes.Reader.pos reader)); } in Eio_main.run @@ fun env -> Eio.Switch.run @@ fun sw -> let dst = Git_eio.Repository.init ~sw ~fs:(Eio.Stdenv.fs env) (Fpath.v (Filename.temp_dir "gsfetch" "")) in match Git_eio.Fetch.session_fetch ~ref_name:"main" channel dst with | Error (`Msg m) -> Alcotest.fail m | Ok _ -> Alcotest.(check (option int)) "nox-git ends its channel at git's byte" (Some (ended "fetch-ssh")) !ended_at let suite = ( "git_ssh", [ Alcotest.test_case "git push over ssh ends its channel when it can" `Quick test_git_push_over_ssh; Alcotest.test_case "git's deletion request is whole at its flush" `Quick test_git_delete_framed; Alcotest.test_case "a v0 fetch over ssh ends its channel where git does" `Quick test_git_fetch_over_ssh; Alcotest.test_case "ssh push and deletion answered on an open channel" `Slow test_ssh_receive_open; Alcotest.test_case "ssh push abandoned half sent ends its session" `Slow test_ssh_receive_abandoned; Alcotest.test_case "ssh clone (in-process)" `Slow test_ssh_clone; Alcotest.test_case "10 times its bound of silent peers" `Quick (test_silent_peers 10); Alcotest.test_case "100 times its bound of silent peers" `Quick (test_silent_peers 100); Alcotest.test_case "ssh incremental (multi-round)" `Slow test_ssh_incremental; Alcotest.test_case "ssh ls-refs (in-process)" `Slow test_ssh_ls_refs; Alcotest.test_case "ssh advertises refs in git-upload-pack's order" `Slow test_ssh_advertisement_order; Alcotest.test_case "ssh session ends on an error it returns" `Slow test_ssh_error_ends_session; Alcotest.test_case "ssh quotes the repository path as Git does" `Slow test_ssh_quoted_path; Alcotest.test_case "ssh with ECDSA host and user keys" `Slow test_ssh_ecdsa; Alcotest.test_case "ssh push (in-process)" `Slow test_ssh_push; Alcotest.test_case "a session carries ten pushes on one connection" `Quick test_session_carries_ten_pushes; Alcotest.test_case "ssh push large pack" `Slow test_ssh_push_large_pack_keeps_reading; Alcotest.test_case "ssh push reports remote stderr" `Quick test_ssh_push_reports_remote_stderr_before_advertisement; Alcotest.test_case "ssh remote stderr is display text" `Quick test_ssh_remote_stderr_is_display_text; Alcotest.test_case "ssh push closes after status" `Slow test_ssh_push_closes_channel_after_status; Alcotest.test_case "ssh push cut off names the remote's refusal" `Quick test_ssh_push_cut_off_reports_remote; Alcotest.test_case "ssh push cut off names a side-band refusal" `Quick test_ssh_push_cut_off_reports_sideband; Alcotest.test_case "host_authenticator fails closed" `Quick test_host_authenticator_fails_closed; Alcotest.test_case "known_hosts: github.com as OpenSSH records it" `Quick test_known_hosts_github; Alcotest.test_case "known_hosts: unreadable file is named" `Quick test_known_hosts_unreadable; Alcotest.test_case "unreachable host errors" `Quick test_unreachable; Alcotest.test_case "a silent peer ends at ConnectTimeout" `Quick test_silent_peer_times_out; Alcotest.test_case "a reset connection names the host and port" `Quick test_reset; Alcotest.test_case "serve announces the address it listens on" `Quick test_ssh_serve_announces_listener; Alcotest.test_case "live clone (opt-in)" `Quick test_live; ] )