import Foundation import Testing @testable import CoreATProtocol @Suite("TokenValidator") struct TokenValidatorTests { @Test("Valid response: DPoP token type, atproto scope, matching subject — no throw") func successPath() throws { let response = makeResponse() let validator = TokenValidator(expectedSubjectDID: "did:plc:abc") #expect(throws: Never.self) { try validator.validate(response) } } @Test("Wrong token type throws ATProtoOAuthError.invalidTokenResponse") func wrongTokenType() { let response = makeResponse(tokenType: "Bearer") let validator = TokenValidator(expectedSubjectDID: nil) #expect { try validator.validate(response) } throws: { error in guard case .invalidTokenResponse = error as? ATProtoOAuthError else { return false } return true } } @Test("Token type is matched without regard to case") func tokenTypeIsCaseInsensitive() throws { let response = makeResponse(tokenType: "dpop") let validator = TokenValidator(expectedSubjectDID: nil) #expect(throws: Never.self) { try validator.validate(response) } } @Test("Missing atproto scope throws ATProtoOAuthError.missingRequiredScope") func missingAtprotoScope() { let response = makeResponse(scope: "transition:generic") let validator = TokenValidator(expectedSubjectDID: nil) #expect(throws: ATProtoOAuthError.self) { try validator.validate(response) } } @Test("Subject mismatch when expected DID is set throws ATProtoOAuthError.subjectMismatch") func subjectMismatch() { let response = makeResponse(subject: "did:plc:wrong") let validator = TokenValidator(expectedSubjectDID: "did:plc:abc") #expect(throws: ATProtoOAuthError.self) { try validator.validate(response) } } @Test("Subject is not checked when expected DID is nil") func subjectIgnoredWhenExpectedNil() throws { let response = makeResponse(subject: "did:plc:anything") let validator = TokenValidator(expectedSubjectDID: nil) #expect(throws: Never.self) { try validator.validate(response) } } @Test("Multi-scope response containing atproto passes") func multiScopeWithAtprotoPasses() throws { let response = makeResponse(scope: "atproto transition:generic transition:chat.bsky") let validator = TokenValidator(expectedSubjectDID: nil) #expect(throws: Never.self) { try validator.validate(response) } } private func makeResponse( accessToken: String = "access-token", refreshToken: String? = "refresh-token", subject: String = "did:plc:abc", scope: String = "atproto transition:generic", tokenType: String = "DPoP", expiresIn: Int = 3600 ) -> OAuthTokenResponse { OAuthTokenResponse( accessToken: accessToken, refreshToken: refreshToken, subject: subject, scope: scope, tokenType: tokenType, expiresIn: expiresIn ) } }