const std = @import("std"); const config = @import("../core/config.zig"); const log = @import("../core/log.zig"); const http_api = @import("../http/api.zig"); const outbound = @import("../internal/outbound.zig"); const scopes = @import("../internal/scopes.zig"); const service_auth = @import("../internal/service_auth.zig"); const store = @import("../storage/store.zig"); const zat = @import("zat"); const http = std.http; const proxy_transport_allocator = std.heap.smp_allocator; // One transport for every handler thread, so its pool holds at most one set // of idle upstream connections and each request sweeps the ones the AppView // has closed. var proxy_transport_mutex: std.Io.Mutex = .init; var proxy_transport_state: ?zat.HttpTransport = null; pub fn xrpcProxy(request: *http_api.Request) !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); if (request.method != .GET and request.method != .POST) { return http_api.xrpcError(request, .bad_request, "InvalidRequest", "XRPC proxy supports GET and POST"); } const method = xrpcMethod(request.url.raw) orelse { return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid XRPC path"); }; if (isProtectedMethod(method)) { return http_api.xrpcError(request, .bad_request, "InvalidToken", "Cannot proxy protected method"); } const proxy_to = http_api.headerValue(request, "atproto-proxy") orelse default: { if (!hasDefaultService(method)) { return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing atproto-proxy header"); } break :default try std.fmt.allocPrint(allocator, "{s}#{s}", .{ config.proxyServiceDid(), config.proxyServiceId() }); }; log.debug("xrpc proxy start method={s} target={s} proxy_to={s}\n", .{ method, request.url.raw, proxy_to }); const service = resolveProxyService(allocator, proxy_to) catch |err| switch (err) { error.InvalidProxyHeader => { log.err("xrpc proxy invalid header method={s} proxy_to={s}\n", .{ method, proxy_to }); return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid atproto-proxy header"); }, error.UnsupportedDidMethod => { log.err("xrpc proxy unsupported did method={s} proxy_to={s}\n", .{ method, proxy_to }); return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Unsupported proxy DID method"); }, error.ServiceNotFound => { log.err("xrpc proxy service not found method={s} proxy_to={s}\n", .{ method, proxy_to }); return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Proxy service not found"); }, error.DidResolutionFailed => { log.err("xrpc proxy did resolution failed method={s} proxy_to={s}\n", .{ method, proxy_to }); return http_api.xrpcError(request, .bad_gateway, "UpstreamFailure", "Could not resolve proxy DID"); }, else => |e| { log.err("xrpc proxy resolve failed method={s} proxy_to={s} err={s}\n", .{ method, proxy_to, @errorName(e) }); return http_api.xrpcError(request, .bad_gateway, "UpstreamFailure", "Could not resolve proxy service"); }, }; // A taken down account can still report, which is how it appeals. const bearer = if (std.mem.eql(u8, method, "com.atproto.moderation.createReport")) http_api.requireBearerAccessOrTakendown(request, allocator) else http_api.requireBearerAccess(request, allocator); const auth_ctx = bearer catch |err| { switch (err) { error.AuthRequired => log.debug("xrpc proxy auth missing method={s} proxy_to={s}\n", .{ method, proxy_to }), error.InvalidToken, error.BadTokenScope => log.err("xrpc proxy auth invalid method={s} proxy_to={s}\n", .{ method, proxy_to }), error.ExpiredToken => log.debug("xrpc proxy auth expired method={s} proxy_to={s}\n", .{ method, proxy_to }), error.UseDpopNonce => {}, } return http_api.bearerErrorResponse(request, err); }; const scope_aud = try std.fmt.allocPrint(allocator, "{s}#{s}", .{ service.did, service.service_id }); if (!scopes.rpcAllows(auth_ctx.oauth_scope, scope_aud, method)) { log.debug("xrpc proxy insufficient_scope method={s} account={s} aud={s}\n", .{ method, auth_ctx.account.did, scope_aud }); return http_api.xrpcError(request, .forbidden, "InsufficientScope", "Insufficient scope"); } const account = auth_ctx.account; log.debug("xrpc proxy auth ok method={s} account={s} service_did={s} endpoint={s}\n", .{ method, account.did, service.did, service.endpoint }); const upstream_url = try std.fmt.allocPrint(allocator, "{s}{s}", .{ service.endpoint, request.url.raw }); const extra_headers = try forwardedHeaders(allocator, request); const payload = if (request.method == .POST) try http_api.readBodyAlloc(request, allocator, 1024 * 1024) else null; var keypair = store.signingKeypair(account.did) catch { log.err("xrpc proxy signing key missing method={s} account={s}\n", .{ method, account.did }); return http_api.xrpcError(request, .bad_gateway, "UpstreamFailure", "Could not load account signing key"); }; const service_token = try zat.service_auth.create(allocator, store.currentIo(), &keypair, .{ .iss = account.did, .sub = account.did, .aud = service.did, .lxm = method }); const authorization = try std.fmt.allocPrint(allocator, "Bearer {s}", .{service_token}); log.debug("xrpc proxy fetch method={s} upstream={s} extra_headers={d}\n", .{ method, upstream_url, extra_headers.len }); const fetch_options: zat.HttpTransport.FetchOptions = .{ .url = upstream_url, .method = http_api.toStdMethod(request.method), .payload = payload, .content_type = if (payload != null) "application/json" else null, .authorization = authorization, .accept = "application/json", .extra_headers = extra_headers, .max_response_size = 10 * 1024 * 1024, .capture_headers = &forwarded_response_headers, }; // A resolved service endpoint comes from a DID document the caller chose. const guarded_options = if (service.configured) fetch_options else outbound.guard(allocator, store.currentIo(), fetch_options) catch |err| { log.err("xrpc proxy refused endpoint method={s} upstream={s} err={s}\n", .{ method, upstream_url, @errorName(err) }); return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Proxied service endpoint is not a public HTTPS address"); }; var result = proxyFetch(guarded_options) catch |err| { log.err("xrpc proxy fetch failed method={s} upstream={s} err={s}\n", .{ method, upstream_url, @errorName(err) }); return http_api.xrpcError(request, .bad_gateway, "UpstreamFailure", "Failed to reach proxied service"); }; defer result.deinit(proxy_transport_allocator); log.debug("xrpc proxy upstream method={s} status={d} body_len={d}\n", .{ method, @backingInt(result.status), result.body.len }); return respondUpstream(request, result); } /// Response headers passed back from the proxied service: the reference PDS's /// content headers and `RES_HEADERS_TO_FORWARD` (pds/src/pipethrough.ts), /// plus `vary` and `etag`, which Tranquil also forwards so a client's /// conditional request can be answered `304` by the service. const forwarded_response_headers = [_][]const u8{ "content-type", "content-language", "atproto-repo-rev", "atproto-content-labelers", "retry-after", "vary", "etag", }; /// A `304` and an empty body go back bodyless; anything else keeps the /// service's content type, falling back to JSON when it sent none. fn respondUpstream(request: *http_api.Request, result: zat.HttpTransport.FetchResult) !void { if (result.status == .not_modified or result.body.len == 0) { try http_api.empty(request, result.status); } else { try http_api.json(request, result.status, result.body); } for (result.headers.entries) |header| try http_api.addResponseHeader(header.name, header.value); } const max_forwarded_headers = 32; /// Request headers a proxied service may read, as the reference PDS forwards /// them: content negotiation, labeler choice, and every `x-atproto-*` header, /// plus `if-none-match` so the service can answer a conditional request, as /// Tranquil does. The caller's authorization and DPoP proof stay with this PDS. fn forwardedHeaders(allocator: std.mem.Allocator, request: *http_api.Request) ![]const std.http.Header { var headers: std.ArrayList(std.http.Header) = .empty; for (request.headers.keys[0..request.headers.len], request.headers.values[0..request.headers.len]) |name, value| { const forwarded = std.ascii.eqlIgnoreCase(name, "accept-language") or std.ascii.eqlIgnoreCase(name, "atproto-accept-labelers") or std.ascii.eqlIgnoreCase(name, "x-bsky-topics") or std.ascii.eqlIgnoreCase(name, "if-none-match") or std.ascii.startsWithIgnoreCase(name, "x-atproto-"); if (!forwarded) continue; if (headers.items.len == max_forwarded_headers) break; try headers.append(allocator, .{ .name = try std.ascii.allocLowerString(allocator, name), .value = try allocator.dupe(u8, value) }); } return headers.toOwnedSlice(allocator); } fn proxyFetch(options: zat.HttpTransport.FetchOptions) !zat.HttpTransport.FetchResult { return proxyTransport().fetch(options) catch |err| switch (err) { error.HttpConnectionClosing => { var transport = zat.HttpTransport.init(store.currentIo(), proxy_transport_allocator); transport.keep_alive = false; defer transport.deinit(); return transport.fetch(options); }, else => return err, }; } fn proxyTransport() *zat.HttpTransport { const io = store.currentIo(); proxy_transport_mutex.lockUncancelable(io); defer proxy_transport_mutex.unlock(io); if (proxy_transport_state == null) { proxy_transport_state = zat.HttpTransport.init(io, proxy_transport_allocator); } return &proxy_transport_state.?; } /// `locally_routed` is whether this PDS implements the requested path itself. pub fn shouldProxy(request: *const http_api.Request, locally_routed: bool) bool { if (request.method != .GET and request.method != .POST) return false; const method = xrpcMethod(request.url.raw) orelse return false; return proxies(method, http_api.headerValue(request, "atproto-proxy") != null, locally_routed); } fn proxies(method: []const u8, has_proxy_header: bool, locally_routed: bool) bool { if (isProtectedMethod(method)) return false; if (has_proxy_header) return true; return !locally_routed and hasDefaultService(method); } /// Methods that go to the configured appview when the client names no service. fn hasDefaultService(method: []const u8) bool { return std.ascii.startsWithIgnoreCase(method, "app.bsky."); } const ProxyService = struct { did: []const u8, service_id: []const u8, endpoint: []const u8, /// Configured by the operator rather than read from a DID document. configured: bool = false, }; fn resolveProxyService(allocator: std.mem.Allocator, proxy_to: []const u8) !ProxyService { const hash = std.mem.indexOfScalar(u8, proxy_to, '#') orelse return error.InvalidProxyHeader; if (hash == 0 or hash + 1 >= proxy_to.len) return error.InvalidProxyHeader; const did = proxy_to[0..hash]; const service_id = proxy_to[hash + 1 ..]; if (try configuredProxyService(allocator, did, service_id)) |service| return service; const parsed_did = zat.Did.parse(did) orelse return error.InvalidProxyHeader; var resolver = service_auth.didResolver(allocator); defer resolver.deinit(); var did_doc = try resolver.resolve(parsed_did); defer did_doc.deinit(); const endpoint = did_doc.serviceEndpoint(proxy_to) orelse return error.ServiceNotFound; return .{ .did = try allocator.dupe(u8, did), .service_id = try allocator.dupe(u8, service_id), .endpoint = try allocator.dupe(u8, std.mem.trim(u8, endpoint, "/")), }; } fn configuredProxyService(allocator: std.mem.Allocator, did: []const u8, service_id: []const u8) !?ProxyService { if (!std.mem.eql(u8, service_id, config.proxyServiceId())) return null; if (!std.mem.eql(u8, did, config.proxyServiceDid())) return null; return .{ .did = try allocator.dupe(u8, did), .service_id = try allocator.dupe(u8, service_id), .endpoint = try allocator.dupe(u8, config.proxyServiceUrl()), .configured = true, }; } fn xrpcMethod(target: []const u8) ?[]const u8 { if (!std.mem.startsWith(u8, target, "/xrpc/")) return null; const start = "/xrpc/".len; const end = std.mem.indexOfScalarPos(u8, target, start, '?') orelse target.len; return target[start..end]; } fn isProtectedMethod(method: []const u8) bool { const protected = [_][]const u8{ "app.bsky.actor.getPreferences", "app.bsky.actor.putPreferences", "com.atproto.admin.deleteAccount", "com.atproto.admin.disableAccountInvites", "com.atproto.admin.disableInviteCodes", "com.atproto.admin.enableAccountInvites", "com.atproto.admin.getAccountInfo", "com.atproto.admin.getAccountInfos", "com.atproto.admin.getInviteCodes", "com.atproto.admin.getSubjectStatus", "com.atproto.admin.searchAccounts", "com.atproto.admin.sendEmail", "com.atproto.admin.updateAccountEmail", "com.atproto.admin.updateAccountHandle", "com.atproto.admin.updateAccountPassword", "com.atproto.admin.updateSubjectStatus", "com.atproto.identity.getRecommendedDidCredentials", "com.atproto.identity.requestPlcOperationSignature", "com.atproto.identity.signPlcOperation", "com.atproto.identity.submitPlcOperation", "com.atproto.identity.updateHandle", "com.atproto.repo.applyWrites", "com.atproto.repo.createRecord", "com.atproto.repo.deleteRecord", "com.atproto.repo.importRepo", "com.atproto.repo.putRecord", "com.atproto.repo.uploadBlob", "com.atproto.server.activateAccount", "com.atproto.server.checkAccountStatus", "com.atproto.server.confirmEmail", "com.atproto.server.confirmSignup", "com.atproto.server.createAccount", "com.atproto.server.createAppPassword", "com.atproto.server.createInviteCode", "com.atproto.server.createInviteCodes", "com.atproto.server.createSession", "com.atproto.server.createTotpSecret", "com.atproto.server.deactivateAccount", "com.atproto.server.deleteAccount", "com.atproto.server.deletePasskey", "com.atproto.server.deleteSession", "com.atproto.server.describeServer", "com.atproto.server.disableTotp", "com.atproto.server.enableTotp", "com.atproto.server.finishPasskeyRegistration", "com.atproto.server.getAccountInviteCodes", "com.atproto.server.getServiceAuth", "com.atproto.server.getSession", "com.atproto.server.getTotpStatus", "com.atproto.server.listAppPasswords", "com.atproto.server.listPasskeys", "com.atproto.server.refreshSession", "com.atproto.server.regenerateBackupCodes", "com.atproto.server.requestAccountDelete", "com.atproto.server.requestEmailConfirmation", "com.atproto.server.requestEmailUpdate", "com.atproto.server.requestPasswordReset", "com.atproto.server.resendMigrationVerification", "com.atproto.server.resendVerification", "com.atproto.server.reserveSigningKey", "com.atproto.server.resetPassword", "com.atproto.server.revokeAppPassword", "com.atproto.server.startPasskeyRegistration", "com.atproto.server.updateEmail", "com.atproto.server.updatePasskey", "com.atproto.server.verifyMigrationEmail", "com.atproto.sync.getBlob", "com.atproto.sync.getBlocks", "com.atproto.sync.getCheckout", "com.atproto.sync.getHead", "com.atproto.sync.getLatestCommit", "com.atproto.sync.getRecord", "com.atproto.sync.getRepo", "com.atproto.sync.getRepoStatus", "com.atproto.sync.listBlobs", "com.atproto.sync.listRepos", "com.atproto.sync.notifyOfUpdate", "com.atproto.sync.requestCrawl", "com.atproto.sync.subscribeRepos", "com.atproto.temp.checkSignupQueue", "com.atproto.temp.dereferenceScope", }; for (protected) |item| { if (std.ascii.eqlIgnoreCase(method, item)) return true; } return false; } test "proxy protected methods are explicit" { try std.testing.expect(isProtectedMethod("com.atproto.repo.applyWrites")); try std.testing.expect(isProtectedMethod("com.atproto.sync.subscribeRepos")); try std.testing.expect(!isProtectedMethod("com.atproto.identity.resolveHandle")); try std.testing.expect(!isProtectedMethod("com.atproto.repo.getRecord")); try std.testing.expect(!isProtectedMethod("com.atproto.repo.listRecords")); } test "app.bsky methods without a proxy header default to the appview" { try std.testing.expect(proxies("app.bsky.feed.getAuthorFeed", false, false)); try std.testing.expect(!proxies("app.bsky.actor.getPreferences", false, true)); try std.testing.expect(!proxies("app.bsky.actor.getPreferences", true, true)); try std.testing.expect(!proxies("com.example.noSuchMethod", false, false)); try std.testing.expect(proxies("com.example.noSuchMethod", true, false)); try std.testing.expect(proxies("com.atproto.repo.getRecord", true, true)); try std.testing.expect(!proxies("com.atproto.repo.getRecord", false, true)); } test "configured proxy service skips did resolution" { const before_did = config.proxyServiceDid(); const before_id = config.proxyServiceId(); const before_url = config.proxyServiceUrl(); defer config.setProxyServiceDid(before_did); defer config.setProxyServiceId(before_id); defer config.setProxyServiceUrl(before_url); config.setProxyServiceDid("did:web:api.bsky.app"); config.setProxyServiceId("bsky_appview"); config.setProxyServiceUrl("https://api.bsky.app"); const service = (try resolveProxyService(std.testing.allocator, "did:web:api.bsky.app#bsky_appview")); defer std.testing.allocator.free(service.did); defer std.testing.allocator.free(service.service_id); defer std.testing.allocator.free(service.endpoint); try std.testing.expectEqualStrings("did:web:api.bsky.app", service.did); try std.testing.expectEqualStrings("bsky_appview", service.service_id); try std.testing.expectEqualStrings("https://api.bsky.app", service.endpoint); }