Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270import Foundation#if canImport(FoundationNetworking)import FoundationNetworking#endifimport 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("<html>captive portal</html>".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 } }}