╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh.zig ────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
270 } 271 } 272 273 if (ui_session.host_request) |request| { 274 ui_session.host_request = null; 275 switch (request) { 276 .show_copyable_text => |copyable_text| { 277 if (terminal_maybe) |*terminal| terminal.deinit(); 278 terminal_maybe = null; 279 try session_writer.interface.print("\x1b[2J\x1b[Hcopy the following text and then press enter to go back:\r\n\r\n{s}\r\n", .{copyable_text}); 280 try session_writer.interface.flush(); 281 continue; 282 }, 283 .sync_events => {}, 284 } 285 } 286 287 try ui_session.applyAndWritePending(io, allocator, &repo); 288 289 // pick up data written by other handles so the next navigation 290 // builds its page from a current moment 291 try ui_session.reloadMoment(allocator, &repo); 292 293 // reconcile navigation: forward to a new page, or back on escape 294 try nav.sync(allocator, &ui_session); 295 296 // the quit button (on the quit tab) asks the host to tear down 297 if (ui_session.quit_requested) break :event_loop; 298 299 try nav.root.build(allocator, .{ 300 .min_size = .{ .width = null, .height = null }, 301 .max_size = .{ .width = last_size.width, .height = last_size.height }, 302 }, nav.root.getFocus()); 303 if (terminal_maybe) |*terminal| _ = try terminal.render(&nav.root, &last_grid, &last_size); 304 } 305 } 306 307 // --------------------------------------------------------------------------- 308 // git path (exec) 309 // --------------------------------------------------------------------------- 310 311 pub const GitService = enum { upload_pack, receive_pack }; 312 313 pub const ParsedGitCommand = struct { 314 service: GitService, 315 dir: []u8, 316 317 pub fn deinit(self: ParsedGitCommand, allocator: std.mem.Allocator) void { 318 allocator.free(self.dir); 319 } 320 }; 321 322 fn runGitSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, command: []const u8) !void { 323 const allocator = sess.conn.allocator; 324 const io = sess.conn.io; 325 326 const parsed = parseGitCommand(allocator, command) catch return writeError(sess, "unsupported command (expected git-upload-pack or git-receive-pack)"); 327 defer parsed.deinit(allocator); 328 const repo_prefix = "/repo/"; 329 const repo_identity = if (std.mem.startsWith(u8, parsed.dir, repo_prefix)) parsed.dir[repo_prefix.len..] else parsed.dir; 330 331 const create_if_missing = parsed.service == .receive_pack; 332 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{}; 333 334 // authenticate pushes: the authenticated key must be registered to the 335 // repo's owner. 336 if (create_if_missing) { 337 const owner_repo = evt.parseOwnerRepoPath(repo_identity) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 338 if (builtin.mode != .Debug and !try isKeyAuthorized(io, allocator, handler.admin_repo_path, owner_repo.owner, &sess.fingerprint)) 339 return writeError(sess, "unauthorized: this SSH key is not registered to the repo owner"); 340 } 341 342 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, handler.repo_root_path, handler.admin_repo_path, repo_identity, create_if_missing)) { 343 .ok => |p| p, 344 .invalid => return writeError(sess, "repo path must be <owner>/<repo>"), 345 .not_found => return writeError(sess, "repo not found"), 346 }; 347 defer allocator.free(repo_path); 348 349 if (try serveIfExists(repo_path, sess, io, allocator, parsed.service)) { 350 try sess.exit(0); 351 return; 352 } 353 354 if (!create_if_missing) return writeError(sess, "repo not found"); 355 356 // create the on-disk repo for the just-minted event and serve the push 357 var repo = try createRepo(any_repo_opts.toRepoOpts(), io, allocator, repo_path); 358 defer repo.deinit(io, allocator); 359 try servePack(repo.self_repo_opts, &repo, sess, io, allocator, parsed.service); 360 try sess.exit(0); 361 } 362 363 // serve an existing repo at `repo_path`, or return false if none is there 364 fn serveIfExists( 365 repo_path: []const u8, 366 sess: *ssh.SessionCtx, 367 io: std.Io, 368 allocator: std.mem.Allocator, 369 service: GitService, 370 ) !bool { 371 // a bare open() creates the directory while probing for the repo, so only 372 // attempt it when the path already exists 373 std.Io.Dir.accessAbsolute(io, repo_path, .{}) catch return false; 374 375 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{}; 376 var any_repo = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 377 error.RepoNotFound => return false, 378 else => |e| return e, 379 }; 380 defer any_repo.deinit(io, allocator); 381 382 switch (any_repo) { 383 inline else => |*repo| try servePack(repo.self_repo_opts, repo, sess, io, allocator, service), 384 } 385 return true; 386 } 387 388 fn createRepo( 389 comptime repo_opts: rp.RepoOpts(.xit), 390 io: std.Io, 391 allocator: std.mem.Allocator, 392 repo_path: []const u8, 393 ) !rp.Repo(.xit, repo_opts) { 394 var repo = try rp.Repo(.xit, repo_opts).init(io, allocator, .{ .path = repo_path }); 395 errdefer repo.deinit(io, allocator); 396 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 397 try repo.addConfig(io, allocator, .{ .name = "receive.denycurrentbranch", .value = "updateinstead" }); 398 return repo; 399 } 400 401 // wrap the channel I/O in std.Io.Reader/Writer adapters so the repo's pack 402 // functions can consume them like any other stream, then run the requested 403 // service 404 fn servePack( 405 comptime repo_opts: rp.RepoOpts(.xit), 406 repo: *rp.Repo(.xit, repo_opts), 407 sess: *ssh.SessionCtx, 408 io: std.Io, 409 allocator: std.mem.Allocator, 410 service: GitService, 411 ) !void { 412 var session_reader_buf: [4096]u8 = undefined; 413 var session_writer_buf: [4096]u8 = undefined; 414 var session_reader = ssh.SessionReader.init(sess, &session_reader_buf); 415 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 416 417 switch (service) { 418 .upload_pack => try repo.uploadPack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 419 .receive_pack => try evt.receivePackAndConsume(repo_opts, io, allocator, repo, &session_reader.interface, &session_writer.interface, .{}), 420 } 421 422 // flush whatever the pack op buffered into our writer adapter 423 session_writer.interface.flush() catch {}; 424 } 425 426 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 427 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 428 defer tokens.deinit(); 429 430 const service_token = tokens.next() orelse return error.InvalidCommand; 431 const dir_token = tokens.next() orelse return error.InvalidCommand; 432 433 const service: GitService = 434 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 435 .upload_pack 436 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 437 .receive_pack 438 else 439 return error.UnsupportedService; 440 441 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 442 } 443 444 // true if `fingerprint` matches one of the named user's registered SSH keys 445 fn isKeyAuthorized( 446 io: std.Io, 447 allocator: std.mem.Allocator, 448 admin_repo_path: []const u8, 449 owner_name: []const u8, 450 fingerprint: *const [ssh.fingerprint_len]u8, 451 ) !bool { 452 var arena = std.heap.ArenaAllocator.init(allocator); 453 defer arena.deinit(); 454 455 const user = (try evt.User.readByName(io, allocator, admin_repo_path, &arena, owner_name)) orelse return false; 456 457 var it = std.mem.splitScalar(u8, user.event.ssh_keys, '\n'); 458 while (it.next()) |line| { 459 const fp = fingerprintOfAuthorizedKey(line) orelse continue; 460 if (std.mem.eql(u8, &fp, fingerprint)) return true; 461 } 462 return false; 463 } 464 465 // the SHA256 fingerprint of one authorized_keys line, or null if the line is 466 // blank or not a parseable "<type> <base64> [comment]" entry 467 fn fingerprintOfAuthorizedKey(line: []const u8) ?[ssh.fingerprint_len]u8 { 468 var it = std.mem.tokenizeAny(u8, line, " \t\r"); 469 _ = it.next() orelse return null; // key type 470 const blob_b64 = it.next() orelse return null; 471 472 const decoder = std.base64.standard.Decoder; 473 const blob_len = decoder.calcSizeForSlice(blob_b64) catch return null; 474 var blob_buf: [4096]u8 = undefined; 475 if (blob_len > blob_buf.len) return null; 476 decoder.decode(blob_buf[0..blob_len], blob_b64) catch return null; 477 478 return ssh.formatFingerprint(blob_buf[0..blob_len]); 479 } 480 481 fn writeError(sess: *ssh.SessionCtx, comptime msg: []const u8) !void { 482 const body = "ERR haxy ssh: " ++ msg; 483 var packet: [body.len + 4]u8 = undefined; 484 const line = try std.fmt.bufPrint(&packet, "{x:0>4}{s}", .{ packet.len, body }); 485 try sess.writeBytes(line); 486 try sess.exit(1); 487 } 488 489 test "parseGitCommand rejects malformed input" { 490 const allocator = std.testing.allocator; 491 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 492 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 493 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 494 } 495 496 test "parseGitCommand happy paths" { 497 const allocator = std.testing.allocator; 498 499 { 500 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 501 defer parsed.deinit(allocator); 502 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 503 try std.testing.expectEqualStrings("some-repo", parsed.dir); 504 } 505 { 506 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 507 defer parsed.deinit(allocator); 508 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 509 try std.testing.expectEqualStrings("user/proj", parsed.dir); 510 } 511 { 512 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 513 defer parsed.deinit(allocator); 514 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 515 try std.testing.expectEqualStrings("repo", parsed.dir); 516 } 517 } 518