import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif import Testing import NetworkingKit @testable import CoreATProtocol @Suite("DPoP nonce challenge detection") struct NonceDetectionTests { /// Builds an HTTPURLResponse that carries a `DPoP-Nonce` header. private func responseWithNonce(_ nonce: String?) throws -> HTTPURLResponse { var headers: [String: String] = [:] if let nonce { headers["DPoP-Nonce"] = nonce } return try #require( HTTPURLResponse( url: URL(string: "https://pds.example/xrpc/com.atproto.repo.getRecord")!, statusCode: 401, httpVersion: "HTTP/1.1", headerFields: headers ) ) } private func nonceChallengeBody() throws -> Data { try JSONSerialization.data(withJSONObject: [ "error": "use_dpop_nonce", "error_description": "use the provided nonce", ]) } private func unrelatedErrorBody() throws -> Data { try JSONSerialization.data(withJSONObject: [ "error": "invalid_token", "error_description": "token is expired", ]) } @Test("Well-formed nonce body with header -> retry requested") func bodyAndHeader() async throws { let delegate = APRouterDelegate() let response = try responseWithNonce("fresh-nonce-1") await delegate.didReceiveErrorResponse(response) let body = try nonceChallengeBody() let error = NetworkError.statusCode( StatusCode(rawValue: 401), data: body, request: nil ) let shouldRetry = try await delegate.shouldRetry(error: error, attempts: 1) #expect(shouldRetry == true) } @Test("Nonce header present but body is malformed -> retry still requested") func malformedBodyFallsBackToHeader() async throws { let delegate = APRouterDelegate() let response = try responseWithNonce("fresh-nonce-2") await delegate.didReceiveErrorResponse(response) let malformed = "broken".data(using: .utf8)! let error = NetworkError.statusCode( StatusCode(rawValue: 401), data: malformed, request: nil ) let shouldRetry = try await delegate.shouldRetry(error: error, attempts: 1) #expect(shouldRetry == true) } @Test("Unrelated 401 (no nonce header, no nonce body) does not retry as nonce") func unrelatedErrorDoesNotLookLikeNonceChallenge() async throws { let delegate = APRouterDelegate() // Response without a DPoP-Nonce header, so header fallback is false. let response = try #require( HTTPURLResponse( url: URL(string: "https://pds.example")!, statusCode: 401, httpVersion: "HTTP/1.1", headerFields: [:] ) ) await delegate.didReceiveErrorResponse(response) let body = try unrelatedErrorBody() let error = NetworkError.statusCode( StatusCode(rawValue: 401), data: body, request: nil ) // First-attempt 401 without a refresh handler falls through to false. // We can't easily assert isDPoPNonceError=false directly without exposing // it, but we can at least ensure shouldRetry returns false when no refresh // handler is registered — which is the production-correct behaviour. await ATProtoSession.shared.reset() let shouldRetry = try await delegate.shouldRetry(error: error, attempts: 1) #expect(shouldRetry == false) } @Test("Nonce detection clears across responses so stale flag doesn't carry over") func flagClearsWhenHeaderAbsent() async throws { let delegate = APRouterDelegate() // First response has a nonce header -> flag set. let withHeader = try responseWithNonce("n1") await delegate.didReceiveErrorResponse(withHeader) // Second response without the header -> flag cleared. let withoutHeader = try #require( HTTPURLResponse( url: URL(string: "https://pds.example")!, statusCode: 500, httpVersion: nil, headerFields: [:] ) ) await delegate.didReceiveErrorResponse(withoutHeader) // A malformed-body 401 that follows should NOT be treated as a nonce // challenge because the most recent response had no header. let malformed = Data("garbage".utf8) let error = NetworkError.statusCode( StatusCode(rawValue: 401), data: malformed, request: nil ) await ATProtoSession.shared.reset() let shouldRetry = try await delegate.shouldRetry(error: error, attempts: 1) #expect(shouldRetry == false) } }