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