╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh.zig ────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
85 defer _ = active_connections.fetchSub(1, .acq_rel); 86 if (prev_count >= max_connections) { 87 serve_common.logError(ctx.io, ctx.err, "ssh: connection limit reached, dropping\n", .{}); 88 return; 89 } 90 91 var connection = Watchdog.Connection{ .stream = &stream }; 92 ctx.watchdog.add(ctx.io, &connection); 93 defer ctx.watchdog.remove(ctx.io, &connection); 94 95 // timed peeks need room for a complete encrypted packet 96 var recv_buf: [ssh.packet_buffer_size]u8 = undefined; 97 var send_buf: [4096]u8 = undefined; 98 var stream_reader = stream.reader(ctx.io, &recv_buf); 99 var stream_writer = stream.writer(ctx.io, &send_buf); 100 ssh.handleConnection( 101 ctx.io, 102 ctx.allocator, 103 &stream_reader.interface, 104 &stream_writer.interface, 105 ctx.host_key, 106 &connection.idle_state, 107 ctx.session_handler, 108 ) catch |session_err| { 109 serve_common.logError(ctx.io, ctx.err, "ssh session failed: {s}\n", .{@errorName(session_err)}); 110 }; 111 } 112 }.h; 113 114 // without the watchdog nothing bounds a connection, so don't listen 115 tasks.concurrent(io, Watchdog.run, .{ watchdog, io }) catch |spawn_err| { 116 serve_common.logError(io, err, "ssh: watchdog spawn failed: {s}\n", .{@errorName(spawn_err)}); 117 return; 118 }; 119 120 serve_common.runListener(io, net_server, tasks, err, "ssh", Context{ 121 .io = io, 122 .allocator = allocator, 123 .host_key = host_key, 124 .session_handler = session_handler, 125 .watchdog = watchdog, 126 .err = err, 127 }, handle); 128 } 129 130 /// one task watches every connection. a connection links its entry only 131 /// while it runs, so the watchdog never sees a closed stream. 132 pub const Watchdog = struct { 133 mutex: std.Io.Mutex = .init, 134 connections: std.DoublyLinkedList = .{}, 135 136 const Connection = struct { 137 node: std.DoublyLinkedList.Node = .{}, 138 stream: *const std.Io.net.Stream, 139 idle_state: ssh.IdleState = .{}, 140 // tick state, touched only by the watchdog 141 last_seen: u64 = 0, 142 presession_ticks: u32 = 0, 143 idle_ticks: u32 = 0, 144 closing_ticks: u32 = 0, 145 146 // interactive sessions are exempt only from the idle timeout, so a 147 // stalled teardown can still be broken 148 fn timedOut(self: *Connection) bool { 149 if (self.idle_state.closing.load(.acquire)) { 150 self.closing_ticks += 1; 151 return self.closing_ticks >= close_drain_timeout_ticks; 152 } 153 if (!self.idle_state.session_started.load(.acquire)) { 154 self.presession_ticks += 1; 155 return self.presession_ticks >= presession_timeout_ticks; 156 } 157 if (self.idle_state.exempt.load(.acquire)) return false; 158 159 // our own work between packets is not the peer idling 160 const seen = self.idle_state.activity.load(.acquire); 161 defer self.last_seen = seen; 162 if (self.idle_state.waiting.load(.acquire) and seen == self.last_seen) { 163 self.idle_ticks += 1; 164 } else { 165 self.idle_ticks = 0; 166 } 167 return self.idle_ticks >= idle_timeout_ticks; 168 } 169 }; 170 171 fn add(self: *Watchdog, io: std.Io, connection: *Connection) void { 172 self.mutex.lockUncancelable(io); 173 defer self.mutex.unlock(io); 174 self.connections.append(&connection.node); 175 } 176 177 fn remove(self: *Watchdog, io: std.Io, connection: *Connection) void { 178 self.mutex.lockUncancelable(io); 179 defer self.mutex.unlock(io); 180 self.connections.remove(&connection.node); 181 } 182 183 fn run(self: *Watchdog, io: std.Io) void { 184 while (true) { 185 io.sleep(watchdog_interval, .awake) catch return; 186 self.mutex.lock(io) catch return; 187 defer self.mutex.unlock(io); 188 var node = self.connections.first; 189 while (node) |n| : (node = n.next) { 190 const connection: *Connection = @fieldParentPtr("node", n); 191 if (connection.timedOut()) connection.stream.shutdown(io, .both) catch {}; 192 } 193 } 194 } 195 }; 196 197 fn runTuiSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, pty: ssh.PtySize, color: bool) !void { 198 // runTui owns the terminal, whose deinit restores the client's screen and 199 // runs as the function unwinds — so any error it returns leaves the TUI torn 200 // down and we can surface the failure on the restored screen before exiting. 201 runTui(handler, sess, pty, color) catch |tui_err| { 202 const err = sess.underlyingError(tui_err); 203 serve_common.logError(sess.conn.io, handler.err, "ssh tui session failed: {s}\n", .{@errorName(err)}); 204 var buf: [256]u8 = undefined; 205 const msg = std.fmt.bufPrint(&buf, "haxy ssh: {s}\r\n", .{@errorName(err)}) catch "haxy ssh: internal error\r\n"; 206 sess.writeBytes(msg) catch {}; 207 try sess.exit(1); 208 }; 209 } 210 211 fn runTui(handler: *const SessionHandler, sess: *ssh.SessionCtx, pty: ssh.PtySize, color: bool) !void { 212 const allocator = sess.conn.allocator; 213 const io = sess.conn.io; 214 215 // some clients (notably scripted ssh with no local controlling tty) 216 // allocate a pty without ever sending a non-zero size. fall back to a 217 // conventional 80x24 in that case so render emits something. 218 var terminal_size = Size{ 219 .width = if (pty.width_cells == 0) 80 else pty.width_cells, 220 .height = if (pty.height_cells == 0) 24 else pty.height_cells, 221 }; 222 223 // session-lifetime allocations (login, prefs); Nav owns the per-page arenas. 224 var session_arena = std.heap.ArenaAllocator.init(allocator); 225 defer session_arena.deinit(); 226 227 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 228 var repo = try Repo.open(io, allocator, .{ .path = handler.admin_repo_path }); 229 defer repo.deinit(io, allocator); 230 var ui_session = try ui.Session.init(&session_arena, &repo, .{}); 231 ui_session.is_terminal = true; 232 ui_session.color = color; 233 ui_session.web_port = handler.wui_port; 234 ui_session.data.git_http_port = handler.git_http_port; 235 ui_session.data.git_ssh_port = handler.git_ssh_port; 236 ui_session.data.git_ssh_prefix = handler.git_ssh_prefix; 237 // let page builders open on-disk repos 238 ui_session.io = io; 239 ui_session.users_dir = handler.users_dir; 240 241 var nav = try ui.Nav.init(allocator, &ui_session); 242 defer nav.deinit(allocator); 243 244 var session_writer_buf: [8192]u8 = undefined; 245 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 246 247 // the terminal's deinit writes leave-alt / show-cursor / disable-mouse and 248 // flushes, restoring the client's screen. as a function-scoped defer it runs 249 // before runTui returns — on the normal path and on any error — so the 250 // caller can write to the client afterward (and sess.exit can close cleanly). 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| { 256 terminal.render_state.no_color = !color; 257 try terminal.queryBackground(); 258 _ = try terminal.render(&nav.root); 259 } 260 261 // event loop. nextEvent blocks until something interesting arrives; 262 // for each event, rebuild the widget tree and re-render so the user 263 // sees the effect of their input on the same iteration. 264 event_loop: while (true) { 265 const event = try nextTuiEvent(sess, if (terminal_maybe) |*terminal| terminal else null); 266 if (event) |ev| switch (ev) { 267 .data => |payload| { 268 defer allocator.free(payload); 269 if (terminal_maybe) |*terminal| { 270 try terminal.writeBytes(payload); 271 } else { 272 // the copyable text stays up until enter 273 if (std.mem.indexOfAny(u8, payload, "\r\n") == null) continue; 274 var terminal = try StreamTerminal.init(allocator, &session_writer.interface, terminal_size); 275 terminal.render_state.no_color = !color; 276 terminal_maybe = terminal; 277 } 278 }, 279 .resize => |sz| { 280 terminal_size = .{ .width = sz.width_cells, .height = sz.height_cells }; 281 if (terminal_maybe) |*terminal| terminal.pushResize(terminal_size) else continue; 282 }, 283 .eof, .close => break :event_loop, 284 }; 285 if (terminal_maybe) |*terminal| { 286 while (terminal.popKey()) |key| { 287 try ui.inputKey(allocator, &nav.root, key, &ui_session); 288 } 289 } 290 291 if (ui_session.host_request) |request| { 292 ui_session.host_request = null; 293 switch (request) { 294 .show_copyable_text => |copyable_text| { 295 if (terminal_maybe) |*terminal| terminal.deinit(); 296 terminal_maybe = null; 297 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}); 298 try session_writer.interface.flush(); 299 continue; 300 }, 301 .sync_events => {}, 302 .undo => |target| ui.Repo.Undo.handleRequest(allocator, &ui_session, target), 303 } 304 } 305 306 // pick up data written by other handles so the next navigation 307 // builds its page from a current moment 308 try ui_session.reloadMoment(allocator, &repo); 309 310 // reconcile navigation: forward to a new page, or back on escape. 311 // the terminal background can change at any time, so recheck it on each page 312 if (try nav.sync(allocator, &ui_session)) { 313 if (terminal_maybe) |*terminal| try terminal.queryBackground(); 314 } 315 316 // the quit button (on the quit tab) asks the host to tear down 317 if (ui_session.quit_requested) break :event_loop; 318 319 try nav.root.build(allocator, .{ 320 .min_size = .{ .width = null, .height = null }, 321 .max_size = .{ .width = terminal_size.width, .height = terminal_size.height }, 322 }, nav.root.getFocus()); 323 if (terminal_maybe) |*terminal| _ = try terminal.render(&nav.root); 324 } 325 } 326 327 // only ambiguous input (a lone ESC or ESC ]) needs a deadline; longer 328 // fragments must remain buffered until complete. a timeout leaves partial SSH 329 // packets in the reader. 330 pub fn nextTuiEvent(sess: *ssh.SessionCtx, terminal: ?*StreamTerminal) !?ssh.Event { 331 if (terminal) |t| { 332 if (t.parser.isAmbiguous()) { 333 sess.conn.read_timeout = escape_timeout.toDeadline(sess.conn.io); 334 defer sess.conn.read_timeout = .none; 335 return sess.nextEvent() catch |err| switch (err) { 336 error.Timeout => { 337 try t.flushEscape(); 338 return null; 339 }, 340 else => return err, 341 }; 342 } 343 } 344 return try sess.nextEvent(); 345 } 346 347 // --------------------------------------------------------------------------- 348 // git path (exec) 349 // --------------------------------------------------------------------------- 350 351 const GitService = enum { upload_pack, receive_pack }; 352 353 const ParsedGitCommand = struct { 354 service: GitService, 355 dir: []u8, 356 357 fn deinit(self: ParsedGitCommand, allocator: std.mem.Allocator) void { 358 allocator.free(self.dir); 359 } 360 }; 361 362 fn runGitSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, exec: ssh.Request.Exec) !void { 363 const allocator = sess.conn.allocator; 364 const io = sess.conn.io; 365 const protocol_version = xit.net_server_common.parseProtocolVersion(exec.git_protocol); 366 367 // the repo's pack functions consume the channel like any other stream. 368 // whatever they leave buffered is flushed before the exit status goes out. 369 var reader_buf: [4096]u8 = undefined; 370 var writer_buf: [4096]u8 = undefined; 371 var reader = ssh.SessionReader.init(sess, &reader_buf); 372 var writer = ssh.SessionWriter.init(sess, &writer_buf); 373 defer writer.interface.flush() catch {}; 374 375 const parsed = parseGitCommand(allocator, exec.command) catch return writeError(sess, "unsupported command (expected git-upload-pack or git-receive-pack)"); 376 defer parsed.deinit(allocator); 377 const repo_identity = std.mem.trimStart(u8, parsed.dir, "/"); 378 379 // a "+" names a fork's patch draft 380 if (std.mem.indexOfScalar(u8, repo_identity, '+') != null) { 381 return runForkSession(handler, sess, repo_identity, parsed.service, protocol_version, &reader.interface, &writer.interface); 382 } 383 384 const create_if_missing = parsed.service == .receive_pack; 385 386 const owner_repo = evt.parseOwnerRepoPath(repo_identity) orelse return writeError(sess, "repo path must be <owner>:<repo>"); 387 var author_arena = std.heap.ArenaAllocator.init(allocator); 388 defer author_arena.deinit(); 389 const author = switch (try authorizeRepoKey(io, &author_arena, handler.admin_repo_path, handler.users_dir, owner_repo.owner, owner_repo.name, parsed.service, &sess.fingerprint)) { 390 .allowed => |user| user, 391 .denied => return switch (parsed.service) { 392 .upload_pack => writeError(sess, "unauthorized: this SSH key cannot read this repo"), 393 .receive_pack => writeError(sess, "unauthorized: this SSH key cannot push to this repo"), 394 }, 395 .not_found => return writeError(sess, "repo not found"), 396 }; 397 398 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, handler.users_dir, handler.admin_repo_path, repo_identity, create_if_missing)) { 399 .ok => |p| p, 400 .invalid => unreachable, // parsed above 401 .not_found => return writeError(sess, "repo not found"), 402 }; 403 defer allocator.free(repo_path); 404 405 if (try serveIfExists(repo_path, handler.users_dir, &reader.interface, &writer.interface, io, allocator, parsed.service, protocol_version, author, handler.err, sess)) return; 406 407 if (!create_if_missing) return writeError(sess, "repo not found"); 408 409 // create the on-disk repo for the just-minted event and serve the push 410 var repo = try rp.Repo(.xit, any_repo_opts.toRepoOpts()).init(io, allocator, .{ .path = repo_path, .bare = true }); 411 defer repo.deinit(io, allocator); 412 try servePack(repo.self_repo_opts, &repo, handler.users_dir, &reader.interface, &writer.interface, io, allocator, parsed.service, protocol_version, author, handler.err, sess); 413 } 414 415 // serve a patch draft: anyone may fetch it, only its author may push to it 416 fn runForkSession( 417 handler: *const SessionHandler, 418 sess: *ssh.SessionCtx, 419 fork_path: []const u8, 420 service: GitService, 421 protocol_version: xit.net_server_common.ProtocolVersion, 422 reader: *std.Io.Reader, 423 writer: *std.Io.Writer, 424 ) !void { 425 const allocator = sess.conn.allocator; 426 const io = sess.conn.io; 427 428 const route = fork.parseRoute(fork_path) orelse return writeError(sess, "invalid fork path"); 429 // the route names the forker and the target repo 430 const forker_repo = evt.parseOwnerRepoPath(route.identity) orelse return writeError(sess, "repo path must be <forker>:<repo>"); 431 432 var admin = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = handler.admin_repo_path }); 433 defer admin.deinit(io, allocator); 434 var admin_arena = std.heap.ArenaAllocator.init(allocator); 435 defer admin_arena.deinit(); 436 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 437 const fork_id = try evt.parseEventId(&route.id); 438 const forker_id = (try evt.User.readIdByName(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, forker_repo.owner)) orelse 439 return writeError(sess, "patch draft not found"); 440 const fork_record = (try evt.readForkById(io, allocator, &admin_arena, handler.users_dir, &forker_id, &fork_id)) orelse 441 return writeError(sess, "patch draft not found"); 442 if (fork_record.removed) return writeError(sess, "patch draft not found"); 443 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, &forker_id)) orelse 444 return writeError(sess, "invalid patch draft"); 445 if (user.removed) return writeError(sess, "invalid patch draft"); 446 if (service == .receive_pack and !isKeyInAuthorizedKeys(user.event.ssh_keys, &sess.fingerprint)) 447 return writeError(sess, "unauthorized: this SSH key is not registered to the patch author"); 448 449 const draft_path = try fork.forkPath(allocator, handler.users_dir, &forker_id, &fork_id); 450 defer allocator.free(draft_path); 451 var draft = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = draft_path }) catch 452 return writeError(sess, "patch draft not found"); 453 defer draft.deinit(io, allocator); 454 if (service == .upload_pack) { 455 var sideband = progress.Sideband{ .writer = writer, .sess = sess }; 456 switch (draft) { 457 inline else => |*repo| try repo.uploadPack(io, allocator, reader, writer, .{ .protocol_version = protocol_version }, &sideband), 458 } 459 } else { 460 const target = (try evt.readRepoById(io, allocator, &admin_arena, handler.users_dir, fork_record.event.repo_user_id[0..evt.event_id_size], fork_record.event.repo_id[0..evt.event_id_size], null)) orelse 461 return writeError(sess, "repo not found"); 462 if (!std.mem.eql(u8, target.repo.event.name, forker_repo.name)) return writeError(sess, "patch draft belongs to another repo"); 463 const target_path = try evt.repoPath(allocator, handler.users_dir, fork_record.event.repo_user_id, fork_record.event.repo_id); 464 defer allocator.free(target_path); 465 const author: evt.CommitAuthor = .{ .name = user.event.name, .email = user.event.email }; 466 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 467 switch (draft) { 468 inline else => |*repo| { 469 var target_repo = rp.Repo(.xit, repo.self_repo_opts).open(io, allocator, .{ .path = target_path }) catch 470 return writeError(sess, "repo not found or has the wrong hash"); 471 defer target_repo.deinit(io, allocator); 472 try push.receiveFork(repo.self_repo_opts, io, allocator, repo, &target_repo, handler.users_dir, &route.id, author, timestamp, reader, writer, handler.err, sess); 473 }, 474 } 475 } 476 } 477 478 // serve an existing repo at `repo_path`, or return false if none is there 479 fn serveIfExists( 480 repo_path: []const u8, 481 users_dir: []const u8, 482 reader: *std.Io.Reader, 483 writer: *std.Io.Writer, 484 io: std.Io, 485 allocator: std.mem.Allocator, 486 service: GitService, 487 protocol_version: xit.net_server_common.ProtocolVersion, 488 author: ?evt.CommitAuthor, 489 error_writer: *std.Io.Writer, 490 sess: ?*ssh.SessionCtx, 491 ) !bool { 492 // a bare open() creates the directory while probing for the repo, so only 493 // attempt it when the path already exists 494 std.Io.Dir.accessAbsolute(io, repo_path, .{}) catch return false; 495 496 var any_repo = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 497 error.RepoNotFound => return false, 498 else => |e| return e, 499 }; 500 defer any_repo.deinit(io, allocator); 501 502 switch (any_repo) { 503 inline else => |*repo| try servePack(repo.self_repo_opts, repo, users_dir, reader, writer, io, allocator, service, protocol_version, author, error_writer, sess), 504 } 505 return true; 506 } 507 508 fn servePack( 509 comptime repo_opts: rp.RepoOpts(.xit), 510 repo: *rp.Repo(.xit, repo_opts), 511 users_dir: []const u8, 512 reader: *std.Io.Reader, 513 writer: *std.Io.Writer, 514 io: std.Io, 515 allocator: std.mem.Allocator, 516 service: GitService, 517 protocol_version: xit.net_server_common.ProtocolVersion, 518 author: ?evt.CommitAuthor, 519 error_writer: *std.Io.Writer, 520 sess: ?*ssh.SessionCtx, 521 ) !void { 522 switch (service) { 523 .upload_pack => { 524 var sideband = progress.Sideband{ .writer = writer, .sess = sess }; 525 try repo.uploadPack(io, allocator, reader, writer, .{ .protocol_version = protocol_version }, &sideband); 526 }, 527 .receive_pack => try push.receivePackAndConsume(repo_opts, io, allocator, repo, reader, writer, .{ .protocol_version = protocol_version }, author, users_dir, error_writer, sess), 528 } 529 } 530 531 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 532 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 533 defer tokens.deinit(); 534 535 const service_token = tokens.next() orelse return error.InvalidCommand; 536 const dir_token = tokens.next() orelse return error.InvalidCommand; 537 538 const service: GitService = 539 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 540 .upload_pack 541 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 542 .receive_pack 543 else 544 return error.UnsupportedService; 545 546 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 547 } 548 549 const RepoAuthorization = union(enum) { allowed: ?evt.CommitAuthor, denied, not_found }; 550 551 fn authorizeRepoKey( 552 io: std.Io, 553 arena: *std.heap.ArenaAllocator, 554 admin_repo_path: []const u8, 555 users_dir: []const u8, 556 owner_name: []const u8, 557 repo_name: []const u8, 558 service: GitService, 559 fingerprint: *const [ssh.fingerprint_len]u8, 560 ) !RepoAuthorization { 561 const allocator = arena.child_allocator; 562 var admin = rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 563 error.RepoNotFound => return .not_found, 564 else => |e| return e, 565 }; 566 defer admin.deinit(io, allocator); 567 568 const moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 569 // no viewer yet, so this carries the base role 570 const repo = (try evt.readRepoByOwnerAndName(io, allocator, arena, moment, users_dir, owner_name, repo_name, null)) orelse { 571 if (service == .upload_pack) return .not_found; 572 const owner = (try evt.User.readByName(io, allocator, admin_repo_path, arena, owner_name)) orelse return .not_found; 573 return if (isKeyInAuthorizedKeys(owner.event.ssh_keys, fingerprint)) 574 .{ .allowed = .{ .name = owner.event.name, .email = owner.event.email } } 575 else 576 .denied; 577 }; 578 579 const min_role: evt.Repo.Role = switch (service) { 580 .upload_pack => .read, 581 .receive_pack => .write, 582 }; 583 // skip the key lookups when the base role is enough 584 if (repo.role.atLeast(min_role)) return .{ .allowed = null }; 585 586 // the creator owns the repo 587 const owner_id = repo.repo.event.user_id[0..evt.event_id_size]; 588 if (try authorWithKey(moment, arena, owner_id, fingerprint)) |author| return .{ .allowed = author }; 589 590 // anyone else holding the key needs a grant with the role. a key can be 591 // shared, so a grant that falls short doesn't end the search. 592 for (try evt.readRepoGrants(io, allocator, arena, users_dir, owner_id, &repo.event_id)) |grant| { 593 if (!grant.role.atLeast(min_role)) continue; 594 if (try authorWithKey(moment, arena, grant.user_id, fingerprint)) |author| return .{ .allowed = author }; 595 } 596 return .denied; 597 } 598 599 // the user as a commit author, or null unless they hold the key 600 fn authorWithKey( 601 moment: evt.AdminDB.HashMap(.read_only), 602 arena: *std.heap.ArenaAllocator, 603 user_id: []const u8, 604 fingerprint: *const [ssh.fingerprint_len]u8, 605 ) !?evt.CommitAuthor { 606 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, user_id)) orelse return null; 607 if (user.removed or !isKeyInAuthorizedKeys(user.event.ssh_keys, fingerprint)) return null; 608 return .{ .name = user.event.name, .email = user.event.email }; 609 } 610 611 fn isKeyInAuthorizedKeys(ssh_keys: []const u8, fingerprint: *const [ssh.fingerprint_len]u8) bool { 612 var it = std.mem.splitScalar(u8, ssh_keys, '\n'); 613 while (it.next()) |line| { 614 const fp = fingerprintOfAuthorizedKey(line) orelse continue; 615 if (std.mem.eql(u8, &fp, fingerprint)) return true; 616 } 617 return false; 618 } 619 620 // the SHA256 fingerprint of one authorized_keys line, or null if the line is 621 // blank or not a parseable "<type> <base64> [comment]" entry 622 fn fingerprintOfAuthorizedKey(line: []const u8) ?[ssh.fingerprint_len]u8 { 623 var it = std.mem.tokenizeAny(u8, line, " \t\r"); 624 _ = it.next() orelse return null; // key type 625 const blob_b64 = it.next() orelse return null; 626 627 const decoder = std.base64.standard.Decoder; 628 const blob_len = decoder.calcSizeForSlice(blob_b64) catch return null; 629 var blob_buf: [4096]u8 = undefined; 630 if (blob_len > blob_buf.len) return null; 631 decoder.decode(blob_buf[0..blob_len], blob_b64) catch return null; 632 633 return ssh.formatFingerprint(blob_buf[0..blob_len]); 634 } 635 636 fn writeError(sess: *ssh.SessionCtx, comptime msg: []const u8) !void { 637 const body = "ERR haxy ssh: " ++ msg; 638 var packet: [body.len + 4]u8 = undefined; 639 const line = try std.fmt.bufPrint(&packet, "{x:0>4}{s}", .{ packet.len, body }); 640 try sess.writeBytes(line); 641 try sess.exit(1); 642 } 643 644 test "parseGitCommand rejects malformed input" { 645 const allocator = std.testing.allocator; 646 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 647 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 648 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 649 } 650 651 test "parseGitCommand happy paths" { 652 const allocator = std.testing.allocator; 653 654 { 655 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 656 defer parsed.deinit(allocator); 657 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 658 try std.testing.expectEqualStrings("some-repo", parsed.dir); 659 } 660 { 661 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 662 defer parsed.deinit(allocator); 663 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 664 try std.testing.expectEqualStrings("user/proj", parsed.dir); 665 } 666 { 667 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 668 defer parsed.deinit(allocator); 669 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 670 try std.testing.expectEqualStrings("repo", parsed.dir); 671 } 672 } 673