╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh.zig ────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
434 const forker_id = (try evt.User.readIdByName(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, forker_repo.owner)) orelse 435 return writeError(sess, "patch draft not found"); 436 const fork_record = (try evt.readForkById(io, allocator, &admin_arena, handler.users_dir, &forker_id, &fork_id)) orelse 437 return writeError(sess, "patch draft not found"); 438 if (fork_record.removed) return writeError(sess, "patch draft not found"); 439 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, &forker_id)) orelse 440 return writeError(sess, "invalid patch draft"); 441 if (user.removed) return writeError(sess, "invalid patch draft"); 442 if (service == .receive_pack and !isKeyInAuthorizedKeys(user.event.ssh_keys, &sess.fingerprint)) 443 return writeError(sess, "unauthorized: this SSH key is not registered to the patch author"); 444 445 const draft_path = try fork.forkPath(allocator, handler.users_dir, &forker_id, &fork_id); 446 defer allocator.free(draft_path); 447 var draft = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = draft_path }) catch 448 return writeError(sess, "patch draft not found"); 449 defer draft.deinit(io, allocator); 450 if (service == .upload_pack) { 451 var sideband = progress.Sideband{ .writer = writer, .sess = sess }; 452 switch (draft) { 453 inline else => |*repo| try repo.uploadPack(io, allocator, reader, writer, .{ .protocol_version = protocol_version }, &sideband), 454 } 455 } else { 456 const target = (try evt.readRepoById(io, allocator, &admin_arena, handler.users_dir, fork_record.event.repo_user_id[0..evt.event_id_size], fork_record.event.repo_id[0..evt.event_id_size], null)) orelse 457 return writeError(sess, "repo not found"); 458 if (!std.mem.eql(u8, target.repo.event.name, forker_repo.name)) return writeError(sess, "patch draft belongs to another repo"); 459 const target_path = try evt.repoPath(allocator, handler.users_dir, fork_record.event.repo_user_id, fork_record.event.repo_id); 460 defer allocator.free(target_path); 461 const author: evt.CommitAuthor = .{ .name = user.event.name, .email = user.event.email }; 462 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 463 switch (draft) { 464 inline else => |*repo| { 465 var target_repo = rp.Repo(.xit, repo.self_repo_opts).open(io, allocator, .{ .path = target_path }) catch 466 return writeError(sess, "repo not found or has the wrong hash"); 467 defer target_repo.deinit(io, allocator); 468 try push.receiveFork(repo.self_repo_opts, io, allocator, repo, &target_repo, handler.users_dir, &route.id, author, timestamp, reader, writer, handler.err, sess); 469 }, 470 } 471 } 472 } 473 474 // serve an existing repo at `repo_path`, or return false if none is there 475 fn serveIfExists( 476 repo_path: []const u8, 477 users_dir: []const u8, 478 reader: *std.Io.Reader, 479 writer: *std.Io.Writer, 480 io: std.Io, 481 allocator: std.mem.Allocator, 482 service: GitService, 483 protocol_version: xit.net_server_common.ProtocolVersion, 484 author: ?evt.CommitAuthor, 485 error_writer: *std.Io.Writer, 486 sess: ?*ssh.SessionCtx, 487 ) !bool { 488 // a bare open() creates the directory while probing for the repo, so only 489 // attempt it when the path already exists 490 std.Io.Dir.accessAbsolute(io, repo_path, .{}) catch return false; 491 492 var any_repo = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 493 error.RepoNotFound => return false, 494 else => |e| return e, 495 }; 496 defer any_repo.deinit(io, allocator); 497 498 switch (any_repo) { 499 inline else => |*repo| try servePack(repo.self_repo_opts, repo, users_dir, reader, writer, io, allocator, service, protocol_version, author, error_writer, sess), 500 } 501 return true; 502 } 503 504 fn servePack( 505 comptime repo_opts: rp.RepoOpts(.xit), 506 repo: *rp.Repo(.xit, repo_opts), 507 users_dir: []const u8, 508 reader: *std.Io.Reader, 509 writer: *std.Io.Writer, 510 io: std.Io, 511 allocator: std.mem.Allocator, 512 service: GitService, 513 protocol_version: xit.net_server_common.ProtocolVersion, 514 author: ?evt.CommitAuthor, 515 error_writer: *std.Io.Writer, 516 sess: ?*ssh.SessionCtx, 517 ) !void { 518 switch (service) { 519 .upload_pack => { 520 var sideband = progress.Sideband{ .writer = writer, .sess = sess }; 521 try repo.uploadPack(io, allocator, reader, writer, .{ .protocol_version = protocol_version }, &sideband); 522 }, 523 .receive_pack => try push.receivePackAndConsume(repo_opts, io, allocator, repo, reader, writer, .{ .protocol_version = protocol_version }, author, users_dir, error_writer, sess), 524 } 525 } 526 527 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 528 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 529 defer tokens.deinit(); 530 531 const service_token = tokens.next() orelse return error.InvalidCommand; 532 const dir_token = tokens.next() orelse return error.InvalidCommand; 533 534 const service: GitService = 535 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 536 .upload_pack 537 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 538 .receive_pack 539 else 540 return error.UnsupportedService; 541 542 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 543 } 544 545 const RepoAuthorization = union(enum) { allowed: ?evt.CommitAuthor, denied, not_found }; 546 547 fn authorizeRepoKey( 548 io: std.Io, 549 arena: *std.heap.ArenaAllocator, 550 admin_repo_path: []const u8, 551 users_dir: []const u8, 552 owner_name: []const u8, 553 repo_name: []const u8, 554 service: GitService, 555 fingerprint: *const [ssh.fingerprint_len]u8, 556 ) !RepoAuthorization { 557 const allocator = arena.child_allocator; 558 var admin = rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 559 error.RepoNotFound => return .not_found, 560 else => |e| return e, 561 }; 562 defer admin.deinit(io, allocator); 563 564 const moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 565 // no viewer yet, so this carries the base role 566 const repo = (try evt.readRepoByOwnerAndName(io, allocator, arena, moment, users_dir, owner_name, repo_name, null)) orelse { 567 if (service == .upload_pack) return .not_found; 568 const owner = (try evt.User.readByName(io, allocator, admin_repo_path, arena, owner_name)) orelse return .not_found; 569 return if (isKeyInAuthorizedKeys(owner.event.ssh_keys, fingerprint)) 570 .{ .allowed = .{ .name = owner.event.name, .email = owner.event.email } } 571 else 572 .denied; 573 }; 574 575 const min_role: evt.Repo.Role = switch (service) { 576 .upload_pack => .read, 577 .receive_pack => .write, 578 }; 579 // skip the key lookups when the base role is enough 580 if (repo.role.atLeast(min_role)) return .{ .allowed = null }; 581 582 // the creator owns the repo 583 const owner_id = repo.repo.event.user_id[0..evt.event_id_size]; 584 if (try authorWithKey(moment, arena, owner_id, fingerprint)) |author| return .{ .allowed = author }; 585 586 // anyone else holding the key needs a grant with the role. a key can be 587 // shared, so a grant that falls short doesn't end the search. 588 for (try evt.readRepoGrants(io, allocator, arena, users_dir, owner_id, &repo.event_id)) |grant| { 589 if (!grant.role.atLeast(min_role)) continue; 590 if (try authorWithKey(moment, arena, grant.user_id, fingerprint)) |author| return .{ .allowed = author }; 591 } 592 return .denied; 593 } 594 595 // the user as a commit author, or null unless they hold the key 596 fn authorWithKey( 597 moment: evt.AdminDB.HashMap(.read_only), 598 arena: *std.heap.ArenaAllocator, 599 user_id: []const u8, 600 fingerprint: *const [ssh.fingerprint_len]u8, 601 ) !?evt.CommitAuthor { 602 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, user_id)) orelse return null; 603 if (user.removed or !isKeyInAuthorizedKeys(user.event.ssh_keys, fingerprint)) return null; 604 return .{ .name = user.event.name, .email = user.event.email }; 605 } 606 607 fn isKeyInAuthorizedKeys(ssh_keys: []const u8, fingerprint: *const [ssh.fingerprint_len]u8) bool { 608 var it = std.mem.splitScalar(u8, ssh_keys, '\n'); 609 while (it.next()) |line| { 610 const fp = fingerprintOfAuthorizedKey(line) orelse continue; 611 if (std.mem.eql(u8, &fp, fingerprint)) return true; 612 } 613 return false; 614 } 615 616 // the SHA256 fingerprint of one authorized_keys line, or null if the line is 617 // blank or not a parseable "<type> <base64> [comment]" entry 618 fn fingerprintOfAuthorizedKey(line: []const u8) ?[ssh.fingerprint_len]u8 { 619 var it = std.mem.tokenizeAny(u8, line, " \t\r"); 620 _ = it.next() orelse return null; // key type 621 const blob_b64 = it.next() orelse return null; 622 623 const decoder = std.base64.standard.Decoder; 624 const blob_len = decoder.calcSizeForSlice(blob_b64) catch return null; 625 var blob_buf: [4096]u8 = undefined; 626 if (blob_len > blob_buf.len) return null; 627 decoder.decode(blob_buf[0..blob_len], blob_b64) catch return null; 628 629 return ssh.formatFingerprint(blob_buf[0..blob_len]); 630 } 631 632 fn writeError(sess: *ssh.SessionCtx, comptime msg: []const u8) !void { 633 const body = "ERR haxy ssh: " ++ msg; 634 var packet: [body.len + 4]u8 = undefined; 635 const line = try std.fmt.bufPrint(&packet, "{x:0>4}{s}", .{ packet.len, body }); 636 try sess.writeBytes(line); 637 try sess.exit(1); 638 } 639 640 test "parseGitCommand rejects malformed input" { 641 const allocator = std.testing.allocator; 642 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 643 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 644 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 645 } 646 647 test "parseGitCommand happy paths" { 648 const allocator = std.testing.allocator; 649 650 { 651 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 652 defer parsed.deinit(allocator); 653 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 654 try std.testing.expectEqualStrings("some-repo", parsed.dir); 655 } 656 { 657 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 658 defer parsed.deinit(allocator); 659 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 660 try std.testing.expectEqualStrings("user/proj", parsed.dir); 661 } 662 { 663 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 664 defer parsed.deinit(allocator); 665 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 666 try std.testing.expectEqualStrings("repo", parsed.dir); 667 } 668 } 669