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