also looking at this
feat: mailbox recovery addresses and password reset by email
#13
21 files
+1503
-10
| @@ -0,0 +1,676 @@ | ||
| 1 | //! Mailbox recovery: a per-mailbox recovery address and the password reset | |
| 2 | //! links sent to it. | |
| 3 | //! | |
| 4 | //! A mailbox may name one address outside itself where a reset link can be | |
| 5 | //! sent. Anyone can ask for a reset by mailbox address; the answer is the same | |
| 6 | //! whether or not the mailbox exists or has a recovery address, and the link | |
| 7 | //! goes only to the recovery address, never to whoever asked. | |
| 8 | //! | |
| 9 | //! Who set the address is recorded in `users.recovery_source`: | |
| 10 | //! - `operator`: the `user:local recovery` CLI, which deploy provisioning uses | |
| 11 | //! - `user`: the mailbox owner, in webmail settings | |
| 12 | //! Provisioning with the `initial` policy leaves a `user` value alone, so a | |
| 13 | //! redeploy does not undo a change the owner made. `managed` always applies. | |
| 14 | //! | |
| 15 | //! Reset tokens are 32 random bytes, sent as 64 hex characters. Only their | |
| 16 | //! SHA-256 is stored (`mailbox_reset_tokens`). A token is single use, expires | |
| 17 | //! after `token_ttl_seconds`, and is voided when a newer one is issued, when | |
| 18 | //! the password changes by any route, and when the recovery address changes. | |
| 19 | ||
| 20 | const std = @import("std"); | |
| 21 | const database = @import("../storage/database.zig"); | |
| 22 | const auth_mod = @import("../auth/auth.zig"); | |
| 23 | const io_compat = @import("../core/io_compat.zig"); | |
| 24 | const compose = @import("webmail_compose.zig"); | |
| 25 | ||
| 26 | /// How long a reset link stays usable. | |
| 27 | pub const token_ttl_seconds: i64 = 30 * 60; | |
| 28 | /// At most this many reset emails per mailbox per hour, whoever asks. | |
| 29 | pub const max_links_per_hour: i64 = 3; | |
| 30 | /// And never two within this many seconds of each other. | |
| 31 | pub const min_link_interval_seconds: i64 = 60; | |
| 32 | /// Token length on the wire: 32 bytes as lowercase hex. | |
| 33 | pub const token_hex_len = 64; | |
| 34 | /// The bounds the webmail password change already enforces. | |
| 35 | pub const min_password_len = 12; | |
| 36 | pub const max_password_len = 1024; | |
| 37 | ||
| 38 | pub const RecoveryError = error{ | |
| 39 | InvalidAddress, | |
| 40 | SameAsMailbox, | |
| 41 | UserNotFound, | |
| 42 | }; | |
| 43 | ||
| 44 | pub const Source = enum { | |
| 45 | operator, | |
| 46 | user, | |
| 47 | ||
| 48 | pub fn parse(text: []const u8) ?Source { | |
| 49 | if (std.mem.eql(u8, text, "operator")) return .operator; | |
| 50 | if (std.mem.eql(u8, text, "user")) return .user; | |
| 51 | return null; | |
| 52 | } | |
| 53 | }; | |
| 54 | ||
| 55 | pub const Policy = enum { | |
| 56 | /// Set the address unless the mailbox owner has set their own. | |
| 57 | initial, | |
| 58 | /// Always set the address. | |
| 59 | managed, | |
| 60 | ||
| 61 | pub fn parse(text: []const u8) ?Policy { | |
| 62 | if (std.mem.eql(u8, text, "initial")) return .initial; | |
| 63 | if (std.mem.eql(u8, text, "managed")) return .managed; | |
| 64 | return null; | |
| 65 | } | |
| 66 | }; | |
| 67 | ||
| 68 | pub const Recovery = struct { | |
| 69 | /// null when the mailbox has none. | |
| 70 | address: ?[]const u8, | |
| 71 | source: ?Source, | |
| 72 | updated_at: ?i64, | |
| 73 | }; | |
| 74 | ||
| 75 | // ── Recovery address ───────────────────────────────────────────────────────── | |
| 76 | ||
| 77 | /// Trim and check a recovery address for `mailbox`. Returns the trimmed slice | |
| 78 | /// (borrowed from `address`). The mailbox itself is refused: a reset link sent | |
| 79 | /// to the mailbox you cannot open is no recovery at all. | |
| 80 | pub fn validateAddress(mailbox: []const u8, address: []const u8) RecoveryError![]const u8 { | |
| 81 | const trimmed = std.mem.trim(u8, address, " \t\r\n"); | |
| 82 | if (trimmed.len == 0 or trimmed.len > 254) return RecoveryError.InvalidAddress; | |
| 83 | if (!compose.isSafeAddress(trimmed)) return RecoveryError.InvalidAddress; | |
| 84 | const at = std.mem.indexOfScalar(u8, trimmed, '@').?; | |
| 85 | // A domain needs a dot; `user@localhost` is not somewhere a person reads mail. | |
| 86 | if (std.mem.indexOfScalar(u8, trimmed[at + 1 ..], '.') == null) return RecoveryError.InvalidAddress; | |
| 87 | if (std.ascii.eqlIgnoreCase(trimmed, mailbox)) return RecoveryError.SameAsMailbox; | |
| 88 | return trimmed; | |
| 89 | } | |
| 90 | ||
| 91 | /// The mailbox's recovery address, or null when the mailbox does not exist. | |
| 92 | pub fn get(allocator: std.mem.Allocator, db: *database.Database, username: []const u8) !?Recovery { | |
| 93 | const s = try db.prepare("SELECT recovery_email, recovery_source, recovery_updated_at FROM users WHERE username = ?1"); | |
| 94 | defer s.finalize(); | |
| 95 | try s.bind(1, username); | |
| 96 | if (!try s.step()) return null; | |
| 97 | const address = s.columnTextOpt(0); | |
| 98 | const source = s.columnTextOpt(1); | |
| 99 | return Recovery{ | |
| 100 | .address = if (address) |a| (if (a.len == 0) null else try allocator.dupe(u8, a)) else null, | |
| 101 | .source = if (source) |text| Source.parse(text) else null, | |
| 102 | .updated_at = s.columnInt64Opt(2), | |
| 103 | }; | |
| 104 | } | |
| 105 | ||
| 106 | /// Set (or, with null, clear) a mailbox's recovery address. Outstanding reset | |
| 107 | /// links are voided: they were sent to the previous address. | |
| 108 | pub fn set(db: *database.Database, username: []const u8, address: ?[]const u8, source: Source, now: i64) !void { | |
| 109 | const value: ?[]const u8 = if (address) |a| try validateAddress(username, a) else null; | |
| 110 | const s = try db.prepare( | |
| 111 | \\UPDATE users SET recovery_email = ?2, recovery_source = ?3, recovery_updated_at = ?4 | |
| 112 | \\WHERE username = ?1 RETURNING username | |
| 113 | ); | |
| 114 | defer s.finalize(); | |
| 115 | try s.bind(1, username); | |
| 116 | try s.bindOpt(2, value); | |
| 117 | try s.bind(3, @tagName(source)); | |
| 118 | try s.bind(4, now); | |
| 119 | if (!try s.step()) return RecoveryError.UserNotFound; | |
| 120 | try db.deleteUserResetTokens(username); | |
| 121 | } | |
| 122 | ||
| 123 | pub const ApplyResult = enum { | |
| 124 | /// The address was written. | |
| 125 | updated, | |
| 126 | /// It already had this address. | |
| 127 | unchanged, | |
| 128 | /// The owner set their own and the policy is `initial`, so it was kept. | |
| 129 | kept_owner_choice, | |
| 130 | }; | |
| 131 | ||
| 132 | /// What deploy provisioning calls: make the mailbox's recovery address | |
| 133 | /// `address`, subject to `policy`. Idempotent. | |
| 134 | pub fn apply(allocator: std.mem.Allocator, db: *database.Database, username: []const u8, address: []const u8, policy: Policy, now: i64) !ApplyResult { | |
| 135 | const wanted = try validateAddress(username, address); | |
| 136 | const current = (try get(allocator, db, username)) orelse return RecoveryError.UserNotFound; | |
| 137 | defer if (current.address) |a| allocator.free(a); | |
| 138 | if (current.address) |existing| { | |
| 139 | if (std.ascii.eqlIgnoreCase(existing, wanted)) return .unchanged; | |
| 140 | } | |
| 141 | if (policy == .initial and current.source == .user) return .kept_owner_choice; | |
| 142 | try set(db, username, wanted, .operator, now); | |
| 143 | return .updated; | |
| 144 | } | |
| 145 | ||
| 146 | // ── Reset tokens ───────────────────────────────────────────────────────────── | |
| 147 | ||
| 148 | /// Hex SHA-256 of a token: what is stored and looked up. | |
| 149 | pub fn hashToken(token: []const u8) [64]u8 { | |
| 150 | var digest: [32]u8 = undefined; | |
| 151 | std.crypto.hash.sha2.Sha256.hash(token, &digest, .{}); | |
| 152 | return hexLower(32, digest); | |
| 153 | } | |
| 154 | ||
| 155 | fn hexLower(comptime n: usize, bytes: [n]u8) [n * 2]u8 { | |
| 156 | const digits = "0123456789abcdef"; | |
| 157 | var out: [n * 2]u8 = undefined; | |
| 158 | for (bytes, 0..) |byte, i| { | |
| 159 | out[i * 2] = digits[byte >> 4]; | |
| 160 | out[i * 2 + 1] = digits[byte & 15]; | |
| 161 | } | |
| 162 | return out; | |
| 163 | } | |
| 164 | ||
| 165 | /// A token as it arrives from a browser: exactly 64 lowercase hex characters. | |
| 166 | /// Anything else is rejected before it costs a database lookup. | |
| 167 | pub fn wellFormedToken(token: []const u8) bool { | |
| 168 | if (token.len != token_hex_len) return false; | |
| 169 | for (token) |c| if (!((c >= '0' and c <= '9') or (c >= 'a' and c <= 'f'))) return false; | |
| 170 | return true; | |
| 171 | } | |
| 172 | ||
| 173 | pub const Issue = union(enum) { | |
| 174 | /// A link should be sent to `recovery`. | |
| 175 | issued: struct { token: [token_hex_len]u8, recovery: []const u8 }, | |
| 176 | /// Nothing is sent. These are distinguished for the server log only; | |
| 177 | /// the HTTP answer is the same for all of them. | |
| 178 | unknown_mailbox, | |
| 179 | disabled, | |
| 180 | no_recovery, | |
| 181 | throttled, | |
| 182 | }; | |
| 183 | ||
| 184 | /// Issue a reset token for `username` (a canonical mailbox key), unless the | |
| 185 | /// mailbox is unknown, disabled, has no recovery address, or has had too many | |
| 186 | /// links recently. A new token voids the mailbox's earlier unused ones. | |
| 187 | pub fn issue(allocator: std.mem.Allocator, db: *database.Database, username: []const u8, ip: ?[]const u8, now: i64) !Issue { | |
| 188 | var recovery: []const u8 = undefined; | |
| 189 | { | |
| 190 | const s = try db.prepare("SELECT enabled, recovery_email FROM users WHERE username = ?1"); | |
| 191 | defer s.finalize(); | |
| 192 | try s.bind(1, username); | |
| 193 | if (!try s.step()) return .unknown_mailbox; | |
| 194 | if (s.columnInt64(0) == 0) return .disabled; | |
| 195 | const address = s.columnTextOpt(1) orelse return .no_recovery; | |
| 196 | if (address.len == 0) return .no_recovery; | |
| 197 | recovery = try allocator.dupe(u8, address); | |
| 198 | } | |
| 199 | errdefer allocator.free(recovery); | |
| 200 | ||
| 201 | // Old rows are only kept for the count below. | |
| 202 | { | |
| 203 | const s = try db.prepare("DELETE FROM mailbox_reset_tokens WHERE created_at < ?1"); | |
| 204 | defer s.finalize(); | |
| 205 | try s.bind(1, now - 24 * 60 * 60); | |
| 206 | _ = try s.step(); | |
| 207 | } | |
| 208 | { | |
| 209 | const s = try db.prepare("SELECT COUNT(*), MAX(created_at) FROM mailbox_reset_tokens WHERE username = ?1 AND created_at > ?2"); | |
| 210 | defer s.finalize(); | |
| 211 | try s.bind(1, username); | |
| 212 | try s.bind(2, now - 60 * 60); | |
| 213 | if (try s.step()) { | |
| 214 | const recent = s.columnInt64(0); | |
| 215 | const last = s.columnInt64Opt(1); | |
| 216 | const too_soon = if (last) |at| now - at < min_link_interval_seconds else false; | |
| 217 | if (recent >= max_links_per_hour or too_soon) { | |
| 218 | allocator.free(recovery); | |
| 219 | return .throttled; | |
| 220 | } | |
| 221 | } | |
| 222 | } | |
| 223 | { | |
| 224 | const s = try db.prepare("UPDATE mailbox_reset_tokens SET used_at = ?2 WHERE username = ?1 AND used_at IS NULL"); | |
| 225 | defer s.finalize(); | |
| 226 | try s.bind(1, username); | |
| 227 | try s.bind(2, now); | |
| 228 | _ = try s.step(); | |
| 229 | } | |
| 230 | ||
| 231 | var random: [32]u8 = undefined; | |
| 232 | io_compat.randomBytes(&random); | |
| 233 | const token = hexLower(32, random); | |
| 234 | const hash = hashToken(&token); | |
| 235 | { | |
| 236 | const s = try db.prepare( | |
| 237 | \\INSERT INTO mailbox_reset_tokens (token_hash, username, recovery_email, created_at, expires_at, ip_address) | |
| 238 | \\VALUES (?1, ?2, ?3, ?4, ?5, ?6) | |
| 239 | ); | |
| 240 | defer s.finalize(); | |
| 241 | try s.bind(1, @as([]const u8, &hash)); | |
| 242 | try s.bind(2, username); | |
| 243 | try s.bind(3, recovery); | |
| 244 | try s.bind(4, now); | |
| 245 | try s.bind(5, now + token_ttl_seconds); | |
| 246 | try s.bindOpt(6, ip); | |
| 247 | _ = try s.step(); | |
| 248 | } | |
| 249 | return .{ .issued = .{ .token = token, .recovery = recovery } }; | |
| 250 | } | |
| 251 | ||
| 252 | /// The mailbox a usable token belongs to, or null. Does not consume it. | |
| 253 | pub fn lookup(allocator: std.mem.Allocator, db: *database.Database, token: []const u8, now: i64) !?[]const u8 { | |
| 254 | if (!wellFormedToken(token)) return null; | |
| 255 | const hash = hashToken(token); | |
| 256 | const s = try db.prepare( | |
| 257 | \\SELECT t.username FROM mailbox_reset_tokens t JOIN users u ON u.username = t.username | |
| 258 | \\WHERE t.token_hash = ?1 AND t.used_at IS NULL AND t.expires_at > ?2 AND u.enabled = 1 | |
| 259 | ); | |
| 260 | defer s.finalize(); | |
| 261 | try s.bind(1, @as([]const u8, &hash)); | |
| 262 | try s.bind(2, now); | |
| 263 | if (!try s.step()) return null; | |
| 264 | return try allocator.dupe(u8, s.columnText(0)); | |
| 265 | } | |
| 266 | ||
| 267 | pub const Completed = struct { | |
| 268 | username: []const u8, | |
| 269 | /// Where the link was sent, for the confirmation notice. | |
| 270 | recovery: []const u8, | |
| 271 | }; | |
| 272 | ||
| 273 | /// Spend a token and set the mailbox's new password. Returns null when the | |
| 274 | /// token is unknown, used, expired, or its mailbox is gone or disabled. | |
| 275 | /// | |
| 276 | /// The token is marked used by a single conditional UPDATE before anything | |
| 277 | /// else happens, so two concurrent submissions of one link cannot both win. | |
| 278 | pub fn complete(allocator: std.mem.Allocator, db: *database.Database, auth: *auth_mod.AuthBackend, token: []const u8, new_password: []const u8, now: i64) !?Completed { | |
| 279 | if (!wellFormedToken(token)) return null; | |
| 280 | const hash = hashToken(token); | |
| 281 | var username: []const u8 = undefined; | |
| 282 | var recovery: []const u8 = undefined; | |
| 283 | { | |
| 284 | const s = try db.prepare( | |
| 285 | \\UPDATE mailbox_reset_tokens SET used_at = ?2 | |
| 286 | \\WHERE token_hash = ?1 AND used_at IS NULL AND expires_at > ?2 | |
| 287 | \\RETURNING username, recovery_email | |
| 288 | ); | |
| 289 | defer s.finalize(); | |
| 290 | try s.bind(1, @as([]const u8, &hash)); | |
| 291 | try s.bind(2, now); | |
| 292 | if (!try s.step()) return null; | |
| 293 | username = try allocator.dupe(u8, s.columnText(0)); | |
| 294 | recovery = try allocator.dupe(u8, s.columnText(1)); | |
| 295 | } | |
| 296 | errdefer { | |
| 297 | allocator.free(username); | |
| 298 | allocator.free(recovery); | |
| 299 | } | |
| 300 | { | |
| 301 | const s = try db.prepare("SELECT enabled FROM users WHERE username = ?1"); | |
| 302 | defer s.finalize(); | |
| 303 | try s.bind(1, username); | |
| 304 | if (!try s.step() or s.columnInt64(0) == 0) { | |
| 305 | allocator.free(username); | |
| 306 | allocator.free(recovery); | |
| 307 | return null; | |
| 308 | } | |
| 309 | } | |
| 310 | // Hashes the password, signs out every browser session, and voids the | |
| 311 | // mailbox's other reset links. | |
| 312 | try auth.changePassword(username, new_password); | |
| 313 | return .{ .username = username, .recovery = recovery }; | |
| 314 | } | |
| 315 | ||
| 316 | // ── Messages ───────────────────────────────────────────────────────────────── | |
| 317 | ||
| 318 | /// The domain a mailbox belongs to, falling back to the server's hostname for | |
| 319 | /// a legacy bare username. | |
| 320 | fn mailboxDomain(username: []const u8, hostname: []const u8) []const u8 { | |
| 321 | if (std.mem.lastIndexOfScalar(u8, username, '@')) |at| return username[at + 1 ..]; | |
| 322 | return hostname; | |
| 323 | } | |
| 324 | ||
| 325 | /// The address the server writes from about `username`: `no-reply@` the | |
| 326 | /// mailbox's own domain, so it is DKIM-signed with that domain's key and | |
| 327 | /// aligns with its SPF and DMARC, exactly like mail the mailbox sends itself. | |
| 328 | pub fn senderFor(allocator: std.mem.Allocator, username: []const u8, hostname: []const u8) ![]const u8 { | |
| 329 | return std.fmt.allocPrint(allocator, "no-reply@{s}", .{mailboxDomain(username, hostname)}); | |
| 330 | } | |
| 331 | ||
| 332 | fn validHost(host: []const u8) bool { | |
| 333 | if (host.len == 0 or host.len > 253) return false; | |
| 334 | for (host) |c| { | |
| 335 | if (!(std.ascii.isAlphanumeric(c) or c == '.' or c == '-' or c == ':')) return false; | |
| 336 | } | |
| 337 | return true; | |
| 338 | } | |
| 339 | ||
| 340 | /// Where a reset link points. | |
| 341 | /// | |
| 342 | /// Never simply the request's Host: that is client-controlled, and a link | |
| 343 | /// built from it would carry the token to whatever server the requester named | |
| 344 | /// (reset poisoning). The request's host is used only when it is one of ours | |
| 345 | /// for this mailbox: `mail.<mailbox domain>` (the tenant's own webmail name) | |
| 346 | /// or the server's hostname. Otherwise the server's hostname. | |
| 347 | pub fn linkBase(allocator: std.mem.Allocator, request_host: ?[]const u8, username: []const u8, hostname: []const u8, https: bool) ![]const u8 { | |
| 348 | const scheme = if (https) "https" else "http"; | |
| 349 | if (request_host) |raw| { | |
| 350 | const host = try std.ascii.allocLowerString(allocator, std.mem.trim(u8, raw, " \t")); | |
| 351 | defer allocator.free(host); | |
| 352 | if (validHost(host)) { | |
| 353 | const name = if (std.mem.indexOfScalar(u8, host, ':')) |colon| host[0..colon] else host; | |
| 354 | const domain = mailboxDomain(username, hostname); | |
| 355 | const tenant = std.mem.startsWith(u8, name, "mail.") and std.ascii.eqlIgnoreCase(name["mail.".len..], domain); | |
| 356 | if (tenant or std.ascii.eqlIgnoreCase(name, hostname)) | |
| 357 | return std.fmt.allocPrint(allocator, "{s}://{s}", .{ scheme, host }); | |
| 358 | } | |
| 359 | } | |
| 360 | return std.fmt.allocPrint(allocator, "{s}://{s}", .{ scheme, hostname }); | |
| 361 | } | |
| 362 | ||
| 363 | /// The link itself. The token rides in the fragment, which browsers do not | |
| 364 | /// send to servers, so it stays out of gateway and access logs. | |
| 365 | pub fn resetLink(allocator: std.mem.Allocator, base: []const u8, token: []const u8) ![]const u8 { | |
| 366 | return std.fmt.allocPrint(allocator, "{s}/reset#token={s}", .{ base, token }); | |
| 367 | } | |
| 368 | ||
| 369 | pub const ResetMail = struct { | |
| 370 | username: []const u8, | |
| 371 | recovery: []const u8, | |
| 372 | link: []const u8, | |
| 373 | ip: ?[]const u8 = null, | |
| 374 | hostname: []const u8, | |
| 375 | }; | |
| 376 | ||
| 377 | pub fn resetMessage(allocator: std.mem.Allocator, m: ResetMail) !compose.Message { | |
| 378 | const to = try allocator.alloc([]const u8, 1); | |
| 379 | to[0] = m.recovery; | |
| 380 | const origin = if (m.ip) |ip| try std.fmt.allocPrint(allocator, "\nThe request came from {s}.\n", .{ip}) else ""; | |
| 381 | return .{ | |
| 382 | .from = try senderFor(allocator, m.username, m.hostname), | |
| 383 | .to = to, | |
| 384 | .subject = try std.fmt.allocPrint(allocator, "Reset the password for {s}", .{m.username}), | |
| 385 | .text_body = try std.fmt.allocPrint(allocator, | |
| 386 | \\Someone asked to reset the password for the mailbox {s}. | |
| 387 | \\This address is its recovery address. | |
| 388 | \\ | |
| 389 | \\To choose a new password, open this link within {d} minutes: | |
| 390 | \\ | |
| 391 | \\{s} | |
| 392 | \\ | |
| 393 | \\The link works once. If you did not ask for this, ignore this | |
| 394 | \\email: the password stays as it is. | |
| 395 | \\{s} | |
| 396 | , .{ m.username, @divTrunc(token_ttl_seconds, 60), m.link, origin }), | |
| 397 | .auto_submitted = true, | |
| 398 | }; | |
| 399 | } | |
| 400 | ||
| 401 | pub fn passwordResetNotice(allocator: std.mem.Allocator, username: []const u8, recovery: []const u8, hostname: []const u8) !compose.Message { | |
| 402 | const to = try allocator.alloc([]const u8, 1); | |
| 403 | to[0] = recovery; | |
| 404 | return .{ | |
| 405 | .from = try senderFor(allocator, username, hostname), | |
| 406 | .to = to, | |
| 407 | .subject = try std.fmt.allocPrint(allocator, "The password for {s} was reset", .{username}), | |
| 408 | .text_body = try std.fmt.allocPrint(allocator, | |
| 409 | \\The password for the mailbox {s} was just reset with a link | |
| 410 | \\sent to this address. Every webmail session was signed out, and | |
| 411 | \\mail apps need the new password. | |
| 412 | \\ | |
| 413 | \\If this was not you, someone can read this inbox: secure it, then | |
| 414 | \\ask the mail administrator to reset the mailbox password. | |
| 415 | \\ | |
| 416 | , .{username}), | |
| 417 | .auto_submitted = true, | |
| 418 | }; | |
| 419 | } | |
| 420 | ||
| 421 | pub fn recoveryChangedNotice(allocator: std.mem.Allocator, username: []const u8, previous: []const u8, hostname: []const u8) !compose.Message { | |
| 422 | const to = try allocator.alloc([]const u8, 1); | |
| 423 | to[0] = previous; | |
| 424 | return .{ | |
| 425 | .from = try senderFor(allocator, username, hostname), | |
| 426 | .to = to, | |
| 427 | .subject = try std.fmt.allocPrint(allocator, "The recovery address for {s} changed", .{username}), | |
| 428 | .text_body = try std.fmt.allocPrint(allocator, | |
| 429 | \\This address is no longer the recovery address for the mailbox | |
| 430 | \\{s}. It was changed in webmail by someone signed in with the | |
| 431 | \\mailbox password. | |
| 432 | \\ | |
| 433 | \\If this was not you, ask the mail administrator to reset the | |
| 434 | \\mailbox password. | |
| 435 | \\ | |
| 436 | , .{username}), | |
| 437 | .auto_submitted = true, | |
| 438 | }; | |
| 439 | } | |
| 440 | ||
| 441 | // ── Tests ──────────────────────────────────────────────────────────────────── | |
| 442 | ||
| 443 | const testing = std.testing; | |
| 444 | ||
| 445 | fn testDb() !database.Database { | |
| 446 | return database.Database.init(testing.allocator, ":memory:"); | |
| 447 | } | |
| 448 | ||
| 449 | test "validateAddress trims, refuses the mailbox itself and malformed input" { | |
| 450 | try testing.expectEqualStrings("pawel@outlook.de", try validateAddress("pawel@hq.training", " pawel@outlook.de ")); | |
| 451 | try testing.expectError(RecoveryError.SameAsMailbox, validateAddress("pawel@hq.training", "Pawel@HQ.training")); | |
| 452 | try testing.expectError(RecoveryError.InvalidAddress, validateAddress("a@b.test", "")); | |
| 453 | try testing.expectError(RecoveryError.InvalidAddress, validateAddress("a@b.test", "no-at-sign")); | |
| 454 | try testing.expectError(RecoveryError.InvalidAddress, validateAddress("a@b.test", "x@localhost")); | |
| 455 | try testing.expectError(RecoveryError.InvalidAddress, validateAddress("a@b.test", "x@y.test\r\nBcc: evil@z.test")); | |
| 456 | try testing.expectError(RecoveryError.InvalidAddress, validateAddress("a@b.test", "<x@y.test>")); | |
| 457 | } | |
| 458 | ||
| 459 | test "recovery address: set, read back, clear, and provisioning policies" { | |
| 460 | var db = try testDb(); | |
| 461 | defer db.deinit(); | |
| 462 | const a = testing.allocator; | |
| 463 | _ = try db.createUser("pawel@hq.test", "hash", "pawel@hq.test"); | |
| 464 | ||
| 465 | const none = (try get(a, &db, "pawel@hq.test")).?; | |
| 466 | try testing.expect(none.address == null); | |
| 467 | try testing.expect(none.source == null); | |
| 468 | try testing.expect((try get(a, &db, "nobody@hq.test")) == null); | |
| 469 | ||
| 470 | // First deploy sets it; the second is a no-op. | |
| 471 | try testing.expectEqual(ApplyResult.updated, try apply(a, &db, "pawel@hq.test", "pawel@outlook.test", .initial, 100)); | |
| 472 | try testing.expectEqual(ApplyResult.unchanged, try apply(a, &db, "pawel@hq.test", "PAWEL@outlook.test", .initial, 101)); | |
| 473 | // Config changing an operator-set address is applied even under `initial`. | |
| 474 | try testing.expectEqual(ApplyResult.updated, try apply(a, &db, "pawel@hq.test", "pawel@gmail.test", .initial, 102)); | |
| 475 | ||
| 476 | // The owner changes it in webmail: `initial` keeps their choice... | |
| 477 | try set(&db, "pawel@hq.test", "pawel@proton.test", .user, 103); | |
| 478 | try testing.expectEqual(ApplyResult.kept_owner_choice, try apply(a, &db, "pawel@hq.test", "pawel@gmail.test", .initial, 104)); | |
| 479 | { | |
| 480 | const r = (try get(a, &db, "pawel@hq.test")).?; | |
| 481 | defer a.free(r.address.?); | |
| 482 | try testing.expectEqualStrings("pawel@proton.test", r.address.?); | |
| 483 | try testing.expectEqual(Source.user, r.source.?); | |
| 484 | try testing.expectEqual(@as(i64, 103), r.updated_at.?); | |
| 485 | } | |
| 486 | // ...and `managed` overrides it. | |
| 487 | try testing.expectEqual(ApplyResult.updated, try apply(a, &db, "pawel@hq.test", "pawel@gmail.test", .managed, 105)); | |
| 488 | { | |
| 489 | const r = (try get(a, &db, "pawel@hq.test")).?; | |
| 490 | defer a.free(r.address.?); | |
| 491 | try testing.expectEqualStrings("pawel@gmail.test", r.address.?); | |
| 492 | try testing.expectEqual(Source.operator, r.source.?); | |
| 493 | } | |
| 494 | // An owner who clears it is also respected by `initial`. | |
| 495 | try set(&db, "pawel@hq.test", null, .user, 106); | |
| 496 | try testing.expectEqual(ApplyResult.kept_owner_choice, try apply(a, &db, "pawel@hq.test", "pawel@gmail.test", .initial, 107)); | |
| 497 | try testing.expect((try get(a, &db, "pawel@hq.test")).?.address == null); | |
| 498 | ||
| 499 | try testing.expectError(RecoveryError.UserNotFound, apply(a, &db, "nobody@hq.test", "x@y.test", .managed, 108)); | |
| 500 | try testing.expectError(RecoveryError.UserNotFound, set(&db, "nobody@hq.test", "x@y.test", .operator, 108)); | |
| 501 | try testing.expectError(RecoveryError.SameAsMailbox, apply(a, &db, "pawel@hq.test", "pawel@hq.test", .managed, 108)); | |
| 502 | } | |
| 503 | ||
| 504 | test "issue answers nothing for unknown, disabled and recovery-less mailboxes" { | |
| 505 | var db = try testDb(); | |
| 506 | defer db.deinit(); | |
| 507 | const a = testing.allocator; | |
| 508 | _ = try db.createUser("plain@hq.test", "hash", "plain@hq.test"); | |
| 509 | _ = try db.createUser("off@hq.test", "hash", "off@hq.test"); | |
| 510 | try set(&db, "off@hq.test", "off@else.test", .operator, 1); | |
| 511 | try db.setUserEnabled("off@hq.test", false); | |
| 512 | ||
| 513 | try testing.expect((try issue(a, &db, "ghost@hq.test", null, 1000)) == .unknown_mailbox); | |
| 514 | try testing.expect((try issue(a, &db, "plain@hq.test", null, 1000)) == .no_recovery); | |
| 515 | try testing.expect((try issue(a, &db, "off@hq.test", null, 1000)) == .disabled); | |
| 516 | } | |
| 517 | ||
| 518 | test "a reset link works once, expires, and the newest one voids the older" { | |
| 519 | var db = try testDb(); | |
| 520 | defer db.deinit(); | |
| 521 | var auth = auth_mod.AuthBackend.init(testing.allocator, &db); | |
| 522 | defer auth.deinit(); | |
| 523 | const a = testing.allocator; | |
| 524 | _ = try auth.createUser("chris@hq.test", "old-password-123", "chris@hq.test"); | |
| 525 | try set(&db, "chris@hq.test", "chris@else.test", .operator, 1); | |
| 526 | ||
| 527 | const first = try issue(a, &db, "chris@hq.test", "203.0.113.9", 1000); | |
| 528 | try testing.expect(first == .issued); | |
| 529 | defer a.free(first.issued.recovery); | |
| 530 | try testing.expectEqualStrings("chris@else.test", first.issued.recovery); | |
| 531 | const t1 = first.issued.token; | |
| 532 | try testing.expect(wellFormedToken(&t1)); | |
| 533 | ||
| 534 | { | |
| 535 | const who = (try lookup(a, &db, &t1, 1001)).?; | |
| 536 | defer a.free(who); | |
| 537 | try testing.expectEqualStrings("chris@hq.test", who); | |
| 538 | } | |
| 539 | // Expired. | |
| 540 | try testing.expect((try lookup(a, &db, &t1, 1000 + token_ttl_seconds)) == null); | |
| 541 | try testing.expect((try complete(a, &db, &auth, &t1, "new-password-456", 1000 + token_ttl_seconds)) == null); | |
| 542 | ||
| 543 | // A second request, after the minimum interval, voids the first link. | |
| 544 | const second = try issue(a, &db, "chris@hq.test", null, 1000 + min_link_interval_seconds); | |
| 545 | try testing.expect(second == .issued); | |
| 546 | defer a.free(second.issued.recovery); | |
| 547 | const t2 = second.issued.token; | |
| 548 | try testing.expect(!std.mem.eql(u8, &t1, &t2)); | |
| 549 | try testing.expect((try lookup(a, &db, &t1, 1070)) == null); | |
| 550 | ||
| 551 | const done = (try complete(a, &db, &auth, &t2, "new-password-456", 1070)).?; | |
| 552 | defer { | |
| 553 | a.free(done.username); | |
| 554 | a.free(done.recovery); | |
| 555 | } | |
| 556 | try testing.expectEqualStrings("chris@hq.test", done.username); | |
| 557 | try testing.expectEqualStrings("chris@else.test", done.recovery); | |
| 558 | try testing.expect(try auth.verifyCredentials("chris@hq.test", "new-password-456")); | |
| 559 | try testing.expect(!try auth.verifyCredentials("chris@hq.test", "old-password-123")); | |
| 560 | ||
| 561 | // Used once; malformed tokens never reach the database. | |
| 562 | try testing.expect((try complete(a, &db, &auth, &t2, "another-password-789", 1071)) == null); | |
| 563 | try testing.expect((try lookup(a, &db, "not-a-token", 1071)) == null); | |
| 564 | const uppercase: [64]u8 = @splat('A'); | |
| 565 | try testing.expect((try lookup(a, &db, &uppercase, 1071)) == null); | |
| 566 | } | |
| 567 | ||
| 568 | test "reset links are rate limited per mailbox" { | |
| 569 | var db = try testDb(); | |
| 570 | defer db.deinit(); | |
| 571 | const a = testing.allocator; | |
| 572 | _ = try db.createUser("rate@hq.test", "hash", "rate@hq.test"); | |
| 573 | try set(&db, "rate@hq.test", "rate@else.test", .operator, 1); | |
| 574 | ||
| 575 | var now: i64 = 10_000; | |
| 576 | var sent: usize = 0; | |
| 577 | // Too soon after the previous one. | |
| 578 | const r0 = try issue(a, &db, "rate@hq.test", null, now); | |
| 579 | if (r0 == .issued) { | |
| 580 | a.free(r0.issued.recovery); | |
| 581 | sent += 1; | |
| 582 | } | |
| 583 | try testing.expect((try issue(a, &db, "rate@hq.test", null, now + 1)) == .throttled); | |
| 584 | // Spaced out, the hourly cap still holds. | |
| 585 | while (sent < max_links_per_hour) { | |
| 586 | now += min_link_interval_seconds; | |
| 587 | const r = try issue(a, &db, "rate@hq.test", null, now); | |
| 588 | try testing.expect(r == .issued); | |
| 589 | a.free(r.issued.recovery); | |
| 590 | sent += 1; | |
| 591 | } | |
| 592 | now += min_link_interval_seconds; | |
| 593 | try testing.expect((try issue(a, &db, "rate@hq.test", null, now)) == .throttled); | |
| 594 | // An hour after the first, one is allowed again. | |
| 595 | const later = try issue(a, &db, "rate@hq.test", null, 10_000 + 60 * 60 + 1); | |
| 596 | try testing.expect(later == .issued); | |
| 597 | a.free(later.issued.recovery); | |
| 598 | } | |
| 599 | ||
| 600 | test "changing the password or the recovery address voids outstanding links" { | |
| 601 | var db = try testDb(); | |
| 602 | defer db.deinit(); | |
| 603 | var auth = auth_mod.AuthBackend.init(testing.allocator, &db); | |
| 604 | defer auth.deinit(); | |
| 605 | const a = testing.allocator; | |
| 606 | _ = try auth.createUser("void@hq.test", "old-password-123", "void@hq.test"); | |
| 607 | try set(&db, "void@hq.test", "void@else.test", .operator, 1); | |
| 608 | ||
| 609 | const r1 = try issue(a, &db, "void@hq.test", null, 1000); | |
| 610 | defer a.free(r1.issued.recovery); | |
| 611 | try auth.changePassword("void@hq.test", "changed-in-webmail-1"); | |
| 612 | try testing.expect((try lookup(a, &db, &r1.issued.token, 1001)) == null); | |
| 613 | ||
| 614 | const r2 = try issue(a, &db, "void@hq.test", null, 2000); | |
| 615 | defer a.free(r2.issued.recovery); | |
| 616 | try set(&db, "void@hq.test", "void@new.test", .user, 2001); | |
| 617 | try testing.expect((try complete(a, &db, &auth, &r2.issued.token, "attacker-password-1", 2002)) == null); | |
| 618 | ||
| 619 | // Deleting the mailbox removes its tokens with it. | |
| 620 | const r3 = try issue(a, &db, "void@hq.test", null, 3000); | |
| 621 | defer a.free(r3.issued.recovery); | |
| 622 | try db.deleteUser("void@hq.test"); | |
| 623 | try testing.expect((try lookup(a, &db, &r3.issued.token, 3001)) == null); | |
| 624 | } | |
| 625 | ||
| 626 | test "linkBase only trusts hosts that belong to the mailbox or the server" { | |
| 627 | const a = testing.allocator; | |
| 628 | const cases = [_]struct { host: ?[]const u8, want: []const u8 }{ | |
| 629 | .{ .host = "mail.hq.training", .want = "https://mail.hq.training" }, | |
| 630 | .{ .host = "MAIL.HQ.TRAINING", .want = "https://mail.hq.training" }, | |
| 631 | .{ .host = "mail.stacksjs.com", .want = "https://mail.stacksjs.com" }, | |
| 632 | // Another tenant's webmail name, an attacker's host, junk, nothing. | |
| 633 | .{ .host = "mail.wildloop.org", .want = "https://mail.stacksjs.com" }, | |
| 634 | .{ .host = "evil.example", .want = "https://mail.stacksjs.com" }, | |
| 635 | .{ .host = "mail.hq.training.evil.example", .want = "https://mail.stacksjs.com" }, | |
| 636 | .{ .host = "mail.hq.training/@evil.example", .want = "https://mail.stacksjs.com" }, | |
| 637 | .{ .host = null, .want = "https://mail.stacksjs.com" }, | |
| 638 | }; | |
| 639 | for (cases) |c| { | |
| 640 | const got = try linkBase(a, c.host, "pawel@hq.training", "mail.stacksjs.com", true); | |
| 641 | defer a.free(got); | |
| 642 | try testing.expectEqualStrings(c.want, got); | |
| 643 | } | |
| 644 | // Local development keeps the port it was reached on. | |
| 645 | const dev = try linkBase(a, "localhost:8099", "dev@localhost", "localhost", false); | |
| 646 | defer a.free(dev); | |
| 647 | try testing.expectEqualStrings("http://localhost:8099", dev); | |
| 648 | } | |
| 649 | ||
| 650 | test "the reset email goes to the recovery address from the mailbox's own domain" { | |
| 651 | var arena = std.heap.ArenaAllocator.init(testing.allocator); | |
| 652 | defer arena.deinit(); | |
| 653 | const a = arena.allocator(); | |
| 654 | const token: [64]u8 = @splat('a'); | |
| 655 | const link = try resetLink(a, "https://mail.hq.training", &token); | |
| 656 | try testing.expectEqualStrings("https://mail.hq.training/reset#token=" ++ token, link); | |
| 657 | const msg = try resetMessage(a, .{ .username = "pawel@hq.training", .recovery = "pawel@outlook.test", .link = link, .ip = "203.0.113.9", .hostname = "mail.stacksjs.com" }); | |
| 658 | try testing.expectEqualStrings("no-reply@hq.training", msg.from); | |
| 659 | try testing.expectEqual(@as(usize, 1), msg.to.len); | |
| 660 | try testing.expectEqualStrings("pawel@outlook.test", msg.to[0]); | |
| 661 | try testing.expect(std.mem.indexOf(u8, msg.text_body, link) != null); | |
| 662 | try testing.expect(std.mem.indexOf(u8, msg.text_body, "30 minutes") != null); | |
| 663 | try testing.expect(std.mem.indexOf(u8, msg.text_body, "203.0.113.9") != null); | |
| 664 | const raw = try compose.buildMime(a, msg, 1700000000, "<t@hq.training>"); | |
| 665 | try testing.expect(std.mem.indexOf(u8, raw, "From: no-reply@hq.training\r\n") != null); | |
| 666 | try testing.expect(std.mem.indexOf(u8, raw, "To: pawel@outlook.test\r\n") != null); | |
| 667 | try testing.expect(std.mem.indexOf(u8, raw, "Auto-Submitted: auto-generated\r\n") != null); | |
| 668 | try testing.expect(std.mem.indexOf(u8, raw, link) != null); | |
| 669 | ||
| 670 | const notice = try passwordResetNotice(a, "pawel@hq.training", "pawel@outlook.test", "mail.stacksjs.com"); | |
| 671 | try testing.expectEqualStrings("pawel@outlook.test", notice.to[0]); | |
| 672 | _ = try compose.buildMime(a, notice, 1, "<n@hq.training>"); | |
| 673 | const changed = try recoveryChangedNotice(a, "legacy", "old@else.test", "mail.stacksjs.com"); | |
| 674 | try testing.expectEqualStrings("no-reply@mail.stacksjs.com", changed.from); | |
| 675 | _ = try compose.buildMime(a, changed, 1, "<c@hq.training>"); | |
| 676 | } | |