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