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