import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif import JWTKit import Testing @testable import CoreATProtocol @Suite("Authorization server client") struct AuthorizationServerClientTests { private static let parSuccess = StubResponse( status: 201, json: #"{"request_uri": "urn:ietf:params:oauth:request_uri:req-1", "expires_in": 300}"# ) private static func nonceChallenge(_ nonce: String?) -> StubResponse { StubResponse( status: 400, headers: nonce.map { ["DPoP-Nonce": $0] } ?? [:], json: #"{"error": "use_dpop_nonce", "error_description": "Authorization server requires nonce in DPoP proof"}"# ) } private func makeClient( network: ScriptedNetwork, proxied: Bool = false, authMethod: ATProtoClientAuthMethod = .none, proxyKeyID: String? = nil, scope: String = "atproto transition:generic", clockSkew: ClockSkewStore = ClockSkewStore() ) async throws -> AuthorizationServerClient { AuthorizationServerClient( server: try OAuthFixture.metadata(), client: .init( id: OAuthFixture.clientID, redirectURI: OAuthFixture.redirectURI, scope: scope, authMethod: authMethod ), proxy: proxied ? AuthProxy(baseURL: OAuthFixture.proxyBaseURL) : nil, proxyKeyID: proxyKeyID, signer: await DPoPProofSigner( privateKey: ES256PrivateKey(), clockSkew: clockSkew, nonceLifetime: .seconds(60) ), clockSkew: clockSkew, transport: network.transport ) } // MARK: - Straight to the server @Test("A pushed authorization request is a form post with a proof for the PAR endpoint") func directPAR() async throws { let network = ScriptedNetwork() await network.on(OAuthFixture.parEndpoint) { _, _ in Self.parSuccess } let client = try await makeClient(network: network) let pkce = PKCE() let requestURI = try await client.pushAuthorizationRequest(pkce: pkce, state: "state-1", loginHint: "alice.test") #expect(requestURI == "urn:ietf:params:oauth:request_uri:req-1") let request = try #require(await network.requests.first) #expect(request.httpMethod == "POST") #expect(request.value(forHTTPHeaderField: "Content-Type") == "application/x-www-form-urlencoded") #expect(request.formFields == [ "response_type": "code", "client_id": OAuthFixture.clientID, "redirect_uri": OAuthFixture.redirectURI, "scope": "atproto transition:generic", "state": "state-1", "code_challenge": pkce.challenge, "code_challenge_method": "S256", "login_hint": "alice.test", ]) let claims = try await DPoPProofReader.verifiedClaims(of: request) #expect(claims.htm == "POST") #expect(claims.htu == OAuthFixture.parEndpoint) #expect(claims.nonce == nil) #expect(claims.ath == nil) #expect(await !client.usesProxy) } @Test("Scopes with reserved characters reach the server as written") func scopeIsEscaped() async throws { let scope = "atproto rpc:app.bsky.feed.getFeed?aud=did:web:api.bsky.app%23bsky_appview repo:a.b?action=create&action=update" let network = ScriptedNetwork() await network.on(OAuthFixture.parEndpoint) { _, _ in Self.parSuccess } let client = try await makeClient(network: network, scope: scope) _ = try await client.pushAuthorizationRequest(pkce: PKCE(), state: "s", loginHint: nil) let fields = try #require(await network.requests.first).formFields #expect(fields["scope"] == scope) #expect(fields["login_hint"] == nil) } @Test("A nonce challenge is answered once, with the server's nonce") func nonceChallengeIsRetried() async throws { let network = ScriptedNetwork() await network.on(OAuthFixture.parEndpoint) { _, attempt in attempt == 1 ? Self.nonceChallenge("nonce-1") : Self.parSuccess } await network.on(OAuthFixture.tokenEndpoint) { _, _ in StubResponse(status: 200, headers: ["DPoP-Nonce": "nonce-2"], json: OAuthFixture.tokenJSON()) } let client = try await makeClient(network: network) _ = try await client.pushAuthorizationRequest(pkce: PKCE(), state: "s", loginHint: nil) _ = try await client.exchange(code: "code", verifier: "verifier") let par = await network.requests(to: OAuthFixture.parEndpoint) try #require(par.count == 2) let first = try await DPoPProofReader.verifiedClaims(of: par[0]) let second = try await DPoPProofReader.verifiedClaims(of: par[1]) #expect(first.nonce == nil) #expect(second.nonce == "nonce-1") #expect(first.jti != second.jti) // The token request starts out with the nonce the server last gave. let token = await network.requests(to: OAuthFixture.tokenEndpoint) try #require(token.count == 1) #expect(try await DPoPProofReader.verifiedClaims(of: token[0]).nonce == "nonce-1") } @Test("A nonce challenge is recognised from the WWW-Authenticate header too") func nonceChallengeInHeader() async throws { let network = ScriptedNetwork() await network.on(OAuthFixture.tokenEndpoint) { _, attempt in attempt == 1 ? StubResponse( status: 401, headers: [ "DPoP-Nonce": "nonce-h", "WWW-Authenticate": #"DPoP error="use_dpop_nonce", error_description="nonce required""#, ], text: "" ) : StubResponse(status: 200, json: OAuthFixture.tokenJSON()) } let client = try await makeClient(network: network) let tokens = try await client.exchange(code: "code", verifier: "verifier") #expect(tokens.accessToken == "access-1") #expect(await network.requests.count == 2) } @Test("A challenge that supplies no new nonce is not retried") func nonceChallengeWithoutNonce() async throws { let network = ScriptedNetwork() await network.on(OAuthFixture.parEndpoint) { _, _ in Self.nonceChallenge(nil) } let client = try await makeClient(network: network) await #expect { try await client.pushAuthorizationRequest(pkce: PKCE(), state: "s", loginHint: nil) } throws: { error in guard case .authenticationFailed(let detail) = error as? ATProtoOAuthError else { return false } return detail.hasPrefix("Pushed authorization request failed: use_dpop_nonce") } #expect(await network.requests.count == 1) } @Test("A server that keeps asking for a nonce is given up on") func endlessNonceChallenges() async throws { let network = ScriptedNetwork() await network.on(OAuthFixture.tokenEndpoint) { _, attempt in Self.nonceChallenge("nonce-\(attempt)") } let client = try await makeClient(network: network) await #expect { try await client.refresh(refreshToken: "refresh") } throws: { error in guard case .tokenRequestFailed(let detail) = error as? ATProtoOAuthError else { return false } return detail.hasPrefix("use_dpop_nonce") } #expect(await network.requests.count == 3) } @Test("A code exchange is a form post, and its tokens are decoded") func directExchange() async throws { let network = ScriptedNetwork() await network.on(OAuthFixture.tokenEndpoint) { _, _ in StubResponse(status: 200, json: OAuthFixture.tokenJSON(scope: "atproto transition:generic")) } let client = try await makeClient(network: network) let tokens = try await client.exchange(code: "the code", verifier: "the-verifier") #expect(tokens == OAuthTokenResponse( accessToken: "access-1", refreshToken: "refresh-1", subject: "did:plc:alice", scope: "atproto transition:generic", tokenType: "DPoP", expiresIn: 300 )) let request = try #require(await network.requests.first) #expect(request.formFields == [ "grant_type": "authorization_code", "code": "the code", "code_verifier": "the-verifier", "redirect_uri": OAuthFixture.redirectURI, "client_id": OAuthFixture.clientID, ]) #expect(try await DPoPProofReader.verifiedClaims(of: request).htu == OAuthFixture.tokenEndpoint) } @Test("A refresh sends only the grant, the token and the client") func directRefresh() async throws { let network = ScriptedNetwork() await network.on(OAuthFixture.tokenEndpoint) { _, _ in StubResponse(status: 200, json: OAuthFixture.tokenJSON(access: "access-2", refresh: "refresh-2")) } let client = try await makeClient(network: network) let tokens = try await client.refresh(refreshToken: "refresh-1") #expect(tokens.accessToken == "access-2") #expect(tokens.refreshToken == "refresh-2") #expect(try #require(await network.requests.first).formFields == [ "grant_type": "refresh_token", "refresh_token": "refresh-1", "client_id": OAuthFixture.clientID, ]) } @Test("A token endpoint refusal reports the server's code and description") func tokenError() async throws { let network = ScriptedNetwork() await network.on(OAuthFixture.tokenEndpoint) { _, _ in StubResponse(status: 400, json: #"{"error": "invalid_grant", "error_description": "Invalid or expired code"}"#) } let client = try await makeClient(network: network) await #expect { try await client.exchange(code: "code", verifier: "verifier") } throws: { error in guard case .tokenRequestFailed(let detail) = error as? ATProtoOAuthError else { return false } return detail == "invalid_grant: Invalid or expired code" } } @Test("A failure that isn't an OAuth error is reported by status, never by its body") func gatewayError() async throws { let network = ScriptedNetwork() await network.on(OAuthFixture.tokenEndpoint) { _, _ in StubResponse(status: 500, text: "invalid_grant somewhere in a stack trace") } let client = try await makeClient(network: network) await #expect { try await client.refresh(refreshToken: "refresh") } throws: { error in guard case .tokenRequestFailed(let detail) = error as? ATProtoOAuthError else { return false } return detail == "HTTP 500" } } @Test("A success that can't be read as tokens is an invalid token response", arguments: [ "{}", "not json", #"{"access_token": "a", "token_type": "DPoP", "scope": "atproto"}"#, #"{"access_token": "a", "token_type": "DPoP", "sub": "did:plc:alice"}"#, ]) func unreadableTokens(body: String) async throws { let network = ScriptedNetwork() await network.on(OAuthFixture.tokenEndpoint) { _, _ in StubResponse(status: 200, text: body) } let client = try await makeClient(network: network) await #expect { try await client.exchange(code: "code", verifier: "verifier") } throws: { error in guard case .invalidTokenResponse = error as? ATProtoOAuthError else { return false } return true } } @Test("Tokens decode without expires_in, and with a fractional one") func lenientLifetime() async throws { let network = ScriptedNetwork() await network.on(OAuthFixture.tokenEndpoint) { _, attempt in StubResponse(status: 200, json: OAuthFixture.tokenJSON(expiresIn: attempt == 1 ? nil : "299.9")) } let client = try await makeClient(network: network) #expect(try await client.refresh(refreshToken: "r").expiresIn == nil) #expect(try await client.refresh(refreshToken: "r").expiresIn == 299) } // MARK: - Clocks @Test("A rejected proof is signed again once the server's clock is known") func clockIsLearnedFromRejection() async throws { let serverNow = Date.now.addingTimeInterval(3600) let network = ScriptedNetwork() await network.on(OAuthFixture.parEndpoint) { _, attempt in attempt == 1 ? StubResponse( status: 400, headers: ["Date": Self.httpDate(serverNow)], json: #"{"error": "invalid_dpop_proof", "error_description": "iat is too far in the past"}"# ) : Self.parSuccess } let client = try await makeClient(network: network) _ = try await client.pushAuthorizationRequest(pkce: PKCE(), state: "s", loginHint: nil) let requests = await network.requests try #require(requests.count == 2) let first = try await DPoPProofReader.verifiedClaims(of: requests[0]) let second = try await DPoPProofReader.verifiedClaims(of: requests[1]) #expect(second.iat - first.iat >= 3590) } @Test("A rejected proof is not signed again when the clocks already agree") func rejectedProofWithoutClockChange() async throws { let network = ScriptedNetwork() await network.on(OAuthFixture.parEndpoint) { _, _ in StubResponse( status: 400, headers: ["Date": Self.httpDate(.now)], json: #"{"error": "invalid_dpop_proof", "error_description": "bad signature"}"# ) } let client = try await makeClient(network: network) await #expect(throws: ATProtoOAuthError.self) { try await client.pushAuthorizationRequest(pkce: PKCE(), state: "s", loginHint: nil) } #expect(await network.requests.count == 1) } @Test("A code exchange is never repeated after a rejected proof: the code may be spent") func exchangeIsNotRepeated() async throws { let network = ScriptedNetwork() await network.on(OAuthFixture.tokenEndpoint) { _, _ in StubResponse( status: 401, headers: ["Date": Self.httpDate(Date.now.addingTimeInterval(3600))], json: #"{"error": "invalid_dpop_proof", "error_description": "Invalid payload JSON"}"# ) } let client = try await makeClient(network: network) await #expect { try await client.exchange(code: "code", verifier: "verifier") } throws: { error in guard case .tokenRequestFailed(let detail) = error as? ATProtoOAuthError else { return false } return detail == "invalid_dpop_proof: Invalid payload JSON" } #expect(await network.requests.count == 1) } // MARK: - Through the auth proxy @Test("Through the proxy, the request is JSON and the proof is still for the server's endpoint") func proxiedPARAndExchange() async throws { let network = ScriptedNetwork() await network.on(OAuthFixture.proxyPAR) { _, _ in var response = Self.parSuccess response.headers[AuthProxy.keyIDHeader] = "key-2" return response } await network.on(OAuthFixture.proxyToken) { _, _ in StubResponse(status: 200, headers: [AuthProxy.keyIDHeader: "key-2"], json: OAuthFixture.tokenJSON()) } let client = try await makeClient(network: network, proxied: true, authMethod: .privateKeyJWT) let pkce = PKCE() _ = try await client.pushAuthorizationRequest(pkce: pkce, state: "state-1", loginHint: "alice.test") _ = try await client.exchange(code: "code-1", verifier: pkce.verifier) let par = try #require(await network.requests(to: OAuthFixture.proxyPAR).first) #expect(par.value(forHTTPHeaderField: "Content-Type") == "application/json") #expect(par.jsonFields == [ "par_endpoint": OAuthFixture.parEndpoint, "issuer": OAuthFixture.issuer, "login_hint": "alice.test", "scope": "atproto transition:generic", "code_challenge": pkce.challenge, "code_challenge_method": "S256", "state": "state-1", "redirect_uri": OAuthFixture.redirectURI, ]) #expect(try await DPoPProofReader.verifiedClaims(of: par).htu == OAuthFixture.parEndpoint) // The exchange asks for the key the proxy signed the PAR with. let token = try #require(await network.requests(to: OAuthFixture.proxyToken).first) #expect(token.jsonFields == [ "token_endpoint": OAuthFixture.tokenEndpoint, "issuer": OAuthFixture.issuer, "grant_type": "authorization_code", "code": "code-1", "redirect_uri": OAuthFixture.redirectURI, "code_verifier": pkce.verifier, "key_id": "key-2", ]) #expect(try await DPoPProofReader.verifiedClaims(of: token).htu == OAuthFixture.tokenEndpoint) #expect(await client.usesProxy) #expect(await client.proxyKeyID == "key-2") #expect(await network.requests.count == 2) } @Test("A nonce the proxy relays is kept for the authorization server, not for the proxy") func proxiedNonce() async throws { let network = ScriptedNetwork() await network.on(OAuthFixture.proxyPAR) { _, attempt in attempt == 1 ? Self.nonceChallenge("relayed-nonce") : Self.parSuccess } await network.on(OAuthFixture.proxyToken) { _, _ in StubResponse(status: 200, json: OAuthFixture.tokenJSON()) } let client = try await makeClient(network: network, proxied: true, authMethod: .privateKeyJWT) _ = try await client.pushAuthorizationRequest(pkce: PKCE(), state: "s", loginHint: nil) _ = try await client.exchange(code: "code", verifier: "verifier") let par = await network.requests(to: OAuthFixture.proxyPAR) try #require(par.count == 2) #expect(try await DPoPProofReader.verifiedClaims(of: par[1]).nonce == "relayed-nonce") // One request, not two: the nonce was already there for the token endpoint. let token = await network.requests(to: OAuthFixture.proxyToken) try #require(token.count == 1) #expect(try await DPoPProofReader.verifiedClaims(of: token[0]).nonce == "relayed-nonce") } @Test("A refresh through the proxy asks for the key the session is bound to") func proxiedRefresh() async throws { let network = ScriptedNetwork() await network.on(OAuthFixture.proxyToken) { _, _ in StubResponse(status: 200, headers: [AuthProxy.keyIDHeader: "key-1"], json: OAuthFixture.tokenJSON()) } let client = try await makeClient( network: network, proxied: true, authMethod: .privateKeyJWT, proxyKeyID: "key-1" ) _ = try await client.refresh(refreshToken: "refresh-1") #expect(try #require(await network.requests.first).jsonFields == [ "token_endpoint": OAuthFixture.tokenEndpoint, "issuer": OAuthFixture.issuer, "grant_type": "refresh_token", "refresh_token": "refresh-1", "key_id": "key-1", ]) } @Test("A confidential client never goes around an unavailable proxy", arguments: [404, 502, 503, 504]) func confidentialClientNeedsProxy(status: Int) async throws { let network = ScriptedNetwork() await network.on(OAuthFixture.proxyToken) { _, _ in StubResponse(status: status, text: "down") } await network.on(OAuthFixture.tokenEndpoint) { _, _ in StubResponse(status: 200, json: OAuthFixture.tokenJSON()) } let client = try await makeClient(network: network, proxied: true, authMethod: .privateKeyJWT) await #expect { try await client.refresh(refreshToken: "refresh-1") } throws: { error in guard case .unavailable(let kind, _) = error as? AuthProxyError else { return false } return kind == .refresh } #expect(await network.requests(to: OAuthFixture.tokenEndpoint).isEmpty) #expect(await client.usesProxy) } @Test("A confidential client reports a proxy it cannot reach") func confidentialClientUnreachableProxy() async throws { let network = ScriptedNetwork() await network.on(OAuthFixture.proxyPAR) { _, _ in throw URLError(.cannotConnectToHost) } let client = try await makeClient(network: network, proxied: true, authMethod: .privateKeyJWT) await #expect { try await client.pushAuthorizationRequest(pkce: PKCE(), state: "s", loginHint: nil) } throws: { error in guard case .unavailable(let kind, _) = error as? AuthProxyError else { return false } return kind == .pushedAuthorizationRequest } } @Test("A timeout is not taken for an unavailable proxy") func timeoutIsNotUnavailability() async throws { let network = ScriptedNetwork() await network.on(OAuthFixture.proxyToken) { _, _ in throw URLError(.timedOut) } let client = try await makeClient(network: network, proxied: true, authMethod: .none) await #expect(throws: URLError.self) { try await client.refresh(refreshToken: "refresh-1") } #expect(await client.usesProxy) } @Test("A public client asks the server itself when the proxy is down, and keeps doing so") func publicClientFallsBack() async throws { let network = ScriptedNetwork() await network.on(OAuthFixture.proxyPAR) { _, _ in throw URLError(.cannotFindHost) } await network.on(OAuthFixture.parEndpoint) { _, _ in Self.parSuccess } await network.on(OAuthFixture.tokenEndpoint) { _, _ in StubResponse(status: 200, json: OAuthFixture.tokenJSON()) } let client = try await makeClient(network: network, proxied: true, authMethod: .none, proxyKeyID: "key-1") _ = try await client.pushAuthorizationRequest(pkce: PKCE(), state: "s", loginHint: nil) _ = try await client.exchange(code: "code", verifier: "verifier") #expect(await network.requests(to: OAuthFixture.proxyPAR).count == 1) #expect(await network.requests(to: OAuthFixture.parEndpoint).count == 1) #expect(await network.requests(to: OAuthFixture.proxyToken).isEmpty) #expect(await network.requests(to: OAuthFixture.tokenEndpoint).count == 1) #expect(await !client.usesProxy) #expect(await client.proxyKeyID == nil) } @Test("The proxy's own refusal is an answer, not an outage") func proxyRefusal() async throws { let network = ScriptedNetwork() await network.on(OAuthFixture.proxyPAR) { _, _ in StubResponse(status: 400, json: #"{"error": "invalid_request", "error_description": "par_endpoint does not match issuer metadata"}"#) } let client = try await makeClient(network: network, proxied: true, authMethod: .privateKeyJWT) await #expect { try await client.pushAuthorizationRequest(pkce: PKCE(), state: "s", loginHint: nil) } throws: { error in guard case .authenticationFailed(let detail) = error as? ATProtoOAuthError else { return false } return detail == "Pushed authorization request failed: invalid_request: par_endpoint does not match issuer metadata" } } @Test("A proxy base URL with a trailing slash still makes clean paths") func proxyURLs() throws { #expect(try AuthProxy(baseURL: "https://auth.test/app/").url(for: .pushedAuthorizationRequest).absoluteString == OAuthFixture.proxyPAR) #expect(try AuthProxy(baseURL: "https://auth.test/app").url(for: .refresh).absoluteString == OAuthFixture.proxyToken) #expect(try AuthProxy(baseURL: "https://auth.test").url(for: .tokenExchange).absoluteString == "https://auth.test/oauth/token") #expect(throws: AuthProxyError.self) { try AuthProxy(baseURL: "not a url").url(for: .refresh) } } // MARK: - Helpers private static func httpDate(_ date: Date) -> String { let formatter = DateFormatter() formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss 'GMT'" formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(secondsFromGMT: 0) return formatter.string(from: date) } }