~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/zat

atproto utils for zig · mirror of https://tangled.org/zat.dev/zat

0
0
111 lines · 4.4 KB Raw History
//! Strict RFC 3986 percent decoding for URI components, including scope values
//! and did:web authorities. Decode once; `+` remains literal. Bytes are not
//! interpreted as UTF-8. This is not form-urlencoded parsing.

const std = @import("std");

const Decoder = struct {
    rest: []const u8,

    fn next(self: *Decoder) error{InvalidPercentEncoding}!?u8 {
        if (self.rest.len == 0) return null;
        const byte = self.rest[0];
        if (byte != '%') {
            self.rest = self.rest[1..];
            return byte;
        }
        if (self.rest.len < 3) return error.InvalidPercentEncoding;
        const high = try hex(self.rest[1]);
        const low = try hex(self.rest[2]);
        self.rest = self.rest[3..];
        return high * 16 + low;
    }
};

fn hex(byte: u8) error{InvalidPercentEncoding}!u8 {
    return std.fmt.charToDigit(byte, 16) catch error.InvalidPercentEncoding;
}

/// Decode into a new slice. The caller owns the returned allocation.
pub fn decodeAlloc(allocator: std.mem.Allocator, input: []const u8) ![]u8 {
    const out = try allocator.alloc(u8, input.len);
    errdefer allocator.free(out);
    var decoder: Decoder = .{ .rest = input };
    var written: usize = 0;
    while (try decoder.next()) |byte| {
        out[written] = byte;
        written += 1;
    }
    return allocator.realloc(out, written);
}

/// Compare without allocating. Malformed escapes never match. This is a byte
/// comparison, not constant-time comparison of secrets or URI normalization.
pub fn decodedEql(encoded: []const u8, plain: []const u8) bool {
    var decoder: Decoder = .{ .rest = encoded };
    var index: usize = 0;
    while (decoder.next() catch return false) |byte| {
        if (index == plain.len or byte != plain[index]) return false;
        index += 1;
    }
    return index == plain.len;
}

test "strict escapes exhaust every pair of bytes" {
    const alphabet = "0123456789abcdef";
    for (0..256) |first| {
        for (0..256) |second| {
            const a: u8 = @intCast(first);
            const b: u8 = @intCast(second);
            const input = [_]u8{ '%', a, b };
            const high = std.mem.indexOfScalar(u8, alphabet, std.ascii.toLower(a));
            const low = std.mem.indexOfScalar(u8, alphabet, std.ascii.toLower(b));
            if (high != null and low != null) {
                const expected = [_]u8{@intCast(high.? * 16 + low.?)};
                const actual = try decodeAlloc(std.testing.allocator, &input);
                defer std.testing.allocator.free(actual);
                try std.testing.expectEqualSlices(u8, &expected, actual);
                try std.testing.expect(decodedEql(&input, &expected));
            } else {
                try std.testing.expectError(error.InvalidPercentEncoding, decodeAlloc(std.testing.allocator, &input));
                try std.testing.expect(!decodedEql(&input, "\x00"));
                try std.testing.expect(!decodedEql(&input, "\n"));
            }
        }
    }
}

test "decode once, preserve plus and arbitrary bytes, compare exact lengths" {
    const cases = [_][2][]const u8{
        .{ "", "" },
        .{ "a+b%2Bc%20d", "a+b+c d" },
        .{ "%2523", "%23" },
        .{ "%00%ff\xc3\xa9", "\x00\xff\xc3\xa9" },
        .{ "did%3Aweb%3Aapi.bsky.chat%23bsky_chat", "did:web:api.bsky.chat#bsky_chat" },
    };
    for (cases) |pair| {
        const result = try decodeAlloc(std.testing.allocator, pair[0]);
        defer std.testing.allocator.free(result);
        try std.testing.expectEqualStrings(pair[1], result);
        try std.testing.expect(decodedEql(pair[0], pair[1]));
    }
    try std.testing.expect(!decodedEql("%2523", "#"));
    try std.testing.expect(!decodedEql("a", "ab"));
    try std.testing.expect(!decodedEql("ab", "a"));
    try std.testing.expect(!decodedEql("", "a"));
    try std.testing.expect(!decodedEql("a", ""));
    for ([_][]const u8{ "%", "%2", "%+A", "%-0", "%_A", "%A_", "abc%GG" }) |input| {
        try std.testing.expectError(error.InvalidPercentEncoding, decodeAlloc(std.testing.allocator, input));
        try std.testing.expect(!decodedEql(input, input));
    }
}

test "allocation failures release partial output" {
    try std.testing.checkAllAllocationFailures(std.testing.allocator, allocationCase, .{});
}

fn allocationCase(allocator: std.mem.Allocator) !void {
    const decoded = try decodeAlloc(allocator, "did%3Aweb%3Aexample.com%3A8443");
    defer allocator.free(decoded);
    try std.testing.expectEqualStrings("did:web:example.com:8443", decoded);
}