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
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
}
}