import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif import JWTKit import Testing @testable import CoreATProtocol @Suite("ATProtoOAuth sign-in") struct ATProtoOAuthSignInTests { @Test("A public client signs in at a server that demands a nonce on every proof") func publicClientAtReferenceServer() async throws { let bench = await OAuthTestBench(.reference) let oauth = await bench.makeOAuth(proxied: false) let result = try await oauth.authenticate(identifier: "alice.test", userAuthenticator: bench.approvingUser()) #expect(result.did == "did:plc:alice") #expect(result.handle == "alice.test") #expect(result.pdsEndpoint == "https://pds.test") #expect(result.accessToken.hasPrefix("access-")) #expect(result.refreshToken?.hasPrefix("refresh-") == true) #expect((1...300).contains(result.expiresIn)) let login = try #require(await bench.store.login) #expect(login.accessToken.value == result.accessToken) #expect(login.refreshToken?.value == result.refreshToken) #expect(login.scopes == "atproto transition:generic") #expect(login.issuingServer == OAuthFixture.issuer) #expect(await bench.store.privateKey != nil) // The first PAR learns the nonce; the token request already has it. #expect(await bench.network.requests(to: OAuthFixture.parEndpoint).count == 2) #expect(await bench.network.requests(to: OAuthFixture.tokenEndpoint).count == 1) #expect(await bench.server.lastPushedFields["login_hint"] == "alice.test") #expect(await bench.server.lastPushedFields["client_id"] == OAuthFixture.clientID) } @Test("A confidential client signs in through the proxy at a server that reads iat as an integer") func confidentialClientAtTranquilServer() async throws { let bench = await OAuthTestBench(.tranquil) let oauth = await bench.makeOAuth(proxied: true) let result = try await oauth.authenticate(identifier: "alice.test", userAuthenticator: bench.approvingUser()) #expect(result.did == "did:plc:alice") #expect(await bench.store.login?.accessToken.value == result.accessToken) #expect(await bench.store.proxyKeyID == "key-1") // Everything went through the proxy, one request each. #expect(await bench.network.requests(to: OAuthFixture.proxyPAR).count == 1) #expect(await bench.network.requests(to: OAuthFixture.proxyToken).count == 1) #expect(await bench.network.requests(to: OAuthFixture.parEndpoint).isEmpty) #expect(await bench.network.requests(to: OAuthFixture.tokenEndpoint).isEmpty) // The token endpoint's proof was for the server, with a whole-second iat. let proof = try #require(await bench.server.acceptedProofs.last) #expect(proof.htu == OAuthFixture.tokenEndpoint) #expect(proof.htm == "POST") } @Test("Signing in works on every combination of server and route", arguments: [ (FakeAuthorizationServer.Flavor.reference, false), (.reference, true), (.tranquil, false), (.tranquil, true), ]) func everyCombination(flavor: FakeAuthorizationServer.Flavor, proxied: Bool) async throws { let bench = await OAuthTestBench(flavor) let oauth = await bench.makeOAuth(proxied: proxied) let result = try await oauth.authenticate(identifier: "alice.test", userAuthenticator: bench.approvingUser()) #expect(result.accessToken == (await bench.store.login?.accessToken.value)) #expect((await bench.store.proxyKeyID != nil) == proxied) } @Test("A sign-in that outlasts the server's nonce still completes", arguments: [ FakeAuthorizationServer.Flavor.reference, .tranquil, ]) func slowSignIn(flavor: FakeAuthorizationServer.Flavor) async throws { let bench = await OAuthTestBench(flavor) let oauth = await bench.makeOAuth(proxied: true) // The user takes ten minutes on the sign-in page. The nonce from the // PAR is long dead by then, and this server spends the code before it // would say so: a proof carrying the stale nonce could not be retried. let result = try await oauth.authenticate( identifier: "alice.test", userAuthenticator: bench.approvingUser { bench.clock.advance(by: .seconds(600)) await bench.server.expireNonces() } ) #expect(result.accessToken == (await bench.store.login?.accessToken.value)) } @Test("Scopes with reserved characters are granted as requested, on either route", arguments: [false, true]) func granularScopes(proxied: Bool) async throws { let scopes = [ "atproto", "blob:*/*", "repo:app.example.post?action=create&action=delete", "rpc:app.bsky.feed.getFeed?aud=did:web:api.bsky.app%23bsky_appview", ] let bench = await OAuthTestBench(.tranquil) let oauth = await bench.makeOAuth(proxied: proxied, scopes: scopes) _ = try await oauth.authenticate(identifier: "alice.test", userAuthenticator: bench.approvingUser()) #expect(await bench.server.lastPushedFields["scope"] == scopes.joined(separator: " ")) #expect(await bench.store.login?.scopes == scopes.joined(separator: " ")) } @Test("Signing in by DID hints the DID and reports the handle from the identity") func signInByDID() async throws { let bench = await OAuthTestBench(.reference) let oauth = await bench.makeOAuth(proxied: false) let result = try await oauth.authenticate(identifier: "did:plc:alice", userAuthenticator: bench.approvingUser()) #expect(result.handle == "alice.test") #expect(await bench.server.lastPushedFields["login_hint"] == "did:plc:alice") } // MARK: - What a failed attempt leaves behind @Test("What the user authenticator throws comes out unchanged, and the stored session survives") func cancelledSignInKeepsSession() async throws { let existing = Login( accessToken: Token(value: "existing-access", expiry: .distantFuture), refreshToken: Token(value: "existing-refresh"), scopes: "atproto", issuingServer: OAuthFixture.issuer ) let bench = await OAuthTestBench(.reference, store: MemoryAuthStore(login: existing)) let oauth = await bench.makeOAuth(proxied: false) let keyBefore = await oauth.privateKeyPEM await #expect(throws: OAuthTestBench.BrowserError.userCancelled) { try await oauth.authenticate(identifier: "alice.test") { _, _ in throw OAuthTestBench.BrowserError.userCancelled } } #expect(await bench.store.login == existing) #expect(await bench.store.storedLogins.isEmpty) #expect(await oauth.privateKeyPEM == keyBefore) } @Test("A stored login is never returned in place of signing in") func storedLoginIsNotReused() async throws { let existing = Login( accessToken: Token(value: "existing-access", expiry: .distantFuture), refreshToken: Token(value: "existing-refresh") ) let bench = await OAuthTestBench(.tranquil, store: MemoryAuthStore(login: existing)) let oauth = await bench.makeOAuth(proxied: true) let result = try await oauth.authenticate(identifier: "alice.test", userAuthenticator: bench.approvingUser()) #expect(result.accessToken != "existing-access") #expect(await bench.store.login?.accessToken.value == result.accessToken) #expect(await bench.network.requests(to: OAuthFixture.proxyPAR).count == 1) } @Test("A stored DPoP key is reused, so a session it already binds keeps working") func storedKeyIsReused() async throws { let key = ES256PrivateKey().pemRepresentation let bench = await OAuthTestBench(.reference, store: MemoryAuthStore(privateKey: Data(key.utf8))) let oauth = await bench.makeOAuth(proxied: false) _ = try await oauth.authenticate(identifier: "alice.test", userAuthenticator: bench.approvingUser()) #expect(await oauth.privateKeyPEM == key) #expect(await bench.store.privateKey == Data(key.utf8)) } @Test("Tokens for another account are refused and nothing is stored") func subjectMismatch() async throws { let bench = await OAuthTestBench(.reference) await bench.server.signEveryoneIn(as: "did:plc:mallory") let oauth = await bench.makeOAuth(proxied: false) await #expect { try await oauth.authenticate(identifier: "alice.test", userAuthenticator: bench.approvingUser()) } throws: { error in guard case .subjectMismatch(let expected, let actual) = error as? ATProtoOAuthError else { return false } return expected == "did:plc:alice" && actual == "did:plc:mallory" } #expect(await bench.store.login == nil) } @Test("A token endpoint refusal reaches the caller as tokenRequestFailed, with the server's words") func tokenRefusal() async throws { let bench = await OAuthTestBench(.tranquil) await bench.network.on(OAuthFixture.proxyToken) { _, _ in StubResponse(status: 401, json: #"{"error": "invalid_dpop_proof", "error_description": "Invalid payload JSON"}"#) } let oauth = await bench.makeOAuth(proxied: true) await #expect { try await oauth.authenticate(identifier: "alice.test", userAuthenticator: bench.approvingUser()) } throws: { error in guard case .tokenRequestFailed(let detail) = error as? ATProtoOAuthError else { return false } return detail == "invalid_dpop_proof: Invalid payload JSON" } #expect(await bench.store.login == nil) } @Test("A network failure reaches the caller as the URLError it is") func networkFailure() async throws { let bench = await OAuthTestBench(.reference) await bench.network.on(OAuthFixture.parEndpoint) { _, _ in throw URLError(.networkConnectionLost) } let oauth = await bench.makeOAuth(proxied: false) await #expect(throws: URLError.self) { try await oauth.authenticate(identifier: "alice.test", userAuthenticator: bench.approvingUser()) } } @Test("Being offline is reported as the network error it is, proxy or not", arguments: [false, true]) func offline(proxied: Bool) async throws { let bench = await OAuthTestBench(.reference) for endpoint in [OAuthFixture.parEndpoint, OAuthFixture.proxyPAR] { await bench.network.on(endpoint) { _, _ in throw URLError(.notConnectedToInternet) } } let oauth = await bench.makeOAuth(proxied: proxied) await #expect { try await oauth.authenticate(identifier: "alice.test", userAuthenticator: bench.approvingUser()) } throws: { error in (error as? URLError)?.code == .notConnectedToInternet } } @Test("A proxy outage is reported as a failed flow that names the proxy") func proxyOutage() async throws { let bench = await OAuthTestBench(.reference) await bench.network.on(OAuthFixture.proxyPAR) { _, _ in StubResponse(status: 503, text: "down") } let oauth = await bench.makeOAuth(proxied: true) await #expect { try await oauth.authenticate(identifier: "alice.test", userAuthenticator: bench.approvingUser()) } throws: { error in guard case .authenticationFailed(let detail) = error as? ATProtoOAuthError else { return false } return detail.hasPrefix("OAuth flow failed: Auth proxy unavailable during PAR request") } // A confidential client must not have tried the server directly. #expect(await bench.network.requests(to: OAuthFixture.parEndpoint).isEmpty) } @Test("An identity that can't be resolved is reported the way apps look for it") func identityResolutionFailure() async throws { struct FailingResolver: ATProtoIdentityResolver { func resolve(identifier: String) async throws -> IdentityResolver.ResolvedIdentity { throw IdentityError.resolutionFailed } func isAuthorizationServer(_ authorizationServer: String, validFor pdsEndpoint: String) async throws -> Bool { true } } let bench = await OAuthTestBench(.reference) let oauth = await ATProtoOAuth( config: ATProtoOAuthConfig(clientMetadataURL: OAuthFixture.clientID, redirectURI: OAuthFixture.redirectURI), storage: bench.store.storage, identityResolver: FailingResolver(), transport: bench.network.transport, clockSkew: bench.clockSkew ) await #expect { try await oauth.authenticate(identifier: "nobody.test", userAuthenticator: bench.approvingUser()) } throws: { error in guard case .authenticationFailed(let detail) = error as? ATProtoOAuthError else { return false } return detail.hasPrefix("Identity resolution failed") } #expect(await bench.network.requests.isEmpty) } @Test("An authorization server the PDS doesn't delegate to is refused before anything is sent to it") func issuerNotValidForPDS() async throws { let bench = await OAuthTestBench(.reference) var resolver = FixedIdentityResolver() resolver.isValidServer = false let oauth = await bench.makeOAuth(proxied: false, identityResolver: resolver) await #expect(throws: ATProtoOAuthError.self) { try await oauth.authenticate(identifier: "alice.test", userAuthenticator: bench.approvingUser()) } #expect(await bench.network.requests(to: OAuthFixture.parEndpoint).isEmpty) } @Test("Metadata that names another issuer stops the sign-in") func metadataIssuerMismatch() async throws { let bench = await OAuthTestBench(.reference) await bench.network.on(OAuthFixture.metadataURL) { _, _ in StubResponse(status: 200, json: OAuthFixture.minimalMetadataJSON.replacingOccurrences( of: "\"issuer\": \"https://pds.test\"", with: "\"issuer\": \"https://evil.test\"" )) } let oauth = await bench.makeOAuth(proxied: false) await #expect { try await oauth.authenticate(identifier: "alice.test", userAuthenticator: bench.approvingUser()) } throws: { error in guard case .issuerMismatch = error as? ATProtoOAuthError else { return false } return true } } @Test("A redirect answering a different request is refused before the code is used") func forgedCallback() async throws { let bench = await OAuthTestBench(.reference) let oauth = await bench.makeOAuth(proxied: false) await #expect { try await oauth.authenticate(identifier: "alice.test") { _, _ in try #require(URL(string: "\(OAuthFixture.redirectURI)?code=stolen&state=forged&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") } #expect(await bench.network.requests(to: OAuthFixture.tokenEndpoint).isEmpty) } @Test("A redirect URI without a scheme is a configuration error") func invalidRedirectURI() async throws { let bench = await OAuthTestBench(.reference) let oauth = await ATProtoOAuth( config: ATProtoOAuthConfig(clientMetadataURL: OAuthFixture.clientID, redirectURI: "no-scheme"), storage: bench.store.storage, identityResolver: FixedIdentityResolver(), transport: bench.network.transport, clockSkew: bench.clockSkew ) await #expect { try await oauth.authenticate(identifier: "alice.test", userAuthenticator: bench.approvingUser()) } throws: { error in guard case .invalidConfiguration = error as? ATProtoOAuthError else { return false } return true } } @Test("The user authenticator is given the redirect URI's scheme") func callbackScheme() async throws { let bench = await OAuthTestBench(.reference) let oauth = await bench.makeOAuth(proxied: false) let approve = bench.approvingUser() _ = try await oauth.authenticate(identifier: "alice.test") { url, scheme in #expect(scheme == "https") #expect(url.absoluteString.hasPrefix("\(OAuthFixture.authorizationEndpoint)?client_id=")) return try await approve(url, scheme) } } } @Suite("ATProtoOAuth refresh") struct ATProtoOAuthRefreshTests { /// Signs in on a bench and hands back a client like the one an app makes /// for a later launch: same storage, new instance. private func signedIn( _ flavor: FakeAuthorizationServer.Flavor, proxied: Bool ) async throws -> (bench: OAuthTestBench, oauth: ATProtoOAuth, login: Login) { let bench = await OAuthTestBench(flavor) _ = try await bench.makeOAuth(proxied: proxied) .authenticate(identifier: "alice.test", userAuthenticator: bench.approvingUser()) let login = try #require(await bench.store.login) return (bench, await bench.makeOAuth(proxied: proxied), login) } @Test("A valid access token is left alone unless the refresh is forced") func notNeeded() async throws { let (bench, oauth, login) = try await signedIn(.reference, proxied: false) #expect(try await oauth.refreshLoginIfNeeded(accountIdentifier: nil, force: false) == nil) #expect(await bench.store.login == login) } @Test("A forced refresh rotates both tokens and stores them", arguments: [ (FakeAuthorizationServer.Flavor.reference, false), (.reference, true), (.tranquil, false), (.tranquil, true), ]) func rotates(flavor: FakeAuthorizationServer.Flavor, proxied: Bool) async throws { let (bench, oauth, login) = try await signedIn(flavor, proxied: proxied) let refreshed = try #require(try await oauth.refreshLoginIfNeeded(accountIdentifier: "alice.test", force: true)) #expect(refreshed.accessToken.value != login.accessToken.value) #expect(refreshed.refreshToken != login.refreshToken) #expect(refreshed.refreshToken != nil) #expect(refreshed.issuingServer == OAuthFixture.issuer) #expect(refreshed.accessToken.valid) #expect(await bench.store.login == refreshed) #expect((await bench.store.proxyKeyID != nil) == proxied) } @Test("Refreshing twice in a row works: each refresh uses the token the last one stored") func refreshesRepeatedly() async throws { let (bench, oauth, _) = try await signedIn(.tranquil, proxied: true) let first = try #require(try await oauth.refreshLoginIfNeeded(accountIdentifier: nil, force: true)) let second = try #require(try await bench.makeOAuth(proxied: true).refreshLoginIfNeeded(accountIdentifier: nil, force: true)) #expect(first.refreshToken != second.refreshToken) #expect(await bench.store.login == second) } @Test("An expired access token is refreshed without being asked twice") func refreshesExpiredToken() async throws { let (bench, _, login) = try await signedIn(.reference, proxied: false) let expired = Login( accessToken: Token(value: login.accessToken.value, expiry: .distantPast), refreshToken: login.refreshToken, scopes: login.scopes, issuingServer: login.issuingServer ) try await bench.store.storage.storeLogin(expired) let refreshed = try await bench.makeOAuth(proxied: false).refreshLoginIfNeeded(accountIdentifier: nil, force: false) #expect(refreshed?.accessToken.valid == true) } @Test("A server that doesn't rotate refresh tokens leaves the session its old one") func keepsRefreshTokenWhenNotRotated() async throws { let (bench, oauth, login) = try await signedIn(.reference, proxied: false) await bench.server.stopRotatingRefreshTokens() let refreshed = try #require(try await oauth.refreshLoginIfNeeded(accountIdentifier: nil, force: true)) #expect(refreshed.accessToken.value != login.accessToken.value) #expect(refreshed.refreshToken == login.refreshToken) // And the kept token keeps working. #expect(try await bench.makeOAuth(proxied: false).refreshLoginIfNeeded(accountIdentifier: nil, force: true) != nil) } @Test("A refresh through the proxy asks for the key the session was started with") func usesStoredProxyKey() async throws { let (bench, oauth, _) = try await signedIn(.tranquil, proxied: true) _ = try await oauth.refreshLoginIfNeeded(accountIdentifier: nil, force: true) let request = try #require(await bench.network.requests(to: OAuthFixture.proxyToken).last) #expect(request.jsonFields["grant_type"] == "refresh_token") #expect(request.jsonFields["key_id"] == "key-1") #expect(request.jsonFields["redirect_uri"] == nil) } @Test("A dead refresh token is reported with the server's error code first") func deadRefreshToken() async throws { let (bench, oauth, login) = try await signedIn(.reference, proxied: false) try await bench.store.storage.storeLogin(Login( accessToken: login.accessToken, refreshToken: Token(value: "revoked"), issuingServer: login.issuingServer )) await #expect { try await oauth.refreshLoginIfNeeded(accountIdentifier: nil, force: true) } throws: { error in guard case .tokenRequestFailed(let detail) = error as? ATProtoOAuthError else { return false } return detail.hasPrefix("invalid_grant") } } @Test("A proxy outage during refresh is not a verdict on the session") func proxyOutage() async throws { let (bench, oauth, login) = try await signedIn(.tranquil, proxied: true) await bench.network.on(OAuthFixture.proxyToken) { _, _ in StubResponse(status: 502, text: "bad gateway") } await #expect(throws: AuthProxyError.self) { try await oauth.refreshLoginIfNeeded(accountIdentifier: nil, force: true) } #expect(await bench.store.login == login) #expect(await bench.network.requests(to: OAuthFixture.tokenEndpoint).isEmpty) } @Test("Metadata that can't be fetched fails the refresh as a network error") func metadataUnavailable() async throws { let (bench, oauth, login) = try await signedIn(.reference, proxied: false) await bench.network.on(OAuthFixture.metadataURL) { _, _ in StubResponse(status: 503, text: "down") } await #expect(throws: URLError.self) { try await oauth.refreshLoginIfNeeded(accountIdentifier: nil, force: true) } #expect(await bench.store.login == login) } @Test("A refresh that comes back as another account is refused and not stored") func refreshSubjectMismatch() async throws { let (bench, oauth, login) = try await signedIn(.reference, proxied: false) await bench.server.signEveryoneIn(as: "did:plc:mallory") await #expect { try await oauth.refreshLoginIfNeeded(accountIdentifier: "alice.test", force: true) } throws: { error in guard case .subjectMismatch = error as? ATProtoOAuthError else { return false } return true } #expect(await bench.store.login == login) } @Test("A login without an issuer is refreshed against the resolved identity's server") func issuerFromIdentity() async throws { let (bench, oauth, login) = try await signedIn(.reference, proxied: false) try await bench.store.storage.storeLogin(Login(accessToken: login.accessToken, refreshToken: login.refreshToken)) let refreshed = try #require(try await oauth.refreshLoginIfNeeded(accountIdentifier: "alice.test", force: true)) #expect(refreshed.issuingServer == OAuthFixture.issuer) // Without an identifier there is nowhere to look. try await bench.store.storage.storeLogin(Login(accessToken: login.accessToken, refreshToken: refreshed.refreshToken)) await #expect { try await oauth.refreshLoginIfNeeded(accountIdentifier: nil, force: true) } throws: { error in guard case .refreshIssuerUnavailable = error as? ATProtoOAuthError else { return false } return true } } }