Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303import Foundationimport Testingimport JWTKit@testable import CoreATProtocol
@Suite("DPoPProofSigner")struct DPoPProofSignerTests { @Test("Sign emits a dpop+jwt header with embedded JWK") func dpopJwtType() async throws { let signer = await makeSigner() let url = try #require(URL(string: "https://pds.example/xrpc/foo"))
let jwt = try await signer.sign(.init( httpMethod: "POST", url: url, accessToken: "tok" ))
let header = try decodeJWTHeader(jwt) #expect(header["typ"] as? String == "dpop+jwt") #expect(header["alg"] as? String == "ES256")
let jwk = try #require(header["jwk"] as? [String: Any]) #expect(jwk["kty"] as? String == "EC") #expect(jwk["crv"] as? String == "P-256") #expect((jwk["x"] as? String)?.isEmpty == false) #expect((jwk["y"] as? String)?.isEmpty == false) }
@Test("htu strips query string and fragment") func htuStripsQueryAndFragment() async throws { let signer = await makeSigner() let url = try #require(URL(string: "https://pds.example/xrpc/foo?bar=baz#frag"))
let jwt = try await signer.sign(.init(httpMethod: "POST", url: url))
let payload = try decodeJWTPayload(jwt) #expect(payload["htu"] as? String == "https://pds.example/xrpc/foo") #expect(payload["htm"] as? String == "POST") }
@Test("ath claim is present only when an access token is supplied") func athPresentOnlyWhenAccessTokenProvided() async throws { let signer = await makeSigner() let url = try #require(URL(string: "https://pds.example/xrpc/foo"))
let withToken = try await signer.sign(.init( httpMethod: "GET", url: url, accessToken: "abc" )) #expect(try decodeJWTPayload(withToken)["ath"] as? String != nil)
let withoutToken = try await signer.sign(.init(httpMethod: "GET", url: url)) #expect(try decodeJWTPayload(withoutToken)["ath"] == nil) }
@Test("Nonce cache is keyed per origin") func nonceCachedPerOrigin() async throws { let signer = await makeSigner() let pds = try #require(URL(string: "https://pds.example/xrpc/foo")) let auth = try #require(URL(string: "https://auth.example/oauth/token"))
await signer.cacheNonce("pds-nonce", from: pds) await signer.cacheNonce("auth-nonce", from: auth)
let pdsJWT = try await signer.sign(.init(httpMethod: "POST", url: pds)) let authJWT = try await signer.sign(.init(httpMethod: "POST", url: auth))
#expect(try decodeJWTPayload(pdsJWT)["nonce"] as? String == "pds-nonce") #expect(try decodeJWTPayload(authJWT)["nonce"] as? String == "auth-nonce") }
@Test("Nonce cache stays bounded under heavy origin churn") func nonceCacheBounded() async throws { let signer = await makeSigner() let totalInsertions = 30 let cacheLimit = 25
for i in 0..<totalInsertions { let url = try #require(URL(string: "https://host\(i).example/foo")) await signer.cacheNonce("nonce-\(i)", from: url) }
// Eviction policy is bounded growth, not LRU — we cannot predict // *which* origins were evicted, but the cache size is invariant. var cachedCount = 0 for i in 0..<totalInsertions { let url = try #require(URL(string: "https://host\(i).example/foo")) let jwt = try await signer.sign(.init(httpMethod: "POST", url: url)) if try decodeJWTPayload(jwt)["nonce"] != nil { cachedCount += 1 } } #expect(cachedCount == cacheLimit)
// The most recent insertion is always retained — its eviction step // runs before its own insertion, so it cannot evict itself. let recent = try #require(URL(string: "https://host\(totalInsertions - 1).example/foo")) let recentJWT = try await signer.sign(.init(httpMethod: "POST", url: recent)) #expect(try decodeJWTPayload(recentJWT)["nonce"] as? String == "nonce-\(totalInsertions - 1)") }
@Test("iat respects observed clock skew") func iatRespectsClockSkew() async throws { let clock = ClockSkewStore(offset: 600) let signer = await DPoPProofSigner( privateKey: ES256PrivateKey(), clockSkew: clock ) let url = try #require(URL(string: "https://pds.example/foo"))
let beforeSign = Date.now let jwt = try await signer.sign(.init(httpMethod: "GET", url: url)) let afterSign = Date.now
let iat = try await DPoPProofReader.verifiedClaims(of: jwt).iat
// Whole seconds, rounded down from the skew-adjusted clock. #expect(iat >= Int(beforeSign.timeIntervalSince1970.rounded(.down)) + 600) #expect(iat <= Int(afterSign.timeIntervalSince1970.rounded(.down)) + 600) }
@Test("iat goes over the wire as a whole number of seconds") func iatIsAnIntegerOnTheWire() async throws { let signer = await makeSigner() let url = try #require(URL(string: "https://pds.example/oauth/token"))
// A fraction would only show up some of the time if the clock happened // to land on a whole second, so sign more than once. for _ in 0..<5 { let jwt = try await signer.sign(.init(httpMethod: "POST", url: url)) let payload = try DPoPProofReader.payloadJSON(of: jwt)
#expect(payload.contains(/"iat":\d+[,}]/), "iat is not an integer in \(payload)") } }
@Test("A server that reads iat into an integer accepts the proof") func strictServerAcceptsProof() async throws { let signer = await makeSigner() let url = try #require(URL(string: "https://pds.example/oauth/token?unused=1"))
let jwt = try await signer.sign(.init(httpMethod: "POST", url: url, accessToken: "token"))
// Decoding `iat` as `Int` fails on a fractional number, which is what // such a server reports as an invalid payload. let claims = try await DPoPProofReader.verifiedClaims(of: jwt) #expect(claims.htm == "POST") #expect(claims.htu == "https://pds.example/oauth/token") #expect(!claims.jti.isEmpty) #expect(claims.ath == DPoPProofSigner.athClaim(for: "token")) }
@Test("numericDate drops the fraction instead of rounding up") func numericDateRoundsDown() { #expect(DPoPProofSigner.numericDate(Date(timeIntervalSince1970: 1_700_000_000.999)) == 1_700_000_000) #expect(DPoPProofSigner.numericDate(Date(timeIntervalSince1970: 1_700_000_000)) == 1_700_000_000) #expect(DPoPProofSigner.numericDate(Date(timeIntervalSince1970: -0.5)) == -1) }
@Test("Each proof gets its own jti") func jtiIsUniquePerProof() async throws { let signer = await makeSigner() let url = try #require(URL(string: "https://pds.example/xrpc/foo"))
var identifiers: Set<String> = [] for _ in 0..<20 { let jwt = try await signer.sign(.init(httpMethod: "GET", url: url)) identifiers.insert(try await DPoPProofReader.verifiedClaims(of: jwt).jti) } #expect(identifiers.count == 20) }
@Test("A nonce older than the signer's lifetime is no longer sent") func nonceExpiresAfterLifetime() async throws { let clock = ManualClock() let signer = await DPoPProofSigner( privateKey: ES256PrivateKey(), clockSkew: ClockSkewStore(), nonceLifetime: .seconds(60), now: { clock.now } ) let url = try #require(URL(string: "https://auth.example/oauth/token")) await signer.cacheNonce("from-par", from: url)
clock.advance(by: .seconds(59)) let fresh = try await signer.sign(.init(httpMethod: "POST", url: url)) #expect(try await DPoPProofReader.verifiedClaims(of: fresh).nonce == "from-par")
clock.advance(by: .seconds(2)) let stale = try await signer.sign(.init(httpMethod: "POST", url: url)) #expect(try await DPoPProofReader.verifiedClaims(of: stale).nonce == nil)
// A nonce the server supplies afterwards starts a new lifetime. await signer.cacheNonce("from-token", from: url) let renewed = try await signer.sign(.init(httpMethod: "POST", url: url)) #expect(try await DPoPProofReader.verifiedClaims(of: renewed).nonce == "from-token") }
@Test("Without a lifetime a nonce is kept until the server replaces it") func nonceWithoutLifetimeIsKept() async throws { let clock = ManualClock() let signer = await DPoPProofSigner( privateKey: ES256PrivateKey(), clockSkew: ClockSkewStore(), nonceLifetime: nil, now: { clock.now } ) let url = try #require(URL(string: "https://pds.example/xrpc/foo")) await signer.cacheNonce("kept", from: url)
clock.advance(by: .seconds(3600)) let jwt = try await signer.sign(.init(httpMethod: "GET", url: url)) #expect(try await DPoPProofReader.verifiedClaims(of: jwt).nonce == "kept") }
@Test("Nonces are shared across a scheme's default port") func nonceSharedAcrossDefaultPort() async throws { let signer = await makeSigner() let implicit = try #require(URL(string: "https://pds.example/xrpc/foo")) let explicit = try #require(URL(string: "https://PDS.example:443/xrpc/bar"))
await signer.cacheNonce("same-origin", from: explicit)
let jwt = try await signer.sign(.init(httpMethod: "GET", url: implicit)) #expect(try await DPoPProofReader.verifiedClaims(of: jwt).nonce == "same-origin") }
@Test("Explicit nonce overrides any cached value for the URL's origin") func explicitNonceOverride() async throws { let signer = await makeSigner() let url = try #require(URL(string: "https://host.example/foo"))
await signer.cacheNonce("cached", from: url)
let withExplicit = try await signer.sign(.init( httpMethod: "POST", url: url, explicitNonce: "explicit" )) #expect(try decodeJWTPayload(withExplicit)["nonce"] as? String == "explicit")
let withoutExplicit = try await signer.sign(.init(httpMethod: "POST", url: url)) #expect(try decodeJWTPayload(withoutExplicit)["nonce"] as? String == "cached") }
@Test("clearNonces drops all cached values") func clearNoncesEmptiesCache() async throws { let signer = await makeSigner() let url = try #require(URL(string: "https://host.example/foo"))
await signer.cacheNonce("first", from: url) await signer.clearNonces()
let jwt = try await signer.sign(.init(httpMethod: "GET", url: url)) #expect(try decodeJWTPayload(jwt)["nonce"] == nil) }
private func makeSigner() async -> DPoPProofSigner { await DPoPProofSigner( privateKey: ES256PrivateKey(), clockSkew: ClockSkewStore() ) }}
// MARK: - JWT decoding helpers
private func decodeJWTHeader(_ jwt: String) throws -> [String: Any] { try decodeJWTSection(jwt, index: 0)}
private func decodeJWTPayload(_ jwt: String) throws -> [String: Any] { try decodeJWTSection(jwt, index: 1)}
private func decodeJWTSection(_ jwt: String, index: Int) throws -> [String: Any] { let parts = jwt.split(separator: ".", omittingEmptySubsequences: false) guard parts.count == 3, index < parts.count else { throw JWTTestError.malformedJWT } let data = try base64URLDecode(String(parts[index])) let object = try JSONSerialization.jsonObject(with: data) return object as? [String: Any] ?? [:]}
private func base64URLDecode(_ value: String) throws -> Data { var base64 = value .replacingOccurrences(of: "-", with: "+") .replacingOccurrences(of: "_", with: "/") let padding = (4 - base64.count % 4) % 4 base64 += String(repeating: "=", count: padding) guard let data = Data(base64Encoded: base64) else { throw JWTTestError.malformedJWT } return data}
private enum JWTTestError: Error { case malformedJWT}