zat.dev/zds
atproto pds · mirror of https://tangled.org/zat.dev/zds
zds 0.25.1 Latest 2 packages, all images
0
0
const std = @import("std");
const request_context = @import("../internal/request_context.zig");
const clock = @import("../core/clock.zig");
const config = @import("../core/config.zig");
const auth = @import("../auth/tokens.zig");
const dpop = @import("../internal/dpop.zig");
const log = @import("../core/log.zig");
const store = @import("../storage/store.zig");
const httpz = @import("httpz");
const http = std.http;
pub const Request = httpz.Request;
pub const Response = httpz.Response;
/// The exact bodies of a page's inline `<script>` and `<style>` elements.
pub const InlineCode = struct {
scripts: []const []const u8 = &.{},
styles: []const []const u8 = &.{},
};
/// Headers for every HTML page this server renders. Each page passes the exact
/// bodies of its inline scripts and styles, which are allowed by hash; nothing
/// else runs or applies, including `style` attributes. Images may come from any
/// HTTPS origin for icon slots. There is no form-action: browsers apply it to
/// every redirect after a submission, which would block OAuth's 303 to the
/// client's redirect_uri.
pub fn htmlSecurityHeaders(comptime code: InlineCode) [4]http.Header {
return securityHeaders(comptime policyHead(code) ++ policy_tail);
}
/// `htmlSecurityHeaders` for a page that also renders one style element whose
/// body is only known per request.
pub fn htmlSecurityHeadersWithStyle(allocator: std.mem.Allocator, comptime code: InlineCode, style: []const u8) ![4]http.Header {
var digest: [32]u8 = undefined;
std.crypto.hash.sha2.Sha256.hash(style, &digest, .{});
var hash: [44]u8 = undefined;
_ = std.base64.standard.Encoder.encode(&hash, &digest);
const head = comptime "default-src 'self'; script-src" ++ hashSources(code.scripts) ++ "; style-src" ++ (if (code.styles.len == 0) "" else hashSources(code.styles));
const policy = try std.fmt.allocPrint(allocator, "{s} 'sha256-{s}'{s}", .{ head, &hash, policy_tail });
return securityHeaders(policy);
}
fn securityHeaders(policy: []const u8) [4]http.Header {
return .{
.{ .name = "content-security-policy", .value = policy },
.{ .name = "x-frame-options", .value = "DENY" },
.{ .name = "x-content-type-options", .value = "nosniff" },
.{ .name = "referrer-policy", .value = "no-referrer" },
};
}
const policy_tail = "; img-src 'self' https: data: blob:; font-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'";
fn policyHead(comptime code: InlineCode) []const u8 {
comptime return "default-src 'self'; script-src" ++ hashSources(code.scripts) ++ "; style-src" ++ hashSources(code.styles);
}
fn hashSources(comptime bodies: []const []const u8) []const u8 {
comptime {
var sources: []const u8 = if (bodies.len == 0) " 'none'" else "";
for (bodies) |body| sources = sources ++ " 'sha256-" ++ hashOf(body) ++ "'";
return sources;
}
}
fn hashOf(comptime body: []const u8) [44]u8 {
comptime {
@setEvalBranchQuota(100_000_000);
var digest: [32]u8 = undefined;
std.crypto.hash.sha2.Sha256.hash(body, &digest, .{});
var out: [44]u8 = undefined;
_ = std.base64.standard.Encoder.encode(&out, &digest);
return out;
}
}
/// Bodies of the `<script>` and `<style>` elements in a trusted, comptime-known
/// template.
pub fn inlineCode(comptime html: []const u8) InlineCode {
comptime return .{ .scripts = elementBodies(html, "script"), .styles = elementBodies(html, "style") };
}
fn elementBodies(comptime html: []const u8, comptime tag: []const u8) []const []const u8 {
comptime {
@setEvalBranchQuota(10_000_000);
var bodies: []const []const u8 = &.{};
var rest = html;
while (std.mem.indexOf(u8, rest, "<" ++ tag ++ ">")) |open| {
const body = rest[open + tag.len + 2 ..];
const close = std.mem.indexOf(u8, body, "</" ++ tag ++ ">").?;
bodies = bodies ++ .{body[0..close]};
rest = body[close..];
}
return bodies;
}
}
threadlocal var active_response: ?*Response = null;
/// The OAuth error a DPoP-scheme bearer check failed with. The reference answers these with the OAuth code as
/// the XRPC error name, and DPoP clients that read the body (atproto-oauth's DpopRetry) act on that code.
const OAuthChallenge = struct { code: []const u8, description: []const u8 };
threadlocal var oauth_challenge: ?OAuthChallenge = null;
pub fn bindResponse(res: *Response) void {
active_response = res;
oauth_challenge = null;
}
pub fn unbindResponse() void {
active_response = null;
oauth_challenge = null;
}
pub fn currentStatus() u16 {
return response().status;
}
fn response() *Response {
return active_response orelse @panic("http response not bound");
}
pub const BearerAccount = struct {
account: auth.Account,
oauth_scope: ?[]const u8,
oauth_client_id: ?[]const u8 = null,
/// A session signed in with an app password, not the account's own credentials.
app_password: bool = false,
/// The limited session of a taken-down account (see takendown_scope).
takendown: bool = false,
};
const TokenScheme = enum {
bearer,
dpop,
fn name(self: TokenScheme) []const u8 {
return switch (self) {
.bearer => "Bearer",
.dpop => "DPoP",
};
}
};
pub const BearerError = error{ AuthRequired, InvalidToken, ExpiredToken, BadTokenScope, UseDpopNonce };
/// the xrpc answer for a failed bearer check: 401 for a missing or unusable
/// credential, 400 ExpiredToken for a genuine session whose exp has passed, and
/// 400 InvalidToken for a session whose scope the route does not take, as the
/// reference PDS answers
pub fn bearerErrorResponse(request: *Request, err: BearerError) !void {
return switch (err) {
error.AuthRequired => xrpcError(request, .unauthorized, "AuthenticationRequired", "Authentication required"),
error.InvalidToken => if (oauth_challenge) |challenge|
xrpcError(request, .unauthorized, challenge.code, challenge.description)
else
xrpcError(request, .unauthorized, "InvalidToken", "Invalid token"),
error.ExpiredToken => xrpcError(request, .bad_request, "ExpiredToken", "Token has expired"),
error.BadTokenScope => xrpcError(request, .bad_request, "InvalidToken", "Bad token scope"),
// The reference names the error with the OAuth code, and DPoP clients that read the body
// (atproto-oauth's DpopRetry) retry only on `use_dpop_nonce`.
error.UseDpopNonce => xrpcError(request, .unauthorized, "use_dpop_nonce", "Resource server requires nonce in DPoP proof"),
};
}
/// How the stats page names the client behind a legacy (password or app
/// password) session, which carries no client_id: a browser app by the host
/// in its Origin header, a native app by the product its User-Agent starts
/// with ("Bluesky/1.98 CFNetwork" is Bluesky). A browser's own "Mozilla"
/// says nothing, so it is null like a missing header.
pub fn legacyClientLabel(request: *const Request) ?[]const u8 {
if (headerValue(request, "origin")) |origin| {
if (clientHost(origin)) |name| return name;
}
const agent = headerValue(request, "user-agent") orelse return null;
return productToken(agent);
}
fn clientHost(origin: []const u8) ?[]const u8 {
const rest = if (std.mem.startsWith(u8, origin, "https://"))
origin["https://".len..]
else if (std.mem.startsWith(u8, origin, "http://"))
origin["http://".len..]
else
return null;
const host = rest[0 .. std.mem.indexOfAny(u8, rest, "/:?#") orelse rest.len];
if (host.len == 0 or host.len > 64) return null;
if (std.mem.eql(u8, host, "localhost") or std.mem.eql(u8, host, "127.0.0.1")) return "an app on a device";
for (host) |c| if (!(std.ascii.isAlphanumeric(c) or c == '.' or c == '-')) return null;
return host;
}
fn productToken(agent: []const u8) ?[]const u8 {
const token = agent[0 .. std.mem.indexOfAny(u8, agent, "/ ;(") orelse agent.len];
if (token.len < 2 or token.len > 40) return null;
if (std.ascii.eqlIgnoreCase(token, "Mozilla")) return null;
for (token) |c| if (!(std.ascii.isAlphanumeric(c) or c == '.' or c == '-' or c == '_')) return null;
return token;
}
/// How the stats page names an OAuth app: the host of a conventional
/// https client_id, else the client_id itself.
pub fn appLabel(client_id: []const u8) []const u8 {
if (std.mem.startsWith(u8, client_id, "http://localhost") or std.mem.startsWith(u8, client_id, "http://127.0.0.1")) return "an app on a device";
if (!std.mem.startsWith(u8, client_id, "https://")) return client_id;
const rest = client_id["https://".len..];
const end = std.mem.indexOfAny(u8, rest, "/:?#") orelse rest.len;
return rest[0..end];
}
pub fn requireBearerAccount(request: *const Request, allocator: std.mem.Allocator) BearerError!auth.Account {
return (try requireBearerAccountWithScope(request, allocator, "com.atproto.access")).account;
}
pub fn requireBearerAccess(request: *const Request, allocator: std.mem.Allocator) BearerError!BearerAccount {
return requireBearerAccountWithScope(request, allocator, "com.atproto.access");
}
/// The admin token presented as `Bearer <token>`, or as the reference PDS takes
/// its admin password: `Basic` with username `admin`.
pub fn adminCredential(header: []const u8, basic_buf: []u8) ?[]const u8 {
if (std.ascii.startsWithIgnoreCase(header, "bearer ")) return std.mem.trim(u8, header["bearer ".len..], " \t");
if (!std.ascii.startsWithIgnoreCase(header, "basic ")) return null;
const encoded = std.mem.trim(u8, header["basic ".len..], " \t");
const decoder = std.base64.standard.Decoder;
const len = decoder.calcSizeForSlice(encoded) catch return null;
if (len > basic_buf.len) return null;
decoder.decode(basic_buf[0..len], encoded) catch return null;
const decoded = basic_buf[0..len];
// The password may itself contain colons, so split at the first one.
const colon = std.mem.indexOfScalar(u8, decoded, ':') orelse return null;
if (!std.mem.eql(u8, decoded[0..colon], "admin")) return null;
return decoded[colon + 1 ..];
}
test "admin credential comes from Bearer or Basic admin" {
var buf: [1024]u8 = undefined;
try std.testing.expectEqualStrings("tok", adminCredential("Bearer tok", &buf).?);
// base64("admin:pass:with:colons")
try std.testing.expectEqualStrings("pass:with:colons", adminCredential("Basic YWRtaW46cGFzczp3aXRoOmNvbG9ucw==", &buf).?);
// base64("someone:pass")
try std.testing.expect(adminCredential("Basic c29tZW9uZTpwYXNz", &buf) == null);
try std.testing.expect(adminCredential("Basic not base64!", &buf) == null);
try std.testing.expect(adminCredential("DPoP tok", &buf) == null);
try std.testing.expect(adminCredential("", &buf) == null);
}
/// Compares digests, so the time a guess takes says nothing about how many of
/// its leading bytes were right.
pub fn adminTokenMatches(provided: []const u8, expected: []const u8) bool {
var provided_digest: [32]u8 = undefined;
var expected_digest: [32]u8 = undefined;
std.crypto.hash.sha2.Sha256.hash(provided, &provided_digest, .{});
std.crypto.hash.sha2.Sha256.hash(expected, &expected_digest, .{});
return std.crypto.timing_safe.eql([32]u8, provided_digest, expected_digest);
}
test "admin token match is exact" {
try std.testing.expect(adminTokenMatches("admin-secret", "admin-secret"));
try std.testing.expect(!adminTokenMatches("admin-secreT", "admin-secret"));
try std.testing.expect(!adminTokenMatches("admin-secret-and-more", "admin-secret"));
try std.testing.expect(!adminTokenMatches("", "admin-secret"));
}
/// Whether the request carries the configured admin token, in either form
/// requireAdminToken takes. Repo reads let it through any account status, as
/// the reference PDS's do.
pub fn hasAdminToken(request: *const Request) bool {
const expected = config.adminToken() orelse return false;
var basic_buf: [1024]u8 = undefined;
const provided = adminCredential(headerValue(request, "authorization") orelse return false, &basic_buf) orelse return false;
return adminTokenMatches(provided, expected);
}
/// How much account status a route checks, as the reference PDS's
/// checkTakedown and checkDeactivated options.
pub const ActiveCheck = enum {
/// Refuses taken down (and suspended) accounts; deactivated ones may act,
/// as migration needs (importRepo, uploadBlob).
takedown,
/// Also refuses deactivated accounts (writes and space management).
takedown_and_deactivation,
};
/// Refuses an account its status does not allow on this route, with the
/// reference PDS's 401 AccountTakedown or AccountDeactivated.
pub fn requireActiveAccount(request: *Request, did: []const u8, check: ActiveCheck) !void {
const status = store.accountStatus(did) catch |err| switch (err) {
error.RepoNotFound => return xrpcError(request, .forbidden, "AccountNotFound", "Account not found"),
else => return err,
};
switch (status) {
.active => {},
.deactivated => if (check == .takedown_and_deactivation)
return xrpcError(request, .unauthorized, "AccountDeactivated", "Account is deactivated"),
.takendown => return xrpcError(request, .unauthorized, "AccountTakedown", "Account has been taken down"),
.suspended => return xrpcError(request, .unauthorized, "AccountSuspended", "Account is suspended"),
.deleted => return xrpcError(request, .forbidden, "AccountNotFound", "Account not found"),
}
}
/// The session a taken-down account gets from createSession with
/// allowTakendown: it can export its data and move its identity, nothing else.
pub const takendown_scope = "com.atproto.takendown";
/// For the routes a taken-down account needs to migrate away. Accepts what
/// requireBearerAccess does, and the takendown session too.
pub fn requireBearerAccessOrTakendown(request: *const Request, allocator: std.mem.Allocator) BearerError!BearerAccount {
return requireBearerAccountWithScope(request, allocator, takendown_scope);
}
pub fn requireBearerAccountWithScope(request: *const Request, allocator: std.mem.Allocator, scope: []const u8) BearerError!BearerAccount {
return bearerAccountWithScope(request, allocator, scope) catch |err| {
// A DPoP-scheme request is an OAuth request, and every token failure there is an OAuth error; the paths
// that do not name a more specific one are invalid_token, as the reference reports them.
if (err == error.InvalidToken and oauth_challenge == null) {
if (headerValue(request, "authorization")) |header| {
if (std.ascii.startsWithIgnoreCase(header, "dpop ")) challengeInvalidToken(allocator, .dpop, "Invalid token");
}
}
return err;
};
}
fn bearerAccountWithScope(request: *const Request, allocator: std.mem.Allocator, scope: []const u8) BearerError!BearerAccount {
const auth_header = headerValue(request, "authorization") orelse {
return error.AuthRequired;
};
const token_scheme: TokenScheme =
if (std.ascii.startsWithIgnoreCase(auth_header, "bearer "))
.bearer
else if (std.ascii.startsWithIgnoreCase(auth_header, "dpop "))
.dpop
else
return error.AuthRequired;
const token_start: usize = if (token_scheme == .bearer) "bearer ".len else "dpop ".len;
const token = std.mem.trim(u8, auth_header[token_start..], " \t");
const claims = auth.parseSessionJwt(allocator, token) catch |err| switch (err) {
error.Invalid => {
log.err("bearer auth invalid: jwt parse/verify failed token_len={d}\n", .{token.len});
challengeInvalidToken(allocator, token_scheme, "Token is invalid");
return error.InvalidToken;
},
error.Expired => {
// OAuth clients refresh on the invalid_token challenge, not on ExpiredToken
const oauth_row = store.getOAuthToken(allocator, token) catch |lookup_err| {
log.err("bearer auth invalid: oauth token lookup failed on expired jwt err={s}\n", .{@errorName(lookup_err)});
return error.InvalidToken;
};
if (oauth_row != null) {
log.err("bearer auth invalid: oauth jwt expired token_len={d}\n", .{token.len});
challengeInvalidToken(allocator, token_scheme, "Token has expired");
return error.InvalidToken;
}
log.err("bearer auth expired: session jwt exp passed token_len={d}\n", .{token.len});
return error.ExpiredToken;
},
};
defer allocator.free(claims.did);
defer allocator.free(claims.scope);
defer allocator.free(claims.jti);
defer if (claims.cnf_jkt) |jkt| allocator.free(jkt);
if (!scopeAllows(claims.scope, scope)) {
log.err("bearer auth invalid: session scope reject claims_scope={s} required={s} did={s}\n", .{ claims.scope, scope, claims.did });
return error.BadTokenScope;
}
const account = (store.findAccount(allocator, claims.did) catch |err| {
log.err("bearer auth invalid: account lookup failed did={s} err={s}\n", .{ claims.did, @errorName(err) });
return error.InvalidToken;
}) orelse {
log.err("bearer auth invalid: account not found did={s}\n", .{claims.did});
return error.InvalidToken;
};
const oauth_token = store.getOAuthToken(allocator, token) catch |err| {
log.err("bearer auth invalid: oauth token lookup failed did={s} err={s}\n", .{ claims.did, @errorName(err) });
return error.InvalidToken;
};
if (oauth_token) |row| {
const ts = now();
if (row.kind != .access) {
log.err("oauth auth invalid: non-access token used for resource auth kind={s} did={s}\n", .{ @tagName(row.kind), row.did });
return error.InvalidToken;
}
if (row.revoked) {
log.err("bearer auth invalid: oauth row revoked=true access_expires_at={d} now={d} did={s}\n", .{ row.access_expires_at, ts, row.did });
challengeInvalidToken(allocator, token_scheme, "Token has been revoked");
return error.InvalidToken;
}
if (row.access_expires_at < ts) {
log.err("bearer auth invalid: oauth row revoked=false access_expires_at={d} now={d} did={s}\n", .{ row.access_expires_at, ts, row.did });
challengeInvalidToken(allocator, token_scheme, "Token has expired");
return error.InvalidToken;
}
if (!std.mem.eql(u8, row.did, claims.did)) {
log.err("bearer auth invalid: oauth row did mismatch row_did={s} claims_did={s}\n", .{ row.did, claims.did });
return error.InvalidToken;
}
if (row.dpop_jkt) |expected_jkt| {
if (token_scheme != .dpop) {
log.err("oauth auth invalid: dpop-bound token used without DPoP auth scheme did={s}\n", .{claims.did});
return error.InvalidToken;
}
if (claims.cnf_jkt == null or !std.mem.eql(u8, claims.cnf_jkt.?, expected_jkt)) {
log.err("oauth auth invalid: token cnf mismatch did={s}\n", .{claims.did});
return error.InvalidToken;
}
_ = dpop.verifyRequest(allocator, request, token, expected_jkt) catch |err| switch (err) {
error.UseDpopNonce, error.MissingProof => {
log.info("oauth dpop nonce challenge did={s} reason={s} client={s}\n", .{ claims.did, @errorName(err), row.client_id });
dpop.challengeResource(allocator) catch {};
return error.UseDpopNonce;
},
else => {
log.err("oauth auth invalid: dpop proof failed did={s} err={s}\n", .{ claims.did, @errorName(err) });
challengeInvalidDpopProof(allocator);
return error.InvalidToken;
},
};
dpop.attachNonce(allocator) catch {};
} else if (token_scheme != .bearer or claims.cnf_jkt != null) {
log.err("oauth auth invalid: bearer token/proof binding mismatch did={s}\n", .{claims.did});
return error.InvalidToken;
}
request_context.noteCaller(account.did, appLabel(row.client_id));
return .{ .account = account, .oauth_scope = row.scope, .oauth_client_id = row.client_id };
}
if (claims.cnf_jkt != null) {
log.err("bearer auth invalid: cnf-bound token had no oauth row did={s}\n", .{claims.did});
return error.InvalidToken;
}
const status = store.sessionTokenStatus(claims.did, claims.jti, claims.scope) catch |err| {
log.err("bearer auth invalid: session token status lookup failed did={s} jti={s} scope={s} err={s}\n", .{ claims.did, claims.jti, claims.scope, @errorName(err) });
return error.InvalidToken;
};
if (status == .active) {
const takendown = std.mem.eql(u8, claims.scope, takendown_scope);
const app_password = !takendown and !std.mem.eql(u8, claims.scope, "com.atproto.access");
request_context.noteCaller(account.did, legacyClientLabel(request) orelse if (app_password) "app passwords" else "password sessions");
return .{ .account = account, .oauth_scope = null, .app_password = !takendown and !std.mem.eql(u8, claims.scope, "com.atproto.access"), .takendown = takendown };
}
log.err("bearer auth refused: session token {s} did={s} jti={s} scope={s}\n", .{ @tagName(status), claims.did, claims.jti, claims.scope });
// a signed refresh token with no live row is a session this server ended, which the
// reference reports as ExpiredToken; a dead access token stays 401 so the client
// refreshes and learns the session is gone from that answer instead
if (std.mem.eql(u8, claims.scope, "com.atproto.refresh")) return error.ExpiredToken;
return error.InvalidToken;
}
fn challengeInvalidToken(allocator: std.mem.Allocator, scheme: TokenScheme, comptime description: []const u8) void {
var buf: [160]u8 = undefined;
const value = formatInvalidTokenChallenge(&buf, scheme, description) catch return;
addResponseHeader("www-authenticate", value) catch return;
if (scheme == .dpop) {
oauth_challenge = .{ .code = "invalid_token", .description = description };
dpop.attachNonce(allocator) catch {};
}
}
fn challengeInvalidDpopProof(allocator: std.mem.Allocator) void {
addResponseHeader("www-authenticate", "DPoP error=\"invalid_dpop_proof\", error_description=\"Invalid DPoP proof\"") catch return;
oauth_challenge = .{ .code = "invalid_dpop_proof", .description = "Invalid DPoP proof" };
dpop.attachNonce(allocator) catch {};
}
fn formatInvalidTokenChallenge(buf: []u8, scheme: TokenScheme, description: []const u8) ![]const u8 {
return std.fmt.bufPrint(
buf,
"{s} error=\"invalid_token\", error_description=\"{s}\"",
.{ scheme.name(), description },
);
}
fn scopeAllows(actual: []const u8, required: []const u8) bool {
if (std.mem.eql(u8, actual, required)) return true;
if (std.mem.eql(u8, required, takendown_scope)) return scopeAllows(actual, "com.atproto.access");
if (!std.mem.eql(u8, required, "com.atproto.access")) return false;
return std.mem.eql(u8, actual, "com.atproto.appPass") or
std.mem.eql(u8, actual, "com.atproto.appPassPrivileged");
}
test "takendown sessions reach only the routes that opt in" {
try std.testing.expect(scopeAllows(takendown_scope, takendown_scope));
try std.testing.expect(!scopeAllows(takendown_scope, "com.atproto.access"));
try std.testing.expect(!scopeAllows(takendown_scope, "com.atproto.refresh"));
try std.testing.expect(scopeAllows("com.atproto.access", takendown_scope));
try std.testing.expect(scopeAllows("com.atproto.appPass", takendown_scope));
try std.testing.expect(!scopeAllows("com.atproto.refresh", takendown_scope));
}
fn now() i64 {
return clock.nowSeconds();
}
pub fn parseJsonBody(request: *Request, allocator: std.mem.Allocator, body: []const u8) !std.json.Parsed(std.json.Value) {
return std.json.parseFromSlice(std.json.Value, allocator, body, .{}) catch {
try xrpcError(request, .bad_request, "InvalidRequest", "Expected JSON body");
return error.InvalidJson;
};
}
pub fn valueString(value: std.json.Value, key: []const u8) ?[]const u8 {
return switch (value) {
.object => |object| switch (object.get(key) orelse return null) {
.string => |string| string,
else => null,
},
else => null,
};
}
/// Reads the request body into `buf`. A body at or past the server's
/// lazy_read_size is only partly buffered: httpz still reports its full
/// length, so `request.body()` would slice past the buffered bytes and
/// panic. Check the length first and read the rest from the socket.
pub fn readBody(request: *Request, buf: []u8) ![]const u8 {
if (request.body_len > buf.len) return error.BodyTooLarge;
if (request.unread_body > 0) {
var body_reader = try request.reader(30_000);
try body_reader.interface.readSliceAll(buf[0..request.body_len]);
return buf[0..request.body_len];
}
const body = request.body() orelse "";
@memcpy(buf[0..body.len], body);
return buf[0..body.len];
}
pub fn readBodyAlloc(request: *Request, allocator: std.mem.Allocator, max_len: usize) ![]const u8 {
if (request.body_len > max_len) return error.BodyTooLarge;
if (request.unread_body > 0) {
var body_reader = try request.reader(30_000);
return try body_reader.interface.readAlloc(allocator, request.body_len);
}
const body = request.body() orelse "";
return try allocator.dupe(u8, body);
}
pub fn headerValue(request: *const Request, name: []const u8) ?[]const u8 {
var lower_buf: [128]u8 = undefined;
const lower = if (name.len <= lower_buf.len) blk: {
for (name, 0..) |c, i| lower_buf[i] = std.ascii.toLower(c);
break :blk lower_buf[0..name.len];
} else name;
return request.header(lower);
}
pub fn queryParam(target: []const u8, name: []const u8, out: []u8) ?[]const u8 {
const query_start = std.mem.indexOfScalar(u8, target, '?') orelse return null;
var params = std.mem.splitScalar(u8, target[query_start + 1 ..], '&');
while (params.next()) |param| {
const eq = std.mem.indexOfScalar(u8, param, '=') orelse continue;
if (!std.mem.eql(u8, param[0..eq], name)) continue;
return percentDecode(param[eq + 1 ..], out) catch null;
}
return null;
}
/// Every value of a repeated query parameter (`?cids=a&cids=b`), decoded.
pub fn queryParamValues(allocator: std.mem.Allocator, target: []const u8, name: []const u8) ![]const []const u8 {
var values: std.ArrayList([]const u8) = .empty;
const query_start = std.mem.indexOfScalar(u8, target, '?') orelse return values.toOwnedSlice(allocator);
var params = std.mem.splitScalar(u8, target[query_start + 1 ..], '&');
while (params.next()) |param| {
const eq = std.mem.indexOfScalar(u8, param, '=') orelse continue;
if (!std.mem.eql(u8, param[0..eq], name)) continue;
const out = try allocator.alloc(u8, param.len - eq - 1);
try values.append(allocator, try percentDecode(param[eq + 1 ..], out));
}
return values.toOwnedSlice(allocator);
}
pub fn queryLimit(target: []const u8, default: usize) usize {
var buf: [16]u8 = undefined;
const raw = queryParam(target, "limit", &buf) orelse return default;
return std.fmt.parseInt(usize, raw, 10) catch default;
}
pub fn percentDecode(input: []const u8, out: []u8) ![]const u8 {
var write: usize = 0;
var read: usize = 0;
while (read < input.len) {
if (write >= out.len) return error.NoSpaceLeft;
switch (input[read]) {
'%' => {
if (read + 2 >= input.len) return error.InvalidPercentEncoding;
out[write] = try std.fmt.parseInt(u8, input[read + 1 .. read + 3], 16);
read += 3;
},
'+' => {
out[write] = ' ';
read += 1;
},
else => |c| {
out[write] = c;
read += 1;
},
}
write += 1;
}
return out[0..write];
}
pub fn corsPreflight(request: *Request) !void {
const res = response();
const allow_headers = if (headerValue(request, "access-control-request-headers")) |requested| blk: {
const trimmed = std.mem.trim(u8, requested, " \t");
break :blk if (trimmed.len > 0) trimmed else default_cors_allow_headers;
} else default_cors_allow_headers;
const headers = [_]http.Header{
.{ .name = "access-control-allow-origin", .value = "*" },
.{ .name = "access-control-allow-methods", .value = "GET, HEAD, POST, OPTIONS" },
.{ .name = "vary", .value = "Access-Control-Request-Headers" },
.{ .name = "access-control-allow-headers", .value = allow_headers },
.{ .name = "access-control-allow-private-network", .value = "true" },
.{ .name = "access-control-max-age", .value = "600" },
.{ .name = "connection", .value = "close" },
};
try setHeaders(res, &headers);
res.setStatus(.no_content);
}
pub fn toStdMethod(method: httpz.Method) http.Method {
return switch (method) {
.GET => .GET,
.HEAD => .HEAD,
.POST => .POST,
.PUT => .PUT,
.PATCH => .PATCH,
.DELETE => .DELETE,
.OPTIONS => .OPTIONS,
else => .GET,
};
}
pub fn upgradeWebsocket(comptime Handler: type, request: *Request, ctx: anytype) !bool {
return httpz.upgradeWebsocket(Handler, request, response(), ctx);
}
/// The body copied into the response's arena. An empty body stays the
/// literal "": copying zero bytes yields Zig's placeholder pointer
/// (0xffff…ffff), and Linux `writev` fails with EFAULT on an iovec at that
/// address even when its length is zero, which httpz treats as unreachable.
fn ownedBody(arena: std.mem.Allocator, body: []const u8) ![]const u8 {
if (body.len == 0) return "";
return arena.dupe(u8, body);
}
pub fn json(request: *Request, status: http.Status, body: []const u8) !void {
_ = request;
const res = response();
try setHeaders(res, &json_headers);
res.setStatus(status);
res.body = try ownedBody(res.arena, body);
}
pub fn empty(request: *Request, status: http.Status) !void {
_ = request;
const res = response();
try setHeaders(res, &empty_headers);
res.setStatus(status);
res.body = "";
}
pub fn text(request: *Request, status: http.Status, body: []const u8) !void {
_ = request;
const res = response();
try setHeaders(res, &text_headers);
res.setStatus(status);
res.body = try ownedBody(res.arena, body);
}
// writes the xrpc error body and fails with HandledResponse so the caller
// stops too. a guard like `return http_api.xrpcError(...)` inside a helper
// invoked with `try` used to return success after writing, and the handler
// went on to do the work and overwrite the error with a 200.
pub fn xrpcError(
request: *Request,
status: http.Status,
error_name: []const u8,
message: []const u8,
) !void {
var buf: [512]u8 = undefined;
const body = try std.fmt.bufPrint(&buf, "{{\"error\":\"{s}\",\"message\":\"{s}\"}}", .{ error_name, message });
logRefusedRepoWrite(request, status, error_name, message);
try json(request, status, body);
return error.HandledResponse;
}
const repo_write_paths = [_][]const u8{
"/xrpc/com.atproto.repo.createRecord",
"/xrpc/com.atproto.repo.putRecord",
"/xrpc/com.atproto.repo.deleteRecord",
"/xrpc/com.atproto.repo.applyWrites",
"/xrpc/com.atproto.repo.uploadBlob",
};
fn isRepoWrite(method: httpz.Method, raw_url: []const u8) bool {
if (method != .POST) return false;
const path = raw_url[0 .. std.mem.indexOfAny(u8, raw_url, "?#") orelse raw_url.len];
for (repo_write_paths) |write_path| if (std.mem.eql(u8, path, write_path)) return true;
return false;
}
/// A refused write leaves no record and no commit, so without this line a
/// client's failed write is invisible on the server.
fn logRefusedRepoWrite(request: *const Request, status: http.Status, error_name: []const u8, message: []const u8) void {
const code = @backingInt(status);
if (code < 400 or code >= 500 or !isRepoWrite(request.method, request.url.raw)) return;
const who = request_context.caller();
log.info("repo write refused path={s} status={d} error={s} message=\"{s}\" did={s} app={s} ua=\"{s}\"\n", .{
request.url.path,
code,
error_name,
message,
if (who) |c| c.did else "-",
if (who) |c| c.app else "-",
headerValue(request, "user-agent") orelse "-",
});
}
test "only repo write routes count as refused writes" {
try std.testing.expect(isRepoWrite(.POST, "/xrpc/com.atproto.repo.createRecord"));
try std.testing.expect(isRepoWrite(.POST, "/xrpc/com.atproto.repo.applyWrites?x=1"));
try std.testing.expect(!isRepoWrite(.GET, "/xrpc/com.atproto.repo.createRecord"));
try std.testing.expect(!isRepoWrite(.POST, "/xrpc/com.atproto.repo.getRecord"));
try std.testing.expect(!isRepoWrite(.POST, "/xrpc/com.atproto.repo.createRecordX"));
}
const json_headers = [_]http.Header{
.{ .name = "content-type", .value = "application/json; charset=utf-8" },
.{ .name = "access-control-allow-origin", .value = "*" },
.{ .name = "access-control-expose-headers", .value = "dpop-nonce, www-authenticate" },
.{ .name = "access-control-allow-private-network", .value = "true" },
.{ .name = "connection", .value = "close" },
};
const empty_headers = [_]http.Header{
.{ .name = "access-control-allow-origin", .value = "*" },
.{ .name = "access-control-expose-headers", .value = "dpop-nonce, www-authenticate" },
.{ .name = "access-control-allow-private-network", .value = "true" },
.{ .name = "connection", .value = "close" },
};
const text_headers = [_]http.Header{
.{ .name = "content-type", .value = "text/plain; charset=utf-8" },
.{ .name = "access-control-allow-origin", .value = "*" },
.{ .name = "access-control-expose-headers", .value = "dpop-nonce, www-authenticate" },
.{ .name = "access-control-allow-private-network", .value = "true" },
.{ .name = "connection", .value = "close" },
};
const default_cors_allow_headers = "atproto-accept-labelers, atproto-proxy, authorization, content-type, dpop, x-bsky-topics";
pub fn respond(request: *Request, status: http.Status, body: []const u8, headers: []const http.Header) !void {
const res = response();
if (wantsConnectionClose(headers)) request.conn.handover = .close;
try setHeaders(res, headers);
res.setStatus(status);
res.body = try ownedBody(res.arena, body);
}
pub fn respondNowClose(request: *Request, status: http.Status, body: []const u8, headers: []const http.Header) !void {
const res = response();
var out: std.Io.Writer.Allocating = .init(res.arena);
defer out.deinit();
// Include headers already attached by authentication handlers (notably
// Set-Cookie), while preserving this direct write for empty redirects.
try setHeaders(res, headers);
try out.writer.print("HTTP/1.1 {d} \r\n", .{@backingInt(status)});
for (res.headers.keys[0..res.headers.len], res.headers.values[0..res.headers.len]) |name, value| {
try out.writer.print("{s}: {s}\r\n", .{ name, value });
}
try out.writer.print("content-length: {d}\r\n\r\n", .{body.len});
request.conn.handover = .close;
try request.conn.writeAll(out.written());
if (body.len > 0) try request.conn.writeAll(body);
res.written = true;
}
/// Sends a body too large to copy into the response (a whole repo CAR)
/// straight to the socket: `writeBody` runs once to count its bytes for
/// Content-Length and once to write them through a fixed 64 KiB buffer. The
/// connection closes after; a failure mid-body just ends it.
pub fn respondStreamNowClose(
request: *Request,
status: http.Status,
headers: []const http.Header,
context: anytype,
comptime writeBody: fn (@TypeOf(context), *std.Io.Writer) anyerror!void,
) !void {
var count_buf: [4096]u8 = undefined;
var counter = std.Io.Writer.Discarding.init(&count_buf);
try writeBody(context, &counter.writer);
return respondSizedStreamNowClose(request, status, headers, counter.fullCount(), context, writeBody);
}
/// `respondStreamNowClose` for a body whose length is already known (a file).
pub fn respondSizedStreamNowClose(
request: *Request,
status: http.Status,
headers: []const http.Header,
content_length: u64,
context: anytype,
comptime writeBody: fn (@TypeOf(context), *std.Io.Writer) anyerror!void,
) !void {
const res = response();
var head: std.Io.Writer.Allocating = .init(res.arena);
defer head.deinit();
try setHeaders(res, headers);
try head.writer.print("HTTP/1.1 {d} \r\n", .{@backingInt(status)});
for (res.headers.keys[0..res.headers.len], res.headers.values[0..res.headers.len]) |name, value| {
try head.writer.print("{s}: {s}\r\n", .{ name, value });
}
try head.writer.print("content-length: {d}\r\n\r\n", .{content_length});
request.conn.handover = .close;
// From here the response is ours: if writing fails the connection just
// closes, rather than httpz appending an error response to a partial body.
res.written = true;
try request.conn.writeAll(head.written());
// HEAD gets the real Content-Length and no body.
if (request.method == .HEAD) return;
var buf: [64 * 1024]u8 = undefined;
var sink: ConnWriter = .{ .conn = request.conn, .writer = .{ .vtable = &.{ .drain = ConnWriter.drain }, .buffer = &buf } };
try writeBody(context, &sink.writer);
try sink.writer.flush();
}
const ConnWriter = struct {
conn: @FieldType(Request, "conn"),
writer: std.Io.Writer,
fn drain(w: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize {
const self: *ConnWriter = @alignCast(@fieldParentPtr("writer", w));
self.conn.writeAll(w.buffered()) catch return error.WriteFailed;
w.end = 0;
var written: usize = 0;
for (data[0 .. data.len - 1]) |bytes| {
self.conn.writeAll(bytes) catch return error.WriteFailed;
written += bytes.len;
}
const pattern = data[data.len - 1];
for (0..splat) |_| {
self.conn.writeAll(pattern) catch return error.WriteFailed;
written += pattern.len;
}
return written;
}
};
fn setHeaders(res: *Response, headers: []const http.Header) !void {
for (headers) |header| try addHeader(res, header.name, header.value);
}
fn wantsConnectionClose(headers: []const http.Header) bool {
for (headers) |header| {
if (std.ascii.eqlIgnoreCase(header.name, "connection") and
std.ascii.eqlIgnoreCase(header.value, "close"))
{
return true;
}
}
return false;
}
pub fn addResponseHeader(name: []const u8, value: []const u8) !void {
try addHeader(response(), name, value);
}
/// Add a header that may repeat, such as `set-cookie`, keeping earlier values.
pub fn appendResponseHeader(name: []const u8, value: []const u8) !void {
try response().headerOpts(name, value, .{ .dupe_name = true, .dupe_value = true });
}
fn addHeader(res: *Response, name: []const u8, value: []const u8) !void {
for (res.headers.keys[0..res.headers.len], 0..) |existing, i| {
if (std.ascii.eqlIgnoreCase(existing, name)) {
res.headers.keys[i] = try res.arena.dupe(u8, name);
res.headers.values[i] = try res.arena.dupe(u8, value);
return;
}
}
try res.headerOpts(name, value, .{ .dupe_name = true, .dupe_value = true });
}
test "an empty response body keeps a pointer writev accepts" {
const empty_body = try ownedBody(std.testing.allocator, "");
try std.testing.expectEqual(@as(usize, 0), empty_body.len);
try std.testing.expect(@intFromPtr(empty_body.ptr) != std.math.maxInt(usize));
const copied = try ownedBody(std.testing.allocator, "x");
defer std.testing.allocator.free(copied);
try std.testing.expectEqualStrings("x", copied);
}
test "HTML pages allow only their own inline scripts and styles" {
const code = comptime inlineCode("<style>p{}</style><p>x</p><script>alert(1)</script><script></script>");
try std.testing.expectEqual(2, code.scripts.len);
try std.testing.expectEqual(1, code.styles.len);
const csp = htmlSecurityHeaders(code)[0].value;
try std.testing.expect(std.mem.indexOf(u8, csp, "script-src 'sha256-bhHHL3z2vDgxUt0W3dWQOrprscmda2Y5pLsLg4GF+pI=' 'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=';") != null);
try std.testing.expect(std.mem.indexOf(u8, csp, "unsafe") == null);
try std.testing.expect(std.mem.indexOf(u8, htmlSecurityHeaders(.{})[0].value, "script-src 'none'; style-src 'none';") != null);
const dynamic = try htmlSecurityHeadersWithStyle(std.testing.allocator, .{ .styles = code.styles }, "");
defer std.testing.allocator.free(dynamic[0].value);
try std.testing.expect(std.mem.indexOf(u8, dynamic[0].value, "style-src 'sha256-" ++ comptime hashOf("p{}") ++ "' 'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU='; img-src") != null);
}
test "decodes query params" {
var buf: [64]u8 = undefined;
try std.testing.expectEqualStrings("did:plc:service", queryParam("/xrpc/foo?aud=did%3Aplc%3Aservice", "aud", &buf).?);
}
test "a DPoP-bound token sent without a nonce gets the reference's use_dpop_nonce challenge" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
try store.init(std.Options.debug_io, ":memory:");
defer store.close();
const account = try store.createAccount(a, "nonce.test", "nonce@test.com", "password", "did:plc:noncechallenge", true);
const token = try auth.createDpopSessionJwt(a, "access", account, "test-jkt");
try store.putOAuthToken(account.did, "https://client.example/client-metadata.json", "atproto transition:generic", token, "refresh", now() + 600, now() + 6000, "test-jkt", "password");
var ht = httpz.testing.init(.{});
defer ht.deinit();
bindResponse(ht.res);
defer unbindResponse();
ht.header("authorization", try std.fmt.allocPrint(a, "DPoP {s}", .{token}));
// No DPoP proof at all, as atproto-oauth's DpopRetry sends first: a nonce challenge, not InvalidToken,
// and uploadBlob must not mistake it for a service-auth token.
try std.testing.expectError(error.UseDpopNonce, requireBearerAccess(ht.req, a));
try std.testing.expectError(error.HandledResponse, bearerErrorResponse(ht.req, error.UseDpopNonce));
try ht.expectStatus(401);
try ht.expectHeader("www-authenticate", "DPoP error=\"use_dpop_nonce\", error_description=\"Resource server requires nonce in DPoP proof\"");
try std.testing.expect(std.mem.startsWith(u8, ht.res.body, "{\"error\":\"use_dpop_nonce\","));
}
const OAuthFailureCase = struct {
authorization: []const u8,
dpop_proof: ?[]const u8 = null,
body_error: []const u8,
challenge: ?[]const u8,
};
fn expectBearerFailure(a: std.mem.Allocator, case: OAuthFailureCase) !void {
var ht = httpz.testing.init(.{});
defer ht.deinit();
bindResponse(ht.res);
defer unbindResponse();
ht.header("authorization", case.authorization);
if (case.dpop_proof) |proof| ht.header("dpop", proof);
const err = if (requireBearerAccess(ht.req, a)) |_| return error.TestUnexpectedResult else |err| err;
try std.testing.expectError(error.HandledResponse, bearerErrorResponse(ht.req, err));
try ht.expectStatus(401);
try ht.expectHeader("www-authenticate", case.challenge);
const prefix = try std.fmt.allocPrint(a, "{{\"error\":\"{s}\",", .{case.body_error});
if (!std.mem.startsWith(u8, ht.res.body, prefix)) {
std.debug.print("{s}: body {s}\n", .{ case.authorization[0..@min(case.authorization.len, 24)], ht.res.body });
return error.TestUnexpectedResult;
}
}
test "every DPoP-scheme token failure answers with the reference's OAuth error code" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
try store.init(std.Options.debug_io, ":memory:");
defer store.close();
const account = try store.createAccount(a, "oauthfail.test", "oauthfail@test.com", "password", "did:plc:oauthfailures", true);
const client = "https://client.example/client-metadata.json";
const bound = try auth.createDpopSessionJwt(a, "access", account, "test-jkt");
try store.putOAuthToken(account.did, client, "atproto", bound, "refresh-bound", now() + 600, now() + 6000, "test-jkt", "password");
const revoked = try auth.createDpopSessionJwt(a, "access", account, "test-jkt");
try store.putOAuthToken(account.did, client, "atproto", revoked, "refresh-revoked", now() + 600, now() + 6000, "test-jkt", "password");
try store.revokeOAuthToken(revoked);
const other_key = try auth.createDpopSessionJwt(a, "access", account, "other-jkt");
try store.putOAuthToken(account.did, client, "atproto", other_key, "refresh-other", now() + 600, now() + 6000, "test-jkt", "password");
const unbound = try auth.createSessionJwt(a, "access", account);
try store.putOAuthToken(account.did, client, "atproto", unbound, "refresh-unbound", now() + 600, now() + 6000, null, "password");
const no_row = try auth.createDpopSessionJwt(a, "access", account, "test-jkt");
const invalid_token = "DPoP error=\"invalid_token\", error_description=\"Invalid token\"";
for ([_]OAuthFailureCase{
.{ .authorization = "DPoP not-a-jwt", .body_error = "invalid_token", .challenge = "DPoP error=\"invalid_token\", error_description=\"Token is invalid\"" },
.{ .authorization = try std.fmt.allocPrint(a, "DPoP {s}", .{revoked}), .body_error = "invalid_token", .challenge = "DPoP error=\"invalid_token\", error_description=\"Token has been revoked\"" },
.{ .authorization = try std.fmt.allocPrint(a, "DPoP {s}", .{other_key}), .body_error = "invalid_token", .challenge = invalid_token },
.{ .authorization = try std.fmt.allocPrint(a, "DPoP {s}", .{unbound}), .body_error = "invalid_token", .challenge = invalid_token },
.{ .authorization = try std.fmt.allocPrint(a, "DPoP {s}", .{no_row}), .body_error = "invalid_token", .challenge = invalid_token },
.{ .authorization = try std.fmt.allocPrint(a, "DPoP {s}", .{bound}), .dpop_proof = "not.a.proof", .body_error = "invalid_dpop_proof", .challenge = "DPoP error=\"invalid_dpop_proof\", error_description=\"Invalid DPoP proof\"" },
// The Bearer scheme also carries password sessions and service auth, which keep their XRPC names.
.{ .authorization = "Bearer not-a-jwt", .body_error = "InvalidToken", .challenge = "Bearer error=\"invalid_token\", error_description=\"Token is invalid\"" },
}) |case| try expectBearerFailure(a, case);
}
test "formats OAuth invalid token challenges" {
var buf: [160]u8 = undefined;
try std.testing.expectEqualStrings(
"Bearer error=\"invalid_token\", error_description=\"Token has expired\"",
try formatInvalidTokenChallenge(&buf, .bearer, "Token has expired"),
);
try std.testing.expectEqualStrings(
"DPoP error=\"invalid_token\", error_description=\"Token has been revoked\"",
try formatInvalidTokenChallenge(&buf, .dpop, "Token has been revoked"),
);
}
test "collects every value of a repeated query parameter" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const values = try queryParamValues(arena.allocator(), "/x?did=a&cids=b%3Ac&other=1&cids=d", "cids");
try std.testing.expectEqual(@as(usize, 2), values.len);
try std.testing.expectEqualStrings("b:c", values[0]);
try std.testing.expectEqualStrings("d", values[1]);
try std.testing.expectEqual(@as(usize, 0), (try queryParamValues(arena.allocator(), "/x", "cids")).len);
}
test "apps are named by the host of their client_id" {
try std.testing.expectEqualStrings("bsky.app", appLabel("https://bsky.app/oauth-client-metadata.json"));
try std.testing.expectEqualStrings("stream.place", appLabel("https://stream.place/oauth/downstream/client-metadata.json"));
try std.testing.expectEqualStrings("an app on a device", appLabel("http://localhost?redirect_uri=x"));
try std.testing.expectEqualStrings("did:web:example.com", appLabel("did:web:example.com"));
}
test "legacy sessions are named by Origin host, then User-Agent product" {
try std.testing.expectEqualStrings("bsky.app", clientHost("https://bsky.app").?);
try std.testing.expectEqualStrings("deck.blue", clientHost("https://deck.blue/").?);
try std.testing.expectEqualStrings("an app on a device", clientHost("http://localhost:19006").?);
try std.testing.expect(clientHost("null") == null);
try std.testing.expectEqualStrings("Bluesky", productToken("Bluesky/1.98.0 CFNetwork/1568 Darwin/24.0.0").?);
try std.testing.expectEqualStrings("okhttp", productToken("okhttp/4.12.0").?);
try std.testing.expect(productToken("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)") == null);
try std.testing.expect(productToken("<script>") == null);
}