import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif import JWTKit import Synchronization @testable import CoreATProtocol // MARK: - Scripted network /// What a scripted endpoint answers with. struct StubResponse: Sendable { var status: Int var headers: [String: String] var body: Data init(status: Int, headers: [String: String] = [:], json: String = "{}") { self.status = status self.headers = headers.merging(["Content-Type": "application/json"]) { given, _ in given } self.body = Data(json.utf8) } init(status: Int, headers: [String: String] = [:], text: String) { self.status = status self.headers = headers self.body = Data(text.utf8) } } /// Stands in for the network: answers each URL from a script and keeps every /// request it was sent. actor ScriptedNetwork { /// - Parameter attempt: 1 for the first request to the URL, then 2, … typealias Responder = @Sendable (_ request: URLRequest, _ attempt: Int) async throws -> StubResponse private var responders: [String: Responder] = [:] private(set) var requests: [URLRequest] = [] func on(_ url: String, respond: @escaping Responder) { responders[url] = respond } func requests(to url: String) -> [URLRequest] { requests.filter { $0.url?.absoluteString == url } } nonisolated var transport: OAuthHTTPTransport { { request in try await self.respond(to: request) } } private func respond(to request: URLRequest) async throws -> (Data, HTTPURLResponse) { guard let url = request.url, let responder = responders[url.absoluteString] else { throw URLError(.unsupportedURL) } requests.append(request) let stub = try await responder(request, requests(to: url.absoluteString).count) guard let response = HTTPURLResponse( url: url, statusCode: stub.status, httpVersion: "HTTP/1.1", headerFields: stub.headers ) else { throw URLError(.badServerResponse) } return (stub.body, response) } } // MARK: - Reading requests extension URLRequest { /// The fields of an `application/x-www-form-urlencoded` body, decoded the /// way a server's form parser reads them. var formFields: [String: String] { guard let httpBody, let body = String(data: httpBody, encoding: .utf8) else { return [:] } var fields: [String: String] = [:] for pair in body.split(separator: "&") { let parts = pair.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false) guard let name = parts.first.flatMap(Self.formDecode) else { continue } fields[name] = parts.count > 1 ? Self.formDecode(parts[1]) : "" } return fields } /// The members of a JSON object body that are strings. var jsonFields: [String: String] { guard let httpBody, let object = try? JSONSerialization.jsonObject(with: httpBody) as? [String: Any] else { return [:] } return object.compactMapValues { $0 as? String } } private static func formDecode(_ value: Substring) -> String? { value.replacingOccurrences(of: "+", with: " ").removingPercentEncoding } } // MARK: - Reading DPoP proofs /// The claims of a DPoP proof as a strict server reads them: `iat` must be a /// whole number, the way servers that parse it into an integer require. struct DPoPProofClaims: JWTPayload, Equatable { let htm: String let htu: String let iat: Int let jti: String let nonce: String? let ath: String? func verify(using key: some JWTAlgorithm) throws {} } enum DPoPProofReader { struct Header: Decodable { struct JWK: Decodable { let kty: String let crv: String let x: String let y: String } let typ: String let alg: String let jwk: JWK } enum ReadError: Error { case notAJWT case missingProof } static func header(of proof: String) throws -> Header { try JSONDecoder().decode(Header.self, from: section(0, of: proof)) } /// The payload exactly as it went over the wire. static func payloadJSON(of proof: String) throws -> String { String(decoding: try section(1, of: proof), as: UTF8.self) } /// Checks the proof's signature against the key in its own header, then /// decodes its claims. static func verifiedClaims(of proof: String) async throws -> DPoPProofClaims { let jwk = try header(of: proof).jwk let keys = JWTKeyCollection() await keys.add(ecdsa: try ES256PublicKey(parameters: (x: jwk.x, y: jwk.y))) return try await keys.verify(proof, as: DPoPProofClaims.self) } static func verifiedClaims(of request: URLRequest) async throws -> DPoPProofClaims { guard let proof = request.value(forHTTPHeaderField: "DPoP") else { throw ReadError.missingProof } return try await verifiedClaims(of: proof) } private static func section(_ index: Int, of proof: String) throws -> Data { let parts = proof.split(separator: ".", omittingEmptySubsequences: false) guard parts.count == 3 else { throw ReadError.notAJWT } var base64 = parts[index] .replacingOccurrences(of: "-", with: "+") .replacingOccurrences(of: "_", with: "/") base64 += String(repeating: "=", count: (4 - base64.count % 4) % 4) guard let data = Data(base64Encoded: base64) else { throw ReadError.notAJWT } return data } } // MARK: - Storage and identity /// Keeps what `ATProtoOAuth` stores in memory. actor MemoryAuthStore { private(set) var login: Login? private(set) var privateKey: Data? private(set) var proxyKeyID: String? private(set) var storedLogins: [Login] = [] init(login: Login? = nil, privateKey: Data? = nil, proxyKeyID: String? = nil) { self.login = login self.privateKey = privateKey self.proxyKeyID = proxyKeyID } private func store(_ login: Login) { self.login = login storedLogins.append(login) } private func store(_ privateKey: Data) { self.privateKey = privateKey } private func store(proxyKeyID: String?) { self.proxyKeyID = proxyKeyID } nonisolated var storage: ATProtoAuthStorage { ATProtoAuthStorage( retrieveLogin: { await self.login }, storeLogin: { await self.store($0) }, retrievePrivateKey: { await self.privateKey }, storePrivateKey: { await self.store($0) }, retrieveAuthProxyKeyID: { _ in await self.proxyKeyID }, storeAuthProxyKeyID: { _, keyID in await self.store(proxyKeyID: keyID) }, clearAuthProxyKeyID: { _ in await self.store(proxyKeyID: nil) } ) } } /// Resolves every identifier to one fixed identity. struct FixedIdentityResolver: ATProtoIdentityResolver { var identity = IdentityResolver.ResolvedIdentity( handle: "alice.test", did: "did:plc:alice", pdsEndpoint: "https://pds.test", authorizationServer: "https://pds.test" ) var isValidServer = true func resolve(identifier: String) async throws -> IdentityResolver.ResolvedIdentity { identity } func isAuthorizationServer(_ authorizationServer: String, validFor pdsEndpoint: String) async throws -> Bool { isValidServer } } // MARK: - Time /// A clock tests move by hand. final class ManualClock: Sendable { private let instant = Mutex(ContinuousClock.now) var now: ContinuousClock.Instant { instant.withLock { $0 } } func advance(by duration: Duration) { instant.withLock { $0 = $0.advanced(by: duration) } } } /// Remembers the waits it was asked for instead of waiting. final class RecordedDelays: Sendable { private let delays = Mutex<[Duration]>([]) var all: [Duration] { delays.withLock { $0 } } func record(_ delay: Duration) { delays.withLock { $0.append(delay) } } } // MARK: - Fixtures enum OAuthFixture { static let issuer = "https://pds.test" static let metadataURL = "https://pds.test/.well-known/oauth-authorization-server" static let parEndpoint = "https://pds.test/oauth/par" static let tokenEndpoint = "https://pds.test/oauth/token" static let authorizationEndpoint = "https://pds.test/oauth/authorize" static let clientID = "https://app.test/oauth/client-metadata.json" static let redirectURI = "https://app.test/oauth/callback" static let proxyBaseURL = "https://auth.test/app" static let proxyPAR = "https://auth.test/app/oauth/par" static let proxyToken = "https://auth.test/app/oauth/token" /// A metadata document with only what the flow needs. static let minimalMetadataJSON = """ { "issuer": "\(issuer)", "authorization_endpoint": "\(authorizationEndpoint)", "token_endpoint": "\(tokenEndpoint)", "pushed_authorization_request_endpoint": "\(parEndpoint)" } """ static func metadata() throws -> AuthorizationServerMetadata { try AuthorizationServerMetadata(data: Data(minimalMetadataJSON.utf8)) } static func tokenJSON( access: String = "access-1", refresh: String? = "refresh-1", subject: String = "did:plc:alice", scope: String = "atproto", tokenType: String = "DPoP", expiresIn: String? = "300" ) -> String { var members = [ "\"access_token\": \"\(access)\"", "\"token_type\": \"\(tokenType)\"", "\"scope\": \"\(scope)\"", "\"sub\": \"\(subject)\"", ] if let refresh { members.append("\"refresh_token\": \"\(refresh)\"") } if let expiresIn { members.append("\"expires_in\": \(expiresIn)") } return "{\(members.joined(separator: ", "))}" } }