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