╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh.zig ────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
333 fn runGitSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, command: []const u8) !void { 334 const allocator = sess.conn.allocator; 335 const io = sess.conn.io; 336 337 const parsed = parseGitCommand(allocator, command) catch return writeError(sess, "unsupported command (expected git-upload-pack or git-receive-pack)"); 338 defer parsed.deinit(allocator); 339 const path = std.mem.trimStart(u8, parsed.dir, "/"); 340 const fork_prefix = "fork/"; 341 342 if (std.mem.startsWith(u8, path, fork_prefix)) { 343 const route = fork.parseRoute(path[fork_prefix.len..]) orelse return writeError(sess, "invalid fork path"); 344 const owner_repo = evt.parseOwnerRepoPath(route.identity) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 345 346 var admin = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = handler.admin_repo_path }); 347 defer admin.deinit(io, allocator); 348 var admin_arena = std.heap.ArenaAllocator.init(allocator); 349 defer admin_arena.deinit(); 350 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 351 const fork_id = try evt.parseEventId(&route.id); 352 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, &fork_id)) orelse 353 return writeError(sess, "patch draft not found"); 354 if (fork_record.removed) return writeError(sess, "patch draft not found"); 355 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, fork_record.event.user_id)) orelse 356 return writeError(sess, "invalid patch draft"); 357 if (user.removed) return writeError(sess, "invalid patch draft"); 358 if (parsed.service == .receive_pack and !isKeyInAuthorizedKeys(user.event.ssh_keys, &sess.fingerprint)) 359 return writeError(sess, "unauthorized: this SSH key is not registered to the patch author"); 360 361 const draft_path = try fork.forkPath(allocator, handler.repo_root_path, &route.id); 362 defer allocator.free(draft_path); 363 var draft = rp.AnyRepo(.xit, .{ .ProgressCtx = *push.PushProgress }).open(io, allocator, .{ .path = draft_path }) catch 364 return writeError(sess, "patch draft not found"); 365 defer draft.deinit(io, allocator); 366 var reader_buf: [4096]u8 = undefined; 367 var writer_buf: [4096]u8 = undefined; 368 var reader = ssh.SessionReader.init(sess, &reader_buf); 369 var writer = ssh.SessionWriter.init(sess, &writer_buf); 370 if (parsed.service == .upload_pack) { 371 switch (draft) { 372 inline else => |*repo| try repo.uploadPack(io, allocator, &reader.interface, &writer.interface, .{}), 373 } 374 } else { 375 const target = (try evt.Repo.readByOwnerAndName(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, owner_repo.owner, owner_repo.name)) orelse 376 return writeError(sess, "repo not found"); 377 if (!std.mem.eql(u8, fork_record.event.repo_id, &target.event_id)) return writeError(sess, "patch draft belongs to another repo"); 378 const target_id = std.fmt.bytesToHex(target.event_id, .lower); 379 const target_path = try std.fs.path.join(allocator, &.{ handler.repo_root_path, &target_id }); 380 defer allocator.free(target_path); 381 const author: evt.CommitAuthor = .{ .name = user.event.name, .email = user.event.email }; 382 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 383 switch (draft) { 384 inline else => |*repo| { 385 var target_repo = rp.Repo(.xit, repo.self_repo_opts).open(io, allocator, .{ .path = target_path }) catch 386 return writeError(sess, "repo not found or has the wrong hash"); 387 defer target_repo.deinit(io, allocator); 388 try push.receiveFork(repo.self_repo_opts, io, allocator, repo, &target_repo, &route.id, author, timestamp, &reader.interface, &writer.interface, handler.err); 389 }, 390 } 391 } 392 writer.interface.flush() catch {}; 393 try sess.exit(0); 394 return; 395 } 396 397 const repo_prefix = "repo/"; 398 const repo_identity = if (std.mem.startsWith(u8, path, repo_prefix)) path[repo_prefix.len..] else path; 399 400 const create_if_missing = parsed.service == .receive_pack; 401 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{ .ProgressCtx = *push.PushProgress }; 402 403 const owner_repo = evt.parseOwnerRepoPath(repo_identity) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 404 switch (try authorizeRepoKey(io, allocator, handler.admin_repo_path, owner_repo.owner, owner_repo.name, parsed.service, &sess.fingerprint)) { 405 .allowed => {}, 406 .denied => return switch (parsed.service) { 407 .upload_pack => writeError(sess, "unauthorized: this SSH key cannot read this repo"), 408 .receive_pack => writeError(sess, "unauthorized: this SSH key cannot push to this repo"), 409 }, 410 .not_found => return writeError(sess, "repo not found"), 411 } 412 413 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, handler.repo_root_path, handler.admin_repo_path, repo_identity, create_if_missing)) { 414 .ok => |p| p, 415 .invalid => return writeError(sess, "repo path must be <owner>/<repo>"), 416 .not_found => return writeError(sess, "repo not found"), 417 }; 418 defer allocator.free(repo_path); 419 420 if (try serveIfExists(repo_path, handler.repo_root_path, sess, io, allocator, parsed.service, handler.err)) { 421 try sess.exit(0); 422 return; 423 } 424 425 if (!create_if_missing) return writeError(sess, "repo not found"); 426 427 // create the on-disk repo for the just-minted event and serve the push 428 var repo = try createRepo(any_repo_opts.toRepoOpts(), io, allocator, repo_path); 429 defer repo.deinit(io, allocator); 430 try servePack(repo.self_repo_opts, &repo, handler.repo_root_path, sess, io, allocator, parsed.service, handler.err); 431 try sess.exit(0); 432 } 433 434 // serve an existing repo at `repo_path`, or return false if none is there 435 fn serveIfExists( 436 repo_path: []const u8, 437 repo_root_path: []const u8, 438 sess: *ssh.SessionCtx, 439 io: std.Io, 440 allocator: std.mem.Allocator, 441 service: GitService, 442 error_writer: *std.Io.Writer, 443 ) !bool { 444 // a bare open() creates the directory while probing for the repo, so only 445 // attempt it when the path already exists 446 std.Io.Dir.accessAbsolute(io, repo_path, .{}) catch return false; 447 448 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{ .ProgressCtx = *push.PushProgress }; 449 var any_repo = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 450 error.RepoNotFound => return false, 451 else => |e| return e, 452 }; 453 defer any_repo.deinit(io, allocator); 454 455 switch (any_repo) { 456 inline else => |*repo| try servePack(repo.self_repo_opts, repo, repo_root_path, sess, io, allocator, service, error_writer), 457 } 458 return true; 459 } 460 461 fn createRepo( 462 comptime repo_opts: rp.RepoOpts(.xit), 463 io: std.Io, 464 allocator: std.mem.Allocator, 465 repo_path: []const u8, 466 ) !rp.Repo(.xit, repo_opts) { 467 var repo = try rp.Repo(.xit, repo_opts).init(io, allocator, .{ .path = repo_path, .bare = true }); 468 errdefer repo.deinit(io, allocator); 469 try repo.setMergeAlgorithm(io, allocator, .patch); 470 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 471 return repo; 472 } 473 474 // wrap the channel I/O in std.Io.Reader/Writer adapters so the repo's pack 475 // functions can consume them like any other stream, then run the requested 476 // service 477 fn servePack( 478 comptime repo_opts: rp.RepoOpts(.xit), 479 repo: *rp.Repo(.xit, repo_opts), 480 repo_root_path: []const u8, 481 sess: *ssh.SessionCtx, 482 io: std.Io, 483 allocator: std.mem.Allocator, 484 service: GitService, 485 error_writer: *std.Io.Writer, 486 ) !void { 487 var session_reader_buf: [4096]u8 = undefined; 488 var session_writer_buf: [4096]u8 = undefined; 489 var session_reader = ssh.SessionReader.init(sess, &session_reader_buf); 490 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 491 492 switch (service) { 493 .upload_pack => try repo.uploadPack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 494 .receive_pack => try push.receivePackAndConsume(repo_opts, io, allocator, repo, &session_reader.interface, &session_writer.interface, .{}, repo_root_path, error_writer), 495 } 496 497 // flush whatever the pack op buffered into our writer adapter 498 session_writer.interface.flush() catch {}; 499 } 500 501 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 502 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 503 defer tokens.deinit(); 504 505 const service_token = tokens.next() orelse return error.InvalidCommand; 506 const dir_token = tokens.next() orelse return error.InvalidCommand; 507 508 const service: GitService = 509 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 510 .upload_pack 511 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 512 .receive_pack 513 else 514 return error.UnsupportedService; 515 516 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 517 } 518 519 const RepoAuthorization = enum { allowed, denied, not_found }; 520 521 fn authorizeRepoKey( 522 io: std.Io, 523 allocator: std.mem.Allocator, 524 admin_repo_path: []const u8, 525 owner_name: []const u8, 526 repo_name: []const u8, 527 service: GitService, 528 fingerprint: *const [ssh.fingerprint_len]u8, 529 ) !RepoAuthorization { 530 var arena = std.heap.ArenaAllocator.init(allocator); 531 defer arena.deinit(); 532 533 var admin = rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 534 error.RepoNotFound => return .not_found, 535 else => |e| return e, 536 }; 537 defer admin.deinit(io, allocator); 538 539 const moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 540 const repo = (try evt.Repo.readByOwnerAndName(evt.AdminDB, evt.admin_repo_opts.hash, moment, &arena, owner_name, repo_name)) orelse { 541 if (service == .upload_pack) return .not_found; 542 const owner = (try evt.User.readByName(io, allocator, admin_repo_path, &arena, owner_name)) orelse return .not_found; 543 return if (isKeyInAuthorizedKeys(owner.event.ssh_keys, fingerprint)) .allowed else .denied; 544 }; 545 546 if ((service == .upload_pack and repo.repo.event.read_access == .public) or 547 (service == .receive_pack and repo.repo.event.write_access == .public)) return .allowed; 548 if (try keyBelongsToUser(moment, &arena, repo.repo.event.user_id, fingerprint)) return .allowed; 549 550 const user_id_lists: []const []const u8 = switch (service) { 551 .upload_pack => &.{ repo.repo.event.write_user_ids, repo.repo.event.read_user_ids }, 552 .receive_pack => &.{repo.repo.event.write_user_ids}, 553 }; 554 for (user_id_lists) |user_ids| { 555 var lines = std.mem.tokenizeScalar(u8, user_ids, '\n'); 556 while (lines.next()) |id| { 557 const user_id = try evt.parseEventId(id); 558 if (try keyBelongsToUser(moment, &arena, &user_id, fingerprint)) return .allowed; 559 } 560 } 561 return .denied; 562 } 563 564 fn keyBelongsToUser( 565 moment: evt.AdminDB.HashMap(.read_only), 566 arena: *std.heap.ArenaAllocator, 567 user_id: []const u8, 568 fingerprint: *const [ssh.fingerprint_len]u8, 569 ) !bool { 570 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, user_id)) orelse return false; 571 return !user.removed and isKeyInAuthorizedKeys(user.event.ssh_keys, fingerprint); 572 } 573 574 fn isKeyInAuthorizedKeys(ssh_keys: []const u8, fingerprint: *const [ssh.fingerprint_len]u8) bool { 575 var it = std.mem.splitScalar(u8, ssh_keys, '\n'); 576 while (it.next()) |line| { 577 const fp = fingerprintOfAuthorizedKey(line) orelse continue; 578 if (std.mem.eql(u8, &fp, fingerprint)) return true; 579 } 580 return false; 581 } 582 583 // the SHA256 fingerprint of one authorized_keys line, or null if the line is 584 // blank or not a parseable "<type> <base64> [comment]" entry 585 fn fingerprintOfAuthorizedKey(line: []const u8) ?[ssh.fingerprint_len]u8 { 586 var it = std.mem.tokenizeAny(u8, line, " \t\r"); 587 _ = it.next() orelse return null; // key type 588 const blob_b64 = it.next() orelse return null; 589 590 const decoder = std.base64.standard.Decoder; 591 const blob_len = decoder.calcSizeForSlice(blob_b64) catch return null; 592 var blob_buf: [4096]u8 = undefined; 593 if (blob_len > blob_buf.len) return null; 594 decoder.decode(blob_buf[0..blob_len], blob_b64) catch return null; 595 596 return ssh.formatFingerprint(blob_buf[0..blob_len]); 597 } 598 599 fn writeError(sess: *ssh.SessionCtx, comptime msg: []const u8) !void { 600 const body = "ERR haxy ssh: " ++ msg; 601 var packet: [body.len + 4]u8 = undefined; 602 const line = try std.fmt.bufPrint(&packet, "{x:0>4}{s}", .{ packet.len, body }); 603 try sess.writeBytes(line); 604 try sess.exit(1); 605 } 606 607 test "parseGitCommand rejects malformed input" { 608 const allocator = std.testing.allocator; 609 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 610 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 611 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 612 } 613 614 test "parseGitCommand happy paths" { 615 const allocator = std.testing.allocator; 616 617 { 618 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 619 defer parsed.deinit(allocator); 620 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 621 try std.testing.expectEqualStrings("some-repo", parsed.dir); 622 } 623 { 624 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 625 defer parsed.deinit(allocator); 626 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 627 try std.testing.expectEqualStrings("user/proj", parsed.dir); 628 } 629 { 630 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 631 defer parsed.deinit(allocator); 632 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 633 try std.testing.expectEqualStrings("repo", parsed.dir); 634 } 635 } 636