╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh.zig ────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
164 // runTui owns the terminal, whose deinit restores the client's screen and 165 // runs as the function unwinds — so any error it returns leaves the TUI torn 166 // down and we can surface the failure on the restored screen before exiting. 167 runTui(handler, sess, pty) catch |err| { 168 serve_common.logError(sess.conn.io, handler.err, "ssh tui session failed: {s}\n", .{@errorName(err)}); 169 var buf: [256]u8 = undefined; 170 const msg = std.fmt.bufPrint(&buf, "haxy ssh: {s}\r\n", .{@errorName(err)}) catch "haxy ssh: internal error\r\n"; 171 sess.writeBytes(msg) catch {}; 172 try sess.exit(1); 173 return; 174 }; 175 try sess.exit(0); 176 } 177 178 fn runTui(handler: *const SessionHandler, sess: *ssh.SessionCtx, pty: ssh.PtySize) !void { 179 const allocator = sess.conn.allocator; 180 const io = sess.conn.io; 181 182 // some clients (notably scripted ssh with no local controlling tty) 183 // allocate a pty without ever sending a non-zero size. fall back to a 184 // conventional 80x24 in that case so render emits something. 185 const effective_pty = ssh.PtySize{ 186 .width_cells = if (pty.width_cells == 0) 80 else pty.width_cells, 187 .height_cells = if (pty.height_cells == 0) 24 else pty.height_cells, 188 }; 189 190 // session-lifetime allocations (login, prefs); Nav owns the per-page arenas. 191 var session_arena = std.heap.ArenaAllocator.init(allocator); 192 defer session_arena.deinit(); 193 194 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 195 var repo = try Repo.open(io, allocator, .{ .path = handler.admin_repo_path }); 196 defer repo.deinit(io, allocator); 197 var ui_session = try ui.Session.init(&session_arena, &repo, .{}); 198 ui_session.is_terminal = true; 199 ui_session.web_port = handler.wui_port; 200 ui_session.data.git_http_port = handler.git_http_port; 201 ui_session.data.git_ssh_port = handler.git_ssh_port; 202 ui_session.data.git_ssh_prefix = handler.git_ssh_prefix; 203 // let page builders open on-disk repos (sibling "repos" dir of the admin repo) 204 ui_session.io = io; 205 ui_session.repos_dir = try std.fs.path.join(session_arena.allocator(), &.{ std.fs.path.dirname(handler.admin_repo_path) orelse ".", "repos" }); 206 207 var nav = try ui.Nav.init(allocator, &ui_session); 208 defer nav.deinit(allocator); 209 210 var session_writer_buf: [8192]u8 = undefined; 211 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 212 213 // the terminal's deinit writes leave-alt / show-cursor / disable-mouse and 214 // flushes, restoring the client's screen. as a function-scoped defer it runs 215 // before runTui returns — on the normal path and on any error — so the 216 // caller can write to the client afterward (and sess.exit can close cleanly). 217 var terminal_size = Size{ 218 .width = effective_pty.width_cells, 219 .height = effective_pty.height_cells, 220 }; 221 var terminal_maybe: ?StreamTerminal = try StreamTerminal.init(allocator, &session_writer.interface, terminal_size); 222 defer if (terminal_maybe) |*terminal| terminal.deinit(); 223 224 // initial render — user sees the page immediately 225 if (terminal_maybe) |*terminal| _ = try terminal.render(&nav.root); 226 227 // event loop. nextEvent blocks until something interesting arrives; 228 // for each event, rebuild the widget tree and re-render so the user 229 // sees the effect of their input on the same iteration. 230 event_loop: while (true) { 231 const event = try sess.nextEvent(); 232 if (terminal_maybe) |*terminal| { 233 switch (event) { 234 .data => |payload| { 235 defer allocator.free(payload); 236 try terminal.writeBytes(payload); 237 while (terminal.popKey()) |key| { 238 try ui.inputKey(allocator, &nav.root, key, &ui_session); 239 } 240 }, 241 .resize => |sz| { 242 terminal_size = .{ .width = sz.width_cells, .height = sz.height_cells }; 243 terminal.pushResize(terminal_size); 244 while (terminal.popKey()) |key| { 245 try ui.inputKey(allocator, &nav.root, key, &ui_session); 246 } 247 }, 248 .eof, .close => break :event_loop, 249 } 250 } else { 251 switch (event) { 252 .data => |payload| { 253 defer allocator.free(payload); 254 if (std.mem.indexOfAny(u8, payload, "\r\n") == null) continue; 255 terminal_maybe = try StreamTerminal.init(allocator, &session_writer.interface, terminal_size); 256 }, 257 .resize => |sz| { 258 terminal_size = .{ .width = sz.width_cells, .height = sz.height_cells }; 259 continue; 260 }, 261 .eof, .close => break :event_loop, 262 } 263 } 264 265 if (ui_session.host_request) |request| { 266 ui_session.host_request = null; 267 switch (request) { 268 .show_copyable_text => |copyable_text| { 269 if (terminal_maybe) |*terminal| terminal.deinit(); 270 terminal_maybe = null; 271 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}); 272 try session_writer.interface.flush(); 273 continue; 274 }, 275 .sync_events => {}, 276 } 277 } 278 279 try ui_session.applyAndWritePending(io, allocator, &repo); 280 281 // pick up data written by other handles so the next navigation 282 // builds its page from a current moment 283 try ui_session.reloadMoment(allocator, &repo); 284 285 // reconcile navigation: forward to a new page, or back on escape 286 try nav.sync(allocator, &ui_session); 287 288 // the quit button (on the quit tab) asks the host to tear down 289 if (ui_session.quit_requested) break :event_loop; 290 291 try nav.root.build(allocator, .{ 292 .min_size = .{ .width = null, .height = null }, 293 .max_size = .{ .width = terminal_size.width, .height = terminal_size.height }, 294 }, nav.root.getFocus()); 295 if (terminal_maybe) |*terminal| _ = try terminal.render(&nav.root); 296 } 297 } 298 299 // --------------------------------------------------------------------------- 300 // git path (exec) 301 // --------------------------------------------------------------------------- 302 303 pub const GitService = enum { upload_pack, receive_pack }; 304 305 pub const ParsedGitCommand = struct { 306 service: GitService, 307 dir: []u8, 308 309 pub fn deinit(self: ParsedGitCommand, allocator: std.mem.Allocator) void { 310 allocator.free(self.dir); 311 } 312 }; 313 314 fn runGitSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, command: []const u8) !void { 315 const allocator = sess.conn.allocator; 316 const io = sess.conn.io; 317 318 const parsed = parseGitCommand(allocator, command) catch return writeError(sess, "unsupported command (expected git-upload-pack or git-receive-pack)"); 319 defer parsed.deinit(allocator); 320 const path = std.mem.trimStart(u8, parsed.dir, "/"); 321 const fork_prefix = "fork/"; 322 323 if (std.mem.startsWith(u8, path, fork_prefix)) { 324 const route = fork.parseRoute(path[fork_prefix.len..]) orelse return writeError(sess, "invalid fork path"); 325 const owner_repo = evt.parseOwnerRepoPath(route.identity) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 326 327 var admin = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = handler.admin_repo_path }); 328 defer admin.deinit(io, allocator); 329 var admin_arena = std.heap.ArenaAllocator.init(allocator); 330 defer admin_arena.deinit(); 331 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 332 const fork_id = try evt.parseEventId(&route.id); 333 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, &fork_id)) orelse 334 return writeError(sess, "patch draft not found"); 335 if (fork_record.removed) return writeError(sess, "patch draft not found"); 336 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, fork_record.event.user_id)) orelse 337 return writeError(sess, "invalid patch draft"); 338 if (user.removed) return writeError(sess, "invalid patch draft"); 339 if (parsed.service == .receive_pack and !isKeyInAuthorizedKeys(user.event.ssh_keys, &sess.fingerprint)) 340 return writeError(sess, "unauthorized: this SSH key is not registered to the patch author"); 341 342 const draft_path = try fork.forkPath(allocator, handler.repo_root_path, &route.id); 343 defer allocator.free(draft_path); 344 var draft = rp.AnyRepo(.xit, .{}).open(io, allocator, .{ .path = draft_path }) catch 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