╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
2528 var iter = request.iterateHeaders(); 2529 while (iter.next()) |header| { 2530 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 2531 var pairs = std.mem.splitScalar(u8, header.value, ';'); 2532 while (pairs.next()) |pair| { 2533 const trimmed = std.mem.trim(u8, pair, " \t"); 2534 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 2535 if (std.mem.eql(u8, trimmed[0..eq], name)) { 2536 return trimmed[eq + 1 ..]; 2537 } 2538 } 2539 } 2540 return null; 2541 } 2542 2543 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 2544 var iter = std.mem.splitScalar(u8, body, '&'); 2545 while (iter.next()) |pair| { 2546 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 2547 if (std.mem.eql(u8, pair[0..eq], key)) { 2548 return try decodeFormValue(allocator, pair[eq + 1 ..]); 2549 } 2550 } 2551 return null; 2552 } 2553 2554 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 2555 var buffer: [256]u8 = undefined; 2556 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 2557 } 2558 2559 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 2560 var out: std.ArrayList(u8) = .empty; 2561 errdefer out.deinit(allocator); 2562 var i: usize = 0; 2563 while (i < encoded.len) : (i += 1) { 2564 switch (encoded[i]) { 2565 '+' => try out.append(allocator, ' '), 2566 '%' => { 2567 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 2568 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 2569 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 2570 try out.append(allocator, hi * 16 + lo); 2571 i += 2; 2572 }, 2573 else => try out.append(allocator, encoded[i]), 2574 } 2575 } 2576 return try out.toOwnedSlice(allocator); 2577 } 2578 2579 // disk-backed web session store. each login mints a random, opaque token 2580 // (not the user's id) that is stored as a file named by the token hex, whose 2581 // contents are the raw user_id bytes. authenticating a request is a lookup of 2582 // the cookie's token; logout deletes the file, revoking the session. there is 2583 // deliberately no expiry — a session lives until logout. form failures use 2584 // files in the flash subdirectory that the redirected GET consumes. the 2585 // directory is cleared whenever the server starts. 2586 pub const SessionStore = struct { 2587 io: std.Io, 2588 dir: std.Io.Dir, 2589 flash_dir: std.Io.Dir, 2590 auto_login: ?[token_hex_len]u8, 2591 2592 pub const token_hex_len = evt.event_id_size * 2; 2593 2594 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 2595 try data_dir.createDirPath(io, "sessions"); 2596 const dir = try data_dir.openDir(io, "sessions", .{}); 2597 errdefer dir.close(io); 2598 try dir.deleteTree(io, "flash"); 2599 try dir.createDirPath(io, "flash"); 2600 const flash_dir = try dir.openDir(io, "flash", .{}); 2601 errdefer flash_dir.close(io); 2602 const auto_login = blk: { 2603 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 2604 defer file.close(io); 2605 var token: [token_hex_len]u8 = undefined; 2606 var storage: [token_hex_len]u8 = undefined; 2607 var reader = file.reader(io, &storage); 2608 reader.interface.readSliceAll(&token) catch break :blk null; 2609 break :blk token; 2610 }; 2611 return .{ .io = io, .dir = dir, .flash_dir = flash_dir, .auto_login = auto_login }; 2612 } 2613 2614 pub fn deinit(self: SessionStore) void { 2615 self.flash_dir.close(self.io); 2616 self.dir.close(self.io); 2617 } 2618 2619 // mint a new session for user_id, returning the token hex to set as the 2620 // cookie value. 2621 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 2622 var token: [evt.event_id_size]u8 = undefined; 2623 self.io.random(&token); 2624 const token_hex = std.fmt.bytesToHex(token, .lower); 2625 const file = try self.dir.createFile(self.io, &token_hex, .{}); 2626 defer file.close(self.io); 2627 try file.writeStreamingAll(self.io, user_id); 2628 return token_hex; 2629 } 2630 2631 fn createFlash(self: SessionStore, allocator: std.mem.Allocator, value: ui.Session.FormFeedback) ![token_hex_len]u8 { 2632 var token: [evt.event_id_size]u8 = undefined; 2633 self.io.random(&token); 2634 const token_hex = std.fmt.bytesToHex(token, .lower); 2635 const file = try self.flash_dir.createFile(self.io, &token_hex, .{}); 2636 errdefer self.flash_dir.deleteFile(self.io, &token_hex) catch {}; 2637 defer file.close(self.io); 2638 2639 var json: std.Io.Writer.Allocating = .init(allocator); 2640 defer json.deinit(); 2641 try std.json.Stringify.value(value, .{}, &json.writer); 2642 try file.writeStreamingAll(self.io, json.written()); 2643 return token_hex; 2644 } 2645 2646 fn takeFlash(self: SessionStore, allocator: std.mem.Allocator, token_hex: []const u8) ?ui.Session.FormFeedback { 2647 if (!isToken(token_hex)) return null; 2648 const file = self.flash_dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return null; 2649 defer self.flash_dir.deleteFile(self.io, token_hex) catch {}; 2650 defer file.close(self.io); 2651 2652 var storage: [4096]u8 = undefined; 2653 var reader = file.reader(self.io, &storage); 2654 const bytes = reader.interface.allocRemaining(allocator, .limited(512 * 1024)) catch return null; 2655 return std.json.parseFromSliceLeaky(ui.Session.FormFeedback, allocator, bytes, .{}) catch null; 2656 } 2657 2658 // resolve a cookie's token to its user_id. returns false (logged out) for a 2659 // missing, malformed, or unknown token. 2660 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 2661 if (!isToken(token_hex)) return false; 2662 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 2663 defer file.close(self.io); 2664 var storage: [evt.event_id_size]u8 = undefined; 2665 var file_reader = file.reader(self.io, &storage); 2666 file_reader.interface.readSliceAll(out) catch return false; 2667 return true; 2668 } 2669 2670 // revoke a session. a no-op for a missing or malformed token. 2671 pub fn remove(self: SessionStore, token_hex: []const u8) void { 2672 if (!isToken(token_hex)) return; 2673 self.dir.deleteFile(self.io, token_hex) catch {}; 2674 } 2675 2676 // leave `token_hex`'s session for visitors arriving without one. only the 2677 // `try` fixture writes one. the name can't collide with a session token. 2678 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 2679 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 2680 defer file.close(self.io); 2681 try file.writeStreamingAll(self.io, token_hex); 2682 } 2683 2684 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 2685 out.* = self.auto_login orelse return false; 2686 return true; 2687 } 2688 2689 const auto_login_name = "auto-login"; 2690 2691 // a token is exactly token_hex_len hex chars. validating before using the 2692 // value as a path keeps attacker-supplied cookies from escaping the 2693 // sessions dir (e.g. via "/" or ".." bytes). 2694 fn isToken(token_hex: []const u8) bool { 2695 if (token_hex.len != token_hex_len) return false; 2696 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 2697 return true; 2698 } 2699 }; 2700