╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh.zig ────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯
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_url = handler.web_url; 235 ui_session.data.git_http_url = handler.web_url; 236 ui_session.data.git_ssh_url = handler.ssh_url; 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.ssh_key = try authorizedKeyLine(session_arena.allocator(), sess.public_key); 242 try ui_session.logInWithSshKey(); 243 244 var nav = try ui.Nav.init(allocator, &ui_session); 245 defer nav.deinit(allocator); 246 247 var session_writer_buf: [8192]u8 = undefined; 248 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 249 250 // the terminal's deinit writes leave-alt / show-cursor / disable-mouse and 251 // flushes, restoring the client's screen. as a function-scoped defer it runs 252 // before runTui returns — on the normal path and on any error — so the 253 // caller can write to the client afterward (and sess.exit can close cleanly). 254 var terminal_maybe: ?StreamTerminal = try StreamTerminal.init(allocator, &session_writer.interface, terminal_size); 255 defer if (terminal_maybe) |*terminal| terminal.deinit(); 256 257 // initial render — user sees the page immediately 258 if (terminal_maybe) |*terminal| { 259 terminal.render_state.no_color = !color; 260 try terminal.queryBackground(); 261 _ = try terminal.render(&nav.root); 262 } 263 264 // event loop. nextEvent blocks until something interesting arrives; 265 // for each event, rebuild the widget tree and re-render so the user 266 // sees the effect of their input on the same iteration. 267 event_loop: while (true) { 268 const event = try nextTuiEvent(sess, if (terminal_maybe) |*terminal| terminal else null); 269 if (event) |ev| switch (ev) { 270 .data => |payload| { 271 defer allocator.free(payload); 272 if (terminal_maybe) |*terminal| { 273 try terminal.writeBytes(payload); 274 } else { 275 // the copyable text stays up until enter 276 if (std.mem.indexOfAny(u8, payload, "\r\n") == null) continue; 277 var terminal = try StreamTerminal.init(allocator, &session_writer.interface, terminal_size); 278 terminal.render_state.no_color = !color; 279 terminal_maybe = terminal; 280 } 281 }, 282 .resize => |sz| { 283 terminal_size = .{ .width = sz.width_cells, .height = sz.height_cells }; 284 if (terminal_maybe) |*terminal| terminal.pushResize(terminal_size) else continue; 285 }, 286 .eof, .close => break :event_loop, 287 }; 288 if (terminal_maybe) |*terminal| { 289 while (terminal.popKey()) |key| { 290 try ui.inputKey(allocator, &nav.root, key, &ui_session); 291 } 292 } 293 294 if (ui_session.host_request) |request| { 295 ui_session.host_request = null; 296 switch (request) { 297 .show_copyable_text => |copyable_text| { 298 if (terminal_maybe) |*terminal| terminal.deinit(); 299 terminal_maybe = null; 300 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}); 301 try session_writer.interface.flush(); 302 continue; 303 }, 304 .sync_events => {}, 305 .undo => |target| ui.Repo.Undo.handleRequest(allocator, &ui_session, target), 306 } 307 } 308 309 // pick up data written by other handles so the next navigation 310 // builds its page from a current moment 311 try ui_session.reloadMoment(allocator, &repo); 312 313 // reconcile navigation: forward to a new page, or back on escape. 314 // the terminal background can change at any time, so recheck it on each page 315 if (try nav.sync(allocator, &ui_session)) { 316 if (terminal_maybe) |*terminal| try terminal.queryBackground(); 317 } 318 319 // the quit button (on the quit tab) asks the host to tear down 320 if (ui_session.quit_requested) break :event_loop; 321 322 try nav.root.build(allocator, .{ 323 .min_size = .{ .width = null, .height = null }, 324 .max_size = .{ .width = terminal_size.width, .height = terminal_size.height }, 325 }, nav.root.getFocus()); 326 if (terminal_maybe) |*terminal| _ = try terminal.render(&nav.root); 327 } 328 } 329 330 // only ambiguous input (a lone ESC or ESC ]) needs a deadline; longer 331 // fragments must remain buffered until complete. a timeout leaves partial SSH 332 // packets in the reader. 333 pub fn nextTuiEvent(sess: *ssh.SessionCtx, terminal: ?*StreamTerminal) !?ssh.Event { 334 if (terminal) |t| { 335 if (t.parser.isAmbiguous()) { 336 sess.conn.read_timeout = escape_timeout.toDeadline(sess.conn.io); 337 defer sess.conn.read_timeout = .none; 338 return sess.nextEvent() catch |err| switch (err) { 339 error.Timeout => { 340 try t.flushEscape(); 341 return null; 342 }, 343 else => return err, 344 }; 345 } 346 } 347 return try sess.nextEvent(); 348 } 349 350 // --------------------------------------------------------------------------- 351 // git path (exec) 352 // --------------------------------------------------------------------------- 353 354 const GitService = enum { upload_pack, receive_pack }; 355 356 const ParsedGitCommand = struct { 357 service: GitService, 358 dir: []u8, 359 360 fn deinit(self: ParsedGitCommand, allocator: std.mem.Allocator) void { 361 allocator.free(self.dir); 362 } 363 }; 364 365 fn runGitSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, exec: ssh.Request.Exec) !void { 366 const allocator = sess.conn.allocator; 367 const io = sess.conn.io; 368 const protocol_version = xit.net_server_common.parseProtocolVersion(exec.git_protocol); 369 370 // the repo's pack functions consume the channel like any other stream. 371 // whatever they leave buffered is flushed before the exit status goes out. 372 var reader_buf: [4096]u8 = undefined; 373 var writer_buf: [4096]u8 = undefined; 374 var reader = ssh.SessionReader.init(sess, &reader_buf); 375 var writer = ssh.SessionWriter.init(sess, &writer_buf); 376 defer writer.interface.flush() catch {}; 377 378 const parsed = parseGitCommand(allocator, exec.command) catch return writeError(sess, "unsupported command (expected git-upload-pack or git-receive-pack)"); 379 defer parsed.deinit(allocator); 380 const repo_identity = std.mem.trimStart(u8, parsed.dir, "/"); 381 382 // a "+" names a fork's patch draft 383 if (std.mem.indexOfScalar(u8, repo_identity, '+') != null) { 384 return runForkSession(handler, sess, repo_identity, parsed.service, protocol_version, &reader.interface, &writer.interface); 385 } 386 387 const owner_repo = evt.parseOwnerRepoPath(repo_identity) orelse return writeError(sess, "repo path must be <owner>:<repo>"); 388 var allowed_arena = std.heap.ArenaAllocator.init(allocator); 389 defer allowed_arena.deinit(); 390 const allowed = switch (try authorizeRepoKey(io, &allowed_arena, handler.admin_repo_path, handler.server.users_dir, owner_repo.owner, owner_repo.name, parsed.service, &sess.fingerprint)) { 391 .allowed => |value| value, 392 .create => |creator| return runCreatingPush(handler, sess, &creator, owner_repo.name, protocol_version, &reader.interface, &writer.interface), 393 .denied => return switch (parsed.service) { 394 .upload_pack => writeError(sess, "unauthorized: this SSH key cannot read this repo"), 395 .receive_pack => writeError(sess, "unauthorized: this SSH key cannot push to this repo"), 396 }, 397 .not_found => return writeError(sess, "repo not found"), 398 }; 399 400 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, handler.server.users_dir, handler.admin_repo_path, repo_identity)) { 401 .ok => |p| p, 402 .invalid => unreachable, // parsed above 403 .not_found => return writeError(sess, "repo not found"), 404 }; 405 defer allocator.free(repo_path); 406 407 var any_repo = try rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }); 408 defer any_repo.deinit(io, allocator); 409 410 switch (any_repo) { 411 inline else => |*repo| switch (allowed) { 412 .fetch => { 413 var sideband = progress.Sideband{ .writer = &writer.interface, .sess = sess }; 414 try repo.uploadPack(io, allocator, &reader.interface, &writer.interface, .{ .protocol_version = protocol_version }, &sideband); 415 }, 416 .push => |pusher| try push.receivePackAndConsume(repo.self_repo_opts, io, allocator, repo, &reader.interface, &writer.interface, .{ 417 .protocol_version = protocol_version, 418 .protected_branches = pusher.protected_branches, 419 .locked_branches = pusher.locked_branches, 420 .pseudo_ref = .{ .name = push.clear_undo_ref, .deletable = pusher.owner }, 421 }, pusher.author, &pusher.user_id, handler.server, handler.err, sess), 422 }, 423 } 424 } 425 426 // push to a repo that doesn't exist yet, creating it in the hash format the 427 // client's first command names 428 fn runCreatingPush( 429 handler: *const SessionHandler, 430 sess: *ssh.SessionCtx, 431 creator: *const RepoCreator, 432 name: []const u8, 433 protocol_version: xit.net_server_common.ProtocolVersion, 434 reader: *std.Io.Reader, 435 writer: *std.Io.Writer, 436 ) !void { 437 const allocator = sess.conn.allocator; 438 const io = sess.conn.io; 439 440 evt.Repo.validateName(name) catch return writeError(sess, "invalid repo name"); 441 442 try xit.net_server_receive_pack.advertiseUncreated(.xit, writer, .{ .protocol_version = protocol_version }); 443 try writer.flush(); 444 // a client with nothing to push creates nothing 445 const hash_kind = (try xit.net_server_receive_pack.peekObjectFormat(reader)) orelse return; 446 447 const location = evt.createRepo(io, allocator, handler.server.users_dir, &creator.owner_id, creator.owner, name, "", .private, hash_kind) catch |err| switch (err) { 448 error.NameTaken => return writeError(sess, "repo was just created by another push, try again"), 449 else => |e| return e, 450 }; 451 const repo_path = try evt.repoPath(allocator, handler.server.users_dir, &location.owner_id, &location.repo_id); 452 defer allocator.free(repo_path); 453 454 switch (hash_kind) { 455 inline else => |kind| { 456 var repo = try rp.Repo(.xit, any_repo_opts.toRepoOptsWithHash(kind)).open(io, allocator, .{ .path = repo_path }); 457 defer repo.deinit(io, allocator); 458 // stateless since the advertisement already went out 459 try push.receivePackAndConsume(repo.self_repo_opts, io, allocator, &repo, reader, writer, .{ .protocol_version = protocol_version, .is_stateless = true, .pseudo_ref = .{ .name = push.clear_undo_ref, .deletable = true } }, creator.owner, &creator.owner_id, handler.server, handler.err, sess); 460 }, 461 } 462 } 463 464 // serve a patch draft: anyone may fetch it, only its author may push to it 465 fn runForkSession( 466 handler: *const SessionHandler, 467 sess: *ssh.SessionCtx, 468 fork_path: []const u8, 469 service: GitService, 470 protocol_version: xit.net_server_common.ProtocolVersion, 471 reader: *std.Io.Reader, 472 writer: *std.Io.Writer, 473 ) !void { 474 const allocator = sess.conn.allocator; 475 const io = sess.conn.io; 476 477 const route = fork.parseRoute(fork_path) orelse return writeError(sess, "invalid fork path"); 478 // the route names the forker and the target repo 479 const forker_repo = evt.parseOwnerRepoPath(route.identity) orelse return writeError(sess, "repo path must be <forker>:<repo>"); 480 481 var admin = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = handler.admin_repo_path }); 482 defer admin.deinit(io, allocator); 483 var admin_arena = std.heap.ArenaAllocator.init(allocator); 484 defer admin_arena.deinit(); 485 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 486 const fork_id = try evt.parseEventId(&route.id); 487 const forker_id = (try evt.User.readIdByName(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, forker_repo.owner)) orelse 488 return writeError(sess, "patch draft not found"); 489 const fork_record = (try evt.readForkById(io, allocator, &admin_arena, handler.server.users_dir, &forker_id, &fork_id)) orelse 490 return writeError(sess, "patch draft not found"); 491 if (fork_record.removed) return writeError(sess, "patch draft not found"); 492 // the url keeps the name the fork was made under, even after a rename 493 if (!std.mem.eql(u8, fork_record.event.repo_name, forker_repo.name)) return writeError(sess, "patch draft not found"); 494 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, &forker_id)) orelse 495 return writeError(sess, "invalid patch draft"); 496 if (user.removed) return writeError(sess, "invalid patch draft"); 497 if (service == .receive_pack and !try evt.User.holdsKey(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, &forker_id, &sess.fingerprint)) 498 return writeError(sess, "unauthorized: this SSH key is not registered to the patch author"); 499 500 const target_owner_id = try evt.parseEventId(&fork_record.event.repo_user_id); 501 const target_id = try evt.parseEventId(&fork_record.event.repo_id); 502 // a deleted target, or one whose owner was deleted, leaves the fork fetchable but not pushable 503 const target = try evt.readRepoById(io, allocator, &admin_arena, handler.server.users_dir, &target_owner_id, &target_id, forker_id); 504 if (target) |value| { 505 // patches that are off take their drafts with them 506 const patch_role = value.repo.event.patch_role orelse return writeError(sess, "patch draft not found"); 507 if (service == .receive_pack) { 508 const role = value.role orelse return writeError(sess, "repo not found"); 509 if (!role.atLeast(patch_role)) return writeError(sess, "unauthorized: your role in this repo may not write patches"); 510 } 511 } 512 if (service == .upload_pack) { 513 // a fork is as readable as its target, and only its forker's once the target is gone 514 const readable = if (target) |value| readable: { 515 const owner = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, &target_owner_id)) orelse unreachable; 516 break :readable try authorizeRepoKey(io, &admin_arena, handler.admin_repo_path, handler.server.users_dir, owner.event.name, value.repo.event.name, .upload_pack, &sess.fingerprint) == .allowed; 517 } else try evt.User.holdsKey(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, &forker_id, &sess.fingerprint); 518 if (!readable) return writeError(sess, "unauthorized: this SSH key cannot read this patch draft"); 519 } 520 521 const draft_path = try fork.forkPath(allocator, handler.server.users_dir, &forker_id, &fork_id); 522 defer allocator.free(draft_path); 523 var draft = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = draft_path }) catch 524 return writeError(sess, "patch draft not found"); 525 defer draft.deinit(io, allocator); 526 if (service == .upload_pack) { 527 var sideband = progress.Sideband{ .writer = writer, .sess = sess }; 528 switch (draft) { 529 inline else => |*repo| try repo.uploadPack(io, allocator, reader, writer, .{ .protocol_version = protocol_version }, &sideband), 530 } 531 } else { 532 if (target == null) return writeError(sess, "the repo this patch draft targets was deleted"); 533 const target_path = try evt.repoPath(allocator, handler.server.users_dir, &target_owner_id, &target_id); 534 defer allocator.free(target_path); 535 const author: evt.CommitAuthor = .{ .name = user.event.name, .email = user.event.email }; 536 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 537 switch (draft) { 538 inline else => |*repo| { 539 var target_repo = rp.Repo(.xit, repo.self_repo_opts).open(io, allocator, .{ .path = target_path }) catch 540 return writeError(sess, "repo not found or has the wrong hash"); 541 defer target_repo.deinit(io, allocator); 542 try push.receiveFork(repo.self_repo_opts, io, allocator, repo, &target_repo, handler.server, &route.id, author, timestamp, reader, writer, handler.err, sess); 543 }, 544 } 545 } 546 } 547 548 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 549 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 550 defer tokens.deinit(); 551 552 const service_token = tokens.next() orelse return error.InvalidCommand; 553 const dir_token = tokens.next() orelse return error.InvalidCommand; 554 555 const service: GitService = 556 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 557 .upload_pack 558 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 559 .receive_pack 560 else 561 return error.UnsupportedService; 562 563 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 564 } 565 566 const RepoAuthorization = union(enum) { allowed: Allowed, create: RepoCreator, denied, not_found }; 567 568 // what a key may do in an existing repo 569 const Allowed = union(enum) { 570 fetch, 571 push: Pusher, 572 }; 573 574 // the key holder a push acts as 575 const Pusher = struct { 576 user_id: [evt.event_id_size]u8, 577 author: evt.CommitAuthor, 578 protected_branches: []const []const u8, 579 locked_branches: []const []const u8, 580 // only owners may clear the undo history 581 owner: bool, 582 }; 583 584 // the owner of a repo a push may create 585 const RepoCreator = struct { 586 owner_id: [evt.event_id_size]u8, 587 owner: evt.CommitAuthor, 588 }; 589 590 fn authorizeRepoKey( 591 io: std.Io, 592 arena: *std.heap.ArenaAllocator, 593 admin_repo_path: []const u8, 594 users_dir: []const u8, 595 owner_name: []const u8, 596 repo_name: []const u8, 597 service: GitService, 598 fingerprint: *const [ssh.fingerprint_len]u8, 599 ) !RepoAuthorization { 600 const allocator = arena.child_allocator; 601 var admin = rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 602 error.RepoNotFound => return .not_found, 603 else => |e| return e, 604 }; 605 defer admin.deinit(io, allocator); 606 607 const moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 608 // no viewer yet, so this carries the base role 609 const repo = (try evt.readRepoByOwnerAndName(io, allocator, arena, moment, users_dir, owner_name, repo_name, null)) orelse { 610 if (service == .upload_pack) return .not_found; 611 const owner_id = (try evt.User.readIdByName(evt.AdminDB, evt.admin_repo_opts.hash, moment, owner_name)) orelse return .not_found; 612 if (!try evt.User.holdsKey(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, &owner_id, fingerprint)) return .denied; 613 return .{ .create = .{ .owner_id = owner_id, .owner = try commitAuthor(moment, arena, &owner_id) } }; 614 }; 615 616 const min_role: evt.Repo.Role = switch (service) { 617 .upload_pack => .read, 618 .receive_pack => .write, 619 }; 620 // any key may fetch a public repo; a push always needs a key holder 621 if (service == .upload_pack and repo.role != null) return .{ .allowed = .fetch }; 622 623 // a key can be shared, so the push acts as the holder with the highest role 624 const owner_id = try evt.parseEventId(&repo.repo.event.user_id); 625 var best: ?struct { id: [evt.event_id_size]u8, role: evt.Repo.Role } = null; 626 for (try evt.User.readIdsByFingerprint(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, fingerprint)) |holder_id| { 627 const seen = (try evt.readRepoById(io, allocator, arena, users_dir, &owner_id, &repo.event_id, holder_id)) orelse return .not_found; 628 const role = seen.role orelse continue; 629 if (best) |held| if (held.role.atLeast(role)) continue; 630 best = .{ .id = holder_id, .role = role }; 631 } 632 const holder = best orelse return .denied; 633 if (!holder.role.atLeast(min_role)) return .denied; 634 return .{ 635 .allowed = switch (service) { 636 .upload_pack => .fetch, 637 .receive_pack => blk: { 638 const names = try repo.repo.event.protectedBranchNames(arena.allocator()); 639 // members change protected branches only by merging a patch 640 const owner = holder.role == .owner; 641 break :blk .{ .push = .{ 642 .user_id = holder.id, 643 .author = try commitAuthor(moment, arena, &holder.id), 644 .protected_branches = if (owner) names else &.{}, 645 .locked_branches = if (owner) &.{} else names, 646 .owner = owner, 647 } }; 648 }, 649 }, 650 }; 651 } 652 653 // an active user as a commit author 654 fn commitAuthor( 655 moment: evt.AdminDB.HashMap(.read_only), 656 arena: *std.heap.ArenaAllocator, 657 user_id: *const [evt.event_id_size]u8, 658 ) !evt.CommitAuthor { 659 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, user_id)) orelse unreachable; 660 return .{ .name = user.event.name, .email = user.event.email }; 661 } 662 663 // the authorized_keys line of a pubkey blob: its type, then the blob in base64 664 fn authorizedKeyLine(allocator: std.mem.Allocator, blob: []const u8) ![]const u8 { 665 var reader = std.Io.Reader.fixed(blob); 666 const key_type = try ssh.takeString(&reader, 64); 667 const encoder = std.base64.standard.Encoder; 668 const line = try allocator.alloc(u8, key_type.len + 1 + encoder.calcSize(blob.len)); 669 @memcpy(line[0..key_type.len], key_type); 670 line[key_type.len] = ' '; 671 _ = encoder.encode(line[key_type.len + 1 ..], blob); 672 return line; 673 } 674 675 fn writeError(sess: *ssh.SessionCtx, comptime msg: []const u8) !void { 676 const body = "ERR haxy ssh: " ++ msg; 677 var packet: [body.len + 4]u8 = undefined; 678 const line = try std.fmt.bufPrint(&packet, "{x:0>4}{s}", .{ packet.len, body }); 679 try sess.writeBytes(line); 680 try sess.exit(1); 681 } 682 683 test "parseGitCommand rejects malformed input" { 684 const allocator = std.testing.allocator; 685 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 686 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 687 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 688 } 689 690 test "parseGitCommand happy paths" { 691 const allocator = std.testing.allocator; 692 693 { 694 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 695 defer parsed.deinit(allocator); 696 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 697 try std.testing.expectEqualStrings("some-repo", parsed.dir); 698 } 699 { 700 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 701 defer parsed.deinit(allocator); 702 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 703 try std.testing.expectEqualStrings("user/proj", parsed.dir); 704 } 705 { 706 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 707 defer parsed.deinit(allocator); 708 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 709 try std.testing.expectEqualStrings("repo", parsed.dir); 710 } 711 } 712