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