╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh.zig ────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯
408 409 switch (any_repo) { 410 inline else => |*repo| switch (parsed.service) { 411 .upload_pack => { 412 var sideband = progress.Sideband{ .writer = &writer.interface, .sess = sess }; 413 try repo.uploadPack(io, allocator, &reader.interface, &writer.interface, .{ .protocol_version = protocol_version }, &sideband); 414 }, 415 .receive_pack => try push.receivePackAndConsume(repo.self_repo_opts, io, allocator, repo, &reader.interface, &writer.interface, .{ .protocol_version = protocol_version }, author, handler.server, handler.err, sess), 416 }, 417 } 418 } 419 420 // push to a repo that doesn't exist yet, creating it in the hash format the 421 // client's first command names 422 fn runCreatingPush( 423 handler: *const SessionHandler, 424 sess: *ssh.SessionCtx, 425 creator: *const RepoCreator, 426 name: []const u8, 427 protocol_version: xit.net_server_common.ProtocolVersion, 428 reader: *std.Io.Reader, 429 writer: *std.Io.Writer, 430 ) !void { 431 const allocator = sess.conn.allocator; 432 const io = sess.conn.io; 433 434 evt.Repo.validateName(name) catch return writeError(sess, "invalid repo name"); 435 436 try xit.net_server_receive_pack.advertiseUncreated(.xit, writer, .{ .protocol_version = protocol_version }); 437 try writer.flush(); 438 // a client with nothing to push creates nothing 439 const hash_kind = (try xit.net_server_receive_pack.peekObjectFormat(reader)) orelse return; 440 441 const location = evt.createRepo(io, allocator, handler.server.users_dir, &creator.owner_id, creator.owner, name, "", .private, hash_kind) catch |err| switch (err) { 442 error.NameTaken => return writeError(sess, "repo was just created by another push, try again"), 443 else => |e| return e, 444 }; 445 const repo_path = try evt.repoPath(allocator, handler.server.users_dir, &location.owner_id, &location.repo_id); 446 defer allocator.free(repo_path); 447 448 switch (hash_kind) { 449 inline else => |kind| { 450 var repo = try rp.Repo(.xit, any_repo_opts.toRepoOptsWithHash(kind)).open(io, allocator, .{ .path = repo_path }); 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_owner_id = try evt.parseEventId(&fork_record.event.repo_user_id); 493 const target_id = try evt.parseEventId(&fork_record.event.repo_id); 494 const target = (try evt.readRepoById(io, allocator, &admin_arena, handler.server.users_dir, &target_owner_id, &target_id, forker_id)) orelse 495 return writeError(sess, "repo not found"); 496 // patches that are off take their drafts with them 497 const patch_role = target.repo.event.patch_role orelse return writeError(sess, "patch draft not found"); 498 if (service == .receive_pack) { 499 const role = target.role orelse return writeError(sess, "repo not found"); 500 if (!role.atLeast(patch_role)) return writeError(sess, "unauthorized: your role in this repo may not write patches"); 501 } 502 503 const draft_path = try fork.forkPath(allocator, handler.server.users_dir, &forker_id, &fork_id); 504 defer allocator.free(draft_path); 505 var draft = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = draft_path }) catch 506 return writeError(sess, "patch draft not found"); 507 defer draft.deinit(io, allocator); 508 if (service == .upload_pack) { 509 var sideband = progress.Sideband{ .writer = writer, .sess = sess }; 510 switch (draft) { 511 inline else => |*repo| try repo.uploadPack(io, allocator, reader, writer, .{ .protocol_version = protocol_version }, &sideband), 512 } 513 } else { 514 if (!std.mem.eql(u8, target.repo.event.name, forker_repo.name)) return writeError(sess, "patch draft belongs to another repo"); 515 const target_path = try evt.repoPath(allocator, handler.server.users_dir, &target_owner_id, &target_id); 516 defer allocator.free(target_path); 517 const author: evt.CommitAuthor = .{ .name = user.event.name, .email = user.event.email }; 518 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 519 switch (draft) { 520 inline else => |*repo| { 521 var target_repo = rp.Repo(.xit, repo.self_repo_opts).open(io, allocator, .{ .path = target_path }) catch 522 return writeError(sess, "repo not found or has the wrong hash"); 523 defer target_repo.deinit(io, allocator); 524 try push.receiveFork(repo.self_repo_opts, io, allocator, repo, &target_repo, handler.server, &route.id, author, timestamp, reader, writer, handler.err, sess); 525 }, 526 } 527 } 528 } 529 530 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 531 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 532 defer tokens.deinit(); 533 534 const service_token = tokens.next() orelse return error.InvalidCommand; 535 const dir_token = tokens.next() orelse return error.InvalidCommand; 536 537 const service: GitService = 538 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 539 .upload_pack 540 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 541 .receive_pack 542 else 543 return error.UnsupportedService; 544 545 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 546 } 547 548 const RepoAuthorization = union(enum) { allowed: ?evt.CommitAuthor, create: RepoCreator, denied, not_found }; 549 550 // the owner of a repo a push may create 551 const RepoCreator = struct { 552 owner_id: [evt.event_id_size]u8, 553 owner: evt.CommitAuthor, 554 }; 555 556 fn authorizeRepoKey( 557 io: std.Io, 558 arena: *std.heap.ArenaAllocator, 559 admin_repo_path: []const u8, 560 users_dir: []const u8, 561 owner_name: []const u8, 562 repo_name: []const u8, 563 service: GitService, 564 fingerprint: *const [ssh.fingerprint_len]u8, 565 ) !RepoAuthorization { 566 const allocator = arena.child_allocator; 567 var admin = rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 568 error.RepoNotFound => return .not_found, 569 else => |e| return e, 570 }; 571 defer admin.deinit(io, allocator); 572 573 const moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 574 // no viewer yet, so this carries the base role 575 const repo = (try evt.readRepoByOwnerAndName(io, allocator, arena, moment, users_dir, owner_name, repo_name, null)) orelse { 576 if (service == .upload_pack) return .not_found; 577 const owner_id = (try evt.User.readIdByName(evt.AdminDB, evt.admin_repo_opts.hash, moment, owner_name)) orelse return .not_found; 578 const owner = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, &owner_id)) orelse unreachable; 579 return if (isKeyInAuthorizedKeys(owner.event.ssh_keys, fingerprint)) 580 .{ .create = .{ .owner_id = owner_id, .owner = .{ .name = owner.event.name, .email = owner.event.email } } } 581 else 582 .denied; 583 }; 584 585 const min_role: evt.Repo.Role = switch (service) { 586 .upload_pack => .read, 587 .receive_pack => .write, 588 }; 589 // skip the key lookups when the base role is enough 590 if (repo.role) |base| { 591 if (base.atLeast(min_role)) return .{ .allowed = null }; 592 } 593 594 // the creator owns the repo 595 const owner_id = try evt.parseEventId(&repo.repo.event.user_id); 596 if (try authorWithKey(moment, arena, &owner_id, fingerprint)) |author| return .{ .allowed = author }; 597 598 // anyone else holding the key needs a grant with the role. a key can be 599 // shared, so a grant that falls short doesn't end the search. 600 for (try evt.readRepoGrants(io, allocator, arena, users_dir, &owner_id, &repo.event_id)) |grant| { 601 if (!grant.role.atLeast(min_role)) continue; 602 if (try authorWithKey(moment, arena, &try evt.parseEventId(&grant.user_id), fingerprint)) |author| return .{ .allowed = author }; 603 } 604 return .denied; 605 } 606 607 // the user as a commit author, or null unless they hold the key 608 fn authorWithKey( 609 moment: evt.AdminDB.HashMap(.read_only), 610 arena: *std.heap.ArenaAllocator, 611 user_id: []const u8, 612 fingerprint: *const [ssh.fingerprint_len]u8, 613 ) !?evt.CommitAuthor { 614 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, user_id)) orelse return null; 615 if (user.removed or !isKeyInAuthorizedKeys(user.event.ssh_keys, fingerprint)) return null; 616 return .{ .name = user.event.name, .email = user.event.email }; 617 } 618 619 fn isKeyInAuthorizedKeys(ssh_keys: []const u8, fingerprint: *const [ssh.fingerprint_len]u8) bool { 620 var it = std.mem.splitScalar(u8, ssh_keys, '\n'); 621 while (it.next()) |line| { 622 const fp = fingerprintOfAuthorizedKey(line) orelse continue; 623 if (std.mem.eql(u8, &fp, fingerprint)) return true; 624 } 625 return false; 626 } 627 628 // the SHA256 fingerprint of one authorized_keys line, or null if the line is 629 // blank or not a parseable "<type> <base64> [comment]" entry 630 fn fingerprintOfAuthorizedKey(line: []const u8) ?[ssh.fingerprint_len]u8 { 631 var it = std.mem.tokenizeAny(u8, line, " \t\r"); 632 _ = it.next() orelse return null; // key type 633 const blob_b64 = it.next() orelse return null; 634 635 const decoder = std.base64.standard.Decoder; 636 const blob_len = decoder.calcSizeForSlice(blob_b64) catch return null; 637 var blob_buf: [4096]u8 = undefined; 638 if (blob_len > blob_buf.len) return null; 639 decoder.decode(blob_buf[0..blob_len], blob_b64) catch return null; 640 641 return ssh.formatFingerprint(blob_buf[0..blob_len]); 642 } 643 644 fn writeError(sess: *ssh.SessionCtx, comptime msg: []const u8) !void { 645 const body = "ERR haxy ssh: " ++ msg; 646 var packet: [body.len + 4]u8 = undefined; 647 const line = try std.fmt.bufPrint(&packet, "{x:0>4}{s}", .{ packet.len, body }); 648 try sess.writeBytes(line); 649 try sess.exit(1); 650 } 651 652 test "parseGitCommand rejects malformed input" { 653 const allocator = std.testing.allocator; 654 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 655 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 656 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 657 } 658 659 test "parseGitCommand happy paths" { 660 const allocator = std.testing.allocator; 661 662 { 663 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 664 defer parsed.deinit(allocator); 665 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 666 try std.testing.expectEqualStrings("some-repo", parsed.dir); 667 } 668 { 669 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 670 defer parsed.deinit(allocator); 671 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 672 try std.testing.expectEqualStrings("user/proj", parsed.dir); 673 } 674 { 675 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 676 defer parsed.deinit(allocator); 677 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 678 try std.testing.expectEqualStrings("repo", parsed.dir); 679 } 680 } 681