import Foundation import Testing import 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..= 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 = [] 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 }