zat.dev/zds
atproto pds · mirror of https://tangled.org/zat.dev/zds
zds 0.25.1 Latest 2 packages, all images
0
0
//! The icon an OAuth client declares, fetched by ZDS so the consent page never
//! loads third-party content. Candidates, in order: the client metadata's
//! `logo_uri`, the icons its homepage declares, then `/favicon.ico` at that
//! origin. Only responses that are recognisably images are kept.
const std = @import("std");
const clock = @import("../../core/clock.zig");
const document_cache = @import("../../internal/document_cache.zig");
const outbound = @import("../../internal/outbound.zig");
const store = @import("../../storage/store.zig");
const zat = @import("zat");
const max_icon_bytes = 256 * 1024;
const max_page_bytes = 512 * 1024;
const fetch_deadline_ns = 4 * std.time.ns_per_s;
const found_ttl_seconds: i64 = 6 * 60 * 60;
const missing_ttl_seconds: i64 = 15 * 60;
const max_page_candidates = 3;
var cache = document_cache.DocumentCache(64).init(std.heap.page_allocator);
pub const Icon = struct {
content_type: []const u8,
bytes: []const u8,
};
/// The client's icon, or null when no candidate resolves to an image. Results,
/// including misses, are cached per client.
pub fn resolve(allocator: std.mem.Allocator, client_id: []const u8, metadata: std.json.Value) !?Icon {
const now = clock.nowSeconds();
if (try cache.get(allocator, client_id, now)) |cached| return decodeCached(cached);
const icon = try find(allocator, client_id, metadata);
const entry = if (icon) |found|
try std.fmt.allocPrint(allocator, "{s}\n{s}", .{ found.content_type, found.bytes })
else
"";
cache.put(client_id, entry, now + if (icon != null) found_ttl_seconds else missing_ttl_seconds) catch {};
return icon;
}
fn decodeCached(entry: []const u8) ?Icon {
const newline = std.mem.indexOfScalar(u8, entry, '\n') orelse return null;
return .{ .content_type = entry[0..newline], .bytes = entry[newline + 1 ..] };
}
fn find(allocator: std.mem.Allocator, client_id: []const u8, metadata: std.json.Value) !?Icon {
if (zat.json.getString(metadata, "logo_uri")) |logo| {
if (fetchImage(allocator, logo)) |icon| return icon;
}
const home = homepage(client_id, zat.json.getString(metadata, "client_uri")) orelse return null;
if (fetchPage(allocator, home)) |page| {
const links = try iconLinks(allocator, page.body, page.url);
for (links[0..@min(links.len, max_page_candidates)]) |url| {
if (fetchImage(allocator, url)) |icon| return icon;
}
}
return fetchImage(allocator, try std.fmt.allocPrint(allocator, "{s}/favicon.ico", .{origin(home).?}));
}
fn fetchImage(allocator: std.mem.Allocator, url: []const u8) ?Icon {
if (std.ascii.startsWithIgnoreCase(url, "data:")) return dataImage(allocator, url);
const body = fetchBody(allocator, url, "image/*", max_icon_bytes) orelse return null;
const content_type = sniff(body) orelse return null;
return .{ .content_type = content_type, .bytes = body };
}
fn fetchBody(allocator: std.mem.Allocator, url: []const u8, accept: []const u8, limit: usize) ?[]const u8 {
const result = fetchOnce(allocator, url, accept, limit) orelse return null;
const status = @backingInt(result.status);
if (status < 200 or status >= 300) return null;
return result.body;
}
const Page = struct { url: []const u8, body: []const u8 };
/// A homepage often redirects to a sign-in page on the same origin. Follow
/// such redirects a couple of times, checking each target like the first.
fn fetchPage(allocator: std.mem.Allocator, start: []const u8) ?Page {
var url = start;
var hops: usize = 0;
while (true) : (hops += 1) {
const result = fetchOnce(allocator, url, "text/html", max_page_bytes) orelse return null;
const status = @backingInt(result.status);
if (status >= 200 and status < 300) return .{ .url = url, .body = result.body };
if (status < 300 or status >= 400 or hops == 2) return null;
const location = result.headers.get("location") orelse return null;
const next = (absoluteUrl(allocator, url, location) catch return null) orelse return null;
if (!std.mem.eql(u8, origin(next) orelse return null, origin(start).?)) return null;
url = next;
}
}
fn fetchOnce(allocator: std.mem.Allocator, url: []const u8, accept: []const u8, limit: usize) ?zat.HttpTransport.FetchResult {
var transport = zat.HttpTransport.init(store.currentIo(), allocator);
defer transport.deinit();
var options = outbound.guard(allocator, store.currentIo(), .{
.url = url,
.accept = accept,
.max_response_size = limit,
.deadline_ns = fetch_deadline_ns,
.capture_headers = &.{"location"},
}) catch return null;
options.on_redirect = .surface;
return transport.fetch(options) catch null;
}
/// An icon a page inlines as a `data:image/...` URL, base64 or percent-encoded.
/// It is held to the same size limit and byte sniffing as a fetched one.
fn dataImage(allocator: std.mem.Allocator, url: []const u8) ?Icon {
const comma = std.mem.indexOfScalar(u8, url, ',') orelse return null;
const header = url["data:".len..comma];
if (!std.ascii.startsWithIgnoreCase(header, "image/")) return null;
const payload = url[comma + 1 ..];
const bytes = if (std.ascii.endsWithIgnoreCase(header, ";base64")) base64: {
const decoder = std.base64.standard.Decoder;
const size = decoder.calcSizeForSlice(payload) catch return null;
if (size > max_icon_bytes) return null;
const out = allocator.alloc(u8, size) catch return null;
decoder.decode(out, payload) catch return null;
break :base64 out;
} else zat.percent.decodeAlloc(allocator, payload) catch return null;
if (bytes.len > max_icon_bytes) return null;
const content_type = sniff(bytes) orelse return null;
return .{ .content_type = content_type, .bytes = bytes };
}
/// The page whose declared icons stand for the client: its `client_uri` when
/// that shares the client_id's origin, otherwise the client_id's origin.
fn homepage(client_id: []const u8, client_uri: ?[]const u8) ?[]const u8 {
const id_origin = origin(client_id) orelse return null;
if (client_uri) |uri| {
if (origin(uri)) |uri_origin| {
if (std.mem.eql(u8, uri_origin, id_origin)) return uri;
}
}
return id_origin;
}
/// `scheme://authority` of an absolute http(s) URL.
fn origin(url: []const u8) ?[]const u8 {
const scheme_end = std.mem.indexOf(u8, url, "://") orelse return null;
const scheme = url[0..scheme_end];
if (!std.mem.eql(u8, scheme, "https") and !std.mem.eql(u8, scheme, "http")) return null;
const authority_start = scheme_end + 3;
const authority_end = std.mem.indexOfAnyPos(u8, url, authority_start, "/?#") orelse url.len;
if (authority_end == authority_start) return null;
return url[0..authority_end];
}
/// The content type of an image the page may show, judged by its bytes.
pub fn sniff(bytes: []const u8) ?[]const u8 {
if (std.mem.startsWith(u8, bytes, "\x89PNG\r\n\x1a\n")) return "image/png";
if (std.mem.startsWith(u8, bytes, "\xff\xd8\xff")) return "image/jpeg";
if (std.mem.startsWith(u8, bytes, "GIF87a") or std.mem.startsWith(u8, bytes, "GIF89a")) return "image/gif";
if (bytes.len >= 12 and std.mem.eql(u8, bytes[0..4], "RIFF") and std.mem.eql(u8, bytes[8..12], "WEBP")) return "image/webp";
if (std.mem.startsWith(u8, bytes, "\x00\x00\x01\x00")) return "image/x-icon";
const text = std.mem.trimStart(u8, bytes, " \t\r\n\xef\xbb\xbf");
if (std.mem.startsWith(u8, text, "<svg") or
(std.mem.startsWith(u8, text, "<?xml") and std.mem.indexOf(u8, text[0..@min(text.len, 1024)], "<svg") != null))
{
return "image/svg+xml";
}
return null;
}
const Link = struct { url: []const u8, score: u32 };
/// Icon URLs a page declares with `<link rel=...icon...>`, best first: touch
/// icons, then scalable ones, then larger declared sizes.
pub fn iconLinks(allocator: std.mem.Allocator, page: []const u8, page_url: []const u8) ![]const []const u8 {
var links: std.ArrayList(Link) = .empty;
var pos: usize = 0;
while (indexOfIgnoreCase(page, pos, "<link")) |start| {
const end = std.mem.indexOfScalarPos(u8, page, start, '>') orelse break;
pos = end;
const tag = page[start + 5 .. end];
const rel = attribute(tag, "rel") orelse continue;
const href = attribute(tag, "href") orelse continue;
const score = iconScore(rel, href, attribute(tag, "sizes"), attribute(tag, "type")) orelse continue;
const decoded = try decodeAmpersands(allocator, std.mem.trim(u8, href, " \t\r\n"));
const url = if (std.ascii.startsWithIgnoreCase(decoded, "data:")) decoded else try absoluteUrl(allocator, page_url, decoded) orelse continue;
try links.append(allocator, .{ .url = url, .score = score });
}
std.mem.sort(Link, links.items, {}, struct {
fn better(_: void, a: Link, b: Link) bool {
return a.score > b.score;
}
}.better);
const urls = try allocator.alloc([]const u8, links.items.len);
for (links.items, urls) |link, *url| url.* = link.url;
return urls;
}
fn iconScore(rel: []const u8, href: []const u8, sizes: ?[]const u8, content_type: ?[]const u8) ?u32 {
var tokens = std.mem.tokenizeAny(u8, rel, " \t\r\n");
var touch = false;
var icon = false;
while (tokens.next()) |token| {
if (std.ascii.eqlIgnoreCase(token, "icon")) icon = true;
if (std.ascii.startsWithIgnoreCase(token, "apple-touch-icon")) touch = true;
}
if (!icon and !touch) return null;
if (touch) return 10_000;
const scalable = std.ascii.endsWithIgnoreCase(href, ".svg") or
std.ascii.startsWithIgnoreCase(href, "data:image/svg+xml") or
(content_type != null and std.ascii.eqlIgnoreCase(content_type.?, "image/svg+xml"));
if (scalable) return 5_000;
if (sizes) |value| {
var best: u32 = 0;
var entries = std.mem.tokenizeScalar(u8, value, ' ');
while (entries.next()) |entry| {
const x = std.mem.indexOfAny(u8, entry, "xX") orelse continue;
best = @max(best, std.fmt.parseInt(u32, entry[0..x], 10) catch 0);
}
if (best > 0) return @min(best, 4_000);
}
return 16;
}
fn attribute(tag: []const u8, name: []const u8) ?[]const u8 {
var pos: usize = 0;
while (indexOfIgnoreCase(tag, pos, name)) |found| {
pos = found + name.len;
const boundary = found == 0 or std.ascii.isWhitespace(tag[found - 1]);
var i = found + name.len;
while (i < tag.len and std.ascii.isWhitespace(tag[i])) i += 1;
if (!boundary or i >= tag.len or tag[i] != '=') continue;
i += 1;
while (i < tag.len and std.ascii.isWhitespace(tag[i])) i += 1;
if (i >= tag.len) return null;
if (tag[i] == '"' or tag[i] == '\'') {
const close = std.mem.indexOfScalarPos(u8, tag, i + 1, tag[i]) orelse return null;
return tag[i + 1 .. close];
}
const close = std.mem.indexOfAnyPos(u8, tag, i, " \t\r\n/") orelse tag.len;
return tag[i..close];
}
return null;
}
fn absoluteUrl(allocator: std.mem.Allocator, base: []const u8, href: []const u8) !?[]const u8 {
const trimmed = std.mem.trim(u8, href, " \t\r\n");
if (trimmed.len == 0) return null;
if (std.ascii.startsWithIgnoreCase(trimmed, "https://")) return try allocator.dupe(u8, trimmed);
if (std.mem.indexOfScalar(u8, trimmed, ':') != null and std.mem.indexOfScalar(u8, trimmed, ':').? < (std.mem.indexOfScalar(u8, trimmed, '/') orelse trimmed.len)) return null;
const base_origin = origin(base) orelse return null;
if (std.mem.startsWith(u8, trimmed, "//")) return try std.fmt.allocPrint(allocator, "{s}:{s}", .{ base[0..std.mem.indexOf(u8, base, "://").?], trimmed });
if (trimmed[0] == '/') return try std.fmt.allocPrint(allocator, "{s}{s}", .{ base_origin, trimmed });
const path_end = std.mem.indexOfAnyPos(u8, base, base_origin.len, "?#") orelse base.len;
const directory_end = if (std.mem.lastIndexOfScalar(u8, base[0..path_end], '/')) |slash| if (slash >= base_origin.len) slash + 1 else null else null;
if (directory_end) |end| return try std.fmt.allocPrint(allocator, "{s}{s}", .{ base[0..end], trimmed });
return try std.fmt.allocPrint(allocator, "{s}/{s}", .{ base_origin, trimmed });
}
fn decodeAmpersands(allocator: std.mem.Allocator, value: []const u8) ![]const u8 {
return std.mem.replaceOwned(u8, allocator, value, "&", "&");
}
fn indexOfIgnoreCase(haystack: []const u8, start: usize, needle: []const u8) ?usize {
if (needle.len > haystack.len) return null;
var i = start;
while (i + needle.len <= haystack.len) : (i += 1) {
if (std.ascii.eqlIgnoreCase(haystack[i .. i + needle.len], needle)) return i;
}
return null;
}
test "icon links prefer touch icons, then scalable and larger ones" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const page =
\\<html><head>
\\<link rel="stylesheet" href="/app.css">
\\<link rel="icon" href="/favicon-32.png" sizes="32x32">
\\<LINK REL='shortcut icon' HREF=favicon.ico>
\\<link rel="mask-icon" href="/mask.svg">
\\<link href="/icon.svg" rel="icon" type="image/svg+xml">
\\<link rel="apple-touch-icon" href="https://cdn.example/touch.png?v=1&x=2">
\\<link rel="icon" href="javascript:alert(1)">
\\</head></html>
;
const links = try iconLinks(arena.allocator(), page, "https://app.example/start/index.html");
try std.testing.expectEqual(@as(usize, 4), links.len);
try std.testing.expectEqualStrings("https://cdn.example/touch.png?v=1&x=2", links[0]);
try std.testing.expectEqualStrings("https://app.example/icon.svg", links[1]);
try std.testing.expectEqualStrings("https://app.example/favicon-32.png", links[2]);
try std.testing.expectEqualStrings("https://app.example/start/favicon.ico", links[3]);
}
test "only recognisable image bytes count as an icon" {
try std.testing.expectEqualStrings("image/png", sniff("\x89PNG\r\n\x1a\n....").?);
try std.testing.expectEqualStrings("image/jpeg", sniff("\xff\xd8\xff\xe0").?);
try std.testing.expectEqualStrings("image/webp", sniff("RIFF\x00\x00\x00\x00WEBPVP8 ").?);
try std.testing.expectEqualStrings("image/x-icon", sniff("\x00\x00\x01\x00\x01\x00").?);
try std.testing.expectEqualStrings("image/svg+xml", sniff("\n<?xml version=\"1.0\"?><svg xmlns=\"http://www.w3.org/2000/svg\"/>").?);
try std.testing.expect(sniff("<!doctype html><html>") == null);
try std.testing.expect(sniff("") == null);
}
test "the homepage is client_uri only on the client's own origin" {
try std.testing.expectEqualStrings("https://noti.waow.tech", homepage("https://noti.waow.tech/oauth-client-metadata.json", "https://noti.waow.tech").?);
try std.testing.expectEqualStrings("https://app.example/home", homepage("https://app.example/client.json", "https://app.example/home").?);
try std.testing.expectEqualStrings("https://app.example", homepage("https://app.example/client.json", "https://elsewhere.example/").?);
try std.testing.expect(homepage("not a url", null) == null);
}
test "an inlined data: icon counts, held to the same checks as a fetched one" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
// As a page builds it with encodeURIComponent.
const svg = "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2020%2020%22%3E%3C%2Fsvg%3E";
const page = try std.fmt.allocPrint(a, "<head><link rel=\"icon\" href=\"/small.png\" sizes=\"16x16\"><link rel=\"icon\" href=\"{s}\"></head>", .{svg});
const links = try iconLinks(a, page, "https://app.example/");
try std.testing.expectEqual(@as(usize, 2), links.len);
try std.testing.expectEqualStrings(svg, links[0]);
const icon = dataImage(a, links[0]).?;
try std.testing.expectEqualStrings("image/svg+xml", icon.content_type);
try std.testing.expect(std.mem.startsWith(u8, icon.bytes, "<svg xmlns=\"http://www.w3.org/2000/svg\""));
const png = dataImage(a, "data:image/png;base64,iVBORw0KGgoAAAA=").?;
try std.testing.expectEqualStrings("image/png", png.content_type);
try std.testing.expect(dataImage(a, "data:text/html,%3Csvg%3E") == null);
try std.testing.expect(dataImage(a, "data:image/png;base64,aGVsbG8=") == null);
try std.testing.expect(dataImage(a, "data:image/svg+xml,%3Csvg%") == null);
try std.testing.expect(dataImage(a, "data:image/svg+xml,%3Csvg%3E%+A") == null);
const plus = dataImage(a, "data:image/svg+xml,%3Csvg%3Ea+b%2Bc%3C/svg%3E").?;
try std.testing.expectEqualStrings("<svg>a+b+c</svg>", plus.bytes);
}