╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh.zig ────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯
368 const protocol_version = xit.net_server_common.parseProtocolVersion(exec.git_protocol); 369 370 // the repo's pack functions consume the channel like any other stream. 371 // whatever they leave buffered is flushed before the exit status goes out. 372 var reader_buf: [4096]u8 = undefined; 373 var writer_buf: [4096]u8 = undefined; 374 var reader = ssh.SessionReader.init(sess, &reader_buf); 375 var writer = ssh.SessionWriter.init(sess, &writer_buf); 376 defer writer.interface.flush() catch {}; 377 378 const parsed = parseGitCommand(allocator, exec.command) catch return writeError(sess, "unsupported command (expected git-upload-pack or git-receive-pack)"); 379 defer parsed.deinit(allocator); 380 const repo_identity = std.mem.trimStart(u8, parsed.dir, "/"); 381 382 // a "+" names a fork's patch draft 383 if (std.mem.indexOfScalar(u8, repo_identity, '+') != null) { 384 return runForkSession(handler, sess, repo_identity, parsed.service, protocol_version, &reader.interface, &writer.interface); 385 } 386 387 const owner_repo = evt.parseOwnerRepoPath(repo_identity) orelse return writeError(sess, "repo path must be <owner>:<repo>"); 388 var allowed_arena = std.heap.ArenaAllocator.init(allocator); 389 defer allowed_arena.deinit(); 390 const allowed = switch (try authorizeRepoKey(io, &allowed_arena, handler.admin_repo_path, handler.server.users_dir, owner_repo.owner, owner_repo.name, parsed.service, &sess.fingerprint)) { 391 .allowed => |value| value, 392 .create => |creator| return runCreatingPush(handler, sess, &creator, owner_repo.name, protocol_version, &reader.interface, &writer.interface), 393 .denied => return switch (parsed.service) { 394 .upload_pack => writeError(sess, "unauthorized: this SSH key cannot read this repo"), 395 .receive_pack => writeError(sess, "unauthorized: this SSH key cannot push to this repo"), 396 }, 397 .not_found => return writeError(sess, "repo not found"), 398 }; 399 400 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, handler.server.users_dir, handler.admin_repo_path, repo_identity)) { 401 .ok => |p| p, 402 .invalid => unreachable, // parsed above 403 .not_found => return writeError(sess, "repo not found"), 404 }; 405 defer allocator.free(repo_path); 406 407 var any_repo = try rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }); 408 defer any_repo.deinit(io, allocator); 409 410 switch (any_repo) { 411 inline else => |*repo| switch (allowed) { 412 .fetch => { 413 var sideband = progress.Sideband{ .writer = &writer.interface, .sess = sess }; 414 try repo.uploadPack(io, allocator, &reader.interface, &writer.interface, .{ .protocol_version = protocol_version }, &sideband); 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 // the url keeps the name the fork was made under, even after a rename 493 if (!std.mem.eql(u8, fork_record.event.repo_name, forker_repo.name)) return writeError(sess, "patch draft not found"); 494 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, &forker_id)) orelse 495 return writeError(sess, "invalid patch draft"); 496 if (user.removed) return writeError(sess, "invalid patch draft"); 497 if (service == .receive_pack and !try evt.User.holdsKey(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, &forker_id, &sess.fingerprint)) 498 return writeError(sess, "unauthorized: this SSH key is not registered to the patch author"); 499 500 const target_owner_id = try evt.parseEventId(&fork_record.event.repo_user_id); 501 const target_id = try evt.parseEventId(&fork_record.event.repo_id); 502 // a deleted target, or one whose owner was deleted, leaves the fork fetchable but not pushable 503 const target = try evt.readRepoById(io, allocator, &admin_arena, handler.server.users_dir, &target_owner_id, &target_id, forker_id); 504 if (target) |value| { 505 // patches that are off take their drafts with them 506 const patch_role = value.repo.event.patch_role orelse return writeError(sess, "patch draft not found"); 507 if (service == .receive_pack) { 508 const role = value.role orelse return writeError(sess, "repo not found"); 509 if (!role.atLeast(patch_role)) return writeError(sess, "unauthorized: your role in this repo may not write patches"); 510 } 511 } 512 if (service == .upload_pack) { 513 // a fork is as readable as its target, and only its forker's once the target is gone 514 const readable = if (target) |value| readable: { 515 const owner = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, &target_owner_id)) orelse unreachable; 516 break :readable try authorizeRepoKey(io, &admin_arena, handler.admin_repo_path, handler.server.users_dir, owner.event.name, value.repo.event.name, .upload_pack, &sess.fingerprint) == .allowed; 517 } else try evt.User.holdsKey(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, &forker_id, &sess.fingerprint); 518 if (!readable) return writeError(sess, "unauthorized: this SSH key cannot read this patch draft"); 519 } 520 521 const draft_path = try fork.forkPath(allocator, handler.server.users_dir, &forker_id, &fork_id); 522 defer allocator.free(draft_path); 523 var draft = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = draft_path }) catch 524 return writeError(sess, "patch draft not found"); 525 defer draft.deinit(io, allocator); 526 if (service == .upload_pack) { 527 var sideband = progress.Sideband{ .writer = writer, .sess = sess }; 528 switch (draft) { 529 inline else => |*repo| try repo.uploadPack(io, allocator, reader, writer, .{ .protocol_version = protocol_version }, &sideband), 530 } 531 } else { 532 if (target == null) return writeError(sess, "the repo this patch draft targets was deleted"); 533 const target_path = try evt.repoPath(allocator, handler.server.users_dir, &target_owner_id, &target_id); 534 defer allocator.free(target_path); 535 const author: evt.CommitAuthor = .{ .name = user.event.name, .email = user.event.email }; 536 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 537 switch (draft) { 538 inline else => |*repo| { 539 var target_repo = rp.Repo(.xit, repo.self_repo_opts).open(io, allocator, .{ .path = target_path }) catch 540 return writeError(sess, "repo not found or has the wrong hash"); 541 defer target_repo.deinit(io, allocator); 542 try push.receiveFork(repo.self_repo_opts, io, allocator, repo, &target_repo, handler.server, &route.id, author, timestamp, reader, writer, handler.err, sess); 543 }, 544 } 545 } 546 } 547 548 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 549 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 550 defer tokens.deinit(); 551 552 const service_token = tokens.next() orelse return error.InvalidCommand; 553 const dir_token = tokens.next() orelse return error.InvalidCommand; 554 555 const service: GitService = 556 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 557 .upload_pack 558 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 559 .receive_pack 560 else 561 return error.UnsupportedService; 562 563 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 564 } 565 566 const RepoAuthorization = union(enum) { allowed: Allowed, create: RepoCreator, denied, not_found }; 567 568 // what a key may do in an existing repo 569 const Allowed = union(enum) { 570 fetch, 571 push: Pusher, 572 }; 573 574 // the key holder a push acts as 575 const Pusher = struct { 576 user_id: [evt.event_id_size]u8, 577 author: evt.CommitAuthor, 578 protected_branches: []const []const u8, 579 locked_branches: []const []const u8, 580 // only owners may clear the undo history 581 owner: bool, 582 }; 583 584 // the owner of a repo a push may create 585 const RepoCreator = struct { 586 owner_id: [evt.event_id_size]u8, 587 owner: evt.CommitAuthor, 588 }; 589 590 fn authorizeRepoKey( 591 io: std.Io, 592 arena: *std.heap.ArenaAllocator, 593 admin_repo_path: []const u8, 594 users_dir: []const u8, 595 owner_name: []const u8, 596 repo_name: []const u8, 597 service: GitService, 598 fingerprint: *const [ssh.fingerprint_len]u8, 599 ) !RepoAuthorization { 600 const allocator = arena.child_allocator; 601 var admin = rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 602 error.RepoNotFound => return .not_found, 603 else => |e| return e, 604 }; 605 defer admin.deinit(io, allocator); 606 607 const moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 608 // no viewer yet, so this carries the base role 609 const repo = (try evt.readRepoByOwnerAndName(io, allocator, arena, moment, users_dir, owner_name, repo_name, null)) orelse { 610 if (service == .upload_pack) return .not_found; 611 const owner_id = (try evt.User.readIdByName(evt.AdminDB, evt.admin_repo_opts.hash, moment, owner_name)) orelse return .not_found; 612 if (!try evt.User.holdsKey(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, &owner_id, fingerprint)) return .denied; 613 return .{ .create = .{ .owner_id = owner_id, .owner = try commitAuthor(moment, arena, &owner_id) } }; 614 }; 615 616 const min_role: evt.Repo.Role = switch (service) { 617 .upload_pack => .read, 618 .receive_pack => .write, 619 }; 620 // any key may fetch a public repo; a push always needs a key holder 621 if (service == .upload_pack and repo.role != null) return .{ .allowed = .fetch }; 622 623 // a key can be shared, so the push acts as the holder with the highest role 624 const owner_id = try evt.parseEventId(&repo.repo.event.user_id); 625 var best: ?struct { id: [evt.event_id_size]u8, role: evt.Repo.Role } = null; 626 for (try evt.User.readIdsByFingerprint(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, fingerprint)) |holder_id| { 627 const seen = (try evt.readRepoById(io, allocator, arena, users_dir, &owner_id, &repo.event_id, holder_id)) orelse return .not_found; 628 const role = seen.role orelse continue; 629 if (best) |held| if (held.role.atLeast(role)) continue; 630 best = .{ .id = holder_id, .role = role }; 631 } 632 const holder = best orelse return .denied; 633 if (!holder.role.atLeast(min_role)) return .denied; 634 return .{ 635 .allowed = switch (service) { 636 .upload_pack => .fetch, 637 .receive_pack => blk: { 638 const names = try repo.repo.event.protectedBranchNames(arena.allocator()); 639 // members change protected branches only by merging a patch 640 const owner = holder.role == .owner; 641 break :blk .{ .push = .{ 642 .user_id = holder.id, 643 .author = try commitAuthor(moment, arena, &holder.id), 644 .protected_branches = if (owner) names else &.{}, 645 .locked_branches = if (owner) &.{} else names, 646 .owner = owner, 647 } }; 648 }, 649 }, 650 }; 651 } 652 653 // an active user as a commit author 654 fn commitAuthor( 655 moment: evt.AdminDB.HashMap(.read_only), 656 arena: *std.heap.ArenaAllocator, 657 user_id: *const [evt.event_id_size]u8, 658 ) !evt.CommitAuthor { 659 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, user_id)) orelse unreachable; 660 return .{ .name = user.event.name, .email = user.event.email }; 661 } 662 663 // the authorized_keys line of a pubkey blob: its type, then the blob in base64 664 fn authorizedKeyLine(allocator: std.mem.Allocator, blob: []const u8) ![]const u8 { 665 var reader = std.Io.Reader.fixed(blob); 666 const key_type = try ssh.takeString(&reader, 64); 667 const encoder = std.base64.standard.Encoder; 668 const line = try allocator.alloc(u8, key_type.len + 1 + encoder.calcSize(blob.len)); 669 @memcpy(line[0..key_type.len], key_type); 670 line[key_type.len] = ' '; 671 _ = encoder.encode(line[key_type.len + 1 ..], blob); 672 return line; 673 } 674 675 fn writeError(sess: *ssh.SessionCtx, comptime msg: []const u8) !void { 676 const body = "ERR haxy ssh: " ++ msg; 677 var packet: [body.len + 4]u8 = undefined; 678 const line = try std.fmt.bufPrint(&packet, "{x:0>4}{s}", .{ packet.len, body }); 679 try sess.writeBytes(line); 680 try sess.exit(1); 681 } 682 683 test "parseGitCommand rejects malformed input" { 684 const allocator = std.testing.allocator; 685 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 686 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 687 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 688 } 689 690 test "parseGitCommand happy paths" { 691 const allocator = std.testing.allocator; 692 693 { 694 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 695 defer parsed.deinit(allocator); 696 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 697 try std.testing.expectEqualStrings("some-repo", parsed.dir); 698 } 699 { 700 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 701 defer parsed.deinit(allocator); 702 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 703 try std.testing.expectEqualStrings("user/proj", parsed.dir); 704 } 705 { 706 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 707 defer parsed.deinit(allocator); 708 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 709 try std.testing.expectEqualStrings("repo", parsed.dir); 710 } 711 } 712