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