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