╭ serve_ssh.zig ────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const xit = @import("xit"); 3 const rp = xit.repo; 4 const xitui = xit.xitui; 5 const StreamTerminal = xitui.stream_terminal.StreamTerminal; 6 const Grid = xitui.grid.Grid; 7 const Size = xitui.layout.Size; 8 const ui = @import("./ui.zig"); 9 const ssh = @import("./serve_ssh_protocol.zig"); 10 const evt = @import("./event.zig"); 11 const serve_common = @import("./serve_common.zig"); 12 13 // listener resource limits. the watchdog gives unauthenticated peers a hard 14 // deadline, detects idle non-interactive sessions from protocol progress, and 15 // bounds the post-CLOSE drain. each connection holds two OS threads under 16 // std.Io.Threaded (session + watchdog), so the cap is sized by thread count. 17 const max_connections: u32 = 4096; 18 const watchdog_interval = std.Io.Duration.fromSeconds(5); 19 const preauth_timeout_ticks: u32 = 6; // 30 seconds 20 const idle_timeout_ticks: u32 = 24; // 120 seconds 21 const close_drain_timeout_ticks: u32 = 2; // 5-10 seconds 22 23 var active_connections: std.atomic.Value(u32) = .init(0); 24 25 pub const SessionHandler = struct { 26 admin_repo_path: []const u8, 27 repo_root_path: []const u8, 28 wui_port: u16, // port the web UI is served on, shown in the TUI footer's url 29 err: *std.Io.Writer, 30 31 pub fn handleSession(self: *const SessionHandler, sess: *ssh.SessionCtx, request: ssh.Request) !void { 32 serve_common.logError(sess.conn.io, self.err, "ssh session: kind={s} key={s}\n", .{ @tagName(request), sess.fingerprint }); 33 switch (request) { 34 .shell => |pty_maybe| { 35 const pty = pty_maybe orelse { 36 // a shell without a pty has no useful TUI to render; in 37 // openssh client terms this is `ssh -T host`. say so and 38 // exit non-zero. 39 try sess.writeBytes("haxy ssh: this server only serves the TUI when a pty is allocated (use a normal `ssh` invocation).\r\n"); 40 try sess.exit(1); 41 return; 42 }; 43 sess.exemptFromIdleTimeout(); 44 try runTuiSession(self, sess, pty); 45 }, 46 .exec => |command| { 47 try runGitSession(self, sess, command); 48 }, 49 } 50 } 51 }; 52 53 pub fn runListener( 54 io: std.Io, 55 allocator: std.mem.Allocator, 56 host_key: *const ssh.HostKey, 57 session_handler: *const SessionHandler, 58 net_server: *std.Io.net.Server, 59 tasks: *std.Io.Group, 60 err: *std.Io.Writer, 61 ) void { 62 const Context = struct { 63 io: std.Io, 64 allocator: std.mem.Allocator, 65 host_key: *const ssh.HostKey, 66 session_handler: *const SessionHandler, 67 err: *std.Io.Writer, 68 }; 69 70 const handle = struct { 71 fn h(ctx: Context, stream: std.Io.net.Stream) void { 72 defer stream.close(ctx.io); 73 74 const prev_count = active_connections.fetchAdd(1, .monotonic); 75 defer _ = active_connections.fetchSub(1, .monotonic); 76 if (prev_count >= max_connections) { 77 serve_common.logError(ctx.io, ctx.err, "ssh: connection limit reached, dropping\n", .{}); 78 return; 79 } 80 81 var idle_state = ssh.IdleState{}; 82 var watchdog_future = std.Io.concurrent(ctx.io, watchdog, .{ ctx.io, &stream, &idle_state }) catch |spawn_err| { 83 serve_common.logError(ctx.io, ctx.err, "ssh: watchdog spawn failed: {s}\n", .{@errorName(spawn_err)}); 84 return; 85 }; 86 defer watchdog_future.cancel(ctx.io); 87 88 var recv_buf: [4096]u8 = undefined; 89 var send_buf: [4096]u8 = undefined; 90 var stream_reader = stream.reader(ctx.io, &recv_buf); 91 var stream_writer = stream.writer(ctx.io, &send_buf); 92 ssh.handleConnection( 93 ctx.io, 94 ctx.allocator, 95 &stream_reader.interface, 96 &stream_writer.interface, 97 ctx.host_key, 98 &idle_state, 99 ctx.session_handler, 100 ) catch |session_err| { 101 serve_common.logError(ctx.io, ctx.err, "ssh session failed: {s}\n", .{@errorName(session_err)}); 102 }; 103 } 104 }.h; 105 106 serve_common.runListener(io, net_server, tasks, err, "ssh", Context{ 107 .io = io, 108 .allocator = allocator, 109 .host_key = host_key, 110 .session_handler = session_handler, 111 .err = err, 112 }, handle); 113 } 114 115 // enforce a hard pre-auth deadline, an idle timeout for non-interactive 116 // sessions, and a bounded close drain. interactive sessions are exempt only 117 // from the idle timeout; the watchdog remains available to break a stalled 118 // teardown. 119 fn watchdog(io: std.Io, stream: *const std.Io.net.Stream, idle_state: *ssh.IdleState) void { 120 var last_seen: u64 = 0; 121 var preauth_ticks: u32 = 0; 122 var idle_ticks: u32 = 0; 123 var closing_ticks: u32 = 0; 124 while (true) { 125 io.sleep(watchdog_interval, .awake) catch return; // canceled — connection is done 126 127 if (idle_state.closing.load(.acquire)) { 128 closing_ticks += 1; 129 if (closing_ticks >= close_drain_timeout_ticks) { 130 stream.shutdown(io, .both) catch {}; 131 return; 132 } 133 continue; 134 } 135 136 if (!idle_state.authenticated.load(.acquire)) { 137 preauth_ticks += 1; 138 if (preauth_ticks >= preauth_timeout_ticks) { 139 stream.shutdown(io, .both) catch {}; 140 return; 141 } 142 continue; 143 } 144 145 if (idle_state.exempt.load(.monotonic)) continue; 146 const seen = idle_state.activity.load(.monotonic); 147 if (seen == last_seen) { 148 idle_ticks += 1; 149 if (idle_ticks >= idle_timeout_ticks) { 150 stream.shutdown(io, .both) catch {}; 151 return; 152 } 153 } else { 154 idle_ticks = 0; 155 } 156 last_seen = seen; 157 } 158 } 159 160 fn runTuiSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, pty: ssh.PtySize) !void { 161 // runTui owns the terminal, whose deinit restores the client's screen and 162 // runs as the function unwinds — so any error it returns leaves the TUI torn 163 // down and we can surface the failure on the restored screen before exiting. 164 runTui(handler, sess, pty) catch |err| { 165 serve_common.logError(sess.conn.io, handler.err, "ssh tui session failed: {s}\n", .{@errorName(err)}); 166 var buf: [256]u8 = undefined; 167 const msg = std.fmt.bufPrint(&buf, "haxy ssh: {s}\r\n", .{@errorName(err)}) catch "haxy ssh: internal error\r\n"; 168 sess.writeBytes(msg) catch {}; 169 try sess.exit(1); 170 return; 171 }; 172 try sess.exit(0); 173 } 174 175 fn runTui(handler: *const SessionHandler, sess: *ssh.SessionCtx, pty: ssh.PtySize) !void { 176 const allocator = sess.conn.allocator; 177 const io = sess.conn.io; 178 179 // some clients (notably scripted ssh with no local controlling tty) 180 // allocate a pty without ever sending a non-zero size. fall back to a 181 // conventional 80x24 in that case so render emits something. 182 const effective_pty = ssh.PtySize{ 183 .width_cells = if (pty.width_cells == 0) 80 else pty.width_cells, 184 .height_cells = if (pty.height_cells == 0) 24 else pty.height_cells, 185 }; 186 187 // session-lifetime allocations (login, prefs); Nav owns the per-page arenas. 188 var session_arena = std.heap.ArenaAllocator.init(allocator); 189 defer session_arena.deinit(); 190 191 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 192 var repo = try Repo.open(io, allocator, .{ .path = handler.admin_repo_path }); 193 defer repo.deinit(io, allocator); 194 var ui_session = try ui.Session.init(&session_arena, &repo, .{}); 195 ui_session.is_terminal = true; 196 ui_session.web_port = handler.wui_port; 197 // let page builders open on-disk repos (sibling "repos" dir of the admin repo) 198 ui_session.io = io; 199 ui_session.repos_dir = try std.fs.path.join(session_arena.allocator(), &.{ std.fs.path.dirname(handler.admin_repo_path) orelse ".", "repos" }); 200 201 var nav = try ui.Nav.init(allocator, &ui_session); 202 defer nav.deinit(allocator); 203 204 var session_writer_buf: [8192]u8 = undefined; 205 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 206 207 // the terminal's deinit writes leave-alt / show-cursor / disable-mouse and 208 // flushes, restoring the client's screen. as a function-scoped defer it runs 209 // before runTui returns — on the normal path and on any error — so the 210 // caller can write to the client afterward (and sess.exit can close cleanly). 211 var terminal = try StreamTerminal.init(allocator, &session_writer.interface, .{ 212 .width = effective_pty.width_cells, 213 .height = effective_pty.height_cells, 214 }); 215 defer terminal.deinit(); 216 217 var last_size = Size{ .width = 0, .height = 0 }; 218 var last_grid = try Grid.init(allocator, last_size); 219 defer last_grid.deinit(); 220 221 // initial render — user sees the page immediately 222 try nav.root.build(allocator, .{ 223 .min_size = .{ .width = null, .height = null }, 224 .max_size = .{ .width = last_size.width, .height = last_size.height }, 225 }, nav.root.getFocus()); 226 _ = try terminal.render(&nav.root, &last_grid, &last_size); 227 228 // event loop. nextEvent blocks until something interesting arrives; 229 // for each event, rebuild the widget tree and re-render so the user 230 // sees the effect of their input on the same iteration. 231 while (!terminal.shouldQuit()) { 232 const event = try sess.nextEvent(); 233 switch (event) { 234 .data => |payload| { 235 defer allocator.free(payload); 236 try terminal.writeBytes(payload); 237 while (terminal.popKey()) |key| { 238 try ui.inputKey(allocator, &nav.root, key, &ui_session); 239 } 240 }, 241 .resize => |sz| { 242 terminal.pushResize(.{ .width = sz.width_cells, .height = sz.height_cells }); 243 while (terminal.popKey()) |key| { 244 try ui.inputKey(allocator, &nav.root, key, &ui_session); 245 } 246 }, 247 // either way no more input can arrive, so nothing is left to 248 // drive the ui — but on .eof the channel is still open, so the 249 // teardown below still reaches the client. 250 .eof, .close => terminal.requestQuit(), 251 } 252 253 try ui_session.applyAndWritePending(io, allocator, &repo); 254 255 // pick up data written by other handles so the next navigation 256 // builds its page from a current moment 257 try ui_session.reloadMoment(&repo); 258 259 // reconcile navigation: forward to a new page, or back on escape 260 try nav.sync(allocator, &ui_session); 261 262 // the quit button (on the quit tab) asks the host to tear down 263 if (ui_session.quit_requested) terminal.requestQuit(); 264 265 try nav.root.build(allocator, .{ 266 .min_size = .{ .width = null, .height = null }, 267 .max_size = .{ .width = last_size.width, .height = last_size.height }, 268 }, nav.root.getFocus()); 269 _ = try terminal.render(&nav.root, &last_grid, &last_size); 270 } 271 } 272 273 // --------------------------------------------------------------------------- 274 // git path (exec) 275 // --------------------------------------------------------------------------- 276 277 pub const GitService = enum { upload_pack, receive_pack }; 278 279 pub const ParsedGitCommand = struct { 280 service: GitService, 281 dir: []u8, 282 283 pub fn deinit(self: ParsedGitCommand, allocator: std.mem.Allocator) void { 284 allocator.free(self.dir); 285 } 286 }; 287 288 fn runGitSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, command: []const u8) !void { 289 const allocator = sess.conn.allocator; 290 const io = sess.conn.io; 291 292 const parsed = parseGitCommand(allocator, command) catch return writeError(sess, "unsupported command (expected git-upload-pack or git-receive-pack)"); 293 defer parsed.deinit(allocator); 294 295 const create_if_missing = parsed.service == .receive_pack; 296 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{}; 297 298 // authenticate pushes: the authenticated key must be registered to the 299 // repo's owner. 300 if (create_if_missing) { 301 const owner_repo = evt.parseOwnerRepoPath(parsed.dir) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 302 if (!try isKeyAuthorized(io, allocator, handler.admin_repo_path, owner_repo.owner, &sess.fingerprint)) 303 return writeError(sess, "unauthorized: this SSH key is not registered to the repo owner"); 304 } 305 306 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, handler.repo_root_path, handler.admin_repo_path, parsed.dir, create_if_missing)) { 307 .ok => |p| p, 308 .invalid => return writeError(sess, "repo path must be <owner>/<repo>"), 309 .not_found => return writeError(sess, "repo not found"), 310 }; 311 defer allocator.free(repo_path); 312 313 if (try serveIfExists(repo_path, sess, io, allocator, parsed.service)) { 314 try sess.exit(0); 315 return; 316 } 317 318 if (!create_if_missing) return writeError(sess, "repo not found"); 319 320 // create the on-disk repo for the just-minted event and serve the push 321 var repo = try createRepo(any_repo_opts.toRepoOpts(), io, allocator, repo_path); 322 defer repo.deinit(io, allocator); 323 try servePack(repo.self_repo_opts, &repo, sess, io, allocator, parsed.service); 324 try sess.exit(0); 325 } 326 327 // serve an existing repo at `repo_path`, or return false if none is there 328 fn serveIfExists( 329 repo_path: []const u8, 330 sess: *ssh.SessionCtx, 331 io: std.Io, 332 allocator: std.mem.Allocator, 333 service: GitService, 334 ) !bool { 335 // a bare open() creates the directory while probing for the repo, so only 336 // attempt it when the path already exists 337 std.Io.Dir.accessAbsolute(io, repo_path, .{}) catch return false; 338 339 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{}; 340 var any_repo = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 341 error.RepoNotFound => return false, 342 else => |e| return e, 343 }; 344 defer any_repo.deinit(io, allocator); 345 346 switch (any_repo) { 347 inline else => |*repo| try servePack(repo.self_repo_opts, repo, sess, io, allocator, service), 348 } 349 return true; 350 } 351 352 fn createRepo( 353 comptime repo_opts: rp.RepoOpts(.xit), 354 io: std.Io, 355 allocator: std.mem.Allocator, 356 repo_path: []const u8, 357 ) !rp.Repo(.xit, repo_opts) { 358 var repo = try rp.Repo(.xit, repo_opts).init(io, allocator, .{ .path = repo_path }); 359 errdefer repo.deinit(io, allocator); 360 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 361 try repo.addConfig(io, allocator, .{ .name = "receive.denycurrentbranch", .value = "updateinstead" }); 362 return repo; 363 } 364 365 // wrap the channel I/O in std.Io.Reader/Writer adapters so the repo's pack 366 // functions can consume them like any other stream, then run the requested 367 // service 368 fn servePack( 369 comptime repo_opts: rp.RepoOpts(.xit), 370 repo: *rp.Repo(.xit, repo_opts), 371 sess: *ssh.SessionCtx, 372 io: std.Io, 373 allocator: std.mem.Allocator, 374 service: GitService, 375 ) !void { 376 var session_reader_buf: [4096]u8 = undefined; 377 var session_writer_buf: [4096]u8 = undefined; 378 var session_reader = ssh.SessionReader.init(sess, &session_reader_buf); 379 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 380 381 switch (service) { 382 .upload_pack => try repo.uploadPack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 383 .receive_pack => try evt.receivePackAndConsume(repo_opts, io, allocator, repo, &session_reader.interface, &session_writer.interface, .{}), 384 } 385 386 // flush whatever the pack op buffered into our writer adapter 387 session_writer.interface.flush() catch {}; 388 } 389 390 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 391 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 392 defer tokens.deinit(); 393 394 const service_token = tokens.next() orelse return error.InvalidCommand; 395 const dir_token = tokens.next() orelse return error.InvalidCommand; 396 397 const service: GitService = 398 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 399 .upload_pack 400 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 401 .receive_pack 402 else 403 return error.UnsupportedService; 404 405 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 406 } 407 408 // true if `fingerprint` matches one of the named user's registered SSH keys 409 fn isKeyAuthorized( 410 io: std.Io, 411 allocator: std.mem.Allocator, 412 admin_repo_path: []const u8, 413 owner_name: []const u8, 414 fingerprint: *const [ssh.fingerprint_len]u8, 415 ) !bool { 416 var arena = std.heap.ArenaAllocator.init(allocator); 417 defer arena.deinit(); 418 419 const user = (try evt.User.readByName(io, allocator, admin_repo_path, &arena, owner_name)) orelse return false; 420 421 var it = std.mem.splitScalar(u8, user.event.ssh_keys, '\n'); 422 while (it.next()) |line| { 423 const fp = fingerprintOfAuthorizedKey(line) orelse continue; 424 if (std.mem.eql(u8, &fp, fingerprint)) return true; 425 } 426 return false; 427 } 428 429 // the SHA256 fingerprint of one authorized_keys line, or null if the line is 430 // blank or not a parseable "<type> <base64> [comment]" entry 431 fn fingerprintOfAuthorizedKey(line: []const u8) ?[ssh.fingerprint_len]u8 { 432 var it = std.mem.tokenizeAny(u8, line, " \t\r"); 433 _ = it.next() orelse return null; // key type 434 const blob_b64 = it.next() orelse return null; 435 436 const decoder = std.base64.standard.Decoder; 437 const blob_len = decoder.calcSizeForSlice(blob_b64) catch return null; 438 var blob_buf: [4096]u8 = undefined; 439 if (blob_len > blob_buf.len) return null; 440 decoder.decode(blob_buf[0..blob_len], blob_b64) catch return null; 441 442 return ssh.formatFingerprint(blob_buf[0..blob_len]); 443 } 444 445 // write an error to the client's stderr and exit non-zero. stderr (not stdout) 446 // because the git exec sessions that call this carry the pack protocol on 447 // stdout, where stray text breaks the client's pkt-line parser. 448 fn writeError(sess: *ssh.SessionCtx, comptime msg: []const u8) !void { 449 try sess.writeStderr("haxy ssh: " ++ msg ++ "\n"); 450 try sess.exit(1); 451 } 452 453 test "parseGitCommand rejects malformed input" { 454 const allocator = std.testing.allocator; 455 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 456 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 457 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 458 } 459 460 test "parseGitCommand happy paths" { 461 const allocator = std.testing.allocator; 462 463 { 464 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 465 defer parsed.deinit(allocator); 466 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 467 try std.testing.expectEqualStrings("some-repo", parsed.dir); 468 } 469 { 470 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 471 defer parsed.deinit(allocator); 472 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 473 try std.testing.expectEqualStrings("user/proj", parsed.dir); 474 } 475 { 476 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 477 defer parsed.deinit(allocator); 478 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 479 try std.testing.expectEqualStrings("repo", parsed.dir); 480 } 481 } 482