╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh.zig ────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
186 .width_cells = if (pty.width_cells == 0) 80 else pty.width_cells, 187 .height_cells = if (pty.height_cells == 0) 24 else pty.height_cells, 188 }; 189 190 // session-lifetime allocations (login, prefs); Nav owns the per-page arenas. 191 var session_arena = std.heap.ArenaAllocator.init(allocator); 192 defer session_arena.deinit(); 193 194 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 195 var repo = try Repo.open(io, allocator, .{ .path = handler.admin_repo_path }); 196 defer repo.deinit(io, allocator); 197 var ui_session = try ui.Session.init(&session_arena, &repo, .{}); 198 ui_session.is_terminal = true; 199 ui_session.web_port = handler.wui_port; 200 ui_session.data.clone_http_port = handler.clone_http_port; 201 ui_session.data.clone_ssh_port = handler.clone_ssh_port; 202 // let page builders open on-disk repos (sibling "repos" dir of the admin repo) 203 ui_session.io = io; 204 ui_session.repos_dir = try std.fs.path.join(session_arena.allocator(), &.{ std.fs.path.dirname(handler.admin_repo_path) orelse ".", "repos" }); 205 206 var nav = try ui.Nav.init(allocator, &ui_session); 207 defer nav.deinit(allocator); 208 209 var session_writer_buf: [8192]u8 = undefined; 210 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 211 212 // the terminal's deinit writes leave-alt / show-cursor / disable-mouse and 213 // flushes, restoring the client's screen. as a function-scoped defer it runs 214 // before runTui returns — on the normal path and on any error — so the 215 // caller can write to the client afterward (and sess.exit can close cleanly). 216 var terminal_size = Size{ 217 .width = effective_pty.width_cells, 218 .height = effective_pty.height_cells, 219 }; 220 var terminal_maybe: ?StreamTerminal = try StreamTerminal.init(allocator, &session_writer.interface, terminal_size); 221 defer if (terminal_maybe) |*terminal| terminal.deinit(); 222 223 var last_size = Size{ .width = 0, .height = 0 }; 224 var last_grid = try Grid.init(allocator, last_size); 225 defer last_grid.deinit(); 226 227 // initial render — user sees the page immediately 228 try nav.root.build(allocator, .{ 229 .min_size = .{ .width = null, .height = null }, 230 .max_size = .{ .width = last_size.width, .height = last_size.height }, 231 }, nav.root.getFocus()); 232 if (terminal_maybe) |*terminal| _ = try terminal.render(&nav.root, &last_grid, &last_size); 233 234 // event loop. nextEvent blocks until something interesting arrives; 235 // for each event, rebuild the widget tree and re-render so the user 236 // sees the effect of their input on the same iteration. 237 event_loop: while (true) { 238 const event = try sess.nextEvent(); 239 if (terminal_maybe) |*terminal| { 240 switch (event) { 241 .data => |payload| { 242 defer allocator.free(payload); 243 try terminal.writeBytes(payload); 244 while (terminal.popKey()) |key| { 245 try ui.inputKey(allocator, &nav.root, key, &ui_session); 246 } 247 }, 248 .resize => |sz| { 249 terminal_size = .{ .width = sz.width_cells, .height = sz.height_cells }; 250 terminal.pushResize(terminal_size); 251 while (terminal.popKey()) |key| { 252 try ui.inputKey(allocator, &nav.root, key, &ui_session); 253 } 254 }, 255 .eof, .close => break :event_loop, 256 } 257 } else { 258 switch (event) { 259 .data => |payload| { 260 defer allocator.free(payload); 261 if (std.mem.indexOfAny(u8, payload, "\r\n") == null) continue; 262 terminal_maybe = try StreamTerminal.init(allocator, &session_writer.interface, terminal_size); 263 last_size = .{ .width = 0, .height = 0 }; 264 }, 265 .resize => |sz| { 266 terminal_size = .{ .width = sz.width_cells, .height = sz.height_cells }; 267 continue; 268 }, 269 .eof, .close => break :event_loop, 270 } 271 } 272 273 if (ui_session.host_request) |request| { 274 ui_session.host_request = null; 275 switch (request) { 276 .show_copyable_text => |copyable_text| { 277 if (terminal_maybe) |*terminal| terminal.deinit(); 278 terminal_maybe = null; 279 try session_writer.interface.print("\x1b[2J\x1b[Hcopy the following text and then press enter to go back:\r\n\r\n{s}\r\n", .{copyable_text}); 280 try session_writer.interface.flush(); 281 continue; 282 }, 283 } 284 } 285 286 try ui_session.applyAndWritePending(io, allocator, &repo); 287 288 // pick up data written by other handles so the next navigation 289 // builds its page from a current moment 290 try ui_session.reloadMoment(allocator, &repo); 291 292 // reconcile navigation: forward to a new page, or back on escape 293 try nav.sync(allocator, &ui_session); 294 295 // the quit button (on the quit tab) asks the host to tear down 296 if (ui_session.quit_requested) break :event_loop; 297 298 try nav.root.build(allocator, .{ 299 .min_size = .{ .width = null, .height = null }, 300 .max_size = .{ .width = last_size.width, .height = last_size.height }, 301 }, nav.root.getFocus()); 302 if (terminal_maybe) |*terminal| _ = try terminal.render(&nav.root, &last_grid, &last_size); 303 } 304 } 305 306 // --------------------------------------------------------------------------- 307 // git path (exec) 308 // --------------------------------------------------------------------------- 309 310 pub const GitService = enum { upload_pack, receive_pack }; 311 312 pub const ParsedGitCommand = struct { 313 service: GitService, 314 dir: []u8, 315 316 pub fn deinit(self: ParsedGitCommand, allocator: std.mem.Allocator) void { 317 allocator.free(self.dir); 318 } 319 }; 320 321 fn runGitSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, command: []const u8) !void { 322 const allocator = sess.conn.allocator; 323 const io = sess.conn.io; 324 325 const parsed = parseGitCommand(allocator, command) catch return writeError(sess, "unsupported command (expected git-upload-pack or git-receive-pack)"); 326 defer parsed.deinit(allocator); 327 const repo_prefix = "/repo/"; 328 const repo_identity = if (std.mem.startsWith(u8, parsed.dir, repo_prefix)) parsed.dir[repo_prefix.len..] else parsed.dir; 329 330 const create_if_missing = parsed.service == .receive_pack; 331 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{}; 332 333 // authenticate pushes: the authenticated key must be registered to the 334 // repo's owner. 335 if (create_if_missing) { 336 const owner_repo = evt.parseOwnerRepoPath(repo_identity) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 337 if (builtin.mode != .Debug and !try isKeyAuthorized(io, allocator, handler.admin_repo_path, owner_repo.owner, &sess.fingerprint)) 338 return writeError(sess, "unauthorized: this SSH key is not registered to the repo owner"); 339 } 340 341 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, handler.repo_root_path, handler.admin_repo_path, repo_identity, create_if_missing)) { 342 .ok => |p| p, 343 .invalid => return writeError(sess, "repo path must be <owner>/<repo>"), 344 .not_found => return writeError(sess, "repo not found"), 345 }; 346 defer allocator.free(repo_path); 347 348 if (try serveIfExists(repo_path, sess, io, allocator, parsed.service)) { 349 try sess.exit(0); 350 return; 351 } 352 353 if (!create_if_missing) return writeError(sess, "repo not found"); 354 355 // create the on-disk repo for the just-minted event and serve the push 356 var repo = try createRepo(any_repo_opts.toRepoOpts(), io, allocator, repo_path); 357 defer repo.deinit(io, allocator); 358 try servePack(repo.self_repo_opts, &repo, sess, io, allocator, parsed.service); 359 try sess.exit(0); 360 } 361 362 // serve an existing repo at `repo_path`, or return false if none is there 363 fn serveIfExists( 364 repo_path: []const u8, 365 sess: *ssh.SessionCtx, 366 io: std.Io, 367 allocator: std.mem.Allocator, 368 service: GitService, 369 ) !bool { 370 // a bare open() creates the directory while probing for the repo, so only 371 // attempt it when the path already exists 372 std.Io.Dir.accessAbsolute(io, repo_path, .{}) catch return false; 373 374 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{}; 375 var any_repo = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 376 error.RepoNotFound => return false, 377 else => |e| return e, 378 }; 379 defer any_repo.deinit(io, allocator); 380 381 switch (any_repo) { 382 inline else => |*repo| try servePack(repo.self_repo_opts, repo, sess, io, allocator, service), 383 } 384 return true; 385 } 386 387 fn createRepo( 388 comptime repo_opts: rp.RepoOpts(.xit), 389 io: std.Io, 390 allocator: std.mem.Allocator, 391 repo_path: []const u8, 392 ) !rp.Repo(.xit, repo_opts) { 393 var repo = try rp.Repo(.xit, repo_opts).init(io, allocator, .{ .path = repo_path }); 394 errdefer repo.deinit(io, allocator); 395 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 396 try repo.addConfig(io, allocator, .{ .name = "receive.denycurrentbranch", .value = "updateinstead" }); 397 return repo; 398 } 399 400 // wrap the channel I/O in std.Io.Reader/Writer adapters so the repo's pack 401 // functions can consume them like any other stream, then run the requested 402 // service 403 fn servePack( 404 comptime repo_opts: rp.RepoOpts(.xit), 405 repo: *rp.Repo(.xit, repo_opts), 406 sess: *ssh.SessionCtx, 407 io: std.Io, 408 allocator: std.mem.Allocator, 409 service: GitService, 410 ) !void { 411 var session_reader_buf: [4096]u8 = undefined; 412 var session_writer_buf: [4096]u8 = undefined; 413 var session_reader = ssh.SessionReader.init(sess, &session_reader_buf); 414 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 415 416 switch (service) { 417 .upload_pack => try repo.uploadPack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 418 .receive_pack => try evt.receivePackAndConsume(repo_opts, io, allocator, repo, &session_reader.interface, &session_writer.interface, .{}), 419 } 420 421 // flush whatever the pack op buffered into our writer adapter 422 session_writer.interface.flush() catch {}; 423 } 424 425 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 426 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 427 defer tokens.deinit(); 428 429 const service_token = tokens.next() orelse return error.InvalidCommand; 430 const dir_token = tokens.next() orelse return error.InvalidCommand; 431 432 const service: GitService = 433 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 434 .upload_pack 435 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 436 .receive_pack 437 else 438 return error.UnsupportedService; 439 440 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 441 } 442 443 // true if `fingerprint` matches one of the named user's registered SSH keys 444 fn isKeyAuthorized( 445 io: std.Io, 446 allocator: std.mem.Allocator, 447 admin_repo_path: []const u8, 448 owner_name: []const u8, 449 fingerprint: *const [ssh.fingerprint_len]u8, 450 ) !bool { 451 var arena = std.heap.ArenaAllocator.init(allocator); 452 defer arena.deinit(); 453 454 const user = (try evt.User.readByName(io, allocator, admin_repo_path, &arena, owner_name)) orelse return false; 455 456 var it = std.mem.splitScalar(u8, user.event.ssh_keys, '\n'); 457 while (it.next()) |line| { 458 const fp = fingerprintOfAuthorizedKey(line) orelse continue; 459 if (std.mem.eql(u8, &fp, fingerprint)) return true; 460 } 461 return false; 462 } 463 464 // the SHA256 fingerprint of one authorized_keys line, or null if the line is 465 // blank or not a parseable "<type> <base64> [comment]" entry 466 fn fingerprintOfAuthorizedKey(line: []const u8) ?[ssh.fingerprint_len]u8 { 467 var it = std.mem.tokenizeAny(u8, line, " \t\r"); 468 _ = it.next() orelse return null; // key type 469 const blob_b64 = it.next() orelse return null; 470 471 const decoder = std.base64.standard.Decoder; 472 const blob_len = decoder.calcSizeForSlice(blob_b64) catch return null; 473 var blob_buf: [4096]u8 = undefined; 474 if (blob_len > blob_buf.len) return null; 475 decoder.decode(blob_buf[0..blob_len], blob_b64) catch return null; 476 477 return ssh.formatFingerprint(blob_buf[0..blob_len]); 478 } 479 480 fn writeError(sess: *ssh.SessionCtx, comptime msg: []const u8) !void { 481 const body = "ERR haxy ssh: " ++ msg; 482 var packet: [body.len + 4]u8 = undefined; 483 const line = try std.fmt.bufPrint(&packet, "{x:0>4}{s}", .{ packet.len, body }); 484 try sess.writeBytes(line); 485 try sess.exit(1); 486 } 487 488 test "parseGitCommand rejects malformed input" { 489 const allocator = std.testing.allocator; 490 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 491 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 492 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 493 } 494 495 test "parseGitCommand happy paths" { 496 const allocator = std.testing.allocator; 497 498 { 499 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 500 defer parsed.deinit(allocator); 501 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 502 try std.testing.expectEqualStrings("some-repo", parsed.dir); 503 } 504 { 505 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 506 defer parsed.deinit(allocator); 507 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 508 try std.testing.expectEqualStrings("user/proj", parsed.dir); 509 } 510 { 511 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 512 defer parsed.deinit(allocator); 513 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 514 try std.testing.expectEqualStrings("repo", parsed.dir); 515 } 516 } 517