╭ 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 13 pub const SessionHandler = struct { 14 admin_repo_path: []const u8, 15 repo_root_path: []const u8, 16 // test mode serves repos directly by path instead of resolving them as 17 // <owner>/<repo> through the event store 18 is_test: bool, 19 err: *std.Io.Writer, 20 21 pub fn handleSession(self: *const SessionHandler, sess: *ssh.SessionCtx, request: ssh.Request) !void { 22 serve_common.logError(self.err, "ssh session: kind={s} key={s}\n", .{ @tagName(request), sess.fingerprint }); 23 switch (request) { 24 .shell => |pty_maybe| { 25 const pty = pty_maybe orelse { 26 // a shell without a pty has no useful TUI to render; in 27 // openssh client terms this is `ssh -T host`. say so and 28 // exit non-zero. 29 try sess.writeBytes("haxy ssh: this server only serves the TUI when a pty is allocated (use a normal `ssh` invocation).\r\n"); 30 try sess.exit(1); 31 return; 32 }; 33 try runTuiSession(self, sess, pty); 34 }, 35 .exec => |command| { 36 try runGitSession(self, sess, command); 37 }, 38 } 39 } 40 }; 41 42 pub fn runListener( 43 io: std.Io, 44 allocator: std.mem.Allocator, 45 host_key: *const ssh.HostKey, 46 session_handler: *const SessionHandler, 47 net_server: *std.Io.net.Server, 48 tasks: *std.Io.Group, 49 err: *std.Io.Writer, 50 ) void { 51 const Context = struct { 52 io: std.Io, 53 allocator: std.mem.Allocator, 54 host_key: *const ssh.HostKey, 55 session_handler: *const SessionHandler, 56 err: *std.Io.Writer, 57 }; 58 59 const handle = struct { 60 fn h(ctx: Context, stream: std.Io.net.Stream) void { 61 defer stream.close(ctx.io); 62 var recv_buf: [4096]u8 = undefined; 63 var send_buf: [4096]u8 = undefined; 64 var stream_reader = stream.reader(ctx.io, &recv_buf); 65 var stream_writer = stream.writer(ctx.io, &send_buf); 66 ssh.handleConnection( 67 ctx.io, 68 ctx.allocator, 69 &stream_reader.interface, 70 &stream_writer.interface, 71 ctx.host_key, 72 ctx.session_handler, 73 ) catch |session_err| { 74 serve_common.logError(ctx.err, "ssh session failed: {s}\n", .{@errorName(session_err)}); 75 }; 76 } 77 }.h; 78 79 serve_common.runListener(io, net_server, tasks, err, "ssh", Context{ 80 .io = io, 81 .allocator = allocator, 82 .host_key = host_key, 83 .session_handler = session_handler, 84 .err = err, 85 }, handle); 86 } 87 88 fn runTuiSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, pty: ssh.PtySize) !void { 89 // runTui owns the terminal, whose deinit restores the client's screen and 90 // runs as the function unwinds — so any error it returns leaves the TUI torn 91 // down and we can surface the failure on the restored screen before exiting. 92 runTui(handler, sess, pty) catch |err| { 93 serve_common.logError(handler.err, "ssh tui session failed: {s}\n", .{@errorName(err)}); 94 var buf: [256]u8 = undefined; 95 const msg = std.fmt.bufPrint(&buf, "haxy ssh: {s}\r\n", .{@errorName(err)}) catch "haxy ssh: internal error\r\n"; 96 sess.writeBytes(msg) catch {}; 97 try sess.exit(1); 98 return; 99 }; 100 try sess.exit(0); 101 } 102 103 fn runTui(handler: *const SessionHandler, sess: *ssh.SessionCtx, pty: ssh.PtySize) !void { 104 const allocator = sess.allocator; 105 const io = sess.io; 106 107 // some clients (notably scripted ssh with no local controlling tty) 108 // allocate a pty without ever sending a non-zero size. fall back to a 109 // conventional 80x24 in that case so render emits something. 110 const effective_pty = ssh.PtySize{ 111 .width_cells = if (pty.width_cells == 0) 80 else pty.width_cells, 112 .height_cells = if (pty.height_cells == 0) 24 else pty.height_cells, 113 }; 114 115 // session-lifetime allocations (login, prefs); Nav owns the per-page arenas. 116 var session_arena = std.heap.ArenaAllocator.init(allocator); 117 defer session_arena.deinit(); 118 119 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 120 var repo = try Repo.open(io, allocator, .{ .path = handler.admin_repo_path }); 121 defer repo.deinit(io, allocator); 122 var ui_session = try ui.Session.init(&session_arena, &repo, .{}); 123 ui_session.is_terminal = true; 124 // let page builders open on-disk repos (sibling "repos" dir of the admin repo) 125 ui_session.io = io; 126 ui_session.repos_dir = try std.fs.path.join(session_arena.allocator(), &.{ std.fs.path.dirname(handler.admin_repo_path) orelse ".", "repos" }); 127 128 var nav = try ui.Nav.init(allocator, &ui_session); 129 defer nav.deinit(allocator); 130 131 var session_writer_buf: [8192]u8 = undefined; 132 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 133 134 // the terminal's deinit writes leave-alt / show-cursor / disable-mouse and 135 // flushes, restoring the client's screen. as a function-scoped defer it runs 136 // before runTui returns — on the normal path and on any error — so the 137 // caller can write to the client afterward (and sess.exit can close cleanly). 138 var terminal = try StreamTerminal.init(allocator, &session_writer.interface, .{ 139 .width = effective_pty.width_cells, 140 .height = effective_pty.height_cells, 141 }); 142 defer terminal.deinit(); 143 144 var last_size = Size{ .width = 0, .height = 0 }; 145 var last_grid = try Grid.init(allocator, last_size); 146 defer last_grid.deinit(); 147 148 // initial render — user sees the page immediately 149 try nav.root.build(allocator, .{ 150 .min_size = .{ .width = null, .height = null }, 151 .max_size = .{ .width = last_size.width, .height = last_size.height }, 152 }, nav.root.getFocus()); 153 _ = try terminal.render(&nav.root, &last_grid, &last_size); 154 155 // event loop. nextEvent blocks until something interesting arrives; 156 // for each event, rebuild the widget tree and re-render so the user 157 // sees the effect of their input on the same iteration. 158 while (!terminal.shouldQuit()) { 159 const event = try sess.nextEvent(); 160 switch (event) { 161 .data => |payload| { 162 defer allocator.free(payload); 163 try terminal.writeBytes(payload); 164 while (terminal.popKey()) |key| { 165 try ui.inputKey(allocator, &nav.root, key, &ui_session); 166 } 167 }, 168 .resize => |sz| { 169 terminal.pushResize(.{ .width = sz.width_cells, .height = sz.height_cells }); 170 while (terminal.popKey()) |key| { 171 try ui.inputKey(allocator, &nav.root, key, &ui_session); 172 } 173 }, 174 .close => terminal.requestQuit(), 175 } 176 177 try ui_session.applyAndWritePending(io, allocator, &repo); 178 179 // reconcile navigation: forward to a new page, or back on escape 180 try nav.sync(allocator, &ui_session); 181 182 // the quit button (on the quit tab) asks the host to tear down 183 if (ui_session.quit_requested) terminal.requestQuit(); 184 185 try nav.root.build(allocator, .{ 186 .min_size = .{ .width = null, .height = null }, 187 .max_size = .{ .width = last_size.width, .height = last_size.height }, 188 }, nav.root.getFocus()); 189 _ = try terminal.render(&nav.root, &last_grid, &last_size); 190 } 191 } 192 193 // --------------------------------------------------------------------------- 194 // git path (exec) 195 // --------------------------------------------------------------------------- 196 197 pub const GitService = enum { upload_pack, receive_pack }; 198 199 pub const ParsedGitCommand = struct { 200 service: GitService, 201 dir: []u8, 202 203 pub fn deinit(self: ParsedGitCommand, allocator: std.mem.Allocator) void { 204 allocator.free(self.dir); 205 } 206 }; 207 208 fn runGitSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, command: []const u8) !void { 209 const allocator = sess.allocator; 210 const io = sess.io; 211 212 const parsed = parseGitCommand(allocator, command) catch return writeError(sess, "unsupported command (expected git-upload-pack or git-receive-pack)"); 213 defer parsed.deinit(allocator); 214 215 const create_if_missing = parsed.service == .receive_pack; 216 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{}; 217 218 // authenticate pushes: the authenticated key must be registered to the 219 // repo's owner. skipped in test mode, which serves repos directly by path. 220 if (create_if_missing and !handler.is_test) { 221 const owner_repo = evt.parseOwnerRepoPath(parsed.dir) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 222 if (!try isKeyAuthorized(io, allocator, handler.admin_repo_path, owner_repo.owner, &sess.fingerprint)) 223 return writeError(sess, "unauthorized: this SSH key is not registered to the repo owner"); 224 } 225 226 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, handler.is_test, handler.repo_root_path, handler.admin_repo_path, parsed.dir, create_if_missing)) { 227 .ok => |p| p, 228 .invalid => return writeError(sess, "repo path must be <owner>/<repo>"), 229 .not_found => return writeError(sess, "repo not found"), 230 }; 231 defer allocator.free(repo_path); 232 233 if (try serveIfExists(repo_path, sess, io, allocator, parsed.service)) { 234 try sess.exit(0); 235 return; 236 } 237 238 if (!create_if_missing) return writeError(sess, "repo not found"); 239 240 // create the on-disk repo for the just-minted event and serve the push 241 var repo = try createRepo(any_repo_opts.toRepoOpts(), io, allocator, repo_path); 242 defer repo.deinit(io, allocator); 243 try servePack(repo.self_repo_opts, &repo, sess, io, allocator, parsed.service); 244 try sess.exit(0); 245 } 246 247 // serve an existing repo at `repo_path`, or return false if none is there 248 fn serveIfExists( 249 repo_path: []const u8, 250 sess: *ssh.SessionCtx, 251 io: std.Io, 252 allocator: std.mem.Allocator, 253 service: GitService, 254 ) !bool { 255 // a bare open() creates the directory while probing for the repo, so only 256 // attempt it when the path already exists 257 std.Io.Dir.accessAbsolute(io, repo_path, .{}) catch return false; 258 259 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{}; 260 var any_repo = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 261 error.RepoNotFound => return false, 262 else => |e| return e, 263 }; 264 defer any_repo.deinit(io, allocator); 265 266 switch (any_repo) { 267 inline else => |*repo| try servePack(repo.self_repo_opts, repo, sess, io, allocator, service), 268 } 269 return true; 270 } 271 272 fn createRepo( 273 comptime repo_opts: rp.RepoOpts(.xit), 274 io: std.Io, 275 allocator: std.mem.Allocator, 276 repo_path: []const u8, 277 ) !rp.Repo(.xit, repo_opts) { 278 var repo = try rp.Repo(.xit, repo_opts).init(io, allocator, .{ .path = repo_path }); 279 errdefer repo.deinit(io, allocator); 280 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 281 try repo.addConfig(io, allocator, .{ .name = "receive.denycurrentbranch", .value = "updateinstead" }); 282 return repo; 283 } 284 285 // wrap the channel I/O in std.Io.Reader/Writer adapters so the repo's pack 286 // functions can consume them like any other stream, then run the requested 287 // service 288 fn servePack( 289 comptime repo_opts: rp.RepoOpts(.xit), 290 repo: *rp.Repo(.xit, repo_opts), 291 sess: *ssh.SessionCtx, 292 io: std.Io, 293 allocator: std.mem.Allocator, 294 service: GitService, 295 ) !void { 296 var session_reader_buf: [4096]u8 = undefined; 297 var session_writer_buf: [4096]u8 = undefined; 298 var session_reader = ssh.SessionReader.init(sess, &session_reader_buf); 299 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 300 301 switch (service) { 302 .upload_pack => try repo.uploadPack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 303 .receive_pack => try repo.receivePack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 304 } 305 306 // flush whatever the pack op buffered into our writer adapter 307 session_writer.interface.flush() catch {}; 308 } 309 310 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 311 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 312 defer tokens.deinit(); 313 314 const service_token = tokens.next() orelse return error.InvalidCommand; 315 const dir_token = tokens.next() orelse return error.InvalidCommand; 316 317 const service: GitService = 318 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 319 .upload_pack 320 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 321 .receive_pack 322 else 323 return error.UnsupportedService; 324 325 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 326 } 327 328 // true if `fingerprint` matches one of the named user's registered SSH keys 329 fn isKeyAuthorized( 330 io: std.Io, 331 allocator: std.mem.Allocator, 332 admin_repo_path: []const u8, 333 owner_name: []const u8, 334 fingerprint: *const [ssh.fingerprint_len]u8, 335 ) !bool { 336 var arena = std.heap.ArenaAllocator.init(allocator); 337 defer arena.deinit(); 338 339 const user = (try evt.User.readByName(io, allocator, admin_repo_path, &arena, owner_name)) orelse return false; 340 341 var it = std.mem.splitScalar(u8, user.ssh_keys, '\n'); 342 while (it.next()) |line| { 343 const fp = fingerprintOfAuthorizedKey(line) orelse continue; 344 if (std.mem.eql(u8, &fp, fingerprint)) return true; 345 } 346 return false; 347 } 348 349 // the SHA256 fingerprint of one authorized_keys line, or null if the line is 350 // blank or not a parseable "<type> <base64> [comment]" entry 351 fn fingerprintOfAuthorizedKey(line: []const u8) ?[ssh.fingerprint_len]u8 { 352 var it = std.mem.tokenizeAny(u8, line, " \t\r"); 353 _ = it.next() orelse return null; // key type 354 const blob_b64 = it.next() orelse return null; 355 356 const decoder = std.base64.standard.Decoder; 357 const blob_len = decoder.calcSizeForSlice(blob_b64) catch return null; 358 var blob_buf: [4096]u8 = undefined; 359 if (blob_len > blob_buf.len) return null; 360 decoder.decode(blob_buf[0..blob_len], blob_b64) catch return null; 361 362 return ssh.formatFingerprint(blob_buf[0..blob_len]); 363 } 364 365 // write an error to the client's stderr and exit non-zero. stderr (not stdout) 366 // because the git exec sessions that call this carry the pack protocol on 367 // stdout, where stray text breaks the client's pkt-line parser. 368 fn writeError(sess: *ssh.SessionCtx, msg: []const u8) !void { 369 var buf: [256]u8 = undefined; 370 const text = try std.fmt.bufPrint(&buf, "haxy ssh: {s}\n", .{msg}); 371 try sess.writeStderr(text); 372 try sess.exit(1); 373 } 374 375 test "parseGitCommand rejects malformed input" { 376 const allocator = std.testing.allocator; 377 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 378 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 379 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 380 } 381 382 test "parseGitCommand happy paths" { 383 const allocator = std.testing.allocator; 384 385 { 386 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 387 defer parsed.deinit(allocator); 388 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 389 try std.testing.expectEqualStrings("some-repo", parsed.dir); 390 } 391 { 392 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 393 defer parsed.deinit(allocator); 394 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 395 try std.testing.expectEqualStrings("user/proj", parsed.dir); 396 } 397 { 398 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 399 defer parsed.deinit(allocator); 400 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 401 try std.testing.expectEqualStrings("repo", parsed.dir); 402 } 403 } 404