╭ 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 |err| { 198 serve_common.logError(sess.conn.io, handler.err, "ssh tui session failed: {s}\n", .{@errorName(err)}); 199 var buf: [256]u8 = undefined; 200 const msg = std.fmt.bufPrint(&buf, "haxy ssh: {s}\r\n", .{@errorName(err)}) catch "haxy ssh: internal error\r\n"; 201 sess.writeBytes(msg) catch {}; 202 try sess.exit(1); 203 return; 204 }; 205 try sess.exit(0); 206 } 207 208 fn runTui(handler: *const SessionHandler, sess: *ssh.SessionCtx, pty: ssh.PtySize) !void { 209 const allocator = sess.conn.allocator; 210 const io = sess.conn.io; 211 212 // some clients (notably scripted ssh with no local controlling tty) 213 // allocate a pty without ever sending a non-zero size. fall back to a 214 // conventional 80x24 in that case so render emits something. 215 const effective_pty = ssh.PtySize{ 216 .width_cells = if (pty.width_cells == 0) 80 else pty.width_cells, 217 .height_cells = if (pty.height_cells == 0) 24 else pty.height_cells, 218 }; 219 220 // session-lifetime allocations (login, prefs); Nav owns the per-page arenas. 221 var session_arena = std.heap.ArenaAllocator.init(allocator); 222 defer session_arena.deinit(); 223 224 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 225 var repo = try Repo.open(io, allocator, .{ .path = handler.admin_repo_path }); 226 defer repo.deinit(io, allocator); 227 var ui_session = try ui.Session.init(&session_arena, &repo, .{}); 228 ui_session.is_terminal = true; 229 ui_session.web_port = handler.wui_port; 230 ui_session.data.git_http_port = handler.git_http_port; 231 ui_session.data.git_ssh_port = handler.git_ssh_port; 232 ui_session.data.git_ssh_prefix = handler.git_ssh_prefix; 233 // let page builders open on-disk repos (sibling "repos" dir of the admin repo) 234 ui_session.io = io; 235 ui_session.repos_dir = try std.fs.path.join(session_arena.allocator(), &.{ std.fs.path.dirname(handler.admin_repo_path) orelse ".", "repos" }); 236 237 var nav = try ui.Nav.init(allocator, &ui_session); 238 defer nav.deinit(allocator); 239 240 var session_writer_buf: [8192]u8 = undefined; 241 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 242 243 // the terminal's deinit writes leave-alt / show-cursor / disable-mouse and 244 // flushes, restoring the client's screen. as a function-scoped defer it runs 245 // before runTui returns — on the normal path and on any error — so the 246 // caller can write to the client afterward (and sess.exit can close cleanly). 247 var terminal_size = Size{ 248 .width = effective_pty.width_cells, 249 .height = effective_pty.height_cells, 250 }; 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| _ = try terminal.render(&nav.root); 256 257 // event loop. nextEvent blocks until something interesting arrives; 258 // for each event, rebuild the widget tree and re-render so the user 259 // sees the effect of their input on the same iteration. 260 event_loop: while (true) { 261 const event = try nextTuiEvent(sess, if (terminal_maybe) |*terminal| terminal else null); 262 if (terminal_maybe) |*terminal| { 263 if (event) |ev| switch (ev) { 264 .data => |payload| { 265 defer allocator.free(payload); 266 try terminal.writeBytes(payload); 267 }, 268 .resize => |sz| { 269 terminal_size = .{ .width = sz.width_cells, .height = sz.height_cells }; 270 terminal.pushResize(terminal_size); 271 }, 272 .eof, .close => break :event_loop, 273 }; 274 while (terminal.popKey()) |key| { 275 try ui.inputKey(allocator, &nav.root, key, &ui_session); 276 } 277 } else { 278 switch (event orelse unreachable) { 279 .data => |payload| { 280 defer allocator.free(payload); 281 if (std.mem.indexOfAny(u8, payload, "\r\n") == null) continue; 282 terminal_maybe = try StreamTerminal.init(allocator, &session_writer.interface, terminal_size); 283 }, 284 .resize => |sz| { 285 terminal_size = .{ .width = sz.width_cells, .height = sz.height_cells }; 286 continue; 287 }, 288 .eof, .close => break :event_loop, 289 } 290 } 291 292 if (ui_session.host_request) |request| { 293 ui_session.host_request = null; 294 switch (request) { 295 .show_copyable_text => |copyable_text| { 296 if (terminal_maybe) |*terminal| terminal.deinit(); 297 terminal_maybe = null; 298 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}); 299 try session_writer.interface.flush(); 300 continue; 301 }, 302 .sync_events => {}, 303 } 304 } 305 306 try ui_session.applyAndWritePending(io, allocator, &repo); 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 try nav.sync(allocator, &ui_session); 314 315 // the quit button (on the quit tab) asks the host to tear down 316 if (ui_session.quit_requested) break :event_loop; 317 318 try nav.root.build(allocator, .{ 319 .min_size = .{ .width = null, .height = null }, 320 .max_size = .{ .width = terminal_size.width, .height = terminal_size.height }, 321 }, nav.root.getFocus()); 322 if (terminal_maybe) |*terminal| _ = try terminal.render(&nav.root); 323 } 324 } 325 326 // only a lone ESC needs a deadline; longer CSI/SS3 fragments must remain 327 // buffered until complete. a timeout leaves partial SSH packets in the reader. 328 pub fn nextTuiEvent(sess: *ssh.SessionCtx, terminal: ?*StreamTerminal) !?ssh.Event { 329 if (terminal) |t| { 330 if (t.parser.esc_len == 1) { 331 sess.conn.read_timeout = escape_timeout.toDeadline(sess.conn.io); 332 defer sess.conn.read_timeout = .none; 333 return sess.nextEvent() catch |err| switch (err) { 334 error.Timeout => { 335 try t.flushEscape(); 336 return null; 337 }, 338 else => return err, 339 }; 340 } 341 } 342 return try sess.nextEvent(); 343 } 344 345 // --------------------------------------------------------------------------- 346 // git path (exec) 347 // --------------------------------------------------------------------------- 348 349 pub const GitService = enum { upload_pack, receive_pack }; 350 351 pub const ParsedGitCommand = struct { 352 service: GitService, 353 dir: []u8, 354 355 pub fn deinit(self: ParsedGitCommand, allocator: std.mem.Allocator) void { 356 allocator.free(self.dir); 357 } 358 }; 359 360 fn runGitSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, command: []const u8) !void { 361 const allocator = sess.conn.allocator; 362 const io = sess.conn.io; 363 364 const parsed = parseGitCommand(allocator, command) catch return writeError(sess, "unsupported command (expected git-upload-pack or git-receive-pack)"); 365 defer parsed.deinit(allocator); 366 const path = std.mem.trimStart(u8, parsed.dir, "/"); 367 const fork_prefix = "fork/"; 368 369 if (std.mem.startsWith(u8, path, fork_prefix)) { 370 const route = fork.parseRoute(path[fork_prefix.len..]) orelse return writeError(sess, "invalid fork path"); 371 const owner_repo = evt.parseOwnerRepoPath(route.identity) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 372 373 var admin = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = handler.admin_repo_path }); 374 defer admin.deinit(io, allocator); 375 var admin_arena = std.heap.ArenaAllocator.init(allocator); 376 defer admin_arena.deinit(); 377 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 378 const fork_id = try evt.parseEventId(&route.id); 379 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, &fork_id)) orelse 380 return writeError(sess, "patch draft not found"); 381 if (fork_record.removed) return writeError(sess, "patch draft not found"); 382 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, fork_record.event.user_id)) orelse 383 return writeError(sess, "invalid patch draft"); 384 if (user.removed) return writeError(sess, "invalid patch draft"); 385 if (parsed.service == .receive_pack and !isKeyInAuthorizedKeys(user.event.ssh_keys, &sess.fingerprint)) 386 return writeError(sess, "unauthorized: this SSH key is not registered to the patch author"); 387 388 const draft_path = try fork.forkPath(allocator, handler.repo_root_path, &route.id); 389 defer allocator.free(draft_path); 390 var draft = rp.AnyRepo(.xit, .{ .ProgressCtx = *push.PushProgress }).open(io, allocator, .{ .path = draft_path }) catch 391 return writeError(sess, "patch draft not found"); 392 defer draft.deinit(io, allocator); 393 var reader_buf: [4096]u8 = undefined; 394 var writer_buf: [4096]u8 = undefined; 395 var reader = ssh.SessionReader.init(sess, &reader_buf); 396 var writer = ssh.SessionWriter.init(sess, &writer_buf); 397 if (parsed.service == .upload_pack) { 398 switch (draft) { 399 inline else => |*repo| try repo.uploadPack(io, allocator, &reader.interface, &writer.interface, .{}), 400 } 401 } else { 402 const target = (try evt.Repo.readByOwnerAndName(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, owner_repo.owner, owner_repo.name)) orelse 403 return writeError(sess, "repo not found"); 404 if (!std.mem.eql(u8, fork_record.event.repo_id, &target.event_id)) return writeError(sess, "patch draft belongs to another repo"); 405 const target_id = std.fmt.bytesToHex(target.event_id, .lower); 406 const target_path = try std.fs.path.join(allocator, &.{ handler.repo_root_path, &target_id }); 407 defer allocator.free(target_path); 408 const author: evt.CommitAuthor = .{ .name = user.event.name, .email = user.event.email }; 409 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 410 switch (draft) { 411 inline else => |*repo| { 412 var target_repo = rp.Repo(.xit, repo.self_repo_opts).open(io, allocator, .{ .path = target_path }) catch 413 return writeError(sess, "repo not found or has the wrong hash"); 414 defer target_repo.deinit(io, allocator); 415 try push.receiveFork(repo.self_repo_opts, io, allocator, repo, &target_repo, &route.id, author, timestamp, &reader.interface, &writer.interface, handler.err); 416 }, 417 } 418 } 419 writer.interface.flush() catch {}; 420 try sess.exit(0); 421 return; 422 } 423 424 const repo_prefix = "repo/"; 425 const repo_identity = if (std.mem.startsWith(u8, path, repo_prefix)) path[repo_prefix.len..] else path; 426 427 const create_if_missing = parsed.service == .receive_pack; 428 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{ .ProgressCtx = *push.PushProgress }; 429 430 const owner_repo = evt.parseOwnerRepoPath(repo_identity) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 431 switch (try authorizeRepoKey(io, allocator, handler.admin_repo_path, owner_repo.owner, owner_repo.name, parsed.service, &sess.fingerprint)) { 432 .allowed => {}, 433 .denied => return switch (parsed.service) { 434 .upload_pack => writeError(sess, "unauthorized: this SSH key cannot read this repo"), 435 .receive_pack => writeError(sess, "unauthorized: this SSH key cannot push to this repo"), 436 }, 437 .not_found => return writeError(sess, "repo not found"), 438 } 439 440 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, handler.repo_root_path, handler.admin_repo_path, repo_identity, create_if_missing)) { 441 .ok => |p| p, 442 .invalid => return writeError(sess, "repo path must be <owner>/<repo>"), 443 .not_found => return writeError(sess, "repo not found"), 444 }; 445 defer allocator.free(repo_path); 446 447 if (try serveIfExists(repo_path, handler.repo_root_path, sess, io, allocator, parsed.service, handler.err)) { 448 try sess.exit(0); 449 return; 450 } 451 452 if (!create_if_missing) return writeError(sess, "repo not found"); 453 454 // create the on-disk repo for the just-minted event and serve the push 455 var repo = try createRepo(any_repo_opts.toRepoOpts(), io, allocator, repo_path); 456 defer repo.deinit(io, allocator); 457 try servePack(repo.self_repo_opts, &repo, handler.repo_root_path, sess, io, allocator, parsed.service, handler.err); 458 try sess.exit(0); 459 } 460 461 // serve an existing repo at `repo_path`, or return false if none is there 462 fn serveIfExists( 463 repo_path: []const u8, 464 repo_root_path: []const u8, 465 sess: *ssh.SessionCtx, 466 io: std.Io, 467 allocator: std.mem.Allocator, 468 service: GitService, 469 error_writer: *std.Io.Writer, 470 ) !bool { 471 // a bare open() creates the directory while probing for the repo, so only 472 // attempt it when the path already exists 473 std.Io.Dir.accessAbsolute(io, repo_path, .{}) catch return false; 474 475 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{ .ProgressCtx = *push.PushProgress }; 476 var any_repo = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 477 error.RepoNotFound => return false, 478 else => |e| return e, 479 }; 480 defer any_repo.deinit(io, allocator); 481 482 switch (any_repo) { 483 inline else => |*repo| try servePack(repo.self_repo_opts, repo, repo_root_path, sess, io, allocator, service, error_writer), 484 } 485 return true; 486 } 487 488 fn createRepo( 489 comptime repo_opts: rp.RepoOpts(.xit), 490 io: std.Io, 491 allocator: std.mem.Allocator, 492 repo_path: []const u8, 493 ) !rp.Repo(.xit, repo_opts) { 494 var repo = try rp.Repo(.xit, repo_opts).init(io, allocator, .{ .path = repo_path, .bare = true }); 495 errdefer repo.deinit(io, allocator); 496 try repo.setMergeAlgorithm(io, allocator, .patch); 497 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 498 return repo; 499 } 500 501 // wrap the channel I/O in std.Io.Reader/Writer adapters so the repo's pack 502 // functions can consume them like any other stream, then run the requested 503 // service 504 fn servePack( 505 comptime repo_opts: rp.RepoOpts(.xit), 506 repo: *rp.Repo(.xit, repo_opts), 507 repo_root_path: []const u8, 508 sess: *ssh.SessionCtx, 509 io: std.Io, 510 allocator: std.mem.Allocator, 511 service: GitService, 512 error_writer: *std.Io.Writer, 513 ) !void { 514 var session_reader_buf: [4096]u8 = undefined; 515 var session_writer_buf: [4096]u8 = undefined; 516 var session_reader = ssh.SessionReader.init(sess, &session_reader_buf); 517 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 518 519 switch (service) { 520 .upload_pack => try repo.uploadPack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 521 .receive_pack => try push.receivePackAndConsume(repo_opts, io, allocator, repo, &session_reader.interface, &session_writer.interface, .{}, repo_root_path, error_writer), 522 } 523 524 // flush whatever the pack op buffered into our writer adapter 525 session_writer.interface.flush() catch {}; 526 } 527 528 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 529 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 530 defer tokens.deinit(); 531 532 const service_token = tokens.next() orelse return error.InvalidCommand; 533 const dir_token = tokens.next() orelse return error.InvalidCommand; 534 535 const service: GitService = 536 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 537 .upload_pack 538 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 539 .receive_pack 540 else 541 return error.UnsupportedService; 542 543 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 544 } 545 546 const RepoAuthorization = enum { allowed, denied, not_found }; 547 548 fn authorizeRepoKey( 549 io: std.Io, 550 allocator: std.mem.Allocator, 551 admin_repo_path: []const u8, 552 owner_name: []const u8, 553 repo_name: []const u8, 554 service: GitService, 555 fingerprint: *const [ssh.fingerprint_len]u8, 556 ) !RepoAuthorization { 557 var arena = std.heap.ArenaAllocator.init(allocator); 558 defer arena.deinit(); 559 560 var admin = rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 561 error.RepoNotFound => return .not_found, 562 else => |e| return e, 563 }; 564 defer admin.deinit(io, allocator); 565 566 const moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 567 const repo = (try evt.Repo.readByOwnerAndName(evt.AdminDB, evt.admin_repo_opts.hash, moment, &arena, owner_name, repo_name)) orelse { 568 if (service == .upload_pack) return .not_found; 569 const owner = (try evt.User.readByName(io, allocator, admin_repo_path, &arena, owner_name)) orelse return .not_found; 570 return if (isKeyInAuthorizedKeys(owner.event.ssh_keys, fingerprint)) .allowed else .denied; 571 }; 572 573 if ((service == .upload_pack and repo.repo.event.read_access == .public) or 574 (service == .receive_pack and repo.repo.event.write_access == .public)) return .allowed; 575 if (try keyBelongsToUser(moment, &arena, repo.repo.event.user_id, fingerprint)) return .allowed; 576 577 const user_id_lists: []const []const u8 = switch (service) { 578 .upload_pack => &.{ repo.repo.event.write_user_ids, repo.repo.event.read_user_ids }, 579 .receive_pack => &.{repo.repo.event.write_user_ids}, 580 }; 581 for (user_id_lists) |user_ids| { 582 var lines = std.mem.tokenizeScalar(u8, user_ids, '\n'); 583 while (lines.next()) |id| { 584 const user_id = try evt.parseEventId(id); 585 if (try keyBelongsToUser(moment, &arena, &user_id, fingerprint)) return .allowed; 586 } 587 } 588 return .denied; 589 } 590 591 fn keyBelongsToUser( 592 moment: evt.AdminDB.HashMap(.read_only), 593 arena: *std.heap.ArenaAllocator, 594 user_id: []const u8, 595 fingerprint: *const [ssh.fingerprint_len]u8, 596 ) !bool { 597 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, user_id)) orelse return false; 598 return !user.removed and isKeyInAuthorizedKeys(user.event.ssh_keys, fingerprint); 599 } 600 601 fn isKeyInAuthorizedKeys(ssh_keys: []const u8, fingerprint: *const [ssh.fingerprint_len]u8) bool { 602 var it = std.mem.splitScalar(u8, ssh_keys, '\n'); 603 while (it.next()) |line| { 604 const fp = fingerprintOfAuthorizedKey(line) orelse continue; 605 if (std.mem.eql(u8, &fp, fingerprint)) return true; 606 } 607 return false; 608 } 609 610 // the SHA256 fingerprint of one authorized_keys line, or null if the line is 611 // blank or not a parseable "<type> <base64> [comment]" entry 612 fn fingerprintOfAuthorizedKey(line: []const u8) ?[ssh.fingerprint_len]u8 { 613 var it = std.mem.tokenizeAny(u8, line, " \t\r"); 614 _ = it.next() orelse return null; // key type 615 const blob_b64 = it.next() orelse return null; 616 617 const decoder = std.base64.standard.Decoder; 618 const blob_len = decoder.calcSizeForSlice(blob_b64) catch return null; 619 var blob_buf: [4096]u8 = undefined; 620 if (blob_len > blob_buf.len) return null; 621 decoder.decode(blob_buf[0..blob_len], blob_b64) catch return null; 622 623 return ssh.formatFingerprint(blob_buf[0..blob_len]); 624 } 625 626 fn writeError(sess: *ssh.SessionCtx, comptime msg: []const u8) !void { 627 const body = "ERR haxy ssh: " ++ msg; 628 var packet: [body.len + 4]u8 = undefined; 629 const line = try std.fmt.bufPrint(&packet, "{x:0>4}{s}", .{ packet.len, body }); 630 try sess.writeBytes(line); 631 try sess.exit(1); 632 } 633 634 test "parseGitCommand rejects malformed input" { 635 const allocator = std.testing.allocator; 636 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 637 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 638 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 639 } 640 641 test "parseGitCommand happy paths" { 642 const allocator = std.testing.allocator; 643 644 { 645 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 646 defer parsed.deinit(allocator); 647 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 648 try std.testing.expectEqualStrings("some-repo", parsed.dir); 649 } 650 { 651 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 652 defer parsed.deinit(allocator); 653 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 654 try std.testing.expectEqualStrings("user/proj", parsed.dir); 655 } 656 { 657 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 658 defer parsed.deinit(allocator); 659 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 660 try std.testing.expectEqualStrings("repo", parsed.dir); 661 } 662 } 663