╭ serve_ssh.zig ────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const xit = @import("xit"); 3 const rp = xit.repo; 4 const xitui = xit.xitui; 5 const StreamTerminal = xitui.stream_terminal.StreamTerminal; 6 const Size = xitui.layout.Size; 7 const ui = @import("./ui.zig"); 8 const ssh = @import("./serve_ssh_protocol.zig"); 9 const evt = @import("./event.zig"); 10 const serve_common = @import("./serve_common.zig"); 11 const fork = @import("./fork.zig"); 12 13 // listener resource limits. the watchdog gives unauthenticated peers a hard 14 // deadline, detects idle non-interactive sessions from protocol progress, and 15 // bounds the post-CLOSE drain. each connection holds two OS threads under 16 // std.Io.Threaded (session + watchdog), so the cap is sized by thread count. 17 const max_connections: u32 = 4096; 18 const watchdog_interval = std.Io.Duration.fromSeconds(5); 19 const preauth_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 net_server: *std.Io.net.Server, 63 tasks: *std.Io.Group, 64 err: *std.Io.Writer, 65 ) void { 66 const Context = struct { 67 io: std.Io, 68 allocator: std.mem.Allocator, 69 host_key: *const ssh.HostKey, 70 session_handler: *const SessionHandler, 71 err: *std.Io.Writer, 72 }; 73 74 const handle = struct { 75 fn h(ctx: Context, stream: std.Io.net.Stream) void { 76 defer stream.close(ctx.io); 77 78 const prev_count = active_connections.fetchAdd(1, .monotonic); 79 defer _ = active_connections.fetchSub(1, .monotonic); 80 if (prev_count >= max_connections) { 81 serve_common.logError(ctx.io, ctx.err, "ssh: connection limit reached, dropping\n", .{}); 82 return; 83 } 84 85 var idle_state = ssh.IdleState{}; 86 var watchdog_future = std.Io.concurrent(ctx.io, watchdog, .{ ctx.io, &stream, &idle_state }) catch |spawn_err| { 87 serve_common.logError(ctx.io, ctx.err, "ssh: watchdog spawn failed: {s}\n", .{@errorName(spawn_err)}); 88 return; 89 }; 90 defer watchdog_future.cancel(ctx.io); 91 92 // timed peeks need room for a complete encrypted packet 93 var recv_buf: [ssh.packet_buffer_size]u8 = undefined; 94 var send_buf: [4096]u8 = undefined; 95 var stream_reader = stream.reader(ctx.io, &recv_buf); 96 var stream_writer = stream.writer(ctx.io, &send_buf); 97 ssh.handleConnection( 98 ctx.io, 99 ctx.allocator, 100 &stream_reader.interface, 101 &stream_writer.interface, 102 ctx.host_key, 103 &idle_state, 104 ctx.session_handler, 105 ) catch |session_err| { 106 serve_common.logError(ctx.io, ctx.err, "ssh session failed: {s}\n", .{@errorName(session_err)}); 107 }; 108 } 109 }.h; 110 111 serve_common.runListener(io, net_server, tasks, err, "ssh", Context{ 112 .io = io, 113 .allocator = allocator, 114 .host_key = host_key, 115 .session_handler = session_handler, 116 .err = err, 117 }, handle); 118 } 119 120 // enforce a hard pre-auth deadline, an idle timeout for non-interactive 121 // sessions, and a bounded close drain. interactive sessions are exempt only 122 // from the idle timeout; the watchdog remains available to break a stalled 123 // teardown. 124 fn watchdog(io: std.Io, stream: *const std.Io.net.Stream, idle_state: *ssh.IdleState) void { 125 var last_seen: u64 = 0; 126 var preauth_ticks: u32 = 0; 127 var idle_ticks: u32 = 0; 128 var closing_ticks: u32 = 0; 129 while (true) { 130 io.sleep(watchdog_interval, .awake) catch return; // canceled — connection is done 131 132 if (idle_state.closing.load(.acquire)) { 133 closing_ticks += 1; 134 if (closing_ticks >= close_drain_timeout_ticks) { 135 stream.shutdown(io, .both) catch {}; 136 return; 137 } 138 continue; 139 } 140 141 if (!idle_state.authenticated.load(.acquire)) { 142 preauth_ticks += 1; 143 if (preauth_ticks >= preauth_timeout_ticks) { 144 stream.shutdown(io, .both) catch {}; 145 return; 146 } 147 continue; 148 } 149 150 if (idle_state.exempt.load(.monotonic)) continue; 151 const seen = idle_state.activity.load(.monotonic); 152 if (seen == last_seen) { 153 idle_ticks += 1; 154 if (idle_ticks >= idle_timeout_ticks) { 155 stream.shutdown(io, .both) catch {}; 156 return; 157 } 158 } else { 159 idle_ticks = 0; 160 } 161 last_seen = seen; 162 } 163 } 164 165 fn runTuiSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, pty: ssh.PtySize) !void { 166 // runTui owns the terminal, whose deinit restores the client's screen and 167 // runs as the function unwinds — so any error it returns leaves the TUI torn 168 // down and we can surface the failure on the restored screen before exiting. 169 runTui(handler, sess, pty) catch |err| { 170 serve_common.logError(sess.conn.io, handler.err, "ssh tui session failed: {s}\n", .{@errorName(err)}); 171 var buf: [256]u8 = undefined; 172 const msg = std.fmt.bufPrint(&buf, "haxy ssh: {s}\r\n", .{@errorName(err)}) catch "haxy ssh: internal error\r\n"; 173 sess.writeBytes(msg) catch {}; 174 try sess.exit(1); 175 return; 176 }; 177 try sess.exit(0); 178 } 179 180 fn runTui(handler: *const SessionHandler, sess: *ssh.SessionCtx, pty: ssh.PtySize) !void { 181 const allocator = sess.conn.allocator; 182 const io = sess.conn.io; 183 184 // some clients (notably scripted ssh with no local controlling tty) 185 // allocate a pty without ever sending a non-zero size. fall back to a 186 // conventional 80x24 in that case so render emits something. 187 const effective_pty = ssh.PtySize{ 188 .width_cells = if (pty.width_cells == 0) 80 else pty.width_cells, 189 .height_cells = if (pty.height_cells == 0) 24 else pty.height_cells, 190 }; 191 192 // session-lifetime allocations (login, prefs); Nav owns the per-page arenas. 193 var session_arena = std.heap.ArenaAllocator.init(allocator); 194 defer session_arena.deinit(); 195 196 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 197 var repo = try Repo.open(io, allocator, .{ .path = handler.admin_repo_path }); 198 defer repo.deinit(io, allocator); 199 var ui_session = try ui.Session.init(&session_arena, &repo, .{}); 200 ui_session.is_terminal = true; 201 ui_session.web_port = handler.wui_port; 202 ui_session.data.git_http_port = handler.git_http_port; 203 ui_session.data.git_ssh_port = handler.git_ssh_port; 204 ui_session.data.git_ssh_prefix = handler.git_ssh_prefix; 205 // let page builders open on-disk repos (sibling "repos" dir of the admin repo) 206 ui_session.io = io; 207 ui_session.repos_dir = try std.fs.path.join(session_arena.allocator(), &.{ std.fs.path.dirname(handler.admin_repo_path) orelse ".", "repos" }); 208 209 var nav = try ui.Nav.init(allocator, &ui_session); 210 defer nav.deinit(allocator); 211 212 var session_writer_buf: [8192]u8 = undefined; 213 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 214 215 // the terminal's deinit writes leave-alt / show-cursor / disable-mouse and 216 // flushes, restoring the client's screen. as a function-scoped defer it runs 217 // before runTui returns — on the normal path and on any error — so the 218 // caller can write to the client afterward (and sess.exit can close cleanly). 219 var terminal_size = Size{ 220 .width = effective_pty.width_cells, 221 .height = effective_pty.height_cells, 222 }; 223 var terminal_maybe: ?StreamTerminal = try StreamTerminal.init(allocator, &session_writer.interface, terminal_size); 224 defer if (terminal_maybe) |*terminal| terminal.deinit(); 225 226 // initial render — user sees the page immediately 227 if (terminal_maybe) |*terminal| _ = try terminal.render(&nav.root); 228 229 // event loop. nextEvent blocks until something interesting arrives; 230 // for each event, rebuild the widget tree and re-render so the user 231 // sees the effect of their input on the same iteration. 232 event_loop: while (true) { 233 const event = try nextTuiEvent(sess, if (terminal_maybe) |*terminal| terminal else null); 234 if (terminal_maybe) |*terminal| { 235 if (event) |ev| switch (ev) { 236 .data => |payload| { 237 defer allocator.free(payload); 238 try terminal.writeBytes(payload); 239 }, 240 .resize => |sz| { 241 terminal_size = .{ .width = sz.width_cells, .height = sz.height_cells }; 242 terminal.pushResize(terminal_size); 243 }, 244 .eof, .close => break :event_loop, 245 }; 246 while (terminal.popKey()) |key| { 247 try ui.inputKey(allocator, &nav.root, key, &ui_session); 248 } 249 } else { 250 switch (event.?) { 251 .data => |payload| { 252 defer allocator.free(payload); 253 if (std.mem.indexOfAny(u8, payload, "\r\n") == null) continue; 254 terminal_maybe = try StreamTerminal.init(allocator, &session_writer.interface, terminal_size); 255 }, 256 .resize => |sz| { 257 terminal_size = .{ .width = sz.width_cells, .height = sz.height_cells }; 258 continue; 259 }, 260 .eof, .close => break :event_loop, 261 } 262 } 263 264 if (ui_session.host_request) |request| { 265 ui_session.host_request = null; 266 switch (request) { 267 .show_copyable_text => |copyable_text| { 268 if (terminal_maybe) |*terminal| terminal.deinit(); 269 terminal_maybe = null; 270 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}); 271 try session_writer.interface.flush(); 272 continue; 273 }, 274 .sync_events => {}, 275 } 276 } 277 278 try ui_session.applyAndWritePending(io, allocator, &repo); 279 280 // pick up data written by other handles so the next navigation 281 // builds its page from a current moment 282 try ui_session.reloadMoment(allocator, &repo); 283 284 // reconcile navigation: forward to a new page, or back on escape 285 try nav.sync(allocator, &ui_session); 286 287 // the quit button (on the quit tab) asks the host to tear down 288 if (ui_session.quit_requested) break :event_loop; 289 290 try nav.root.build(allocator, .{ 291 .min_size = .{ .width = null, .height = null }, 292 .max_size = .{ .width = terminal_size.width, .height = terminal_size.height }, 293 }, nav.root.getFocus()); 294 if (terminal_maybe) |*terminal| _ = try terminal.render(&nav.root); 295 } 296 } 297 298 // only a lone ESC needs a deadline; longer CSI/SS3 fragments must remain 299 // buffered until complete. a timeout leaves partial SSH packets in the reader. 300 pub fn nextTuiEvent(sess: *ssh.SessionCtx, terminal: ?*StreamTerminal) !?ssh.Event { 301 if (terminal) |t| { 302 if (t.parser.esc_len == 1) { 303 sess.conn.read_timeout = escape_timeout.toDeadline(sess.conn.io); 304 defer sess.conn.read_timeout = .none; 305 return sess.nextEvent() catch |err| switch (err) { 306 error.Timeout => { 307 try t.flushEscape(); 308 return null; 309 }, 310 else => return err, 311 }; 312 } 313 } 314 return try sess.nextEvent(); 315 } 316 317 // --------------------------------------------------------------------------- 318 // git path (exec) 319 // --------------------------------------------------------------------------- 320 321 pub const GitService = enum { upload_pack, receive_pack }; 322 323 pub const ParsedGitCommand = struct { 324 service: GitService, 325 dir: []u8, 326 327 pub fn deinit(self: ParsedGitCommand, allocator: std.mem.Allocator) void { 328 allocator.free(self.dir); 329 } 330 }; 331 332 fn runGitSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, command: []const u8) !void { 333 const allocator = sess.conn.allocator; 334 const io = sess.conn.io; 335 336 const parsed = parseGitCommand(allocator, command) catch return writeError(sess, "unsupported command (expected git-upload-pack or git-receive-pack)"); 337 defer parsed.deinit(allocator); 338 const path = std.mem.trimStart(u8, parsed.dir, "/"); 339 const fork_prefix = "fork/"; 340 341 if (std.mem.startsWith(u8, path, fork_prefix)) { 342 const route = fork.parseRoute(path[fork_prefix.len..]) orelse return writeError(sess, "invalid fork path"); 343 const owner_repo = evt.parseOwnerRepoPath(route.identity) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 344 345 var admin = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = handler.admin_repo_path }); 346 defer admin.deinit(io, allocator); 347 var admin_arena = std.heap.ArenaAllocator.init(allocator); 348 defer admin_arena.deinit(); 349 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 350 const fork_id = try evt.parseEventId(&route.id); 351 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, &fork_id)) orelse 352 return writeError(sess, "patch draft not found"); 353 if (fork_record.removed) return writeError(sess, "patch draft not found"); 354 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, fork_record.event.user_id)) orelse 355 return writeError(sess, "invalid patch draft"); 356 if (user.removed) return writeError(sess, "invalid patch draft"); 357 if (parsed.service == .receive_pack and !isKeyInAuthorizedKeys(user.event.ssh_keys, &sess.fingerprint)) 358 return writeError(sess, "unauthorized: this SSH key is not registered to the patch author"); 359 360 const draft_path = try fork.forkPath(allocator, handler.repo_root_path, &route.id); 361 defer allocator.free(draft_path); 362 var draft = rp.AnyRepo(.xit, .{}).open(io, allocator, .{ .path = draft_path }) catch 363 return writeError(sess, "patch draft not found"); 364 defer draft.deinit(io, allocator); 365 var reader_buf: [4096]u8 = undefined; 366 var writer_buf: [4096]u8 = undefined; 367 var reader = ssh.SessionReader.init(sess, &reader_buf); 368 var writer = ssh.SessionWriter.init(sess, &writer_buf); 369 if (parsed.service == .upload_pack) { 370 switch (draft) { 371 inline else => |*repo| try repo.uploadPack(io, allocator, &reader.interface, &writer.interface, .{}), 372 } 373 } else { 374 const target = (try evt.Repo.readByOwnerAndName(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, owner_repo.owner, owner_repo.name)) orelse 375 return writeError(sess, "repo not found"); 376 if (!std.mem.eql(u8, fork_record.event.repo_id, &target.event_id)) return writeError(sess, "patch draft belongs to another repo"); 377 const target_id = std.fmt.bytesToHex(target.event_id, .lower); 378 const target_path = try std.fs.path.join(allocator, &.{ handler.repo_root_path, &target_id }); 379 defer allocator.free(target_path); 380 const author: evt.CommitAuthor = .{ .name = user.event.name, .email = user.event.email }; 381 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 382 switch (draft) { 383 inline else => |*repo| { 384 var target_repo = rp.Repo(.xit, repo.self_repo_opts).open(io, allocator, .{ .path = target_path }) catch 385 return writeError(sess, "repo not found or has the wrong hash"); 386 defer target_repo.deinit(io, allocator); 387 try fork.receivePack(repo.self_repo_opts, io, allocator, repo, &target_repo, &route.id, author, timestamp, &reader.interface, &writer.interface, handler.err); 388 }, 389 } 390 } 391 writer.interface.flush() catch {}; 392 try sess.exit(0); 393 return; 394 } 395 396 const repo_prefix = "repo/"; 397 const repo_identity = if (std.mem.startsWith(u8, path, repo_prefix)) path[repo_prefix.len..] else path; 398 399 const create_if_missing = parsed.service == .receive_pack; 400 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{}; 401 402 const owner_repo = evt.parseOwnerRepoPath(repo_identity) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 403 switch (try authorizeRepoKey(io, allocator, handler.admin_repo_path, owner_repo.owner, owner_repo.name, parsed.service, &sess.fingerprint)) { 404 .allowed => {}, 405 .denied => return switch (parsed.service) { 406 .upload_pack => writeError(sess, "unauthorized: this SSH key cannot read this repo"), 407 .receive_pack => writeError(sess, "unauthorized: this SSH key cannot push to this repo"), 408 }, 409 .not_found => return writeError(sess, "repo not found"), 410 } 411 412 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, handler.repo_root_path, handler.admin_repo_path, repo_identity, create_if_missing)) { 413 .ok => |p| p, 414 .invalid => return writeError(sess, "repo path must be <owner>/<repo>"), 415 .not_found => return writeError(sess, "repo not found"), 416 }; 417 defer allocator.free(repo_path); 418 419 if (try serveIfExists(repo_path, handler.repo_root_path, sess, io, allocator, parsed.service, handler.err)) { 420 try sess.exit(0); 421 return; 422 } 423 424 if (!create_if_missing) return writeError(sess, "repo not found"); 425 426 // create the on-disk repo for the just-minted event and serve the push 427 var repo = try createRepo(any_repo_opts.toRepoOpts(), io, allocator, repo_path); 428 defer repo.deinit(io, allocator); 429 try servePack(repo.self_repo_opts, &repo, handler.repo_root_path, sess, io, allocator, parsed.service, handler.err); 430 try sess.exit(0); 431 } 432 433 // serve an existing repo at `repo_path`, or return false if none is there 434 fn serveIfExists( 435 repo_path: []const u8, 436 repo_root_path: []const u8, 437 sess: *ssh.SessionCtx, 438 io: std.Io, 439 allocator: std.mem.Allocator, 440 service: GitService, 441 error_writer: *std.Io.Writer, 442 ) !bool { 443 // a bare open() creates the directory while probing for the repo, so only 444 // attempt it when the path already exists 445 std.Io.Dir.accessAbsolute(io, repo_path, .{}) catch return false; 446 447 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{}; 448 var any_repo = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 449 error.RepoNotFound => return false, 450 else => |e| return e, 451 }; 452 defer any_repo.deinit(io, allocator); 453 454 switch (any_repo) { 455 inline else => |*repo| try servePack(repo.self_repo_opts, repo, repo_root_path, sess, io, allocator, service, error_writer), 456 } 457 return true; 458 } 459 460 fn createRepo( 461 comptime repo_opts: rp.RepoOpts(.xit), 462 io: std.Io, 463 allocator: std.mem.Allocator, 464 repo_path: []const u8, 465 ) !rp.Repo(.xit, repo_opts) { 466 var repo = try rp.Repo(.xit, repo_opts).init(io, allocator, .{ .path = repo_path }); 467 errdefer repo.deinit(io, allocator); 468 try repo.setMergeAlgorithm(io, allocator, .diff3); 469 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 470 try repo.addConfig(io, allocator, .{ .name = "receive.denycurrentbranch", .value = "updateinstead" }); 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 evt.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