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