╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh.zig ────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯
415 }, 416 .push => |pusher| try push.receivePackAndConsume(repo.self_repo_opts, io, allocator, repo, &reader.interface, &writer.interface, .{ 417 .protocol_version = protocol_version, 418 .protected_branches = pusher.protected_branches, 419 .locked_branches = pusher.locked_branches, 420 .pseudo_ref = .{ .name = push.clear_undo_ref, .deletable = pusher.owner }, 421 }, pusher.author, &pusher.user_id, handler.server, handler.err, sess), 422 }, 423 } 424 } 425 426 // push to a repo that doesn't exist yet, creating it in the hash format the 427 // client's first command names 428 fn runCreatingPush( 429 handler: *const SessionHandler, 430 sess: *ssh.SessionCtx, 431 creator: *const RepoCreator, 432 name: []const u8, 433 protocol_version: xit.net_server_common.ProtocolVersion, 434 reader: *std.Io.Reader, 435 writer: *std.Io.Writer, 436 ) !void { 437 const allocator = sess.conn.allocator; 438 const io = sess.conn.io; 439 440 evt.Repo.validateName(name) catch return writeError(sess, "invalid repo name"); 441 442 try xit.net_server_receive_pack.advertiseUncreated(.xit, writer, .{ .protocol_version = protocol_version }); 443 try writer.flush(); 444 // a client with nothing to push creates nothing 445 const hash_kind = (try xit.net_server_receive_pack.peekObjectFormat(reader)) orelse return; 446 447 const location = evt.createRepo(io, allocator, handler.server.users_dir, &creator.owner_id, creator.owner, name, "", .private, hash_kind) catch |err| switch (err) { 448 error.NameTaken => return writeError(sess, "repo was just created by another push, try again"), 449 else => |e| return e, 450 }; 451 const repo_path = try evt.repoPath(allocator, handler.server.users_dir, &location.owner_id, &location.repo_id); 452 defer allocator.free(repo_path); 453 454 switch (hash_kind) { 455 inline else => |kind| { 456 var repo = try rp.Repo(.xit, any_repo_opts.toRepoOptsWithHash(kind)).open(io, allocator, .{ .path = repo_path }); 457 defer repo.deinit(io, allocator); 458 // stateless since the advertisement already went out 459 try push.receivePackAndConsume(repo.self_repo_opts, io, allocator, &repo, reader, writer, .{ .protocol_version = protocol_version, .is_stateless = true, .pseudo_ref = .{ .name = push.clear_undo_ref, .deletable = true } }, creator.owner, &creator.owner_id, handler.server, handler.err, sess); 460 }, 461 } 462 } 463 464 // serve a patch draft: anyone may fetch it, only its author may push to it 465 fn runForkSession( 466 handler: *const SessionHandler, 467 sess: *ssh.SessionCtx, 468 fork_path: []const u8, 469 service: GitService, 470 protocol_version: xit.net_server_common.ProtocolVersion, 471 reader: *std.Io.Reader, 472 writer: *std.Io.Writer, 473 ) !void { 474 const allocator = sess.conn.allocator; 475 const io = sess.conn.io; 476 477 const route = fork.parseRoute(fork_path) orelse return writeError(sess, "invalid fork path"); 478 // the route names the forker and the target repo 479 const forker_repo = evt.parseOwnerRepoPath(route.identity) orelse return writeError(sess, "repo path must be <forker>:<repo>"); 480 481 var admin = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = handler.admin_repo_path }); 482 defer admin.deinit(io, allocator); 483 var admin_arena = std.heap.ArenaAllocator.init(allocator); 484 defer admin_arena.deinit(); 485 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 486 const fork_id = try evt.parseEventId(&route.id); 487 const forker_id = (try evt.User.readIdByName(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, forker_repo.owner)) orelse 488 return writeError(sess, "patch draft not found"); 489 const fork_record = (try evt.readForkById(io, allocator, &admin_arena, handler.server.users_dir, &forker_id, &fork_id)) orelse 490 return writeError(sess, "patch draft not found"); 491 if (fork_record.removed) return writeError(sess, "patch draft not found"); 492 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, &forker_id)) orelse 493 return writeError(sess, "invalid patch draft"); 494 if (user.removed) return writeError(sess, "invalid patch draft"); 495 if (service == .receive_pack and !try evt.User.holdsKey(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, &forker_id, &sess.fingerprint)) 496 return writeError(sess, "unauthorized: this SSH key is not registered to the patch author"); 497 498 const target_owner_id = try evt.parseEventId(&fork_record.event.repo_user_id); 499 const target_id = try evt.parseEventId(&fork_record.event.repo_id); 500 const target = (try evt.readRepoById(io, allocator, &admin_arena, handler.server.users_dir, &target_owner_id, &target_id, forker_id)) orelse 501 return writeError(sess, "repo not found"); 502 // patches that are off take their drafts with them 503 const patch_role = target.repo.event.patch_role orelse return writeError(sess, "patch draft not found"); 504 if (service == .receive_pack) { 505 const role = target.role orelse return writeError(sess, "repo not found"); 506 if (!role.atLeast(patch_role)) return writeError(sess, "unauthorized: your role in this repo may not write patches"); 507 } 508 509 const draft_path = try fork.forkPath(allocator, handler.server.users_dir, &forker_id, &fork_id); 510 defer allocator.free(draft_path); 511 var draft = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = draft_path }) catch 512 return writeError(sess, "patch draft not found"); 513 defer draft.deinit(io, allocator); 514 if (service == .upload_pack) { 515 var sideband = progress.Sideband{ .writer = writer, .sess = sess }; 516 switch (draft) { 517 inline else => |*repo| try repo.uploadPack(io, allocator, reader, writer, .{ .protocol_version = protocol_version }, &sideband), 518 } 519 } else { 520 if (!std.mem.eql(u8, target.repo.event.name, forker_repo.name)) return writeError(sess, "patch draft belongs to another repo"); 521 const target_path = try evt.repoPath(allocator, handler.server.users_dir, &target_owner_id, &target_id); 522 defer allocator.free(target_path); 523 const author: evt.CommitAuthor = .{ .name = user.event.name, .email = user.event.email }; 524 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 525 switch (draft) { 526 inline else => |*repo| { 527 var target_repo = rp.Repo(.xit, repo.self_repo_opts).open(io, allocator, .{ .path = target_path }) catch 528 return writeError(sess, "repo not found or has the wrong hash"); 529 defer target_repo.deinit(io, allocator); 530 try push.receiveFork(repo.self_repo_opts, io, allocator, repo, &target_repo, handler.server, &route.id, author, timestamp, reader, writer, handler.err, sess); 531 }, 532 } 533 } 534 } 535 536 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 537 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 538 defer tokens.deinit(); 539 540 const service_token = tokens.next() orelse return error.InvalidCommand; 541 const dir_token = tokens.next() orelse return error.InvalidCommand; 542 543 const service: GitService = 544 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 545 .upload_pack 546 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 547 .receive_pack 548 else 549 return error.UnsupportedService; 550 551 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 552 } 553 554 const RepoAuthorization = union(enum) { allowed: Allowed, create: RepoCreator, denied, not_found }; 555 556 // what a key may do in an existing repo 557 const Allowed = union(enum) { 558 fetch, 559 push: Pusher, 560 }; 561 562 // the key holder a push acts as 563 const Pusher = struct { 564 user_id: [evt.event_id_size]u8, 565 author: evt.CommitAuthor, 566 protected_branches: []const []const u8, 567 locked_branches: []const []const u8, 568 // only owners may clear the undo history 569 owner: bool, 570 }; 571 572 // the owner of a repo a push may create 573 const RepoCreator = struct { 574 owner_id: [evt.event_id_size]u8, 575 owner: evt.CommitAuthor, 576 }; 577 578 fn authorizeRepoKey( 579 io: std.Io, 580 arena: *std.heap.ArenaAllocator, 581 admin_repo_path: []const u8, 582 users_dir: []const u8, 583 owner_name: []const u8, 584 repo_name: []const u8, 585 service: GitService, 586 fingerprint: *const [ssh.fingerprint_len]u8, 587 ) !RepoAuthorization { 588 const allocator = arena.child_allocator; 589 var admin = rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 590 error.RepoNotFound => return .not_found, 591 else => |e| return e, 592 }; 593 defer admin.deinit(io, allocator); 594 595 const moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 596 // no viewer yet, so this carries the base role 597 const repo = (try evt.readRepoByOwnerAndName(io, allocator, arena, moment, users_dir, owner_name, repo_name, null)) orelse { 598 if (service == .upload_pack) return .not_found; 599 const owner_id = (try evt.User.readIdByName(evt.AdminDB, evt.admin_repo_opts.hash, moment, owner_name)) orelse return .not_found; 600 if (!try evt.User.holdsKey(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, &owner_id, fingerprint)) return .denied; 601 return .{ .create = .{ .owner_id = owner_id, .owner = try commitAuthor(moment, arena, &owner_id) } }; 602 }; 603 604 const min_role: evt.Repo.Role = switch (service) { 605 .upload_pack => .read, 606 .receive_pack => .write, 607 }; 608 // any key may fetch a public repo; a push always needs a key holder 609 if (service == .upload_pack and repo.role != null) return .{ .allowed = .fetch }; 610 611 // a key can be shared, so the push acts as the holder with the highest role 612 const owner_id = try evt.parseEventId(&repo.repo.event.user_id); 613 var best: ?struct { id: [evt.event_id_size]u8, role: evt.Repo.Role } = null; 614 for (try evt.User.readIdsByFingerprint(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, fingerprint)) |holder_id| { 615 const seen = (try evt.readRepoById(io, allocator, arena, users_dir, &owner_id, &repo.event_id, holder_id)) orelse return .not_found; 616 const role = seen.role orelse continue; 617 if (best) |held| if (held.role.atLeast(role)) continue; 618 best = .{ .id = holder_id, .role = role }; 619 } 620 const holder = best orelse return .denied; 621 if (!holder.role.atLeast(min_role)) return .denied; 622 return .{ 623 .allowed = switch (service) { 624 .upload_pack => .fetch, 625 .receive_pack => blk: { 626 const names = try repo.repo.event.protectedBranchNames(arena.allocator()); 627 // members change protected branches only by merging a patch 628 const owner = holder.role == .owner; 629 break :blk .{ .push = .{ 630 .user_id = holder.id, 631 .author = try commitAuthor(moment, arena, &holder.id), 632 .protected_branches = if (owner) names else &.{}, 633 .locked_branches = if (owner) &.{} else names, 634 .owner = owner, 635 } }; 636 }, 637 }, 638 }; 639 } 640 641 // an active user as a commit author 642 fn commitAuthor( 643 moment: evt.AdminDB.HashMap(.read_only), 644 arena: *std.heap.ArenaAllocator, 645 user_id: *const [evt.event_id_size]u8, 646 ) !evt.CommitAuthor { 647 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, user_id)) orelse unreachable; 648 return .{ .name = user.event.name, .email = user.event.email }; 649 } 650 651 // the authorized_keys line of a pubkey blob: its type, then the blob in base64 652 fn authorizedKeyLine(allocator: std.mem.Allocator, blob: []const u8) ![]const u8 { 653 var reader = std.Io.Reader.fixed(blob); 654 const key_type = try ssh.takeString(&reader, 64); 655 const encoder = std.base64.standard.Encoder; 656 const line = try allocator.alloc(u8, key_type.len + 1 + encoder.calcSize(blob.len)); 657 @memcpy(line[0..key_type.len], key_type); 658 line[key_type.len] = ' '; 659 _ = encoder.encode(line[key_type.len + 1 ..], blob); 660 return line; 661 } 662 663 fn writeError(sess: *ssh.SessionCtx, comptime msg: []const u8) !void { 664 const body = "ERR haxy ssh: " ++ msg; 665 var packet: [body.len + 4]u8 = undefined; 666 const line = try std.fmt.bufPrint(&packet, "{x:0>4}{s}", .{ packet.len, body }); 667 try sess.writeBytes(line); 668 try sess.exit(1); 669 } 670 671 test "parseGitCommand rejects malformed input" { 672 const allocator = std.testing.allocator; 673 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 674 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 675 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 676 } 677 678 test "parseGitCommand happy paths" { 679 const allocator = std.testing.allocator; 680 681 { 682 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 683 defer parsed.deinit(allocator); 684 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 685 try std.testing.expectEqualStrings("some-repo", parsed.dir); 686 } 687 { 688 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 689 defer parsed.deinit(allocator); 690 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 691 try std.testing.expectEqualStrings("user/proj", parsed.dir); 692 } 693 { 694 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 695 defer parsed.deinit(allocator); 696 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 697 try std.testing.expectEqualStrings("repo", parsed.dir); 698 } 699 } 700