╭ serve_ssh.zig ────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯
1 const std = @import("std"); 2 const push = @import("push.zig"); 3 const xit = @import("xit"); 4 const rp = xit.repo; 5 const xitui = xit.xitui; 6 const StreamTerminal = xitui.stream_terminal.StreamTerminal; 7 const Size = xitui.layout.Size; 8 const ui = @import("./ui.zig"); 9 const ssh = @import("./serve_ssh_protocol.zig"); 10 const evt = @import("./event.zig"); 11 const serve_common = @import("./serve_common.zig"); 12 const fork = @import("./fork.zig"); 13 const progress = @import("./progress.zig"); 14 15 // listener resource limits. the watchdog gives peers a hard deadline to start 16 // a session, times out non-interactive sessions that stall while we're blocked 17 // on the peer, and bounds the post-CLOSE drain. 18 const max_connections: u32 = 4096; 19 const watchdog_interval = std.Io.Duration.fromSeconds(5); 20 const presession_timeout_ticks: u32 = 6; // 30 seconds 21 const idle_timeout_ticks: u32 = 24; // 120 seconds 22 const close_drain_timeout_ticks: u32 = 2; // 5-10 seconds 23 const escape_timeout: std.Io.Timeout = .{ .duration = .{ .raw = .fromMilliseconds(25), .clock = .awake } }; 24 25 var active_connections: std.atomic.Value(u32) = .init(0); 26 27 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{ .ProgressCtx = *progress.Sideband }; 28 29 pub const SessionHandler = struct { 30 admin_repo_path: []const u8, 31 users_dir: []const u8, 32 wui_port: u16, // port the web UI is served on, shown in the TUI footer's url 33 git_http_port: ?u16, 34 git_ssh_port: ?u16, 35 git_ssh_prefix: []const u8, 36 err: *std.Io.Writer, 37 38 /// returning without an exit leaves the protocol layer to send status 0 39 pub fn handleSession(self: *const SessionHandler, sess: *ssh.SessionCtx, request: ssh.Request) !void { 40 serve_common.logError(sess.conn.io, self.err, "ssh session: kind={s} key={s}\n", .{ @tagName(request), sess.fingerprint }); 41 switch (request) { 42 .shell => |shell| { 43 const pty = shell.pty orelse { 44 // a shell without a pty has no useful TUI to render; in 45 // openssh client terms this is `ssh -T host`. say so and 46 // exit non-zero. 47 try sess.writeBytes("haxy ssh: this server only serves the TUI when a pty is allocated (use a normal `ssh` invocation).\r\n"); 48 try sess.exit(1); 49 return; 50 }; 51 sess.exemptFromIdleTimeout(); 52 try runTuiSession(self, sess, pty, shell.color); 53 }, 54 .exec => |exec| { 55 try runGitSession(self, sess, exec); 56 }, 57 } 58 } 59 }; 60 61 pub fn runListener( 62 io: std.Io, 63 allocator: std.mem.Allocator, 64 host_key: *const ssh.HostKey, 65 session_handler: *const SessionHandler, 66 watchdog: *Watchdog, 67 net_server: *std.Io.net.Server, 68 tasks: *std.Io.Group, 69 err: *std.Io.Writer, 70 ) void { 71 const Context = struct { 72 io: std.Io, 73 allocator: std.mem.Allocator, 74 host_key: *const ssh.HostKey, 75 session_handler: *const SessionHandler, 76 watchdog: *Watchdog, 77 err: *std.Io.Writer, 78 }; 79 80 const handle = struct { 81 fn h(ctx: Context, stream: std.Io.net.Stream) void { 82 defer stream.close(ctx.io); 83 84 const prev_count = active_connections.fetchAdd(1, .acq_rel); 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 owner_repo = evt.parseOwnerRepoPath(repo_identity) orelse return writeError(sess, "repo path must be <owner>:<repo>"); 385 var author_arena = std.heap.ArenaAllocator.init(allocator); 386 defer author_arena.deinit(); 387 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)) { 388 .allowed => |user| user, 389 .create => |creator| return runCreatingPush(handler, sess, &creator, owner_repo.name, protocol_version, &reader.interface, &writer.interface), 390 .denied => return switch (parsed.service) { 391 .upload_pack => writeError(sess, "unauthorized: this SSH key cannot read this repo"), 392 .receive_pack => writeError(sess, "unauthorized: this SSH key cannot push to this repo"), 393 }, 394 .not_found => return writeError(sess, "repo not found"), 395 }; 396 397 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, handler.users_dir, handler.admin_repo_path, repo_identity)) { 398 .ok => |p| p, 399 .invalid => unreachable, // parsed above 400 .not_found => return writeError(sess, "repo not found"), 401 }; 402 defer allocator.free(repo_path); 403 404 var any_repo = try rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }); 405 defer any_repo.deinit(io, allocator); 406 407 switch (any_repo) { 408 inline else => |*repo| switch (parsed.service) { 409 .upload_pack => { 410 var sideband = progress.Sideband{ .writer = &writer.interface, .sess = sess }; 411 try repo.uploadPack(io, allocator, &reader.interface, &writer.interface, .{ .protocol_version = protocol_version }, &sideband); 412 }, 413 .receive_pack => try push.receivePackAndConsume(repo.self_repo_opts, io, allocator, repo, &reader.interface, &writer.interface, .{ .protocol_version = protocol_version }, author, handler.users_dir, handler.err, sess), 414 }, 415 } 416 } 417 418 // push to a repo that doesn't exist yet, creating it in the hash format the 419 // client's first command names 420 fn runCreatingPush( 421 handler: *const SessionHandler, 422 sess: *ssh.SessionCtx, 423 creator: *const RepoCreator, 424 name: []const u8, 425 protocol_version: xit.net_server_common.ProtocolVersion, 426 reader: *std.Io.Reader, 427 writer: *std.Io.Writer, 428 ) !void { 429 const allocator = sess.conn.allocator; 430 const io = sess.conn.io; 431 432 evt.Repo.validateName(name) catch return writeError(sess, "invalid repo name"); 433 434 try xit.net_server_receive_pack.advertiseUncreated(.xit, writer, .{ .protocol_version = protocol_version }); 435 try writer.flush(); 436 // a client with nothing to push creates nothing 437 const hash_kind = (try xit.net_server_receive_pack.peekObjectFormat(reader)) orelse return; 438 439 const location = evt.createRepo(io, allocator, handler.users_dir, &creator.owner_id, creator.owner, name, "", .private, hash_kind) catch |err| switch (err) { 440 error.NameTaken => return writeError(sess, "repo was just created by another push, try again"), 441 else => |e| return e, 442 }; 443 const repo_path = try evt.repoPath(allocator, handler.users_dir, &location.owner_id, &location.repo_id); 444 defer allocator.free(repo_path); 445 446 switch (hash_kind) { 447 inline else => |kind| { 448 var repo = try rp.Repo(.xit, any_repo_opts.toRepoOptsWithHash(kind)).open(io, allocator, .{ .path = repo_path }); 449 defer repo.deinit(io, allocator); 450 // stateless since the advertisement already went out 451 try push.receivePackAndConsume(repo.self_repo_opts, io, allocator, &repo, reader, writer, .{ .protocol_version = protocol_version, .is_stateless = true }, creator.owner, handler.users_dir, handler.err, sess); 452 }, 453 } 454 } 455 456 // serve a patch draft: anyone may fetch it, only its author may push to it 457 fn runForkSession( 458 handler: *const SessionHandler, 459 sess: *ssh.SessionCtx, 460 fork_path: []const u8, 461 service: GitService, 462 protocol_version: xit.net_server_common.ProtocolVersion, 463 reader: *std.Io.Reader, 464 writer: *std.Io.Writer, 465 ) !void { 466 const allocator = sess.conn.allocator; 467 const io = sess.conn.io; 468 469 const route = fork.parseRoute(fork_path) orelse return writeError(sess, "invalid fork path"); 470 // the route names the forker and the target repo 471 const forker_repo = evt.parseOwnerRepoPath(route.identity) orelse return writeError(sess, "repo path must be <forker>:<repo>"); 472 473 var admin = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = handler.admin_repo_path }); 474 defer admin.deinit(io, allocator); 475 var admin_arena = std.heap.ArenaAllocator.init(allocator); 476 defer admin_arena.deinit(); 477 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 478 const fork_id = try evt.parseEventId(&route.id); 479 const forker_id = (try evt.User.readIdByName(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, forker_repo.owner)) orelse 480 return writeError(sess, "patch draft not found"); 481 const fork_record = (try evt.readForkById(io, allocator, &admin_arena, handler.users_dir, &forker_id, &fork_id)) orelse 482 return writeError(sess, "patch draft not found"); 483 if (fork_record.removed) return writeError(sess, "patch draft not found"); 484 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, &forker_id)) orelse 485 return writeError(sess, "invalid patch draft"); 486 if (user.removed) return writeError(sess, "invalid patch draft"); 487 if (service == .receive_pack and !isKeyInAuthorizedKeys(user.event.ssh_keys, &sess.fingerprint)) 488 return writeError(sess, "unauthorized: this SSH key is not registered to the patch author"); 489 490 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], forker_id)) orelse 491 return writeError(sess, "repo not found"); 492 // patches that are off take their drafts with them 493 const patch_role = target.repo.event.patch_role orelse return writeError(sess, "patch draft not found"); 494 if (service == .receive_pack) { 495 const role = target.role orelse return writeError(sess, "repo not found"); 496 if (!role.atLeast(patch_role)) return writeError(sess, "unauthorized: your role in this repo may not write patches"); 497 } 498 499 const draft_path = try fork.forkPath(allocator, handler.users_dir, &forker_id, &fork_id); 500 defer allocator.free(draft_path); 501 var draft = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = draft_path }) catch 502 return writeError(sess, "patch draft not found"); 503 defer draft.deinit(io, allocator); 504 if (service == .upload_pack) { 505 var sideband = progress.Sideband{ .writer = writer, .sess = sess }; 506 switch (draft) { 507 inline else => |*repo| try repo.uploadPack(io, allocator, reader, writer, .{ .protocol_version = protocol_version }, &sideband), 508 } 509 } else { 510 if (!std.mem.eql(u8, target.repo.event.name, forker_repo.name)) return writeError(sess, "patch draft belongs to another repo"); 511 const target_path = try evt.repoPath(allocator, handler.users_dir, fork_record.event.repo_user_id, fork_record.event.repo_id); 512 defer allocator.free(target_path); 513 const author: evt.CommitAuthor = .{ .name = user.event.name, .email = user.event.email }; 514 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 515 switch (draft) { 516 inline else => |*repo| { 517 var target_repo = rp.Repo(.xit, repo.self_repo_opts).open(io, allocator, .{ .path = target_path }) catch 518 return writeError(sess, "repo not found or has the wrong hash"); 519 defer target_repo.deinit(io, allocator); 520 try push.receiveFork(repo.self_repo_opts, io, allocator, repo, &target_repo, handler.users_dir, &route.id, author, timestamp, reader, writer, handler.err, sess); 521 }, 522 } 523 } 524 } 525 526 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 527 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 528 defer tokens.deinit(); 529 530 const service_token = tokens.next() orelse return error.InvalidCommand; 531 const dir_token = tokens.next() orelse return error.InvalidCommand; 532 533 const service: GitService = 534 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 535 .upload_pack 536 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 537 .receive_pack 538 else 539 return error.UnsupportedService; 540 541 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 542 } 543 544 const RepoAuthorization = union(enum) { allowed: ?evt.CommitAuthor, create: RepoCreator, denied, not_found }; 545 546 // the owner of a repo a push may create 547 const RepoCreator = struct { 548 owner_id: [evt.event_id_size]u8, 549 owner: evt.CommitAuthor, 550 }; 551 552 fn authorizeRepoKey( 553 io: std.Io, 554 arena: *std.heap.ArenaAllocator, 555 admin_repo_path: []const u8, 556 users_dir: []const u8, 557 owner_name: []const u8, 558 repo_name: []const u8, 559 service: GitService, 560 fingerprint: *const [ssh.fingerprint_len]u8, 561 ) !RepoAuthorization { 562 const allocator = arena.child_allocator; 563 var admin = rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 564 error.RepoNotFound => return .not_found, 565 else => |e| return e, 566 }; 567 defer admin.deinit(io, allocator); 568 569 const moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 570 // no viewer yet, so this carries the base role 571 const repo = (try evt.readRepoByOwnerAndName(io, allocator, arena, moment, users_dir, owner_name, repo_name, null)) orelse { 572 if (service == .upload_pack) return .not_found; 573 const owner_id = (try evt.User.readIdByName(evt.AdminDB, evt.admin_repo_opts.hash, moment, owner_name)) orelse return .not_found; 574 const owner = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, &owner_id)) orelse unreachable; 575 return if (isKeyInAuthorizedKeys(owner.event.ssh_keys, fingerprint)) 576 .{ .create = .{ .owner_id = owner_id, .owner = .{ .name = owner.event.name, .email = owner.event.email } } } 577 else 578 .denied; 579 }; 580 581 const min_role: evt.Repo.Role = switch (service) { 582 .upload_pack => .read, 583 .receive_pack => .write, 584 }; 585 // skip the key lookups when the base role is enough 586 if (repo.role) |base| { 587 if (base.atLeast(min_role)) return .{ .allowed = null }; 588 } 589 590 // the creator owns the repo 591 const owner_id = repo.repo.event.user_id[0..evt.event_id_size]; 592 if (try authorWithKey(moment, arena, owner_id, fingerprint)) |author| return .{ .allowed = author }; 593 594 // anyone else holding the key needs a grant with the role. a key can be 595 // shared, so a grant that falls short doesn't end the search. 596 for (try evt.readRepoGrants(io, allocator, arena, users_dir, owner_id, &repo.event_id)) |grant| { 597 if (!grant.role.atLeast(min_role)) continue; 598 if (try authorWithKey(moment, arena, grant.user_id, fingerprint)) |author| return .{ .allowed = author }; 599 } 600 return .denied; 601 } 602 603 // the user as a commit author, or null unless they hold the key 604 fn authorWithKey( 605 moment: evt.AdminDB.HashMap(.read_only), 606 arena: *std.heap.ArenaAllocator, 607 user_id: []const u8, 608 fingerprint: *const [ssh.fingerprint_len]u8, 609 ) !?evt.CommitAuthor { 610 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, user_id)) orelse return null; 611 if (user.removed or !isKeyInAuthorizedKeys(user.event.ssh_keys, fingerprint)) return null; 612 return .{ .name = user.event.name, .email = user.event.email }; 613 } 614 615 fn isKeyInAuthorizedKeys(ssh_keys: []const u8, fingerprint: *const [ssh.fingerprint_len]u8) bool { 616 var it = std.mem.splitScalar(u8, ssh_keys, '\n'); 617 while (it.next()) |line| { 618 const fp = fingerprintOfAuthorizedKey(line) orelse continue; 619 if (std.mem.eql(u8, &fp, fingerprint)) return true; 620 } 621 return false; 622 } 623 624 // the SHA256 fingerprint of one authorized_keys line, or null if the line is 625 // blank or not a parseable "<type> <base64> [comment]" entry 626 fn fingerprintOfAuthorizedKey(line: []const u8) ?[ssh.fingerprint_len]u8 { 627 var it = std.mem.tokenizeAny(u8, line, " \t\r"); 628 _ = it.next() orelse return null; // key type 629 const blob_b64 = it.next() orelse return null; 630 631 const decoder = std.base64.standard.Decoder; 632 const blob_len = decoder.calcSizeForSlice(blob_b64) catch return null; 633 var blob_buf: [4096]u8 = undefined; 634 if (blob_len > blob_buf.len) return null; 635 decoder.decode(blob_buf[0..blob_len], blob_b64) catch return null; 636 637 return ssh.formatFingerprint(blob_buf[0..blob_len]); 638 } 639 640 fn writeError(sess: *ssh.SessionCtx, comptime msg: []const u8) !void { 641 const body = "ERR haxy ssh: " ++ msg; 642 var packet: [body.len + 4]u8 = undefined; 643 const line = try std.fmt.bufPrint(&packet, "{x:0>4}{s}", .{ packet.len, body }); 644 try sess.writeBytes(line); 645 try sess.exit(1); 646 } 647 648 test "parseGitCommand rejects malformed input" { 649 const allocator = std.testing.allocator; 650 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 651 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 652 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 653 } 654 655 test "parseGitCommand happy paths" { 656 const allocator = std.testing.allocator; 657 658 { 659 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 660 defer parsed.deinit(allocator); 661 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 662 try std.testing.expectEqualStrings("some-repo", parsed.dir); 663 } 664 { 665 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 666 defer parsed.deinit(allocator); 667 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 668 try std.testing.expectEqualStrings("user/proj", parsed.dir); 669 } 670 { 671 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 672 defer parsed.deinit(allocator); 673 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 674 try std.testing.expectEqualStrings("repo", parsed.dir); 675 } 676 } 677