1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
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))
}
}