import Foundation import XCTest @testable import OldFella extension ATProtoServiceTests { func testModerationRequestsAndFailure() async throws { let suite = "ModerationTests.\(UUID().uuidString)" let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) let configuration = URLSessionConfiguration.ephemeral configuration.protocolClasses = [StubURLProtocol.self] let session = URLSession(configuration: configuration) StubURLProtocol.clearRequests() let expiry = Int(Date().addingTimeInterval(3600).timeIntervalSince1970) let payload = Data("{\"exp\":\(expiry)}".utf8).base64EncodedString().replacingOccurrences(of: "=", with: "") let token = "header.\(payload).signature" var muteStatus = 200 StubURLProtocol.handler = { request in try self.moderationResponse(request, token: token, muteStatus: muteStatus) } defer { StubURLProtocol.handler = nil session.invalidateAndCancel() defaults.removePersistentDomain(forName: suite) } let service = ATProtoBlueskyService(defaults: defaults, session: session) _ = try await service.signIn(handle: "moderator.example", appPassword: "test-password", authFactorToken: nil) let state = try await service.moderationState(actorID: "did:plc:target") XCTAssertTrue(state.isMuted) XCTAssertTrue(state.isBlocked) try await service.setMuted(true, actorID: "did:plc:target") try await service.setMuted(false, actorID: "did:plc:target") for status in [499, 408, 429, 400] { muteStatus = status do { try await service.setMuted(true, actorID: "did:plc:target") XCTFail("Expected status \(status) to fail") } catch ModerationWriteError.rejected { XCTAssertEqual(status, 400) } catch { XCTAssertNotEqual(status, 400) } } let blockURI = try await service.setBlocked(true, actorID: "did:plc:target", blockURI: nil) XCTAssertEqual(blockURI, "at://did:plc:moderator/app.bsky.graph.block/key") _ = try await service.setBlocked(false, actorID: "did:plc:target", blockURI: blockURI) try await service.report(.account("did:plc:target"), reason: "com.atproto.moderation.defs#reasonSpam") do { try await service.report( .post(uri: "at://did:plc:target/app.bsky.feed.post/key", cid: "cid"), reason: "com.atproto.moderation.defs#reasonSpam") XCTFail("Expected the report to fail") } catch ModerationWriteError.rejected(let message) { XCTAssertEqual(message, "Report rejected") } try await service.signOut() } func testEmptyDisplayNamesFallBackToHandle() { XCTAssertEqual(Post.Author(id: "id", name: "", handle: "person.example").name, "person.example") XCTAssertEqual(Post.Author(id: "id", name: " \n", handle: "person.example").name, "person.example") XCTAssertEqual(Post.Author(id: "id", name: "Person", handle: "person.example").name, "Person") XCTAssertEqual(Account(handle: "person.example", displayName: "").displayName, "person.example") XCTAssertEqual(Account(handle: "person.example", displayName: " ").displayName, "person.example") } func byteRange(of value: String, in text: String) -> (Int, Int) { let range = text.range(of: value)! let start = range.lowerBound.samePosition(in: text.utf8)! let end = range.upperBound.samePosition(in: text.utf8)! return ( text.utf8.distance(from: text.utf8.startIndex, to: start), text.utf8.distance(from: text.utf8.startIndex, to: end) ) } func testMutedQuoteAndAncestorAreNotRestoredFromCachedContent() async throws { let configuration = URLSessionConfiguration.ephemeral configuration.protocolClasses = [StubURLProtocol.self] let session = URLSession(configuration: configuration) let selected = "at://did:plc:author/app.bsky.feed.post/selected" let quoted = "at://did:plc:muted/app.bsky.feed.post/quoted" func post(_ uri: String, muted: Bool = false) -> [String: Any] { [ "uri": uri, "cid": "cid", "author": ["did": "did:plc:author", "handle": "author.example", "viewer": ["muted": muted]], "record": ["text": "text"], "indexedAt": "2024-05-06T12:34:56.123Z" ] } var selectedPost = post(selected) selectedPost["embed"] = [ "$type": "app.bsky.embed.record#view", "record": [ "$type": "app.bsky.embed.record#viewRecord", "uri": quoted, "cid": "cid", "author": ["did": "did:plc:muted", "handle": "muted.example", "viewer": ["muted": true]], "value": ["text": "hidden"], "indexedAt": "2024-05-06T12:34:56.123Z" ] ] let grandparent = "at://did:plc:author/app.bsky.feed.post/grandparent" let parent = "at://did:plc:author/app.bsky.feed.post/parent" let thread: [String: Any] = [ "post": selectedPost, "parent": ["post": post(parent, muted: true), "parent": ["post": post(grandparent)]] ] StubURLProtocol.handler = { _ in (200, try JSONSerialization.data(withJSONObject: ["thread": thread])) } defer { StubURLProtocol.handler = nil session.invalidateAndCancel() } let service = ATProtoBlueskyService(defaults: .standard, session: session) let result = try await service.loadThread(uri: selected) XCTAssertEqual(result.posts.map(\.id), [grandparent, selected]) XCTAssertEqual(result.mutedPostIDs, [parent]) XCTAssertNil(result.posts.last?.quote) } private func moderationResponse(_ request: URLRequest, token: String, muteStatus: Int) throws -> (Int, Data) { if let response = try moderationResponseIdentity(request, token: token, muteStatus: muteStatus) { return response } return try moderationResponseAction(request, token: token, muteStatus: muteStatus) } private func moderationResponseIdentity(_ request: URLRequest, token: String, muteStatus: Int) throws -> ( Int, Data )? { switch request.url?.path { case "/xrpc/com.atproto.identity.resolveHandle": return (200, Data("{\"did\":\"did:plc:moderator\"}".utf8)) case "/did:plc:moderator": return ( 200, Data( ("{\"id\":\"did:plc:moderator\",\"service\":[{\"id\":\"#atproto_pds\"," + "\"type\":\"AtprotoPersonalDataServer\"," + "\"serviceEndpoint\":\"https://moderation-pds.example.test\"}]}") .utf8) ) case "/xrpc/com.atproto.server.createSession": return ( 200, Data( ("{\"handle\":\"moderator.example\",\"did\":\"did:plc:moderator\"," + "\"accessJwt\":\"\(token)\",\"refreshJwt\":\"refresh\"}") .utf8) ) case "/xrpc/app.bsky.actor.getProfile": return ( 200, Data( ("{\"did\":\"did:plc:moderator\",\"handle\":\"moderator.example\"," + "\"viewer\":{\"muted\":true," + "\"blocking\":\"at://did:plc:moderator/app.bsky.graph.block/key\"}}") .utf8) ) default: return nil } } private func moderationResponseAction(_ request: URLRequest, token: String, muteStatus: Int) throws -> (Int, Data) { switch request.url?.path { case "/xrpc/app.bsky.graph.muteActor", "/xrpc/app.bsky.graph.unmuteActor": XCTAssertEqual(request.value(forHTTPHeaderField: "atproto-proxy"), "did:web:api.bsky.app#bsky_appview") let body = try XCTUnwrap( JSONSerialization.jsonObject(with: StubURLProtocol.recordedBody(for: request.url!)!) as? [String: String]) XCTAssertEqual(body["actor"], "did:plc:target") return ( muteStatus, muteStatus == 200 ? Data() : Data("{\"error\":\"InvalidRequest\",\"message\":\"Rejected\"}".utf8) ) case "/xrpc/com.atproto.repo.createRecord": let body = try XCTUnwrap( JSONSerialization.jsonObject(with: StubURLProtocol.recordedBody(for: request.url!)!) as? [String: Any]) XCTAssertEqual(body["repo"] as? String, "did:plc:moderator") XCTAssertEqual(body["collection"] as? String, "app.bsky.graph.block") XCTAssertEqual((body["record"] as? [String: Any])?["subject"] as? String, "did:plc:target") return (200, Data("{\"uri\":\"at://did:plc:moderator/app.bsky.graph.block/key\",\"cid\":\"cid\"}".utf8)) case "/xrpc/com.atproto.repo.deleteRecord": let body = try XCTUnwrap( JSONSerialization.jsonObject(with: StubURLProtocol.recordedBody(for: request.url!)!) as? [String: String]) XCTAssertEqual(body["repo"], "did:plc:moderator") XCTAssertEqual(body["collection"], "app.bsky.graph.block") XCTAssertEqual(body["rkey"], "key") return (200, Data("{}".utf8)) case "/xrpc/com.atproto.moderation.createReport": return try moderationReportResponse(request) default: XCTFail("Unexpected request: \(request.url?.absoluteString ?? "nil")") return (404, Data("{\"error\":\"NotFound\"}".utf8)) } } private func moderationReportResponse(_ request: URLRequest) throws -> (Int, Data) { XCTAssertEqual( request.value(forHTTPHeaderField: "atproto-proxy"), "did:plc:ar7c4by46qjdydhdevvrndac#atproto_labeler") let body = try XCTUnwrap( JSONSerialization.jsonObject(with: StubURLProtocol.recordedBody(for: request.url!)!) as? [String: Any]) let subject = try XCTUnwrap(body["subject"] as? [String: String]) XCTAssertEqual(body["reasonType"] as? String, "com.atproto.moderation.defs#reasonSpam") if subject["did"] != nil { XCTAssertEqual(subject["$type"], "com.atproto.admin.defs#repoRef") XCTAssertEqual(subject["did"], "did:plc:target") return (200, Data("{}".utf8)) } XCTAssertEqual(subject["$type"], "com.atproto.repo.strongRef") XCTAssertEqual(subject["uri"], "at://did:plc:target/app.bsky.feed.post/key") XCTAssertEqual(subject["cid"], "cid") return (400, Data("{\"error\":\"InvalidRequest\",\"message\":\"Report rejected\"}".utf8)) } }