Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135import Foundation#if canImport(FoundationNetworking)import FoundationNetworking#endifimport Testingimport 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 = "<html>broken</html>".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) }}