╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh.zig ────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
210 const io = sess.conn.io; 211 212 // some clients (notably scripted ssh with no local controlling tty) 213 // allocate a pty without ever sending a non-zero size. fall back to a 214 // conventional 80x24 in that case so render emits something. 215 const effective_pty = ssh.PtySize{ 216 .width_cells = if (pty.width_cells == 0) 80 else pty.width_cells, 217 .height_cells = if (pty.height_cells == 0) 24 else pty.height_cells, 218 }; 219 220 // session-lifetime allocations (login, prefs); Nav owns the per-page arenas. 221 var session_arena = std.heap.ArenaAllocator.init(allocator); 222 defer session_arena.deinit(); 223 224 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 225 var repo = try Repo.open(io, allocator, .{ .path = handler.admin_repo_path }); 226 defer repo.deinit(io, allocator); 227 var ui_session = try ui.Session.init(&session_arena, &repo, .{}); 228 ui_session.is_terminal = true; 229 ui_session.web_port = handler.wui_port; 230 ui_session.data.git_http_port = handler.git_http_port; 231 ui_session.data.git_ssh_port = handler.git_ssh_port; 232 ui_session.data.git_ssh_prefix = handler.git_ssh_prefix; 233 // let page builders open on-disk repos (sibling "repos" dir of the admin repo) 234 ui_session.io = io; 235 ui_session.repos_dir = try std.fs.path.join(session_arena.allocator(), &.{ std.fs.path.dirname(handler.admin_repo_path) orelse ".", "repos" }); 236 237 var nav = try ui.Nav.init(allocator, &ui_session); 238 defer nav.deinit(allocator); 239 240 var session_writer_buf: [8192]u8 = undefined; 241 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 242 243 // the terminal's deinit writes leave-alt / show-cursor / disable-mouse and 244 // flushes, restoring the client's screen. as a function-scoped defer it runs 245 // before runTui returns — on the normal path and on any error — so the 246 // caller can write to the client afterward (and sess.exit can close cleanly). 247 var terminal_size = Size{ 248 .width = effective_pty.width_cells, 249 .height = effective_pty.height_cells, 250 }; 251 var terminal_maybe: ?StreamTerminal = try StreamTerminal.init(allocator, &session_writer.interface, terminal_size); 252 defer if (terminal_maybe) |*terminal| terminal.deinit(); 253 254 // initial render — user sees the page immediately 255 if (terminal_maybe) |*terminal| _ = try terminal.render(&nav.root); 256 257 // event loop. nextEvent blocks until something interesting arrives; 258 // for each event, rebuild the widget tree and re-render so the user 259 // sees the effect of their input on the same iteration. 260 event_loop: while (true) { 261 const event = try nextTuiEvent(sess, if (terminal_maybe) |*terminal| terminal else null); 262 if (terminal_maybe) |*terminal| { 263 if (event) |ev| switch (ev) { 264 .data => |payload| { 265 defer allocator.free(payload); 266 try terminal.writeBytes(payload); 267 }, 268 .resize => |sz| { 269 terminal_size = .{ .width = sz.width_cells, .height = sz.height_cells }; 270 terminal.pushResize(terminal_size); 271 }, 272 .eof, .close => break :event_loop, 273 }; 274 while (terminal.popKey()) |key| { 275 try ui.inputKey(allocator, &nav.root, key, &ui_session); 276 } 277 } else { 278 switch (event orelse unreachable) { 279 .data => |payload| { 280 defer allocator.free(payload); 281 if (std.mem.indexOfAny(u8, payload, "\r\n") == null) continue; 282 terminal_maybe = try StreamTerminal.init(allocator, &session_writer.interface, terminal_size); 283 }, 284 .resize => |sz| { 285 terminal_size = .{ .width = sz.width_cells, .height = sz.height_cells }; 286 continue; 287 }, 288 .eof, .close => break :event_loop, 289 } 290 } 291 292 if (ui_session.host_request) |request| { 293 ui_session.host_request = null; 294 switch (request) { 295 .show_copyable_text => |copyable_text| { 296 if (terminal_maybe) |*terminal| terminal.deinit(); 297 terminal_maybe = null; 298 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}); 299 try session_writer.interface.flush(); 300 continue; 301 }, 302 .sync_events => {}, 303 } 304 } 305 306 try ui_session.applyAndWritePending(io, allocator, &repo); 307 308 // pick up data written by other handles so the next navigation 309 // builds its page from a current moment 310 try ui_session.reloadMoment(allocator, &repo); 311 312 // reconcile navigation: forward to a new page, or back on escape 313 try nav.sync(allocator, &ui_session); 314 315 // the quit button (on the quit tab) asks the host to tear down 316 if (ui_session.quit_requested) break :event_loop; 317 318 try nav.root.build(allocator, .{ 319 .min_size = .{ .width = null, .height = null }, 320 .max_size = .{ .width = terminal_size.width, .height = terminal_size.height }, 321 }, nav.root.getFocus()); 322 if (terminal_maybe) |*terminal| _ = try terminal.render(&nav.root); 323 } 324 } 325 326 // only a lone ESC needs a deadline; longer CSI/SS3 fragments must remain 327 // buffered until complete. a timeout leaves partial SSH packets in the reader. 328 pub fn nextTuiEvent(sess: *ssh.SessionCtx, terminal: ?*StreamTerminal) !?ssh.Event { 329 if (terminal) |t| { 330 if (t.parser.esc_len == 1) { 331 sess.conn.read_timeout = escape_timeout.toDeadline(sess.conn.io); 332 defer sess.conn.read_timeout = .none; 333 return sess.nextEvent() catch |err| switch (err) { 334 error.Timeout => { 335 try t.flushEscape(); 336 return null; 337 }, 338 else => return err, 339 }; 340 } 341 } 342 return try sess.nextEvent(); 343 } 344 345 // --------------------------------------------------------------------------- 346 // git path (exec) 347 // --------------------------------------------------------------------------- 348 349 pub const GitService = enum { upload_pack, receive_pack }; 350 351 pub const ParsedGitCommand = struct { 352 service: GitService, 353 dir: []u8, 354 355 pub fn deinit(self: ParsedGitCommand, allocator: std.mem.Allocator) void { 356 allocator.free(self.dir); 357 } 358 }; 359 360 fn runGitSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, command: []const u8) !void { 361 const allocator = sess.conn.allocator; 362 const io = sess.conn.io; 363 364 const parsed = parseGitCommand(allocator, command) catch return writeError(sess, "unsupported command (expected git-upload-pack or git-receive-pack)"); 365 defer parsed.deinit(allocator); 366 const path = std.mem.trimStart(u8, parsed.dir, "/"); 367 const fork_prefix = "fork/"; 368 369 if (std.mem.startsWith(u8, path, fork_prefix)) { 370 const route = fork.parseRoute(path[fork_prefix.len..]) orelse return writeError(sess, "invalid fork path"); 371 const owner_repo = evt.parseOwnerRepoPath(route.identity) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 372 373 var admin = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = handler.admin_repo_path }); 374 defer admin.deinit(io, allocator); 375 var admin_arena = std.heap.ArenaAllocator.init(allocator); 376 defer admin_arena.deinit(); 377 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 378 const fork_id = try evt.parseEventId(&route.id); 379 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, &fork_id)) orelse 380 return writeError(sess, "patch draft not found"); 381 if (fork_record.removed) return writeError(sess, "patch draft not found"); 382 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, fork_record.event.user_id)) orelse 383 return writeError(sess, "invalid patch draft"); 384 if (user.removed) return writeError(sess, "invalid patch draft"); 385 if (parsed.service == .receive_pack and !isKeyInAuthorizedKeys(user.event.ssh_keys, &sess.fingerprint)) 386 return writeError(sess, "unauthorized: this SSH key is not registered to the patch author"); 387 388 const draft_path = try fork.forkPath(allocator, handler.repo_root_path, &route.id); 389 defer allocator.free(draft_path); 390 var draft = rp.AnyRepo(.xit, .{ .ProgressCtx = *push.PushProgress }).open(io, allocator, .{ .path = draft_path }) catch 391 return writeError(sess, "patch draft not found"); 392 defer draft.deinit(io, allocator); 393 var reader_buf: [4096]u8 = undefined; 394 var writer_buf: [4096]u8 = undefined; 395 var reader = ssh.SessionReader.init(sess, &reader_buf); 396 var writer = ssh.SessionWriter.init(sess, &writer_buf); 397 if (parsed.service == .upload_pack) { 398 switch (draft) { 399 inline else => |*repo| try repo.uploadPack(io, allocator, &reader.interface, &writer.interface, .{}), 400 } 401 } else { 402 const target = (try evt.Repo.readByOwnerAndName(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, owner_repo.owner, owner_repo.name)) orelse 403 return writeError(sess, "repo not found"); 404 if (!std.mem.eql(u8, fork_record.event.repo_id, &target.event_id)) return writeError(sess, "patch draft belongs to another repo"); 405 const target_id = std.fmt.bytesToHex(target.event_id, .lower); 406 const target_path = try std.fs.path.join(allocator, &.{ handler.repo_root_path, &target_id }); 407 defer allocator.free(target_path); 408 const author: evt.CommitAuthor = .{ .name = user.event.name, .email = user.event.email }; 409 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 410 switch (draft) { 411 inline else => |*repo| { 412 var target_repo = rp.Repo(.xit, repo.self_repo_opts).open(io, allocator, .{ .path = target_path }) catch 413 return writeError(sess, "repo not found or has the wrong hash"); 414 defer target_repo.deinit(io, allocator); 415 try push.receiveFork(repo.self_repo_opts, io, allocator, repo, &target_repo, &route.id, author, timestamp, &reader.interface, &writer.interface, handler.err); 416 }, 417 } 418 } 419 writer.interface.flush() catch {}; 420 try sess.exit(0); 421 return; 422 } 423 424 const repo_prefix = "repo/"; 425 const repo_identity = if (std.mem.startsWith(u8, path, repo_prefix)) path[repo_prefix.len..] else path; 426 427 const create_if_missing = parsed.service == .receive_pack; 428 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{ .ProgressCtx = *push.PushProgress }; 429 430 const owner_repo = evt.parseOwnerRepoPath(repo_identity) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 431 switch (try authorizeRepoKey(io, allocator, handler.admin_repo_path, owner_repo.owner, owner_repo.name, parsed.service, &sess.fingerprint)) { 432 .allowed => {}, 433 .denied => return switch (parsed.service) { 434 .upload_pack => writeError(sess, "unauthorized: this SSH key cannot read this repo"), 435 .receive_pack => writeError(sess, "unauthorized: this SSH key cannot push to this repo"), 436 }, 437 .not_found => return writeError(sess, "repo not found"), 438 } 439 440 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, handler.repo_root_path, handler.admin_repo_path, repo_identity, create_if_missing)) { 441 .ok => |p| p, 442 .invalid => return writeError(sess, "repo path must be <owner>/<repo>"), 443 .not_found => return writeError(sess, "repo not found"), 444 }; 445 defer allocator.free(repo_path); 446 447 if (try serveIfExists(repo_path, handler.repo_root_path, sess, io, allocator, parsed.service, handler.err)) { 448 try sess.exit(0); 449 return; 450 } 451 452 if (!create_if_missing) return writeError(sess, "repo not found"); 453 454 // create the on-disk repo for the just-minted event and serve the push 455 var repo = try createRepo(any_repo_opts.toRepoOpts(), io, allocator, repo_path); 456 defer repo.deinit(io, allocator); 457 try servePack(repo.self_repo_opts, &repo, handler.repo_root_path, sess, io, allocator, parsed.service, handler.err); 458 try sess.exit(0); 459 } 460 461 // serve an existing repo at `repo_path`, or return false if none is there 462 fn serveIfExists( 463 repo_path: []const u8, 464 repo_root_path: []const u8, 465 sess: *ssh.SessionCtx, 466 io: std.Io, 467 allocator: std.mem.Allocator, 468 service: GitService, 469 error_writer: *std.Io.Writer, 470 ) !bool { 471 // a bare open() creates the directory while probing for the repo, so only 472 // attempt it when the path already exists 473 std.Io.Dir.accessAbsolute(io, repo_path, .{}) catch return false; 474 475 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{ .ProgressCtx = *push.PushProgress }; 476 var any_repo = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 477 error.RepoNotFound => return false, 478 else => |e| return e, 479 }; 480 defer any_repo.deinit(io, allocator); 481 482 switch (any_repo) { 483 inline else => |*repo| try servePack(repo.self_repo_opts, repo, repo_root_path, sess, io, allocator, service, error_writer), 484 } 485 return true; 486 } 487 488 fn createRepo( 489 comptime repo_opts: rp.RepoOpts(.xit), 490 io: std.Io, 491 allocator: std.mem.Allocator, 492 repo_path: []const u8, 493 ) !rp.Repo(.xit, repo_opts) { 494 var repo = try rp.Repo(.xit, repo_opts).init(io, allocator, .{ .path = repo_path, .bare = true }); 495 errdefer repo.deinit(io, allocator); 496 try repo.setMergeAlgorithm(io, allocator, .patch); 497 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 498 return repo; 499 } 500 501 // wrap the channel I/O in std.Io.Reader/Writer adapters so the repo's pack 502 // functions can consume them like any other stream, then run the requested 503 // service 504 fn servePack( 505 comptime repo_opts: rp.RepoOpts(.xit), 506 repo: *rp.Repo(.xit, repo_opts), 507 repo_root_path: []const u8, 508 sess: *ssh.SessionCtx, 509 io: std.Io, 510 allocator: std.mem.Allocator, 511 service: GitService, 512 error_writer: *std.Io.Writer, 513 ) !void { 514 var session_reader_buf: [4096]u8 = undefined; 515 var session_writer_buf: [4096]u8 = undefined; 516 var session_reader = ssh.SessionReader.init(sess, &session_reader_buf); 517 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 518 519 switch (service) { 520 .upload_pack => try repo.uploadPack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 521 .receive_pack => try push.receivePackAndConsume(repo_opts, io, allocator, repo, &session_reader.interface, &session_writer.interface, .{}, repo_root_path, error_writer), 522 } 523 524 // flush whatever the pack op buffered into our writer adapter 525 session_writer.interface.flush() catch {}; 526 } 527 528 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 529 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 530 defer tokens.deinit(); 531 532 const service_token = tokens.next() orelse return error.InvalidCommand; 533 const dir_token = tokens.next() orelse return error.InvalidCommand; 534 535 const service: GitService = 536 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 537 .upload_pack 538 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 539 .receive_pack 540 else 541 return error.UnsupportedService; 542 543 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 544 } 545 546 const RepoAuthorization = enum { allowed, denied, not_found }; 547 548 fn authorizeRepoKey( 549 io: std.Io, 550 allocator: std.mem.Allocator, 551 admin_repo_path: []const u8, 552 owner_name: []const u8, 553 repo_name: []const u8, 554 service: GitService, 555 fingerprint: *const [ssh.fingerprint_len]u8, 556 ) !RepoAuthorization { 557 var arena = std.heap.ArenaAllocator.init(allocator); 558 defer arena.deinit(); 559 560 var admin = rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 561 error.RepoNotFound => return .not_found, 562 else => |e| return e, 563 }; 564 defer admin.deinit(io, allocator); 565 566 const moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 567 const repo = (try evt.Repo.readByOwnerAndName(evt.AdminDB, evt.admin_repo_opts.hash, moment, &arena, owner_name, repo_name)) orelse { 568 if (service == .upload_pack) return .not_found; 569 const owner = (try evt.User.readByName(io, allocator, admin_repo_path, &arena, owner_name)) orelse return .not_found; 570 return if (isKeyInAuthorizedKeys(owner.event.ssh_keys, fingerprint)) .allowed else .denied; 571 }; 572 573 if ((service == .upload_pack and repo.repo.event.read_access == .public) or 574 (service == .receive_pack and repo.repo.event.write_access == .public)) return .allowed; 575 if (try keyBelongsToUser(moment, &arena, repo.repo.event.user_id, fingerprint)) return .allowed; 576 577 const user_id_lists: []const []const u8 = switch (service) { 578 .upload_pack => &.{ repo.repo.event.write_user_ids, repo.repo.event.read_user_ids }, 579 .receive_pack => &.{repo.repo.event.write_user_ids}, 580 }; 581 for (user_id_lists) |user_ids| { 582 var lines = std.mem.tokenizeScalar(u8, user_ids, '\n'); 583 while (lines.next()) |id| { 584 const user_id = try evt.parseEventId(id); 585 if (try keyBelongsToUser(moment, &arena, &user_id, fingerprint)) return .allowed; 586 } 587 } 588 return .denied; 589 } 590 591 fn keyBelongsToUser( 592 moment: evt.AdminDB.HashMap(.read_only), 593 arena: *std.heap.ArenaAllocator, 594 user_id: []const u8, 595 fingerprint: *const [ssh.fingerprint_len]u8, 596 ) !bool { 597 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, user_id)) orelse return false; 598 return !user.removed and isKeyInAuthorizedKeys(user.event.ssh_keys, fingerprint); 599 } 600 601 fn isKeyInAuthorizedKeys(ssh_keys: []const u8, fingerprint: *const [ssh.fingerprint_len]u8) bool { 602 var it = std.mem.splitScalar(u8, ssh_keys, '\n'); 603 while (it.next()) |line| { 604 const fp = fingerprintOfAuthorizedKey(line) orelse continue; 605 if (std.mem.eql(u8, &fp, fingerprint)) return true; 606 } 607 return false; 608 } 609 610 // the SHA256 fingerprint of one authorized_keys line, or null if the line is 611 // blank or not a parseable "<type> <base64> [comment]" entry 612 fn fingerprintOfAuthorizedKey(line: []const u8) ?[ssh.fingerprint_len]u8 { 613 var it = std.mem.tokenizeAny(u8, line, " \t\r"); 614 _ = it.next() orelse return null; // key type 615 const blob_b64 = it.next() orelse return null; 616 617 const decoder = std.base64.standard.Decoder; 618 const blob_len = decoder.calcSizeForSlice(blob_b64) catch return null; 619 var blob_buf: [4096]u8 = undefined; 620 if (blob_len > blob_buf.len) return null; 621 decoder.decode(blob_buf[0..blob_len], blob_b64) catch return null; 622 623 return ssh.formatFingerprint(blob_buf[0..blob_len]); 624 } 625 626 fn writeError(sess: *ssh.SessionCtx, comptime msg: []const u8) !void { 627 const body = "ERR haxy ssh: " ++ msg; 628 var packet: [body.len + 4]u8 = undefined; 629 const line = try std.fmt.bufPrint(&packet, "{x:0>4}{s}", .{ packet.len, body }); 630 try sess.writeBytes(line); 631 try sess.exit(1); 632 } 633 634 test "parseGitCommand rejects malformed input" { 635 const allocator = std.testing.allocator; 636 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 637 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 638 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 639 } 640 641 test "parseGitCommand happy paths" { 642 const allocator = std.testing.allocator; 643 644 { 645 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 646 defer parsed.deinit(allocator); 647 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 648 try std.testing.expectEqualStrings("some-repo", parsed.dir); 649 } 650 { 651 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 652 defer parsed.deinit(allocator); 653 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 654 try std.testing.expectEqualStrings("user/proj", parsed.dir); 655 } 656 { 657 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 658 defer parsed.deinit(allocator); 659 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 660 try std.testing.expectEqualStrings("repo", parsed.dir); 661 } 662 } 663