import Foundation import XCTest @testable import OldFella extension ATProtoServiceTests { func testAuthorFeedPreservesReplyContextAndRepostAuthor() async throws { let configuration = URLSessionConfiguration.ephemeral configuration.protocolClasses = [StubURLProtocol.self] let session = URLSession(configuration: configuration) let repostReason = repostFixture let body: [String: Any] = [ "feed": [ [ "post": replyFixturePost("reply"), "reply": [ "root": replyFixturePost("root"), "parent": replyFixturePost("parent"), "grandparentAuthor": [ "did": "did:plc:grandparent", "handle": "grandparent.example", "viewer": ["following": "at://did:plc:reader/app.bsky.graph.follow/grandparent"] ] ] ], ["post": replyFixturePost("repost"), "reason": repostReason], [ "post": replyFixturePost( "quote", embed: [ "$type": "app.bsky.embed.record#view", "record": ["uri": "quoted", "cid": "quoted-cid"] ]) ] ] ] let data = try JSONSerialization.data(withJSONObject: body) StubURLProtocol.handler = { _ in (200, data) } defer { StubURLProtocol.handler = nil session.invalidateAndCancel() } let service = ATProtoBlueskyService(defaults: .standard, session: session) let page = try await service.loadAuthorPosts(actorID: "did:plc:reposter", cursor: nil) XCTAssertEqual(page.posts.map(\.id), ["reply", "repost", "quote"]) XCTAssertEqual(page.replyContexts["reply"]?.map(\.id), ["root", "parent"]) XCTAssertEqual(page.posts.first?.replyGrandparentAuthor?.id, "did:plc:grandparent") XCTAssertEqual(page.posts.first?.replyGrandparentAuthor?.isFollowing, true) XCTAssertEqual(page.repostedBy["repost"]?.id, "did:plc:reposter") XCTAssertEqual(page.repostedBy["repost"]?.name, "Reposter") XCTAssertEqual(page.repostedBy["repost"]?.avatarURL?.absoluteString, "https://cdn.example.test/reposter.jpg") XCTAssertNil(page.repostedBy["quote"]) } func testAuthorFeedReturnsAndSendsCursor() async throws { let configuration = URLSessionConfiguration.ephemeral configuration.protocolClasses = [StubURLProtocol.self] let session = URLSession(configuration: configuration) StubURLProtocol.clearRequests() StubURLProtocol.handler = { _ in (200, Data("{\"feed\":[],\"cursor\":\"author-next\"}".utf8)) } defer { StubURLProtocol.handler = nil session.invalidateAndCancel() } let service = ATProtoBlueskyService(defaults: .standard, session: session) let firstPage = try await service.loadAuthorPosts(actorID: "did:plc:author", cursor: nil) let secondPage = try await service.loadAuthorPosts(actorID: "did:plc:author", cursor: firstPage.cursor) XCTAssertEqual(firstPage.cursor, "author-next") XCTAssertEqual(secondPage.cursor, "author-next") let requests = StubURLProtocol.recordedRequests.filter { $0.url?.path == "/xrpc/app.bsky.feed.getAuthorFeed" } XCTAssertEqual(requests.count, 2) let firstQuery = URLComponents(url: try XCTUnwrap(requests[0].url), resolvingAgainstBaseURL: false)?.queryItems let secondQuery = URLComponents(url: try XCTUnwrap(requests[1].url), resolvingAgainstBaseURL: false)?.queryItems XCTAssertNil(firstQuery?.first(where: { $0.name == "cursor" })) XCTAssertEqual(firstQuery?.first(where: { $0.name == "limit" })?.value, "70") XCTAssertEqual(secondQuery?.first(where: { $0.name == "limit" })?.value, "70") XCTAssertEqual(secondQuery?.first(where: { $0.name == "cursor" })?.value, "author-next") } func testExpiredAccessTokenRefreshUsesRefreshTokenAuthorization() async throws { let suiteName = "OldFellaRefreshTests.\(UUID().uuidString)" let defaults = try XCTUnwrap(UserDefaults(suiteName: suiteName)) let configuration = URLSessionConfiguration.ephemeral configuration.protocolClasses = [StubURLProtocol.self] let session = URLSession(configuration: configuration) let expiredPayload = Data("{\"exp\":1}".utf8).base64EncodedString() .replacingOccurrences(of: "+", with: "-") .replacingOccurrences(of: "/", with: "_") .replacingOccurrences(of: "=", with: "") let expiredToken = "header.\(expiredPayload).signature" let futureExpiry = Int(Date().addingTimeInterval(3600).timeIntervalSince1970) let futurePayload = Data("{\"exp\":\(futureExpiry)}".utf8).base64EncodedString() .replacingOccurrences(of: "+", with: "-") .replacingOccurrences(of: "/", with: "_") .replacingOccurrences(of: "=", with: "") let accessToken = "header.\(futurePayload).signature" StubURLProtocol.clearRequests() StubURLProtocol.handler = { request in try self.expiredTokenResponse(request, expiredToken: expiredToken, accessToken: accessToken) } defer { StubURLProtocol.handler = nil session.invalidateAndCancel() defaults.removePersistentDomain(forName: suiteName) } let service = ATProtoBlueskyService(defaults: defaults, session: session) _ = try await service.signIn(handle: "refresh.example", appPassword: "test-password", authFactorToken: nil) let profile = try await service.loadProfile(actorID: "did:plc:refresh") XCTAssertEqual(profile?.author.id, "did:plc:refresh") XCTAssertEqual( StubURLProtocol.recordedRequests.filter { $0.url?.path == "/xrpc/com.atproto.server.refreshSession" }.count, 1) try await service.signOut() } private func expiredTokenResponse(_ request: URLRequest, expiredToken: String, accessToken: String) throws -> ( Int, Data ) { switch request.url?.path { case "/xrpc/com.atproto.identity.resolveHandle": return (200, Data("{\"did\":\"did:plc:refresh\"}".utf8)) case "/did:plc:refresh": return ( 200, Data( ("{\"id\":\"did:plc:refresh\",\"service\":[{\"id\":\"#atproto_pds\"," + "\"type\":\"AtprotoPersonalDataServer\"," + "\"serviceEndpoint\":\"https://refresh-pds.example.test\"}]}") .utf8) ) case "/xrpc/com.atproto.server.createSession": return ( 200, Data( ("{\"handle\":\"refresh.example\",\"did\":\"did:plc:refresh\"," + "\"accessJwt\":\"\(expiredToken)\",\"refreshJwt\":\"refresh-token-secret\"}") .utf8) ) case "/xrpc/com.atproto.server.refreshSession": XCTAssertEqual(request.url?.host, "refresh-pds.example.test") XCTAssertEqual(request.httpMethod, "POST") XCTAssertNil(request.value(forHTTPHeaderField: "atproto-proxy")) XCTAssertEqual(request.value(forHTTPHeaderField: "Authorization"), "Bearer refresh-token-secret") XCTAssertNil(request.httpBody) return ( 200, Data( ("{\"accessJwt\":\"\(accessToken)\",\"refreshJwt\":\"new-refresh-token\"," + "\"handle\":\"refresh.example\",\"did\":\"did:plc:refresh\"}") .utf8) ) case "/xrpc/app.bsky.actor.getProfile": XCTAssertEqual(request.value(forHTTPHeaderField: "Authorization"), "Bearer \(accessToken)") return (200, Data("{\"did\":\"did:plc:refresh\",\"handle\":\"refresh.example\"}".utf8)) default: return (404, Data("{\"error\":\"NotFound\"}".utf8)) } } private var repostFixture: [String: Any] { [ "$type": "app.bsky.feed.defs#reasonRepost", "indexedAt": "2024-05-06T12:34:56.123Z", "by": [ "did": "did:plc:reposter", "handle": "reposter.example", "displayName": "Reposter", "avatar": "https://cdn.example.test/reposter.jpg" ] ] } private func replyFixturePost(_ id: String, embed: [String: Any]? = nil) -> [String: Any] { let author: [String: Any] = ["did": "did:plc:author", "handle": "author.example"] var value: [String: Any] = [ "uri": id, "cid": "cid", "author": author, "record": ["text": id], "indexedAt": "2024-05-06T12:34:56.123Z" ] value["embed"] = embed return value } }