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