╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh.zig ────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
326 327 // only a lone ESC needs a deadline; longer CSI/SS3 fragments must remain 328 // buffered until complete. a timeout leaves partial SSH packets in the reader. 329 pub fn nextTuiEvent(sess: *ssh.SessionCtx, terminal: ?*StreamTerminal) !?ssh.Event { 330 if (terminal) |t| { 331 if (t.parser.esc_len == 1) { 332 sess.conn.read_timeout = escape_timeout.toDeadline(sess.conn.io); 333 defer sess.conn.read_timeout = .none; 334 return sess.nextEvent() catch |err| switch (err) { 335 error.Timeout => { 336 try t.flushEscape(); 337 return null; 338 }, 339 else => return err, 340 }; 341 } 342 } 343 return try sess.nextEvent(); 344 } 345 346 // --------------------------------------------------------------------------- 347 // git path (exec) 348 // --------------------------------------------------------------------------- 349 350 pub const GitService = enum { upload_pack, receive_pack }; 351 352 pub const ParsedGitCommand = struct { 353 service: GitService, 354 dir: []u8, 355 356 pub fn deinit(self: ParsedGitCommand, allocator: std.mem.Allocator) void { 357 allocator.free(self.dir); 358 } 359 }; 360 361 fn runGitSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, exec: ssh.Request.Exec) !void { 362 const allocator = sess.conn.allocator; 363 const io = sess.conn.io; 364 const protocol_version = xit.net_server_common.parseProtocolVersion(exec.git_protocol); 365 366 const parsed = parseGitCommand(allocator, exec.command) catch return writeError(sess, "unsupported command (expected git-upload-pack or git-receive-pack)"); 367 defer parsed.deinit(allocator); 368 const path = std.mem.trimStart(u8, parsed.dir, "/"); 369 const fork_prefix = "fork/"; 370 371 if (std.mem.startsWith(u8, path, fork_prefix)) { 372 const route = fork.parseRoute(path[fork_prefix.len..]) orelse return writeError(sess, "invalid fork path"); 373 const owner_repo = evt.parseOwnerRepoPath(route.identity) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 374 375 var admin = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = handler.admin_repo_path }); 376 defer admin.deinit(io, allocator); 377 var admin_arena = std.heap.ArenaAllocator.init(allocator); 378 defer admin_arena.deinit(); 379 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 380 const fork_id = try evt.parseEventId(&route.id); 381 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, &fork_id)) orelse 382 return writeError(sess, "patch draft not found"); 383 if (fork_record.removed) return writeError(sess, "patch draft not found"); 384 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, fork_record.event.user_id)) orelse 385 return writeError(sess, "invalid patch draft"); 386 if (user.removed) return writeError(sess, "invalid patch draft"); 387 if (parsed.service == .receive_pack and !isKeyInAuthorizedKeys(user.event.ssh_keys, &sess.fingerprint)) 388 return writeError(sess, "unauthorized: this SSH key is not registered to the patch author"); 389 390 const draft_path = try fork.forkPath(allocator, handler.repo_root_path, &route.id); 391 defer allocator.free(draft_path); 392 var draft = rp.AnyRepo(.xit, .{ .ProgressCtx = *push.PushProgress }).open(io, allocator, .{ .path = draft_path }) catch 393 return writeError(sess, "patch draft not found"); 394 defer draft.deinit(io, allocator); 395 var reader_buf: [4096]u8 = undefined; 396 var writer_buf: [4096]u8 = undefined; 397 var reader = ssh.SessionReader.init(sess, &reader_buf); 398 var writer = ssh.SessionWriter.init(sess, &writer_buf); 399 if (parsed.service == .upload_pack) { 400 switch (draft) { 401 inline else => |*repo| try repo.uploadPack(io, allocator, &reader.interface, &writer.interface, .{ .protocol_version = protocol_version }), 402 } 403 } else { 404 const target = (try evt.Repo.readByOwnerAndName(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, owner_repo.owner, owner_repo.name)) orelse 405 return writeError(sess, "repo not found"); 406 if (!std.mem.eql(u8, fork_record.event.repo_id, &target.event_id)) return writeError(sess, "patch draft belongs to another repo"); 407 const target_id = std.fmt.bytesToHex(target.event_id, .lower); 408 const target_path = try std.fs.path.join(allocator, &.{ handler.repo_root_path, &target_id }); 409 defer allocator.free(target_path); 410 const author: evt.CommitAuthor = .{ .name = user.event.name, .email = user.event.email }; 411 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 412 switch (draft) { 413 inline else => |*repo| { 414 var target_repo = rp.Repo(.xit, repo.self_repo_opts).open(io, allocator, .{ .path = target_path }) catch 415 return writeError(sess, "repo not found or has the wrong hash"); 416 defer target_repo.deinit(io, allocator); 417 try push.receiveFork(repo.self_repo_opts, io, allocator, repo, &target_repo, &route.id, author, timestamp, &reader.interface, &writer.interface, handler.err); 418 }, 419 } 420 } 421 writer.interface.flush() catch {}; 422 try sess.exit(0); 423 return; 424 } 425 426 const repo_prefix = "repo/"; 427 const repo_identity = if (std.mem.startsWith(u8, path, repo_prefix)) path[repo_prefix.len..] else path; 428 429 const create_if_missing = parsed.service == .receive_pack; 430 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{ .ProgressCtx = *push.PushProgress }; 431 432 const owner_repo = evt.parseOwnerRepoPath(repo_identity) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 433 switch (try authorizeRepoKey(io, allocator, handler.admin_repo_path, owner_repo.owner, owner_repo.name, parsed.service, &sess.fingerprint)) { 434 .allowed => {}, 435 .denied => return switch (parsed.service) { 436 .upload_pack => writeError(sess, "unauthorized: this SSH key cannot read this repo"), 437 .receive_pack => writeError(sess, "unauthorized: this SSH key cannot push to this repo"), 438 }, 439 .not_found => return writeError(sess, "repo not found"), 440 } 441 442 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, handler.repo_root_path, handler.admin_repo_path, repo_identity, create_if_missing)) { 443 .ok => |p| p, 444 .invalid => return writeError(sess, "repo path must be <owner>/<repo>"), 445 .not_found => return writeError(sess, "repo not found"), 446 }; 447 defer allocator.free(repo_path); 448 449 if (try serveIfExists(repo_path, handler.repo_root_path, sess, io, allocator, parsed.service, protocol_version, handler.err)) { 450 try sess.exit(0); 451 return; 452 } 453 454 if (!create_if_missing) return writeError(sess, "repo not found"); 455 456 // create the on-disk repo for the just-minted event and serve the push 457 var repo = try createRepo(any_repo_opts.toRepoOpts(), io, allocator, repo_path); 458 defer repo.deinit(io, allocator); 459 try servePack(repo.self_repo_opts, &repo, handler.repo_root_path, sess, io, allocator, parsed.service, protocol_version, handler.err); 460 try sess.exit(0); 461 } 462 463 // serve an existing repo at `repo_path`, or return false if none is there 464 fn serveIfExists( 465 repo_path: []const u8, 466 repo_root_path: []const u8, 467 sess: *ssh.SessionCtx, 468 io: std.Io, 469 allocator: std.mem.Allocator, 470 service: GitService, 471 protocol_version: xit.net_server_common.ProtocolVersion, 472 error_writer: *std.Io.Writer, 473 ) !bool { 474 // a bare open() creates the directory while probing for the repo, so only 475 // attempt it when the path already exists 476 std.Io.Dir.accessAbsolute(io, repo_path, .{}) catch return false; 477 478 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{ .ProgressCtx = *push.PushProgress }; 479 var any_repo = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 480 error.RepoNotFound => return false, 481 else => |e| return e, 482 }; 483 defer any_repo.deinit(io, allocator); 484 485 switch (any_repo) { 486 inline else => |*repo| try servePack(repo.self_repo_opts, repo, repo_root_path, sess, io, allocator, service, protocol_version, error_writer), 487 } 488 return true; 489 } 490 491 fn createRepo( 492 comptime repo_opts: rp.RepoOpts(.xit), 493 io: std.Io, 494 allocator: std.mem.Allocator, 495 repo_path: []const u8, 496 ) !rp.Repo(.xit, repo_opts) { 497 var repo = try rp.Repo(.xit, repo_opts).init(io, allocator, .{ .path = repo_path, .bare = true }); 498 errdefer repo.deinit(io, allocator); 499 try repo.setMergeAlgorithm(io, allocator, .patch); 500 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 501 return repo; 502 } 503 504 // wrap the channel I/O in std.Io.Reader/Writer adapters so the repo's pack 505 // functions can consume them like any other stream, then run the requested 506 // service 507 fn servePack( 508 comptime repo_opts: rp.RepoOpts(.xit), 509 repo: *rp.Repo(.xit, repo_opts), 510 repo_root_path: []const u8, 511 sess: *ssh.SessionCtx, 512 io: std.Io, 513 allocator: std.mem.Allocator, 514 service: GitService, 515 protocol_version: xit.net_server_common.ProtocolVersion, 516 error_writer: *std.Io.Writer, 517 ) !void { 518 var session_reader_buf: [4096]u8 = undefined; 519 var session_writer_buf: [4096]u8 = undefined; 520 var session_reader = ssh.SessionReader.init(sess, &session_reader_buf); 521 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 522 523 switch (service) { 524 .upload_pack => try repo.uploadPack(io, allocator, &session_reader.interface, &session_writer.interface, .{ .protocol_version = protocol_version }), 525 .receive_pack => try push.receivePackAndConsume(repo_opts, io, allocator, repo, &session_reader.interface, &session_writer.interface, .{ .protocol_version = protocol_version }, repo_root_path, error_writer), 526 } 527 528 // flush whatever the pack op buffered into our writer adapter 529 session_writer.interface.flush() catch {}; 530 } 531 532 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 533 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 534 defer tokens.deinit(); 535 536 const service_token = tokens.next() orelse return error.InvalidCommand; 537 const dir_token = tokens.next() orelse return error.InvalidCommand; 538 539 const service: GitService = 540 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 541 .upload_pack 542 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 543 .receive_pack 544 else 545 return error.UnsupportedService; 546 547 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 548 } 549 550 const RepoAuthorization = enum { allowed, denied, not_found }; 551 552 fn authorizeRepoKey( 553 io: std.Io, 554 allocator: std.mem.Allocator, 555 admin_repo_path: []const u8, 556 owner_name: []const u8, 557 repo_name: []const u8, 558 service: GitService, 559 fingerprint: *const [ssh.fingerprint_len]u8, 560 ) !RepoAuthorization { 561 var arena = std.heap.ArenaAllocator.init(allocator); 562 defer arena.deinit(); 563 564 var admin = rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 565 error.RepoNotFound => return .not_found, 566 else => |e| return e, 567 }; 568 defer admin.deinit(io, allocator); 569 570 const moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 571 const repo = (try evt.Repo.readByOwnerAndName(evt.AdminDB, evt.admin_repo_opts.hash, moment, &arena, owner_name, repo_name)) orelse { 572 if (service == .upload_pack) return .not_found; 573 const owner = (try evt.User.readByName(io, allocator, admin_repo_path, &arena, owner_name)) orelse return .not_found; 574 return if (isKeyInAuthorizedKeys(owner.event.ssh_keys, fingerprint)) .allowed else .denied; 575 }; 576 577 if ((service == .upload_pack and repo.repo.event.read_access == .public) or 578 (service == .receive_pack and repo.repo.event.write_access == .public)) return .allowed; 579 if (try keyBelongsToUser(moment, &arena, repo.repo.event.user_id, fingerprint)) return .allowed; 580 581 const user_id_lists: []const []const u8 = switch (service) { 582 .upload_pack => &.{ repo.repo.event.write_user_ids, repo.repo.event.read_user_ids }, 583 .receive_pack => &.{repo.repo.event.write_user_ids}, 584 }; 585 for (user_id_lists) |user_ids| { 586 var lines = std.mem.tokenizeScalar(u8, user_ids, '\n'); 587 while (lines.next()) |id| { 588 const user_id = try evt.parseEventId(id); 589 if (try keyBelongsToUser(moment, &arena, &user_id, fingerprint)) return .allowed; 590 } 591 } 592 return .denied; 593 } 594 595 fn keyBelongsToUser( 596 moment: evt.AdminDB.HashMap(.read_only), 597 arena: *std.heap.ArenaAllocator, 598 user_id: []const u8, 599 fingerprint: *const [ssh.fingerprint_len]u8, 600 ) !bool { 601 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, user_id)) orelse return false; 602 return !user.removed and isKeyInAuthorizedKeys(user.event.ssh_keys, fingerprint); 603 } 604 605 fn isKeyInAuthorizedKeys(ssh_keys: []const u8, fingerprint: *const [ssh.fingerprint_len]u8) bool { 606 var it = std.mem.splitScalar(u8, ssh_keys, '\n'); 607 while (it.next()) |line| { 608 const fp = fingerprintOfAuthorizedKey(line) orelse continue; 609 if (std.mem.eql(u8, &fp, fingerprint)) return true; 610 } 611 return false; 612 } 613 614 // the SHA256 fingerprint of one authorized_keys line, or null if the line is 615 // blank or not a parseable "<type> <base64> [comment]" entry 616 fn fingerprintOfAuthorizedKey(line: []const u8) ?[ssh.fingerprint_len]u8 { 617 var it = std.mem.tokenizeAny(u8, line, " \t\r"); 618 _ = it.next() orelse return null; // key type 619 const blob_b64 = it.next() orelse return null; 620 621 const decoder = std.base64.standard.Decoder; 622 const blob_len = decoder.calcSizeForSlice(blob_b64) catch return null; 623 var blob_buf: [4096]u8 = undefined; 624 if (blob_len > blob_buf.len) return null; 625 decoder.decode(blob_buf[0..blob_len], blob_b64) catch return null; 626 627 return ssh.formatFingerprint(blob_buf[0..blob_len]); 628 } 629 630 fn writeError(sess: *ssh.SessionCtx, comptime msg: []const u8) !void { 631 const body = "ERR haxy ssh: " ++ msg; 632 var packet: [body.len + 4]u8 = undefined; 633 const line = try std.fmt.bufPrint(&packet, "{x:0>4}{s}", .{ packet.len, body }); 634 try sess.writeBytes(line); 635 try sess.exit(1); 636 } 637 638 test "parseGitCommand rejects malformed input" { 639 const allocator = std.testing.allocator; 640 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 641 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 642 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 643 } 644 645 test "parseGitCommand happy paths" { 646 const allocator = std.testing.allocator; 647 648 { 649 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 650 defer parsed.deinit(allocator); 651 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 652 try std.testing.expectEqualStrings("some-repo", parsed.dir); 653 } 654 { 655 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 656 defer parsed.deinit(allocator); 657 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 658 try std.testing.expectEqualStrings("user/proj", parsed.dir); 659 } 660 { 661 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 662 defer parsed.deinit(allocator); 663 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 664 try std.testing.expectEqualStrings("repo", parsed.dir); 665 } 666 } 667