Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207import Foundationimport HTTPTypesimport Hummingbirdimport HummingbirdAuthimport Logging
/// Resolves the real client address behind the proxies and stores it on the/// context for the request log, the rate limiter and the Podcast Index/// budget. It runs before the request log for that reason: a middleware only/// sees what the ones before it put on the context.struct ClientAddressMiddleware: RouterMiddleware { typealias Context = AppRequestContext
let resolver: ClientAddressResolver
func handle(_ request: Request, context: Context, next: (Request, Context) async throws -> Response) async throws -> Response { var context = context context.clientAddress = resolver.resolve(peer: context.peerAddress, headers: request.headers) return try await next(request, context) }}
/// Reads the bearer token or `X-API-Key` header and attaches the principal.////// With no token the request continues without an identity when auth is/// required (the `/xrpc` group then answers 401), or as the anonymous read/// principal when it is not. A token that matches nothing is rejected here.struct TokenAuthenticator<Context: AuthRequestContext<Principal>>: AuthenticatorMiddleware { let authorizer: TokenAuthorizer let authRequired: Bool
func authenticate(request: Request, context: Context) async throws -> Principal? { guard let token = Self.token(from: request) else { return authRequired ? nil : .anonymous } guard let principal = authorizer.authenticate(token: token) else { throw AppError(.unauthorized, code: "InvalidToken", message: "invalid authentication token") } return principal }
static func token(from request: Request) -> String? { if let bearer = request.headers.bearer?.token.trimmingCharacters(in: .whitespaces), !bearer.isEmpty { return bearer } if let key = request.headers[HeaderNames.apiKey]?.trimmingCharacters(in: .whitespaces), !key.isEmpty { return key } return nil }}
/// Requires a scope on routes outside the `/xrpc` group, such as `/metrics`.struct RequireScopeMiddleware: RouterMiddleware { typealias Context = AppRequestContext
let scope: Principal.Scope
func handle(_ request: Request, context: Context, next: (Request, Context) async throws -> Response) async throws -> Response { guard let principal = context.identity else { throw AppError.authRequired() } guard principal.hasScope(scope) else { throw AppError.forbidden() } return try await next(request, context) }}
/// For user-scoped routes: the `did` query parameter must be the caller's own/// DID unless the caller is an admin or a service token.struct RequireQueryDIDMiddleware: RouterMiddleware { typealias Context = AuthenticatedRequestContext
let parameter: String
func handle(_ request: Request, context: Context, next: (Request, Context) async throws -> Response) async throws -> Response { if context.principal.isAdmin || context.principal.isService { return try await next(request, context) } guard let requested = QueryValues.trimmed(request.uri.queryParameters[Substring(parameter)].map(String.init)) else { throw AppError.invalidRequest("\(parameter) is required") } guard requested == context.principal.subject else { throw AppError.forbidden("token subject does not match requested DID") } return try await next(request, context) }}
/// Answers 429 when a caller is over its limit. Read callers share the app/// token, so they are keyed by client address; admin and service callers by/// subject. A request with neither an identity nor an address is refused,/// because that means the proxy configuration is wrong.struct RateLimitMiddleware: RouterMiddleware { typealias Context = AppRequestContext
let limiter: RateLimiter static let exemptPaths: Set<String> = ["/_health", "/_live", "/metrics"]
func handle(_ request: Request, context: Context, next: (Request, Context) async throws -> Response) async throws -> Response { guard limiter.enabled, request.method != .options, !Self.exemptPaths.contains(request.uri.path) else { return try await next(request, context) } guard let key = Self.key(for: context) else { AppMetrics.rateLimitRejection(kind: "unknown") throw AppError.invalidRequest("could not identify caller; reverse proxy may be misconfigured") } guard await limiter.allow(key) else { AppMetrics.rateLimitRejection(kind: key.metricsKind) throw AppError(.tooManyRequests, code: "RateLimited", message: "rate limit exceeded", headers: [.retryAfter: "1"]) } return try await next(request, context) }
static func key(for context: AppRequestContext) -> RateLimiter.Key? { if let principal = context.identity, principal.isAdmin || principal.isService, !principal.isService || context.clientAddress == nil { return .subject(principal.subject) } if let address = context.clientAddress { return .address(address.description) } if let principal = context.identity { return .subject(principal.subject) } return nil }}
/// An origin allowlist. Wildcards are refused at configuration time, so every/// allowed origin is echoed back explicitly.struct CORSAllowlistMiddleware<Context: RequestContext>: RouterMiddleware { let allowedOrigins: Set<String>
init(allowedOrigins: [String]) { self.allowedOrigins = Set(allowedOrigins) }
func handle(_ request: Request, context: Context, next: (Request, Context) async throws -> Response) async throws -> Response { guard let origin = request.headers[.origin], allowedOrigins.contains(origin) else { if request.method == .options { return Response(status: .noContent) } return try await next(request, context) } var headers: HTTPFields = [ .accessControlAllowOrigin: origin, .vary: "Origin", .accessControlAllowMethods: "GET, POST, OPTIONS", .accessControlAllowHeaders: "Origin, Content-Type, Accept, Authorization, X-API-Key", ] if request.method == .options { headers[.accessControlMaxAge] = "600" return Response(status: .noContent, headers: headers) } var response = try await next(request, context) for field in headers { response.headers[field.name] = field.value } return response }}
/// Logs one line per request: method, path, status and client address. The/// query string is left out on purpose, because tokens can travel in it.////// An error no handler turned into a response is answered with a bare 500,/// so this is the only place that can say what it was.struct RequestLogMiddleware: RouterMiddleware { typealias Context = AppRequestContext
let logger: Logger
func handle(_ request: Request, context: Context, next: (Request, Context) async throws -> Response) async throws -> Response { let start = ContinuousClock.now do { let response = try await next(request, context) log(request, context: context, status: response.status.code, start: start) return response } catch let error as HTTPResponseError { log(request, context: context, status: error.status.code, start: start) throw error } catch { log(request, context: context, status: 500, start: start, failure: error) throw error } }
private func log(_ request: Request, context: Context, status: Int, start: ContinuousClock.Instant, failure: (any Error)? = nil) { let elapsed = start.duration(to: .now) var metadata: Logger.Metadata = [ "method": "\(request.method)", "path": "\(request.uri.path)", "status": "\(status)", "ip": "\(context.clientAddress?.description ?? context.peerAddress?.description ?? "-")", "ms": "\(elapsed.components.seconds * 1000 + elapsed.components.attoseconds / 1_000_000_000_000_000)", ] guard let failure else { logger.info("request", metadata: metadata) return } metadata["error"] = "\(ErrorSummary.describe(failure))" logger.error("request failed", metadata: metadata) }}
enum HeaderNames { static let xForwardedFor: HTTPField.Name = HTTPField.Name("X-Forwarded-For") ?? .via static let apiKey: HTTPField.Name = HTTPField.Name("X-API-Key") ?? .authorization}