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