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

zat.dev/zlay

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

0
0
157 lines · 6.0 KB Raw History
//! hostname — relay host parsing & validation.
//!
//! mirrors indigo relay's ParseHostname rules (reject IPs, ports, localhost,
//! malformed DNS names). this is relay policy, not generic DNS validation,
//! which is why it lives under atproto/ rather than util/.

const std = @import("std");
const Allocator = std.mem.Allocator;

pub const HostValidationError = error{
    EmptyHostname,
    InvalidCharacter,
    InvalidLabel,
    TooFewLabels,
    LooksLikeIpAddress,
    PortNotAllowed,
    LocalhostNotAllowed,
    DomainBanned,
    HostUnreachable,
    NotAPds,
    IsARelay,
};

/// validate and normalize a hostname for crawling.
/// rejects IPs, ports, localhost, invalid DNS names.
/// returns lowercased hostname on success (caller owns the allocation).
pub fn validateHostname(allocator: Allocator, raw: []const u8) HostValidationError![]u8 {
    if (raw.len == 0) return error.EmptyHostname;

    // strip scheme if present
    var hostname = raw;
    for ([_][]const u8{ "https://", "http://", "wss://", "ws://" }) |scheme| {
        if (hostname.len > scheme.len and std.ascii.startsWithIgnoreCase(hostname, scheme)) {
            hostname = hostname[scheme.len..];
            break;
        }
    }

    // strip trailing slash and path
    if (std.mem.indexOfScalar(u8, hostname, '/')) |i| {
        hostname = hostname[0..i];
    }

    // reject ports (Go relay rejects non-localhost ports)
    if (std.mem.indexOfScalar(u8, hostname, ':')) |_| {
        return error.PortNotAllowed;
    }

    // reject localhost
    if (std.ascii.eqlIgnoreCase(hostname, "localhost")) {
        return error.LocalhostNotAllowed;
    }

    // validate characters and split into labels
    var label_count: usize = 0;
    var all_labels_numeric = true;
    var it = std.mem.splitScalar(u8, hostname, '.');
    while (it.next()) |label| {
        if (label.len == 0 or label.len > 63) return error.InvalidLabel;
        // labels must be alphanumeric with hyphens, no leading/trailing hyphens
        if (label[0] == '-' or label[label.len - 1] == '-') return error.InvalidLabel;
        var is_numeric = true;
        for (label) |c| {
            if (!std.ascii.isAlphanumeric(c) and c != '-') return error.InvalidCharacter;
            if (!std.ascii.isDigit(c)) is_numeric = false;
        }
        if (!is_numeric) all_labels_numeric = false;
        label_count += 1;
    }

    // need at least 2 labels (e.g. "pds.example.com", "bsky.network")
    if (label_count < 2) return error.TooFewLabels;

    // all-numeric labels = IP address (e.g. "192.168.1.1")
    if (all_labels_numeric) return error.LooksLikeIpAddress;

    // lowercase normalize
    const result = allocator.alloc(u8, hostname.len) catch return error.EmptyHostname;
    for (hostname, 0..) |c, i| {
        result[i] = std.ascii.toLower(c);
    }
    return result;
}

/// extract hostname from a URL like "https://pds.example.com" or
/// "https://pds.example.com:443/path". borrows from `url` — no allocation.
pub fn extractHostFromUrl(url: []const u8) ?[]const u8 {
    // strip scheme
    var rest = url;
    if (std.mem.startsWith(u8, rest, "https://")) {
        rest = rest["https://".len..];
    } else if (std.mem.startsWith(u8, rest, "http://")) {
        rest = rest["http://".len..];
    }
    // strip path
    if (std.mem.indexOfScalar(u8, rest, '/')) |i| {
        rest = rest[0..i];
    }
    // strip port
    if (std.mem.indexOfScalar(u8, rest, ':')) |i| {
        rest = rest[0..i];
    }
    if (rest.len == 0) return null;
    return rest;
}

// --- tests ---

test "validateHostname accepts valid PDS hostnames" {
    const alloc = std.testing.allocator;

    const h1 = try validateHostname(alloc, "pds.example.com");
    defer alloc.free(h1);
    try std.testing.expectEqualStrings("pds.example.com", h1);

    const h2 = try validateHostname(alloc, "bsky.network");
    defer alloc.free(h2);
    try std.testing.expectEqualStrings("bsky.network", h2);

    // lowercases
    const h3 = try validateHostname(alloc, "PDS.Example.COM");
    defer alloc.free(h3);
    try std.testing.expectEqualStrings("pds.example.com", h3);

    // strips scheme
    const h4 = try validateHostname(alloc, "https://pds.example.com");
    defer alloc.free(h4);
    try std.testing.expectEqualStrings("pds.example.com", h4);

    // strips path
    const h5 = try validateHostname(alloc, "pds.example.com/some/path");
    defer alloc.free(h5);
    try std.testing.expectEqualStrings("pds.example.com", h5);
}

test "validateHostname rejects invalid hostnames" {
    const alloc = std.testing.allocator;

    try std.testing.expectError(error.EmptyHostname, validateHostname(alloc, ""));
    try std.testing.expectError(error.LocalhostNotAllowed, validateHostname(alloc, "localhost"));
    try std.testing.expectError(error.TooFewLabels, validateHostname(alloc, "intranet"));
    try std.testing.expectError(error.LooksLikeIpAddress, validateHostname(alloc, "192.168.1.1"));
    try std.testing.expectError(error.LooksLikeIpAddress, validateHostname(alloc, "10.0.0.1"));
    try std.testing.expectError(error.PortNotAllowed, validateHostname(alloc, "pds.example.com:443"));
    try std.testing.expectError(error.InvalidCharacter, validateHostname(alloc, "pds.exam ple.com"));
    try std.testing.expectError(error.InvalidCharacter, validateHostname(alloc, "pds.exam_ple.com"));
    try std.testing.expectError(error.InvalidLabel, validateHostname(alloc, "-pds.example.com"));
    try std.testing.expectError(error.InvalidLabel, validateHostname(alloc, "pds-.example.com"));
    try std.testing.expectError(error.InvalidLabel, validateHostname(alloc, "pds..example.com"));
}

test "extractHostFromUrl strips scheme, path, and port" {
    try std.testing.expectEqualStrings("pds.example.com", extractHostFromUrl("https://pds.example.com").?);
    try std.testing.expectEqualStrings("pds.example.com", extractHostFromUrl("https://pds.example.com:443/x").?);
    try std.testing.expectEqualStrings("pds.example.com", extractHostFromUrl("http://pds.example.com/path").?);
    try std.testing.expect(extractHostFromUrl("https://") == null);
}