╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh.zig ────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
346 347 const GitService = enum { upload_pack, receive_pack }; 348 349 const ParsedGitCommand = struct { 350 service: GitService, 351 dir: []u8, 352 353 fn deinit(self: ParsedGitCommand, allocator: std.mem.Allocator) void { 354 allocator.free(self.dir); 355 } 356 }; 357 358 fn runGitSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, exec: ssh.Request.Exec) !void { 359 const allocator = sess.conn.allocator; 360 const io = sess.conn.io; 361 const protocol_version = xit.net_server_common.parseProtocolVersion(exec.git_protocol); 362 363 // the repo's pack functions consume the channel like any other stream. 364 // whatever they leave buffered is flushed before the exit status goes out. 365 var reader_buf: [4096]u8 = undefined; 366 var writer_buf: [4096]u8 = undefined; 367 var reader = ssh.SessionReader.init(sess, &reader_buf); 368 var writer = ssh.SessionWriter.init(sess, &writer_buf); 369 defer writer.interface.flush() catch {}; 370 371 const parsed = parseGitCommand(allocator, exec.command) catch return writeError(sess, "unsupported command (expected git-upload-pack or git-receive-pack)"); 372 defer parsed.deinit(allocator); 373 const path = std.mem.trimStart(u8, parsed.dir, "/"); 374 const fork_prefix = "fork/"; 375 376 if (std.mem.startsWith(u8, path, fork_prefix)) { 377 return runForkSession(handler, sess, path[fork_prefix.len..], parsed.service, protocol_version, &reader.interface, &writer.interface); 378 } 379 380 const repo_prefix = "repo/"; 381 const repo_identity = if (std.mem.startsWith(u8, path, repo_prefix)) path[repo_prefix.len..] else path; 382 383 const create_if_missing = parsed.service == .receive_pack; 384 385 const owner_repo = evt.parseOwnerRepoPath(repo_identity) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 386 var author_arena = std.heap.ArenaAllocator.init(allocator); 387 defer author_arena.deinit(); 388 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)) { 389 .allowed => |user| user, 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, create_if_missing)) { 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 if (try serveIfExists(repo_path, handler.users_dir, &reader.interface, &writer.interface, io, allocator, parsed.service, protocol_version, author, handler.err, sess)) return; 405 406 if (!create_if_missing) return writeError(sess, "repo not found"); 407 408 // create the on-disk repo for the just-minted event and serve the push 409 var repo = try rp.Repo(.xit, any_repo_opts.toRepoOpts()).init(io, allocator, .{ .path = repo_path, .bare = true }); 410 defer repo.deinit(io, allocator); 411 try servePack(repo.self_repo_opts, &repo, handler.users_dir, &reader.interface, &writer.interface, io, allocator, parsed.service, protocol_version, author, handler.err, sess); 412 } 413 414 // serve a patch draft: anyone may fetch it, only its author may push to it 415 fn runForkSession( 416 handler: *const SessionHandler, 417 sess: *ssh.SessionCtx, 418 fork_path: []const u8, 419 service: GitService, 420 protocol_version: xit.net_server_common.ProtocolVersion, 421 reader: *std.Io.Reader, 422 writer: *std.Io.Writer, 423 ) !void { 424 const allocator = sess.conn.allocator; 425 const io = sess.conn.io; 426 427 const route = fork.parseRoute(fork_path) orelse return writeError(sess, "invalid fork path"); 428 // the route names the forker and the target repo 429 const forker_repo = evt.parseOwnerRepoPath(route.identity) orelse return writeError(sess, "repo path must be <forker>/<repo>"); 430 431 var admin = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = handler.admin_repo_path }); 432 defer admin.deinit(io, allocator); 433 var admin_arena = std.heap.ArenaAllocator.init(allocator); 434 defer admin_arena.deinit(); 435 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 436 const fork_id = try evt.parseEventId(&route.id); 437 const forker_id = (try evt.User.readIdByName(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, forker_repo.owner)) orelse 438 return writeError(sess, "patch draft not found"); 439 const fork_record = (try evt.readForkById(io, allocator, &admin_arena, handler.users_dir, &forker_id, &fork_id)) orelse 440 return writeError(sess, "patch draft not found"); 441 if (fork_record.removed) return writeError(sess, "patch draft not found"); 442 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, &forker_id)) orelse 443 return writeError(sess, "invalid patch draft"); 444 if (user.removed) return writeError(sess, "invalid patch draft"); 445 if (service == .receive_pack and !isKeyInAuthorizedKeys(user.event.ssh_keys, &sess.fingerprint)) 446 return writeError(sess, "unauthorized: this SSH key is not registered to the patch author"); 447 448 const draft_path = try fork.forkPath(allocator, handler.users_dir, &forker_id, &fork_id); 449 defer allocator.free(draft_path); 450 var draft = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = draft_path }) catch 451 return writeError(sess, "patch draft not found"); 452 defer draft.deinit(io, allocator); 453 if (service == .upload_pack) { 454 var sideband = progress.Sideband{ .writer = writer, .sess = sess }; 455 switch (draft) { 456 inline else => |*repo| try repo.uploadPack(io, allocator, reader, writer, .{ .protocol_version = protocol_version }, &sideband), 457 } 458 } else { 459 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)) orelse 460 return writeError(sess, "repo not found"); 461 if (!std.mem.eql(u8, target.event.name, forker_repo.name)) return writeError(sess, "patch draft belongs to another repo"); 462 const target_path = try evt.repoPath(allocator, handler.users_dir, fork_record.event.repo_user_id, fork_record.event.repo_id); 463 defer allocator.free(target_path); 464 const author: evt.CommitAuthor = .{ .name = user.event.name, .email = user.event.email }; 465 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 466 switch (draft) { 467 inline else => |*repo| { 468 var target_repo = rp.Repo(.xit, repo.self_repo_opts).open(io, allocator, .{ .path = target_path }) catch 469 return writeError(sess, "repo not found or has the wrong hash"); 470 defer target_repo.deinit(io, allocator); 471 try push.receiveFork(repo.self_repo_opts, io, allocator, repo, &target_repo, handler.users_dir, &route.id, author, timestamp, reader, writer, handler.err, sess); 472 }, 473 } 474 } 475 } 476 477 // serve an existing repo at `repo_path`, or return false if none is there 478 fn serveIfExists( 479 repo_path: []const u8, 480 users_dir: []const u8, 481 reader: *std.Io.Reader, 482 writer: *std.Io.Writer, 483 io: std.Io, 484 allocator: std.mem.Allocator, 485 service: GitService, 486 protocol_version: xit.net_server_common.ProtocolVersion, 487 author: ?evt.CommitAuthor, 488 error_writer: *std.Io.Writer, 489 sess: ?*ssh.SessionCtx, 490 ) !bool { 491 // a bare open() creates the directory while probing for the repo, so only 492 // attempt it when the path already exists 493 std.Io.Dir.accessAbsolute(io, repo_path, .{}) catch return false; 494 495 var any_repo = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 496 error.RepoNotFound => return false, 497 else => |e| return e, 498 }; 499 defer any_repo.deinit(io, allocator); 500 501 switch (any_repo) { 502 inline else => |*repo| try servePack(repo.self_repo_opts, repo, users_dir, reader, writer, io, allocator, service, protocol_version, author, error_writer, sess), 503 } 504 return true; 505 } 506 507 fn servePack( 508 comptime repo_opts: rp.RepoOpts(.xit), 509 repo: *rp.Repo(.xit, repo_opts), 510 users_dir: []const u8, 511 reader: *std.Io.Reader, 512 writer: *std.Io.Writer, 513 io: std.Io, 514 allocator: std.mem.Allocator, 515 service: GitService, 516 protocol_version: xit.net_server_common.ProtocolVersion, 517 author: ?evt.CommitAuthor, 518 error_writer: *std.Io.Writer, 519 sess: ?*ssh.SessionCtx, 520 ) !void { 521 switch (service) { 522 .upload_pack => { 523 var sideband = progress.Sideband{ .writer = writer, .sess = sess }; 524 try repo.uploadPack(io, allocator, reader, writer, .{ .protocol_version = protocol_version }, &sideband); 525 }, 526 .receive_pack => try push.receivePackAndConsume(repo_opts, io, allocator, repo, reader, writer, .{ .protocol_version = protocol_version }, author, users_dir, error_writer, sess), 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, denied, not_found }; 549 550 fn authorizeRepoKey( 551 io: std.Io, 552 arena: *std.heap.ArenaAllocator, 553 admin_repo_path: []const u8, 554 users_dir: []const u8, 555 owner_name: []const u8, 556 repo_name: []const u8, 557 service: GitService, 558 fingerprint: *const [ssh.fingerprint_len]u8, 559 ) !RepoAuthorization { 560 const allocator = arena.child_allocator; 561 var admin = rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 562 error.RepoNotFound => return .not_found, 563 else => |e| return e, 564 }; 565 defer admin.deinit(io, allocator); 566 567 const moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 568 const repo = (try evt.readRepoByOwnerAndName(io, allocator, arena, moment, users_dir, owner_name, repo_name)) orelse { 569 if (service == .upload_pack) return .not_found; 570 const owner = (try evt.User.readByName(io, allocator, admin_repo_path, arena, owner_name)) orelse return .not_found; 571 return if (isKeyInAuthorizedKeys(owner.event.ssh_keys, fingerprint)) 572 .{ .allowed = .{ .name = owner.event.name, .email = owner.event.email } } 573 else 574 .denied; 575 }; 576 577 const min_role: evt.Repo.Role = switch (service) { 578 .upload_pack => .read, 579 .receive_pack => .write, 580 }; 581 // skip the key lookups when the base role is enough 582 if (evt.Repo.roleOf(repo.repo, null).atLeast(min_role)) return .{ .allowed = null }; 583 584 const user = (try repoUserWithKey(moment, arena, repo.repo.event, fingerprint)) orelse return .denied; 585 if (!evt.Repo.roleOf(repo.repo, user.id).atLeast(min_role)) return .denied; 586 return .{ .allowed = user.author }; 587 } 588 589 const UserWithKey = struct { 590 id: [evt.event_id_size]u8, 591 author: evt.CommitAuthor, 592 }; 593 594 // the repo's owner or collaborator holding the key, or null for anyone else 595 fn repoUserWithKey( 596 moment: evt.AdminDB.HashMap(.read_only), 597 arena: *std.heap.ArenaAllocator, 598 repo: evt.Repo, 599 fingerprint: *const [ssh.fingerprint_len]u8, 600 ) !?UserWithKey { 601 if (try userWithKey(moment, arena, repo.user_id, fingerprint)) |user| return user; 602 603 for ([_][]const u8{ repo.owner_user_ids, repo.write_user_ids, repo.read_user_ids }) |user_ids| { 604 var lines = std.mem.tokenizeScalar(u8, user_ids, '\n'); 605 while (lines.next()) |id| { 606 const user_id = try evt.parseEventId(id); 607 if (try userWithKey(moment, arena, &user_id, fingerprint)) |user| return user; 608 } 609 } 610 return null; 611 } 612 613 fn userWithKey( 614 moment: evt.AdminDB.HashMap(.read_only), 615 arena: *std.heap.ArenaAllocator, 616 user_id: []const u8, 617 fingerprint: *const [ssh.fingerprint_len]u8, 618 ) !?UserWithKey { 619 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, user_id)) orelse return null; 620 if (user.removed or !isKeyInAuthorizedKeys(user.event.ssh_keys, fingerprint)) return null; 621 return .{ 622 .id = user_id[0..evt.event_id_size].*, 623 .author = .{ .name = user.event.name, .email = user.event.email }, 624 }; 625 } 626 627 fn isKeyInAuthorizedKeys(ssh_keys: []const u8, fingerprint: *const [ssh.fingerprint_len]u8) bool { 628 var it = std.mem.splitScalar(u8, ssh_keys, '\n'); 629 while (it.next()) |line| { 630 const fp = fingerprintOfAuthorizedKey(line) orelse continue; 631 if (std.mem.eql(u8, &fp, fingerprint)) return true; 632 } 633 return false; 634 } 635 636 // the SHA256 fingerprint of one authorized_keys line, or null if the line is 637 // blank or not a parseable "<type> <base64> [comment]" entry 638 fn fingerprintOfAuthorizedKey(line: []const u8) ?[ssh.fingerprint_len]u8 { 639 var it = std.mem.tokenizeAny(u8, line, " \t\r"); 640 _ = it.next() orelse return null; // key type 641 const blob_b64 = it.next() orelse return null; 642 643 const decoder = std.base64.standard.Decoder; 644 const blob_len = decoder.calcSizeForSlice(blob_b64) catch return null; 645 var blob_buf: [4096]u8 = undefined; 646 if (blob_len > blob_buf.len) return null; 647 decoder.decode(blob_buf[0..blob_len], blob_b64) catch return null; 648 649 return ssh.formatFingerprint(blob_buf[0..blob_len]); 650 } 651 652 fn writeError(sess: *ssh.SessionCtx, comptime msg: []const u8) !void { 653 const body = "ERR haxy ssh: " ++ msg; 654 var packet: [body.len + 4]u8 = undefined; 655 const line = try std.fmt.bufPrint(&packet, "{x:0>4}{s}", .{ packet.len, body }); 656 try sess.writeBytes(line); 657 try sess.exit(1); 658 } 659 660 test "parseGitCommand rejects malformed input" { 661 const allocator = std.testing.allocator; 662 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 663 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 664 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 665 } 666 667 test "parseGitCommand happy paths" { 668 const allocator = std.testing.allocator; 669 670 { 671 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 672 defer parsed.deinit(allocator); 673 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 674 try std.testing.expectEqualStrings("some-repo", parsed.dir); 675 } 676 { 677 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 678 defer parsed.deinit(allocator); 679 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 680 try std.testing.expectEqualStrings("user/proj", parsed.dir); 681 } 682 { 683 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 684 defer parsed.deinit(allocator); 685 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 686 try std.testing.expectEqualStrings("repo", parsed.dir); 687 } 688 } 689