// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! SASLprep as passlib's `passlib.utils.saslprep` has it, for the `scram` //! scheme. //! //! SASLprep (RFC 4013) prepares a password before SCRAM hashes it: it maps //! some characters to a space and deletes others, normalizes to NFKC, and //! refuses what is left if it holds a prohibited character. Implementations //! disagree at the edges, and a hash is only reproducible under the same //! reading. zig-scram has two readings, PostgreSQL's and the RFC's, and //! passlib's is neither. It is the RFC's except in three places: //! //! * **U+200B ZERO WIDTH SPACE is deleted.** RFC 3454 lists it both among the //! characters mapped to a space (C.1.2) and among those mapped to nothing //! (B.1). passlib tests B.1 first, so it goes; PostgreSQL and libidn test //! C.1.2 first, so it becomes a space. //! * **Unassigned code points are checked after normalization.** A character //! Unicode 3.2 did not have, which the RFC refuses, is accepted if NFKC //! turns it into assigned characters, as it turns U+1F100 into "0.". //! * **NFKC is a current Unicode's**, Python's there and uucode's here, //! rather than 3.2's. The two agree on every character Unicode had by the //! older of the two versions. //! //! The mapping, prohibited-character and bidi tables are zig-scram's, which //! are RFC 3454's, and so is its NFKC. const std = @import("std"); const Allocator = std.mem.Allocator; const testing = std.testing; const scram = @import("scram"); const nfkc = scram.nfkc; const tables = scram.stringprep_tables; /// A prepared password. `bytes` may alias the input, so keep the input alive /// as long as the result, and call `deinit` either way. pub const Prepared = scram.saslprep.Prepared; pub const Error = error{ /// Not valid UTF-8, or holds a character SASLprep prohibits, or breaks /// the bidirectional-text rules: where passlib raises `ValueError`. InvalidPassword, OutOfMemory, }; /// `input` through passlib's SASLprep. pub fn prep(gpa: Allocator, input: []const u8) Error!Prepared { // Printable ASCII is its own SASLprep, and the ASCII control characters // are all prohibited (C.2.1). var ascii = true; for (input) |byte| { if (byte >= 0x80) { ascii = false; } else if (byte < 0x20 or byte == 0x7f) { return error.InvalidPassword; } } if (ascii) return .{ .bytes = input, .owned = false }; const view = std.unicode.Utf8View.init(input) catch return error.InvalidPassword; var mapped: std.ArrayList(u21) = .empty; defer mapped.deinit(gpa); // Step 1, B.1 before C.1.2, as passlib's generator expression has it. var it = view.iterator(); while (it.nextCodepoint()) |cp| { if (tables.contains(tables.commonly_mapped_to_nothing, cp)) continue; try mapped.append(gpa, if (tables.contains(tables.non_ascii_space, cp)) ' ' else cp); } if (mapped.items.len == 0) return .{ .bytes = "", .owned = false }; // Step 2. const normalized = try nfkc.normalize(gpa, mapped.items); defer gpa.free(normalized); if (normalized.len == 0) return .{ .bytes = "", .owned = false }; // Steps 3 and 4 on the normalized string, unassigned code points // included. A string that starts right-to-left must end so and hold no // left-to-right character; one that does not start so may hold no // right-to-left character at all. That is RFC 3454's rule put the way // passlib puts it. const rtl = tables.contains(tables.rand_al_cat, normalized[0]); if (rtl and !tables.contains(tables.rand_al_cat, normalized[normalized.len - 1])) return error.InvalidPassword; const forbidden_bidi = if (rtl) tables.l_cat else tables.rand_al_cat; for (normalized) |cp| { if (tables.contains(tables.unassigned, cp)) return error.InvalidPassword; if (tables.contains(tables.prohibited_output, cp)) return error.InvalidPassword; if (tables.contains(forbidden_bidi, cp)) return error.InvalidPassword; } var out: std.ArrayList(u8) = .empty; errdefer out.deinit(gpa); var buf: [4]u8 = undefined; for (normalized) |cp| { // From valid UTF-8 or from the normalization tables, so encodable. const n = std.unicode.utf8Encode(cp, &buf) catch unreachable; try out.appendSlice(gpa, buf[0..n]); } return .{ .bytes = try out.toOwnedSlice(gpa), .owned = true }; } fn expectPrep(expected: []const u8, input: []const u8) !void { const p = try prep(testing.allocator, input); defer p.deinit(testing.allocator); try testing.expectEqualStrings(expected, p.bytes); } test "passlib's answers" { // Each from passlib 1.7.4's saslprep() under Python 3.14. try expectPrep("hunter2", "hunter2"); try expectPrep("IX", "I\u{00AD}X"); try expectPrep("IX \u{00E0}", "\u{2168}\u{3000}a\u{0300}"); try expectPrep("", "\u{00AD}"); try expectPrep("ab", "a\u{200B}b"); try expectPrep("\u{0300}", "\u{0340}"); try expectPrep("0.", "\u{1F100}"); for ([_][]const u8{ "a\tb", "\x7f", "\xff", "a\u{2028}b", "a\u{0221}b", "\u{05D0}a\u{05D1}", "\u{0627}1" }) |bad| { try testing.expectError(error.InvalidPassword, prep(testing.allocator, bad)); } }