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

zat.dev/zlay

atproto relay in zig · mirror of https://tangled.org/zat.dev/zlay

0
0
69 lines · 2.6 KB Raw History
const std = @import("std");

pub const Entry = struct {
    frame: []const u8,
    curve_type: u8,
    pubkey: []const u8,
};

pub fn parse(allocator: std.mem.Allocator, bytes: []const u8) ![]Entry {
    if (bytes.len < 4) return error.ShortCorpus;
    const count = std.mem.readInt(u32, bytes[0..4], .big);
    if (count > (bytes.len - 4) / 40) return error.ShortCorpus;
    const entries = try allocator.alloc(Entry, count);
    errdefer allocator.free(entries);
    var at: usize = 4;
    for (entries) |*entry| {
        if (bytes.len - at < 4) return error.ShortCorpus;
        const len = std.mem.readInt(u32, bytes[at..][0..4], .big);
        at += 4;
        if (len == 0) return error.EmptyFrame;
        if (len > bytes.len - at) return error.ShortCorpus;
        const frame = bytes[at..][0..len];
        at += len;
        if (bytes.len - at < 2) return error.ShortCorpus;
        const curve = bytes[at];
        const key_len = bytes[at + 1];
        at += 2;
        if (curve > 1 or key_len != 33) return error.InvalidCorpusKey;
        if (key_len > bytes.len - at) return error.ShortCorpus;
        entry.* = .{ .frame = frame, .curve_type = curve, .pubkey = bytes[at..][0..key_len] };
        at += key_len;
    }
    if (at != bytes.len) return error.TrailingCorpus;
    return entries;
}

const fixture: [44]u8 = blk: {
    var bytes: [44]u8 = @splat(2);
    @memcpy(bytes[0..11], &[_]u8{ 0, 0, 0, 1, 0, 0, 0, 1, 0xaa, 0, 33 });
    break :blk bytes;
};

test "entries borrow original frame and signing key bytes" {
    const entries = try parse(std.testing.allocator, &fixture);
    defer std.testing.allocator.free(entries);
    try std.testing.expectEqual(@as(usize, 1), entries.len);
    try std.testing.expectEqualSlices(u8, &.{0xaa}, entries[0].frame);
    try std.testing.expectEqual(@intFromPtr(&fixture[8]), @intFromPtr(entries[0].frame.ptr));
    try std.testing.expectEqual(@intFromPtr(&fixture[11]), @intFromPtr(entries[0].pubkey.ptr));
}

test "every truncated prefix and trailing byte is rejected" {
    for (0..fixture.len) |len| {
        try std.testing.expectError(error.ShortCorpus, parse(std.testing.allocator, fixture[0..len]));
    }
    var trailing: [45]u8 = undefined;
    @memcpy(trailing[0..44], &fixture);
    trailing[44] = 0;
    try std.testing.expectError(error.TrailingCorpus, parse(std.testing.allocator, &trailing));
}

test "unsupported curves and key widths are rejected" {
    var bytes = fixture;
    bytes[9] = 2;
    try std.testing.expectError(error.InvalidCorpusKey, parse(std.testing.allocator, &bytes));
    bytes = fixture;
    bytes[10] = 32;
    try std.testing.expectError(error.InvalidCorpusKey, parse(std.testing.allocator, &bytes));
}