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