import Foundation import Testing @testable import CoreATProtocol @Suite("Form URL encoding") struct FormURLEncodingTests { @Test("Fields are joined in order") func joinsFieldsInOrder() { let body = FormURLEncoding.encode([ (name: "grant_type", value: "authorization_code"), (name: "code", value: "abc-123_~."), ]) #expect(String(decoding: body, as: UTF8.self) == "grant_type=authorization_code&code=abc-123_~.") } @Test("Scope syntax survives a round trip through a form decoder", arguments: [ "atproto transition:generic", "atproto blob:*/* identity:handle", "rpc:app.bsky.feed.getFeed?aud=did:web:api.bsky.app%23bsky_appview", "repo:app.example.one?action=create&action=update", "include:app.example.authFull?aud=*", "a+b=c&d", "naïve ✓ 日本", ]) func scopeRoundTrips(scope: String) throws { var request = URLRequest(url: try #require(URL(string: "https://pds.test/oauth/par"))) request.httpBody = FormURLEncoding.encode([ (name: "scope", value: scope), (name: "state", value: "s"), ]) #expect(request.formFields == ["scope": scope, "state": "s"]) } @Test("Everything a form decoder treats specially is escaped") func escapesReservedCharacters() { #expect(FormURLEncoding.escape("a b") == "a%20b") #expect(FormURLEncoding.escape("a+b") == "a%2Bb") #expect(FormURLEncoding.escape("a&b=c") == "a%26b%3Dc") #expect(FormURLEncoding.escape("%23") == "%2523") #expect(FormURLEncoding.escape("https://app.test/cb?x=1#f") == "https%3A%2F%2Fapp.test%2Fcb%3Fx%3D1%23f") #expect(FormURLEncoding.escape("é") == "%C3%A9") #expect(FormURLEncoding.escape("") == "") } } @Suite("PKCE") struct PKCETests { @Test("S256 challenge matches the RFC 7636 appendix B example") func rfcVector() { let pkce = PKCE(verifier: "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk") #expect(pkce.challenge == "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM") #expect(PKCE.method == "S256") } @Test("A generated verifier is 43 unreserved characters and never repeats") func generatedVerifier() { let first = PKCE() let second = PKCE() #expect(first.verifier.count == 43) #expect(first.verifier.allSatisfy { $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "-" || $0 == "_") }) #expect(first.verifier != second.verifier) #expect(first.challenge == PKCE(verifier: first.verifier).challenge) } } @Suite("Stored logins") struct LoginCodingTests { /// A login as an app wrote it to the Keychain with a default `JSONEncoder` /// before this package defined `Login` itself. private let storedWithDefaultDates = """ { "accessToken": {"value": "access", "expiry": 784500000.5}, "refreshToken": {"value": "refresh"}, "scopes": "atproto transition:generic", "issuingServer": "https://bsky.social", "additionalParams": {"did": "did:plc:abc"} } """ /// The same, from an app that encodes dates as ISO 8601. private let storedWithISODates = """ { "accessToken": {"value": "access", "expiry": "2026-11-13T21:00:00Z"}, "refreshToken": {"value": "refresh"}, "scopes": "atproto", "issuingServer": "https://pds.example" } """ @Test("A login stored by an earlier release decodes unchanged") func decodesEarlierFormat() throws { let login = try JSONDecoder().decode(Login.self, from: Data(storedWithDefaultDates.utf8)) #expect(login.accessToken.value == "access") #expect(login.accessToken.expiry == Date(timeIntervalSinceReferenceDate: 784_500_000.5)) #expect(login.refreshToken == Token(value: "refresh")) #expect(login.scopes == "atproto transition:generic") #expect(login.issuingServer == "https://bsky.social") #expect(login.additionalParams == ["did": "did:plc:abc"]) } @Test("A login stored with ISO 8601 dates decodes unchanged") func decodesISODates() throws { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 let login = try decoder.decode(Login.self, from: Data(storedWithISODates.utf8)) #expect(login.accessToken.expiry == Date(timeIntervalSince1970: 1_794_603_600)) #expect(login.refreshToken?.expiry == nil) #expect(login.additionalParams == nil) } @Test("Encoding keeps the stored key names") func encodesStoredKeys() throws { let login = Login( accessToken: Token(value: "access", expiry: Date(timeIntervalSinceReferenceDate: 10)), refreshToken: Token(value: "refresh"), scopes: "atproto", issuingServer: "https://pds.example" ) let object = try #require( try JSONSerialization.jsonObject(with: JSONEncoder().encode(login)) as? [String: Any] ) #expect(Set(object.keys) == ["accessToken", "refreshToken", "scopes", "issuingServer"]) #expect((object["accessToken"] as? [String: Any])?["value"] as? String == "access") #expect((object["accessToken"] as? [String: Any])?["expiry"] as? Double == 10) #expect((object["refreshToken"] as? [String: Any])?.keys.sorted() == ["value"]) #expect(try JSONDecoder().decode(Login.self, from: JSONEncoder().encode(login)) == login) } @Test("A token is valid until its expiry, and always without one") func tokenValidity() { #expect(Token(value: "t").valid) #expect(Token(value: "t", expiry: .distantFuture).valid) #expect(!Token(value: "t", expiry: .distantPast).valid) #expect(Token(value: "t", expiresIn: 60).valid) #expect(!Token(value: "t", expiresIn: -1).valid) } } @Suite("OAuth error bodies") struct OAuthErrorBodyTests { @Test("An authorization server error decodes with its description") func authorizationServerError() throws { let body = try #require(OAuthErrorBody(data: Data(#"{"error":"invalid_grant","error_description":"Invalid or expired code"}"#.utf8))) #expect(body == OAuthErrorBody(error: "invalid_grant", errorDescription: "Invalid or expired code")) #expect(body.summary == "invalid_grant: Invalid or expired code") } @Test("An XRPC error's message stands in for the description") func xrpcError() throws { let body = try #require(OAuthErrorBody(data: Data(#"{"error":"use_dpop_nonce","message":"DPoP nonce required"}"#.utf8))) #expect(body.error == "use_dpop_nonce") #expect(body.errorDescription == "DPoP nonce required") } @Test("The summary starts with the code even without a description") func summaryWithoutDescription() throws { let body = try #require(OAuthErrorBody(data: Data(#"{"error":"server_error"}"#.utf8))) #expect(body.summary.hasPrefix("server_error")) } @Test("Anything that isn't an OAuth error is not decoded", arguments: [ "502 Bad Gateway", "", #"{"message":"no error member"}"#, #"["invalid_grant"]"#, ]) func notAnError(body: String) { #expect(OAuthErrorBody(data: Data(body.utf8)) == nil) } } @Suite("URL origins") struct URLOriginTests { @Test("Origins compare without regard to case, path or a default port", arguments: [ ("https://PDS.Example/xrpc/foo?x=1", "https://pds.example"), ("https://pds.example:443/oauth/token", "https://pds.example"), ("http://localhost:80", "http://localhost"), ("https://pds.example:8443/", "https://pds.example:8443"), ("http://pds.example:443", "http://pds.example:443"), ]) func normalizes(input: String, expected: String) throws { #expect(URLOrigin.normalized(try #require(URL(string: input))) == expected) } @Test("A URL without a scheme or host has no origin", arguments: ["pds.example", "/just/a/path", "mailto:a@b.c"]) func noOrigin(input: String) throws { #expect(URLOrigin.normalized(try #require(URL(string: input))) == nil) } @Test("Issuers match on origin, and two unusable values never match") func validateIssuer() { #expect(throws: Never.self) { try ATProtoOAuth.validateIssuer("https://pds.example", matches: "https://PDS.example:443/") } #expect(throws: ATProtoOAuthError.self) { try ATProtoOAuth.validateIssuer("https://evil.example", matches: "https://pds.example") } #expect(throws: ATProtoOAuthError.self) { try ATProtoOAuth.validateIssuer("not a url", matches: "also not a url") } } }