╭ 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 14 // listener resource limits. the watchdog gives peers a hard deadline to start 15 // a session, times out non-interactive sessions that stall while we're blocked 16 // on the peer, and bounds the post-CLOSE drain. 17 const max_connections: u32 = 4096; 18 const watchdog_interval = std.Io.Duration.fromSeconds(5); 19 const presession_timeout_ticks: u32 = 6; // 30 seconds 20 const idle_timeout_ticks: u32 = 24; // 120 seconds 21 const close_drain_timeout_ticks: u32 = 2; // 5-10 seconds 22 const escape_timeout: std.Io.Timeout = .{ .duration = .{ .raw = .fromMilliseconds(25), .clock = .awake } }; 23 24 var active_connections: std.atomic.Value(u32) = .init(0); 25 26 pub const SessionHandler = struct { 27 admin_repo_path: []const u8, 28 repo_root_path: []const u8, 29 wui_port: u16, // port the web UI is served on, shown in the TUI footer's url 30 git_http_port: ?u16, 31 git_ssh_port: ?u16, 32 git_ssh_prefix: []const u8, 33 err: *std.Io.Writer, 34 35 pub fn handleSession(self: *const SessionHandler, sess: *ssh.SessionCtx, request: ssh.Request) !void { 36 serve_common.logError(sess.conn.io, self.err, "ssh session: kind={s} key={s}\n", .{ @tagName(request), sess.fingerprint }); 37 switch (request) { 38 .shell => |pty_maybe| { 39 const pty = pty_maybe orelse { 40 // a shell without a pty has no useful TUI to render; in 41 // openssh client terms this is `ssh -T host`. say so and 42 // exit non-zero. 43 try sess.writeBytes("haxy ssh: this server only serves the TUI when a pty is allocated (use a normal `ssh` invocation).\r\n"); 44 try sess.exit(1); 45 return; 46 }; 47 sess.exemptFromIdleTimeout(); 48 try runTuiSession(self, sess, pty); 49 }, 50 .exec => |command| { 51 try runGitSession(self, sess, command); 52 }, 53 } 54 } 55 }; 56 57 pub fn runListener( 58 io: std.Io, 59 allocator: std.mem.Allocator, 60 host_key: *const ssh.HostKey, 61 session_handler: *const SessionHandler, 62 watchdog: *Watchdog, 63 net_server: *std.Io.net.Server, 64 tasks: *std.Io.Group, 65 err: *std.Io.Writer, 66 ) void { 67 const Context = struct { 68 io: std.Io, 69 allocator: std.mem.Allocator, 70 host_key: *const ssh.HostKey, 71 session_handler: *const SessionHandler, 72 watchdog: *Watchdog, 73 err: *std.Io.Writer, 74 }; 75 76 const handle = struct { 77 fn h(ctx: Context, stream: std.Io.net.Stream) void { 78 defer stream.close(ctx.io); 79 80 const prev_count = active_connections.fetchAdd(1, .monotonic); 81 defer _ = active_connections.fetchSub(1, .monotonic); 82 if (prev_count >= max_connections) { 83 serve_common.logError(ctx.io, ctx.err, "ssh: connection limit reached, dropping\n", .{}); 84 return; 85 } 86 87 var connection = Watchdog.Connection{ .stream = &stream }; 88 ctx.watchdog.add(ctx.io, &connection); 89 defer ctx.watchdog.remove(ctx.io, &connection); 90 91 // timed peeks need room for a complete encrypted packet 92 var recv_buf: [ssh.packet_buffer_size]u8 = undefined; 93 var send_buf: [4096]u8 = undefined; 94 var stream_reader = stream.reader(ctx.io, &recv_buf); 95 var stream_writer = stream.writer(ctx.io, &send_buf); 96 ssh.handleConnection( 97 ctx.io, 98 ctx.allocator, 99 &stream_reader.interface, 100 &stream_writer.interface, 101 ctx.host_key, 102 &connection.idle_state, 103 ctx.session_handler, 104 ) catch |session_err| { 105 serve_common.logError(ctx.io, ctx.err, "ssh session failed: {s}\n", .{@errorName(session_err)}); 106 }; 107 } 108 }.h; 109 110 // without the watchdog nothing bounds a connection, so don't listen 111 tasks.concurrent(io, Watchdog.run, .{ watchdog, io }) catch |spawn_err| { 112 serve_common.logError(io, err, "ssh: watchdog spawn failed: {s}\n", .{@errorName(spawn_err)}); 113 return; 114 }; 115 116 serve_common.runListener(io, net_server, tasks, err, "ssh", Context{ 117 .io = io, 118 .allocator = allocator, 119 .host_key = host_key, 120 .session_handler = session_handler, 121 .watchdog = watchdog, 122 .err = err, 123 }, handle); 124 } 125 126 /// one task watches every connection. a connection links its entry only 127 /// while it runs, so the watchdog never sees a closed stream. 128 pub const Watchdog = struct { 129 mutex: std.Io.Mutex = .init, 130 connections: std.DoublyLinkedList = .{}, 131 132 const Connection = struct { 133 node: std.DoublyLinkedList.Node = .{}, 134 stream: *const std.Io.net.Stream, 135 idle_state: ssh.IdleState = .{}, 136 // tick state, touched only by the watchdog 137 last_seen: u64 = 0, 138 presession_ticks: u32 = 0, 139 idle_ticks: u32 = 0, 140 closing_ticks: u32 = 0, 141 142 // interactive sessions are exempt only from the idle timeout, so a 143 // stalled teardown can still be broken 144 fn timedOut(self: *Connection) bool { 145 if (self.idle_state.closing.load(.acquire)) { 146 self.closing_ticks += 1; 147 return self.closing_ticks >= close_drain_timeout_ticks; 148 } 149 if (!self.idle_state.session_started.load(.acquire)) { 150 self.presession_ticks += 1; 151 return self.presession_ticks >= presession_timeout_ticks; 152 } 153 if (self.idle_state.exempt.load(.acquire)) return false; 154 155 // our own work between packets is not the peer idling 156 const seen = self.idle_state.activity.load(.monotonic); 157 defer self.last_seen = seen; 158 if (self.idle_state.waiting.load(.acquire) and seen == self.last_seen) { 159 self.idle_ticks += 1; 160 } else { 161 self.idle_ticks = 0; 162 } 163 return self.idle_ticks >= idle_timeout_ticks; 164 } 165 }; 166 167 fn add(self: *Watchdog, io: std.Io, connection: *Connection) void { 168 self.mutex.lockUncancelable(io); 169 defer self.mutex.unlock(io); 170 self.connections.append(&connection.node); 171 } 172 173 fn remove(self: *Watchdog, io: std.Io, connection: *Connection) void { 174 self.mutex.lockUncancelable(io); 175 defer self.mutex.unlock(io); 176 self.connections.remove(&connection.node); 177 } 178 179 fn run(self: *Watchdog, io: std.Io) void { 180 while (true) { 181 io.sleep(watchdog_interval, .awake) catch return; 182 self.mutex.lock(io) catch return; 183 defer self.mutex.unlock(io); 184 var node = self.connections.first; 185 while (node) |n| : (node = n.next) { 186 const connection: *Connection = @fieldParentPtr("node", n); 187 if (connection.timedOut()) connection.stream.shutdown(io, .both) catch {}; 188 } 189 } 190 } 191 }; 192 193 fn runTuiSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, pty: ssh.PtySize) !void { 194 // runTui owns the terminal, whose deinit restores the client's screen and 195 // runs as the function unwinds — so any error it returns leaves the TUI torn 196 // down and we can surface the failure on the restored screen before exiting. 197 runTui(handler, sess, pty) catch |tui_err| { 198 const err = sess.underlyingError(tui_err); 199 serve_common.logError(sess.conn.io, handler.err, "ssh tui session failed: {s}\n", .{@errorName(err)}); 200 var buf: [256]u8 = undefined; 201 const msg = std.fmt.bufPrint(&buf, "haxy ssh: {s}\r\n", .{@errorName(err)}) catch "haxy ssh: internal error\r\n"; 202 sess.writeBytes(msg) catch {}; 203 try sess.exit(1); 204 return; 205 }; 206 try sess.exit(0); 207 } 208 209 fn runTui(handler: *const SessionHandler, sess: *ssh.SessionCtx, pty: ssh.PtySize) !void { 210 const allocator = sess.conn.allocator; 211 const io = sess.conn.io; 212 213 // some clients (notably scripted ssh with no local controlling tty) 214 // allocate a pty without ever sending a non-zero size. fall back to a 215 // conventional 80x24 in that case so render emits something. 216 const effective_pty = ssh.PtySize{ 217 .width_cells = if (pty.width_cells == 0) 80 else pty.width_cells, 218 .height_cells = if (pty.height_cells == 0) 24 else pty.height_cells, 219 }; 220 221 // session-lifetime allocations (login, prefs); Nav owns the per-page arenas. 222 var session_arena = std.heap.ArenaAllocator.init(allocator); 223 defer session_arena.deinit(); 224 225 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 226 var repo = try Repo.open(io, allocator, .{ .path = handler.admin_repo_path }); 227 defer repo.deinit(io, allocator); 228 var ui_session = try ui.Session.init(&session_arena, &repo, .{}); 229 ui_session.is_terminal = true; 230 ui_session.web_port = handler.wui_port; 231 ui_session.data.git_http_port = handler.git_http_port; 232 ui_session.data.git_ssh_port = handler.git_ssh_port; 233 ui_session.data.git_ssh_prefix = handler.git_ssh_prefix; 234 // let page builders open on-disk repos (sibling "repos" dir of the admin repo) 235 ui_session.io = io; 236 ui_session.repos_dir = try std.fs.path.join(session_arena.allocator(), &.{ std.fs.path.dirname(handler.admin_repo_path) orelse ".", "repos" }); 237 238 var nav = try ui.Nav.init(allocator, &ui_session); 239 defer nav.deinit(allocator); 240 241 var session_writer_buf: [8192]u8 = undefined; 242 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 243 244 // the terminal's deinit writes leave-alt / show-cursor / disable-mouse and 245 // flushes, restoring the client's screen. as a function-scoped defer it runs 246 // before runTui returns — on the normal path and on any error — so the 247 // caller can write to the client afterward (and sess.exit can close cleanly). 248 var terminal_size = Size{ 249 .width = effective_pty.width_cells, 250 .height = effective_pty.height_cells, 251 }; 252 var terminal_maybe: ?StreamTerminal = try StreamTerminal.init(allocator, &session_writer.interface, terminal_size); 253 defer if (terminal_maybe) |*terminal| terminal.deinit(); 254 255 // initial render — user sees the page immediately 256 if (terminal_maybe) |*terminal| _ = try terminal.render(&nav.root); 257 258 // event loop. nextEvent blocks until something interesting arrives; 259 // for each event, rebuild the widget tree and re-render so the user 260 // sees the effect of their input on the same iteration. 261 event_loop: while (true) { 262 const event = try nextTuiEvent(sess, if (terminal_maybe) |*terminal| terminal else null); 263 if (terminal_maybe) |*terminal| { 264 if (event) |ev| switch (ev) { 265 .data => |payload| { 266 defer allocator.free(payload); 267 try terminal.writeBytes(payload); 268 }, 269 .resize => |sz| { 270 terminal_size = .{ .width = sz.width_cells, .height = sz.height_cells }; 271 terminal.pushResize(terminal_size); 272 }, 273 .eof, .close => break :event_loop, 274 }; 275 while (terminal.popKey()) |key| { 276 try ui.inputKey(allocator, &nav.root, key, &ui_session); 277 } 278 } else { 279 switch (event orelse unreachable) { 280 .data => |payload| { 281 defer allocator.free(payload); 282 if (std.mem.indexOfAny(u8, payload, "\r\n") == null) continue; 283 terminal_maybe = try StreamTerminal.init(allocator, &session_writer.interface, terminal_size); 284 }, 285 .resize => |sz| { 286 terminal_size = .{ .width = sz.width_cells, .height = sz.height_cells }; 287 continue; 288 }, 289 .eof, .close => break :event_loop, 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 } 305 } 306 307 try ui_session.applyAndWritePending(io, allocator, &repo); 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 try nav.sync(allocator, &ui_session); 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 a lone ESC needs a deadline; longer CSI/SS3 fragments must remain 328 // buffered until complete. a timeout leaves partial SSH packets in the reader. 329 pub fn nextTuiEvent(sess: *ssh.SessionCtx, terminal: ?*StreamTerminal) !?ssh.Event { 330 if (terminal) |t| { 331 if (t.parser.esc_len == 1) { 332 sess.conn.read_timeout = escape_timeout.toDeadline(sess.conn.io); 333 defer sess.conn.read_timeout = .none; 334 return sess.nextEvent() catch |err| switch (err) { 335 error.Timeout => { 336 try t.flushEscape(); 337 return null; 338 }, 339 else => return err, 340 }; 341 } 342 } 343 return try sess.nextEvent(); 344 } 345 346 // --------------------------------------------------------------------------- 347 // git path (exec) 348 // --------------------------------------------------------------------------- 349 350 pub const GitService = enum { upload_pack, receive_pack }; 351 352 pub const ParsedGitCommand = struct { 353 service: GitService, 354 dir: []u8, 355 356 pub fn deinit(self: ParsedGitCommand, allocator: std.mem.Allocator) void { 357 allocator.free(self.dir); 358 } 359 }; 360 361 fn runGitSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, command: []const u8) !void { 362 const allocator = sess.conn.allocator; 363 const io = sess.conn.io; 364 365 const parsed = parseGitCommand(allocator, command) catch return writeError(sess, "unsupported command (expected git-upload-pack or git-receive-pack)"); 366 defer parsed.deinit(allocator); 367 const path = std.mem.trimStart(u8, parsed.dir, "/"); 368 const fork_prefix = "fork/"; 369 370 if (std.mem.startsWith(u8, path, fork_prefix)) { 371 const route = fork.parseRoute(path[fork_prefix.len..]) orelse return writeError(sess, "invalid fork path"); 372 const owner_repo = evt.parseOwnerRepoPath(route.identity) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 373 374 var admin = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = handler.admin_repo_path }); 375 defer admin.deinit(io, allocator); 376 var admin_arena = std.heap.ArenaAllocator.init(allocator); 377 defer admin_arena.deinit(); 378 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 379 const fork_id = try evt.parseEventId(&route.id); 380 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, &fork_id)) orelse 381 return writeError(sess, "patch draft not found"); 382 if (fork_record.removed) return writeError(sess, "patch draft not found"); 383 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, fork_record.event.user_id)) orelse 384 return writeError(sess, "invalid patch draft"); 385 if (user.removed) return writeError(sess, "invalid patch draft"); 386 if (parsed.service == .receive_pack and !isKeyInAuthorizedKeys(user.event.ssh_keys, &sess.fingerprint)) 387 return writeError(sess, "unauthorized: this SSH key is not registered to the patch author"); 388 389 const draft_path = try fork.forkPath(allocator, handler.repo_root_path, &route.id); 390 defer allocator.free(draft_path); 391 var draft = rp.AnyRepo(.xit, .{ .ProgressCtx = *push.PushProgress }).open(io, allocator, .{ .path = draft_path }) catch 392 return writeError(sess, "patch draft not found"); 393 defer draft.deinit(io, allocator); 394 var reader_buf: [4096]u8 = undefined; 395 var writer_buf: [4096]u8 = undefined; 396 var reader = ssh.SessionReader.init(sess, &reader_buf); 397 var writer = ssh.SessionWriter.init(sess, &writer_buf); 398 if (parsed.service == .upload_pack) { 399 switch (draft) { 400 inline else => |*repo| try repo.uploadPack(io, allocator, &reader.interface, &writer.interface, .{}), 401 } 402 } else { 403 const target = (try evt.Repo.readByOwnerAndName(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, owner_repo.owner, owner_repo.name)) orelse 404 return writeError(sess, "repo not found"); 405 if (!std.mem.eql(u8, fork_record.event.repo_id, &target.event_id)) return writeError(sess, "patch draft belongs to another repo"); 406 const target_id = std.fmt.bytesToHex(target.event_id, .lower); 407 const target_path = try std.fs.path.join(allocator, &.{ handler.repo_root_path, &target_id }); 408 defer allocator.free(target_path); 409 const author: evt.CommitAuthor = .{ .name = user.event.name, .email = user.event.email }; 410 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 411 switch (draft) { 412 inline else => |*repo| { 413 var target_repo = rp.Repo(.xit, repo.self_repo_opts).open(io, allocator, .{ .path = target_path }) catch 414 return writeError(sess, "repo not found or has the wrong hash"); 415 defer target_repo.deinit(io, allocator); 416 try push.receiveFork(repo.self_repo_opts, io, allocator, repo, &target_repo, &route.id, author, timestamp, &reader.interface, &writer.interface, handler.err); 417 }, 418 } 419 } 420 writer.interface.flush() catch {}; 421 try sess.exit(0); 422 return; 423 } 424 425 const repo_prefix = "repo/"; 426 const repo_identity = if (std.mem.startsWith(u8, path, repo_prefix)) path[repo_prefix.len..] else path; 427 428 const create_if_missing = parsed.service == .receive_pack; 429 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{ .ProgressCtx = *push.PushProgress }; 430 431 const owner_repo = evt.parseOwnerRepoPath(repo_identity) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 432 switch (try authorizeRepoKey(io, allocator, handler.admin_repo_path, owner_repo.owner, owner_repo.name, parsed.service, &sess.fingerprint)) { 433 .allowed => {}, 434 .denied => return switch (parsed.service) { 435 .upload_pack => writeError(sess, "unauthorized: this SSH key cannot read this repo"), 436 .receive_pack => writeError(sess, "unauthorized: this SSH key cannot push to this repo"), 437 }, 438 .not_found => return writeError(sess, "repo not found"), 439 } 440 441 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, handler.repo_root_path, handler.admin_repo_path, repo_identity, create_if_missing)) { 442 .ok => |p| p, 443 .invalid => return writeError(sess, "repo path must be <owner>/<repo>"), 444 .not_found => return writeError(sess, "repo not found"), 445 }; 446 defer allocator.free(repo_path); 447 448 if (try serveIfExists(repo_path, handler.repo_root_path, sess, io, allocator, parsed.service, handler.err)) { 449 try sess.exit(0); 450 return; 451 } 452 453 if (!create_if_missing) return writeError(sess, "repo not found"); 454 455 // create the on-disk repo for the just-minted event and serve the push 456 var repo = try createRepo(any_repo_opts.toRepoOpts(), io, allocator, repo_path); 457 defer repo.deinit(io, allocator); 458 try servePack(repo.self_repo_opts, &repo, handler.repo_root_path, sess, io, allocator, parsed.service, handler.err); 459 try sess.exit(0); 460 } 461 462 // serve an existing repo at `repo_path`, or return false if none is there 463 fn serveIfExists( 464 repo_path: []const u8, 465 repo_root_path: []const u8, 466 sess: *ssh.SessionCtx, 467 io: std.Io, 468 allocator: std.mem.Allocator, 469 service: GitService, 470 error_writer: *std.Io.Writer, 471 ) !bool { 472 // a bare open() creates the directory while probing for the repo, so only 473 // attempt it when the path already exists 474 std.Io.Dir.accessAbsolute(io, repo_path, .{}) catch return false; 475 476 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{ .ProgressCtx = *push.PushProgress }; 477 var any_repo = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 478 error.RepoNotFound => return false, 479 else => |e| return e, 480 }; 481 defer any_repo.deinit(io, allocator); 482 483 switch (any_repo) { 484 inline else => |*repo| try servePack(repo.self_repo_opts, repo, repo_root_path, sess, io, allocator, service, error_writer), 485 } 486 return true; 487 } 488 489 fn createRepo( 490 comptime repo_opts: rp.RepoOpts(.xit), 491 io: std.Io, 492 allocator: std.mem.Allocator, 493 repo_path: []const u8, 494 ) !rp.Repo(.xit, repo_opts) { 495 var repo = try rp.Repo(.xit, repo_opts).init(io, allocator, .{ .path = repo_path, .bare = true }); 496 errdefer repo.deinit(io, allocator); 497 try repo.setMergeAlgorithm(io, allocator, .patch); 498 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 499 return repo; 500 } 501 502 // wrap the channel I/O in std.Io.Reader/Writer adapters so the repo's pack 503 // functions can consume them like any other stream, then run the requested 504 // service 505 fn servePack( 506 comptime repo_opts: rp.RepoOpts(.xit), 507 repo: *rp.Repo(.xit, repo_opts), 508 repo_root_path: []const u8, 509 sess: *ssh.SessionCtx, 510 io: std.Io, 511 allocator: std.mem.Allocator, 512 service: GitService, 513 error_writer: *std.Io.Writer, 514 ) !void { 515 var session_reader_buf: [4096]u8 = undefined; 516 var session_writer_buf: [4096]u8 = undefined; 517 var session_reader = ssh.SessionReader.init(sess, &session_reader_buf); 518 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 519 520 switch (service) { 521 .upload_pack => try repo.uploadPack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 522 .receive_pack => try push.receivePackAndConsume(repo_opts, io, allocator, repo, &session_reader.interface, &session_writer.interface, .{}, repo_root_path, error_writer), 523 } 524 525 // flush whatever the pack op buffered into our writer adapter 526 session_writer.interface.flush() catch {}; 527 } 528 529 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 530 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 531 defer tokens.deinit(); 532 533 const service_token = tokens.next() orelse return error.InvalidCommand; 534 const dir_token = tokens.next() orelse return error.InvalidCommand; 535 536 const service: GitService = 537 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 538 .upload_pack 539 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 540 .receive_pack 541 else 542 return error.UnsupportedService; 543 544 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 545 } 546 547 const RepoAuthorization = enum { allowed, denied, not_found }; 548 549 fn authorizeRepoKey( 550 io: std.Io, 551 allocator: std.mem.Allocator, 552 admin_repo_path: []const u8, 553 owner_name: []const u8, 554 repo_name: []const u8, 555 service: GitService, 556 fingerprint: *const [ssh.fingerprint_len]u8, 557 ) !RepoAuthorization { 558 var arena = std.heap.ArenaAllocator.init(allocator); 559 defer arena.deinit(); 560 561 var admin = rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 562 error.RepoNotFound => return .not_found, 563 else => |e| return e, 564 }; 565 defer admin.deinit(io, allocator); 566 567 const moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 568 const repo = (try evt.Repo.readByOwnerAndName(evt.AdminDB, evt.admin_repo_opts.hash, moment, &arena, owner_name, repo_name)) orelse { 569 if (service == .upload_pack) return .not_found; 570 const owner = (try evt.User.readByName(io, allocator, admin_repo_path, &arena, owner_name)) orelse return .not_found; 571 return if (isKeyInAuthorizedKeys(owner.event.ssh_keys, fingerprint)) .allowed else .denied; 572 }; 573 574 if ((service == .upload_pack and repo.repo.event.read_access == .public) or 575 (service == .receive_pack and repo.repo.event.write_access == .public)) return .allowed; 576 if (try keyBelongsToUser(moment, &arena, repo.repo.event.user_id, fingerprint)) return .allowed; 577 578 const user_id_lists: []const []const u8 = switch (service) { 579 .upload_pack => &.{ repo.repo.event.write_user_ids, repo.repo.event.read_user_ids }, 580 .receive_pack => &.{repo.repo.event.write_user_ids}, 581 }; 582 for (user_id_lists) |user_ids| { 583 var lines = std.mem.tokenizeScalar(u8, user_ids, '\n'); 584 while (lines.next()) |id| { 585 const user_id = try evt.parseEventId(id); 586 if (try keyBelongsToUser(moment, &arena, &user_id, fingerprint)) return .allowed; 587 } 588 } 589 return .denied; 590 } 591 592 fn keyBelongsToUser( 593 moment: evt.AdminDB.HashMap(.read_only), 594 arena: *std.heap.ArenaAllocator, 595 user_id: []const u8, 596 fingerprint: *const [ssh.fingerprint_len]u8, 597 ) !bool { 598 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, user_id)) orelse return false; 599 return !user.removed and isKeyInAuthorizedKeys(user.event.ssh_keys, fingerprint); 600 } 601 602 fn isKeyInAuthorizedKeys(ssh_keys: []const u8, fingerprint: *const [ssh.fingerprint_len]u8) bool { 603 var it = std.mem.splitScalar(u8, ssh_keys, '\n'); 604 while (it.next()) |line| { 605 const fp = fingerprintOfAuthorizedKey(line) orelse continue; 606 if (std.mem.eql(u8, &fp, fingerprint)) return true; 607 } 608 return false; 609 } 610 611 // the SHA256 fingerprint of one authorized_keys line, or null if the line is 612 // blank or not a parseable "<type> <base64> [comment]" entry 613 fn fingerprintOfAuthorizedKey(line: []const u8) ?[ssh.fingerprint_len]u8 { 614 var it = std.mem.tokenizeAny(u8, line, " \t\r"); 615 _ = it.next() orelse return null; // key type 616 const blob_b64 = it.next() orelse return null; 617 618 const decoder = std.base64.standard.Decoder; 619 const blob_len = decoder.calcSizeForSlice(blob_b64) catch return null; 620 var blob_buf: [4096]u8 = undefined; 621 if (blob_len > blob_buf.len) return null; 622 decoder.decode(blob_buf[0..blob_len], blob_b64) catch return null; 623 624 return ssh.formatFingerprint(blob_buf[0..blob_len]); 625 } 626 627 fn writeError(sess: *ssh.SessionCtx, comptime msg: []const u8) !void { 628 const body = "ERR haxy ssh: " ++ msg; 629 var packet: [body.len + 4]u8 = undefined; 630 const line = try std.fmt.bufPrint(&packet, "{x:0>4}{s}", .{ packet.len, body }); 631 try sess.writeBytes(line); 632 try sess.exit(1); 633 } 634 635 test "parseGitCommand rejects malformed input" { 636 const allocator = std.testing.allocator; 637 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 638 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 639 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 640 } 641 642 test "parseGitCommand happy paths" { 643 const allocator = std.testing.allocator; 644 645 { 646 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 647 defer parsed.deinit(allocator); 648 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 649 try std.testing.expectEqualStrings("some-repo", parsed.dir); 650 } 651 { 652 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 653 defer parsed.deinit(allocator); 654 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 655 try std.testing.expectEqualStrings("user/proj", parsed.dir); 656 } 657 { 658 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 659 defer parsed.deinit(allocator); 660 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 661 try std.testing.expectEqualStrings("repo", parsed.dir); 662 } 663 } 664