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