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