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