import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif import Testing @testable import CoreATProtocol @Suite("Authorization server metadata") struct AuthorizationServerMetadataTests { @Test("A document with only the endpoints the flow needs is enough") func minimalDocument() throws { let metadata = try OAuthFixture.metadata() #expect(metadata.issuer == OAuthFixture.issuer) #expect(metadata.authorizationEndpoint.string == OAuthFixture.authorizationEndpoint) #expect(metadata.tokenEndpoint.url.absoluteString == OAuthFixture.tokenEndpoint) #expect(metadata.pushedAuthorizationRequestEndpoint.string == OAuthFixture.parEndpoint) #expect(!metadata.authorizationResponseIssParameterSupported) } @Test("A full document decodes, whatever else it advertises") func fullDocument() throws { let json = """ { "issuer": "https://pds.example", "authorization_endpoint": "https://pds.example/oauth/authorize", "token_endpoint": "https://pds.example/oauth/token", "jwks_uri": "https://pds.example/oauth/jwks", "scopes_supported": ["atproto", "transition:generic"], "response_types_supported": ["code"], "response_modes_supported": ["query", "fragment"], "grant_types_supported": ["authorization_code", "refresh_token"], "token_endpoint_auth_methods_supported": ["none", "private_key_jwt"], "token_endpoint_auth_signing_alg_values_supported": ["ES256"], "code_challenge_methods_supported": ["S256"], "pushed_authorization_request_endpoint": "https://pds.example/oauth/par", "require_pushed_authorization_requests": true, "dpop_signing_alg_values_supported": ["ES256"], "authorization_response_iss_parameter_supported": true, "client_id_metadata_document_supported": true, "prompt_values_supported": ["none", "login"], "something_from_a_future_spec": {"nested": [1, 2, 3]} } """ let metadata = try AuthorizationServerMetadata(data: Data(json.utf8)) #expect(metadata.issuer == "https://pds.example") #expect(metadata.authorizationResponseIssParameterSupported) } @Test("A missing or insecure endpoint is named in the error", arguments: [ ("issuer", "\"issuer\": \"https://pds.test\"", "\"issuer\": \"http://pds.test\""), ("token_endpoint", "\"token_endpoint\": \"https://pds.test/oauth/token\"", "\"token_endpoint\": \"http://pds.test/oauth/token\""), ("authorization_endpoint", "\"authorization_endpoint\": \"https://pds.test/oauth/authorize\"", "\"authorization_endpoint\": 7"), ("pushed_authorization_request_endpoint", "\"pushed_authorization_request_endpoint\": \"https://pds.test/oauth/par\"", "\"unrelated\": true"), ]) func malformedField(field: String, member: String, replacement: String) throws { let json = OAuthFixture.minimalMetadataJSON.replacingOccurrences(of: member, with: replacement) try #require(json != OAuthFixture.minimalMetadataJSON) #expect { try AuthorizationServerMetadata(data: Data(json.utf8)) } throws: { error in guard case .malformedServerMetadata(let named, _) = error as? ATProtoOAuthError else { return false } return named == field } } @Test("A body that isn't a JSON object is a response that can't be parsed") func notJSON() { #expect(throws: URLError.self) { try AuthorizationServerMetadata(data: Data("captive portal".utf8)) } } @Test("Loading asks the issuer's well-known URL and checks the issuer it names") func loadsFromWellKnownURL() async throws { let network = ScriptedNetwork() await network.on(OAuthFixture.metadataURL) { _, _ in StubResponse(status: 200, json: OAuthFixture.minimalMetadataJSON) } let metadata = try await AuthorizationServerMetadata.load( issuer: OAuthFixture.issuer, transport: network.transport ) #expect(metadata == (try OAuthFixture.metadata())) let request = try #require(await network.requests.first) #expect(request.value(forHTTPHeaderField: "Accept") == "application/json") } @Test("An issuer with a port keeps it in the well-known URL") func keepsIssuerPort() async throws { let network = ScriptedNetwork() let json = OAuthFixture.minimalMetadataJSON .replacingOccurrences(of: "https://pds.test", with: "https://pds.test:8443") await network.on("https://pds.test:8443/.well-known/oauth-authorization-server") { _, _ in StubResponse(status: 200, json: json) } let metadata = try await AuthorizationServerMetadata.load( issuer: "https://pds.test:8443", transport: network.transport ) #expect(metadata.tokenEndpoint.string == "https://pds.test:8443/oauth/token") } @Test("A document that names another issuer is refused") func issuerMixUp() async throws { let network = ScriptedNetwork() let json = OAuthFixture.minimalMetadataJSON .replacingOccurrences(of: "\"issuer\": \"https://pds.test\"", with: "\"issuer\": \"https://evil.test\"") await network.on(OAuthFixture.metadataURL) { _, _ in StubResponse(status: 200, json: json) } await #expect { try await AuthorizationServerMetadata.load(issuer: OAuthFixture.issuer, transport: network.transport) } throws: { error in guard case .issuerMismatch = error as? ATProtoOAuthError else { return false } return true } } @Test("Anything but 200 is a bad server response", arguments: [404, 500, 503]) func unsuccessfulStatus(status: Int) async throws { let network = ScriptedNetwork() await network.on(OAuthFixture.metadataURL) { _, _ in StubResponse(status: status, json: OAuthFixture.minimalMetadataJSON) } await #expect(throws: URLError.self) { try await AuthorizationServerMetadata.load(issuer: OAuthFixture.issuer, transport: network.transport) } } @Test("The authorization URL carries the client ID and request URI, fully escaped") func authorizationURL() throws { let metadata = try OAuthFixture.metadata() let url = try metadata.authorizationURL( clientID: OAuthFixture.clientID, requestURI: "urn:ietf:params:oauth:request_uri:req+a/b==" ) #expect(url.absoluteString.hasPrefix("https://pds.test/oauth/authorize?client_id=https%3A%2F%2Fapp.test")) let components = try #require(URLComponents(url: url, resolvingAgainstBaseURL: false)) let items = try #require(components.queryItems) #expect(items.first { $0.name == "client_id" }?.value == OAuthFixture.clientID) #expect(items.first { $0.name == "request_uri" }?.value == "urn:ietf:params:oauth:request_uri:req+a/b==") #expect(components.percentEncodedQuery?.contains("+") == false) } @Test("A query the authorization endpoint already has is kept") func authorizationURLKeepsExistingQuery() throws { let json = OAuthFixture.minimalMetadataJSON.replacingOccurrences( of: "https://pds.test/oauth/authorize", with: "https://pds.test/oauth/authorize?tenant=a%20b" ) let metadata = try AuthorizationServerMetadata(data: Data(json.utf8)) let url = try metadata.authorizationURL(clientID: "c", requestURI: "r") #expect(url.absoluteString == "https://pds.test/oauth/authorize?tenant=a%20b&client_id=c&request_uri=r") } } @Suite("Authorization callback") struct AuthorizationCallbackTests { private func callback( _ query: String, state: String = "expected-state", issParameterSupported: Bool = false ) throws -> AuthorizationCallback { var json = OAuthFixture.minimalMetadataJSON if issParameterSupported { json = json.replacingOccurrences( of: "\"issuer\"", with: "\"authorization_response_iss_parameter_supported\": true, \"issuer\"" ) } return try AuthorizationCallback( redirectURL: try #require(URL(string: "\(OAuthFixture.redirectURI)?\(query)")), expectedState: state, server: try AuthorizationServerMetadata(data: Data(json.utf8)) ) } @Test("A response for this request yields its code") func success() throws { let callback = try callback("code=abc%2B123&state=expected-state&iss=https%3A%2F%2Fpds.test") #expect(callback.code == "abc+123") } @Test("A custom-scheme redirect is read the same way") func customScheme() throws { let callback = try AuthorizationCallback( redirectURL: try #require(URL(string: "com.example.app:/callback?state=s&code=c&iss=https://pds.test")), expectedState: "s", server: try OAuthFixture.metadata() ) #expect(callback.code == "c") } @Test("A response for another request is refused before anything else is read") func stateMismatch() { #expect { try callback("code=abc&state=someone-elses&iss=https%3A%2F%2Fpds.test") } throws: { error in guard case .authenticationFailed(let detail) = error as? ATProtoOAuthError else { return false } return detail.contains("different sign-in attempt") } } @Test("A response with no state, or no code, is malformed", arguments: [ "code=abc&iss=https%3A%2F%2Fpds.test", "state=expected-state&iss=https%3A%2F%2Fpds.test", "state=expected-state&code=&iss=https%3A%2F%2Fpds.test", ]) func malformed(query: String) { #expect { try callback(query) } throws: { error in guard case .malformedAuthorizationCallback = error as? ATProtoOAuthError else { return false } return true } } @Test("The server's error is reported with its code and description") func authorizationError() { #expect { try callback("error=access_denied&error_description=The+user+said+no&state=expected-state") } throws: { error in guard case .authenticationFailed(let detail) = error as? ATProtoOAuthError else { return false } return detail == "Authorization failed: access_denied: The user said no" } } @Test("An error without a description is reported by its code alone") func authorizationErrorWithoutDescription() { #expect { try callback("error=access_denied&state=expected-state") } throws: { error in guard case .authenticationFailed(let detail) = error as? ATProtoOAuthError else { return false } return detail == "Authorization failed: access_denied" } } @Test("A code from another issuer is refused") func issuerMismatch() { #expect { try callback("code=abc&state=expected-state&iss=https%3A%2F%2Fevil.test") } throws: { error in guard case .issuerMismatch(let expected, let actual) = error as? ATProtoOAuthError else { return false } return expected == "https://pds.test" && actual == "https://evil.test" } } @Test("A missing issuer is accepted only from a server that never promised one") func missingIssuer() throws { #expect(try callback("code=abc&state=expected-state").code == "abc") #expect { try callback("code=abc&state=expected-state", issParameterSupported: true) } throws: { error in guard case .malformedAuthorizationCallback = error as? ATProtoOAuthError else { return false } return true } } }