import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif import Synchronization import Testing @testable import CoreATProtocol /// A refresh spends a single-use token. These tests are about everything /// that can come between sending it and storing its successor. @Suite("ATProtoOAuth refresh, interrupted") struct RefreshExchangeTests { private func signedIn( _ flavor: FakeAuthorizationServer.Flavor, proxied: Bool ) async throws -> (bench: OAuthTestBench, login: Login) { let bench = await OAuthTestBench(flavor) _ = try await bench.makeOAuth(proxied: proxied) .authenticate(identifier: "alice.test", userAuthenticator: bench.approvingUser()) return (bench, try #require(await bench.store.login)) } /// Requests that asked the token endpoint, directly or through the /// proxy, for a refresh. private func refreshRequests(on bench: OAuthTestBench, proxied: Bool) async -> [URLRequest] { if proxied { return await bench.network.requests(to: OAuthFixture.proxyToken) .filter { $0.jsonFields["grant_type"] == "refresh_token" } } return await bench.network.requests(to: OAuthFixture.tokenEndpoint) .filter { $0.formFields["grant_type"] == "refresh_token" } } // MARK: - An answer that never arrives @Test("A refresh whose answer is lost on the way is asked for again with the same token", arguments: [ FakeAuthorizationServer.Flavor.reference, .tranquil, ]) func lostAnswer(flavor: FakeAuthorizationServer.Flavor) async throws { let (bench, login) = try await signedIn(flavor, proxied: true) // The server rotates the token, and the connection dies before the // answer is back: what a phone leaving Wi-Fi does to a request. let answersLost = Mutex(0) await bench.network.on(OAuthFixture.proxyToken) { [proxy = bench.proxy] request, _ in let response = await proxy.token(request) let isFirstSuccess = response.status == 200 && answersLost.withLock { lost in defer { lost += 1 } return lost == 0 } if isFirstSuccess { throw URLError(.networkConnectionLost) } return response } let refreshed = try #require( try await bench.makeOAuth(proxied: true).refreshLoginIfNeeded(accountIdentifier: nil, force: true) ) #expect(refreshed.refreshToken != login.refreshToken) #expect(refreshed.accessToken.value != login.accessToken.value) #expect(await bench.store.login == refreshed) // Every attempt offered the one token the app had. let sentTokens = Set(await refreshRequests(on: bench, proxied: true).compactMap { $0.jsonFields["refresh_token"] }) #expect(sentTokens == [try #require(login.refreshToken).value]) #expect(await bench.proxy.refreshAnswers.replayCount == 1) #expect(bench.retryDelays.all == [.milliseconds(500)]) // The session goes on: the stored token is the server's current one. #expect(try await bench.makeOAuth(proxied: true).refreshLoginIfNeeded(accountIdentifier: nil, force: true) != nil) } @Test("A refresh that never reached the server is simply made at the next attempt", arguments: [false, true]) func requestNeverArrived(proxied: Bool) async throws { let (bench, login) = try await signedIn(.tranquil, proxied: proxied) let url = proxied ? OAuthFixture.proxyToken : OAuthFixture.tokenEndpoint let failures = Mutex(0) await bench.network.on(url) { [bench] request, _ in let fails = failures.withLock { failed in defer { failed += 1 } return failed < 2 } if fails { throw URLError(.timedOut) } if proxied { return await bench.proxy.token(request) } return await bench.server.token(fields: request.formFields, proof: request.value(forHTTPHeaderField: "DPoP")) } let refreshed = try #require( try await bench.makeOAuth(proxied: proxied).refreshLoginIfNeeded(accountIdentifier: nil, force: true) ) #expect(refreshed.refreshToken != login.refreshToken) #expect(await bench.store.login == refreshed) #expect(bench.retryDelays.all == [.milliseconds(500), .seconds(2)]) } @Test("A refresh that keeps getting no answer gives up as the network error it is, and the session stays") func noAnswerAtAll() async throws { let (bench, login) = try await signedIn(.tranquil, proxied: true) await bench.network.on(OAuthFixture.proxyToken) { _, _ in throw URLError(.notConnectedToInternet) } await #expect(throws: URLError.self) { try await bench.makeOAuth(proxied: true).refreshLoginIfNeeded(accountIdentifier: nil, force: true) } #expect(await bench.store.login == login) #expect(await refreshRequests(on: bench, proxied: true).count == 3) #expect(bench.retryDelays.all == [.milliseconds(500), .seconds(2)]) } @Test("A proxy that can't say what the server answered is asked again") func proxyHiccup() async throws { let (bench, login) = try await signedIn(.tranquil, proxied: true) let outages = Mutex(0) await bench.network.on(OAuthFixture.proxyToken) { [proxy = bench.proxy] request, _ in let isDown = outages.withLock { seen in defer { seen += 1 } return seen == 0 } return isDown ? StubResponse(status: 502, text: "bad gateway") : await proxy.token(request) } let refreshed = try #require( try await bench.makeOAuth(proxied: true).refreshLoginIfNeeded(accountIdentifier: nil, force: true) ) #expect(refreshed.refreshToken != login.refreshToken) #expect(await bench.network.requests(to: OAuthFixture.tokenEndpoint).isEmpty) } @Test("The server's refusal is an answer: it is not asked twice") func refusalIsNotRetried() async throws { let (bench, login) = try await signedIn(.tranquil, proxied: true) try await bench.store.storage.storeLogin(Login( accessToken: login.accessToken, refreshToken: Token(value: "revoked"), issuingServer: login.issuingServer )) await #expect { try await bench.makeOAuth(proxied: true).refreshLoginIfNeeded(accountIdentifier: nil, force: true) } throws: { error in (error as? ATProtoOAuthError)?.endsSession == true } #expect(await refreshRequests(on: bench, proxied: true).count == 1) #expect(bench.retryDelays.all.isEmpty) } @Test("Without a proxy to keep the answer, a lost one ends the session, and the error says so") func lostAnswerWithoutProxy() async throws { let (bench, _) = try await signedIn(.tranquil, proxied: false) let answersLost = Mutex(0) await bench.network.on(OAuthFixture.tokenEndpoint) { [server = bench.server] request, _ in let response = await server.token(fields: request.formFields, proof: request.value(forHTTPHeaderField: "DPoP")) let isFirstSuccess = response.status == 200 && answersLost.withLock { lost in defer { lost += 1 } return lost == 0 } if isFirstSuccess { throw URLError(.networkConnectionLost) } return response } await #expect { try await bench.makeOAuth(proxied: false).refreshLoginIfNeeded(accountIdentifier: nil, force: true) } throws: { error in (error as? ATProtoOAuthError)?.tokenEndpointErrorCode == "invalid_grant" } } // MARK: - More than one caller @Test("Two refreshes of one session at the same time are one exchange") func concurrentRefreshes() async throws { // No proxy, so nothing but the client keeps a second request from // reaching the server as a replay. let (bench, login) = try await signedIn(.tranquil, proxied: false) let answerMayLeave = Latch() await bench.network.on(OAuthFixture.tokenEndpoint) { [server = bench.server] request, _ in await answerMayLeave.wait() return await server.token(fields: request.formFields, proof: request.value(forHTTPHeaderField: "DPoP")) } let first = await bench.makeOAuth(proxied: false) let second = await bench.makeOAuth(proxied: false) async let firstLogin = first.refreshLoginIfNeeded(accountIdentifier: nil, force: true) async let secondLogin = second.refreshLoginIfNeeded(accountIdentifier: nil, force: true) try await Task.sleep(for: .milliseconds(100)) await answerMayLeave.open() let logins = try await [firstLogin, secondLogin] #expect(logins[0] != nil) #expect(logins[0] == logins[1]) #expect(logins[0]?.refreshToken != login.refreshToken) #expect(await refreshRequests(on: bench, proxied: false).count == 1) #expect(await bench.store.storedLogins.count == 2, "one sign-in, one refresh") } @Test("A caller whose turn comes after the session was refreshed takes what is stored") func alreadyRefreshed() async throws { let (bench, login) = try await signedIn(.tranquil, proxied: false) let refreshed = Login( accessToken: Token(value: "access-newer", expiresIn: 300), refreshToken: Token(value: "refresh-newer"), scopes: login.scopes, issuingServer: login.issuingServer ) // The caller reads the session, and by the time its exchange would // start somebody else has stored the next one. let reads = Mutex(0) let base = bench.store.storage let storage = ATProtoAuthStorage( retrieveLogin: { let isFirstRead = reads.withLock { count in defer { count += 1 } return count == 0 } return isFirstRead ? login : refreshed }, storeLogin: base.storeLogin, retrievePrivateKey: base.retrievePrivateKey, storePrivateKey: base.storePrivateKey ) let result = try await bench.makeOAuth(proxied: false, storage: storage) .refreshLoginIfNeeded(accountIdentifier: nil, force: true) #expect(result == refreshed) #expect(await refreshRequests(on: bench, proxied: false).isEmpty) } @Test("A caller whose turn comes after signing out refreshes nothing") func signedOutMeanwhile() async throws { let (bench, login) = try await signedIn(.tranquil, proxied: false) let reads = Mutex(0) let base = bench.store.storage let storage = ATProtoAuthStorage( retrieveLogin: { let isFirstRead = reads.withLock { count in defer { count += 1 } return count == 0 } return isFirstRead ? login : nil }, storeLogin: base.storeLogin, retrievePrivateKey: base.retrievePrivateKey, storePrivateKey: base.storePrivateKey ) let result = try await bench.makeOAuth(proxied: false, storage: storage) .refreshLoginIfNeeded(accountIdentifier: nil, force: true) #expect(result == nil) #expect(await refreshRequests(on: bench, proxied: false).isEmpty) #expect(await bench.store.storedLogins.count == 1, "nothing stored after the sign-in") } // MARK: - A caller that stops waiting @Test("Cancelling the caller does not cut the exchange short: the new tokens are stored") func cancelledCaller() async throws { let (bench, login) = try await signedIn(.tranquil, proxied: true) let serverAnswered = Latch() let answerMayLeave = Latch() await bench.network.on(OAuthFixture.proxyToken) { [proxy = bench.proxy] request, _ in let response = await proxy.token(request) await serverAnswered.open() await answerMayLeave.wait() // What URLSession does to the request of a cancelled task. if Task.isCancelled { throw URLError(.cancelled) } return response } let oauth = await bench.makeOAuth(proxied: true) let caller = Task { try await oauth.refreshLoginIfNeeded(accountIdentifier: nil, force: true) } await serverAnswered.wait() caller.cancel() await answerMayLeave.open() _ = await caller.result let stored = try #require(await bench.store.login) #expect(stored.refreshToken != login.refreshToken) // And the stored token is good for the next refresh. await bench.network.on(OAuthFixture.proxyToken) { [proxy = bench.proxy] request, _ in await proxy.token(request) } #expect(try await bench.makeOAuth(proxied: true).refreshLoginIfNeeded(accountIdentifier: nil, force: true) != nil) } } @Suite("What a failed refresh says about the session") struct RefreshFailureTests { @Test("Only a refused grant, or a stored session with a part missing, ends the session", arguments: [ (ATProtoOAuthError.tokenRequestFailed("invalid_grant: Refresh token replayed"), true), (.tokenRequestFailed("invalid_grant: "), true), (.refreshTokenUnavailable, true), (.refreshKeyUnavailable, true), (.refreshIssuerUnavailable, true), // The server could not fetch the client's metadata or keys just now. (.tokenRequestFailed("invalid_client_metadata: Unable to obtain jwks from \"https://auth.example/jwks.json\""), false), (.tokenRequestFailed("invalid_client: Client authentication failed"), false), (.tokenRequestFailed("unauthorized_client: "), false), (.tokenRequestFailed("invalid_dpop_proof: iat is too far in the past"), false), (.tokenRequestFailed("use_dpop_nonce: Authorization server requires nonce in DPoP proof"), false), (.tokenRequestFailed("invalid_request: token_endpoint does not match issuer metadata"), false), (.tokenRequestFailed("too_many_requests: rate limit exceeded"), false), (.tokenRequestFailed("server_error: invalid_grant may follow"), false), (.tokenRequestFailed("HTTP 503"), false), (.invalidTokenResponse, false), (.authenticationFailed("Authorization server issuer is not valid for resolved PDS."), false), (.subjectMismatch(expected: "did:plc:alice", actual: "did:plc:mallory"), false), ]) func endsSession(error: ATProtoOAuthError, expected: Bool) { #expect(error.endsSession == expected) } @Test("The token endpoint's error code is read off the front of the detail", arguments: [ (ATProtoOAuthError.tokenRequestFailed("invalid_grant: Refresh token replayed"), "invalid_grant" as String?), (.tokenRequestFailed("invalid_client_metadata: Unable to obtain jwks"), "invalid_client_metadata"), (.tokenRequestFailed("invalid_grant: "), "invalid_grant"), (.tokenRequestFailed("HTTP 503"), nil), (.tokenRequestFailed("not a code: something"), nil), (.tokenRequestFailed(": nothing"), nil), (.authenticationFailed("invalid_grant: said elsewhere"), nil), (.refreshTokenUnavailable, nil), ]) func errorCode(error: ATProtoOAuthError, expected: String?) { #expect(error.tokenEndpointErrorCode == expected) } @Test("Losing the connection, or the proxy, leaves the answer unknown; a refusal does not", arguments: [ (URLError(.networkConnectionLost) as any Error, true), (URLError(.timedOut), true), (URLError(.notConnectedToInternet), true), (URLError(.cannotConnectToHost), true), (AuthProxyError.unavailable(requestKind: .refresh, detail: "Proxy returned HTTP 502"), true), (URLError(.cancelled), false), (URLError(.badURL), false), (ATProtoOAuthError.tokenRequestFailed("invalid_grant: Refresh token replayed"), false), (ATProtoOAuthError.invalidTokenResponse, false), (CancellationError(), false), ]) func answerUnknown(error: any Error, expected: Bool) { #expect(LostAnswerRetry.leavesAnswerUnknown(error) == expected) } @Test("Work run without suspension gives back what it returns and throws what it throws") func withoutSuspensionPassesThrough() async throws { struct Failure: Error {} #expect(await withoutSuspension(reason: "test") { 7 } == 7) await #expect(throws: Failure.self) { try await withoutSuspension(reason: "test") { throw Failure() } } } } /// Holds its waiters until it is opened, and lets everyone through after. actor Latch { private var isOpen = false private var waiters: [CheckedContinuation] = [] func open() { isOpen = true for waiter in waiters { waiter.resume() } waiters = [] } func wait() async { guard !isOpen else { return } await withCheckedContinuation { waiters.append($0) } } }