~ knotless Search/
↑↓ move↵ open⇧↵ all results

geesawra.industries/old-fella

Old people's social media app

0
1
main
241 lines · 11.5 KB Raw History
import Foundation
import XCTest

@testable import OldFella

extension ATProtoServiceTests {
    func testLoadPostPreservesTextAndMapsOnlyValidFacets() async throws {
        let configuration = URLSessionConfiguration.ephemeral
        configuration.protocolClasses = [StubURLProtocol.self]
        let session = URLSession(configuration: configuration)
        StubURLProtocol.clearRequests()
        let uri = "at://did:plc:facet/app.bsky.feed.post/one"
        let text = "🌙 https://example.com @friend.example #sky and https://ordinary.example"
        let facets = facetFixture(text: text)
        let postObject: [String: Any] = [
            "uri": uri,
            "cid": "facet-cid",
            "author": ["did": "did:plc:author", "handle": "author.example"],
            "record": ["text": text, "facets": facets],
            "indexedAt": "2024-05-06T12:34:56.123Z"
        ]
        StubURLProtocol.handler = { request in
            XCTAssertEqual(request.url?.host, "public.api.bsky.app")
            XCTAssertNil(request.value(forHTTPHeaderField: "Authorization"))
            if request.url?.path == "/xrpc/app.bsky.unspecced.getPostThreadV2" {
                return (404, Data("{\"error\":\"MethodNotFound\"}".utf8))
            }
            let response = try JSONSerialization.data(withJSONObject: ["thread": ["post": postObject, "replies": []]])
            return (200, response)
        }
        defer {
            StubURLProtocol.handler = nil
            session.invalidateAndCancel()
        }

        let service = ATProtoBlueskyService(defaults: .standard, session: session)
        let loadedPosts = try await service.loadPost(uri: uri)
        let post = try XCTUnwrap(loadedPosts.first)
        XCTAssertEqual(post.text, text)
        XCTAssertEqual(post.facets.count, 4)
        XCTAssertEqual(
            post.facets.map(\.feature),
            [
                .link(URL(string: "https://example.com")!),
                .mention("did:plc:friend"),
                .tag("sky"),
                .link(URL(string: "https://ordinary.example")!)
            ])
        XCTAssertTrue(post.links.isEmpty)
    }

    func testThreadUsesValidNumbersFromV2WithoutChangingThePostOrder() async throws {
        let configuration = URLSessionConfiguration.ephemeral
        configuration.protocolClasses = [StubURLProtocol.self]
        let session = URLSession(configuration: configuration)
        let prefix = "at://did:plc:reader/app.bsky.feed.post/"
        func post(_ name: String) -> [String: Any] {
            [
                "uri": prefix + name, "cid": "\(name)-cid",
                "author": ["did": "did:plc:reader", "handle": "reader.example"],
                "record": ["text": name], "indexedAt": "2024-05-06T12:34:56Z"
            ]
        }
        func numbered(_ name: String, _ index: Int, hidden: Bool = false) -> [String: Any] {
            [
                "uri": prefix + name,
                "value": [
                    "post": post(name), "opThread": true, "hiddenByThreadgate": hidden,
                    "opThreadPostIndex": index, "opThreadPostCount": 2
                ]
            ]
        }
        StubURLProtocol.handler = { request in
            if request.url?.path == "/xrpc/app.bsky.unspecced.getPostThreadV2" {
                let query = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)?.queryItems
                XCTAssertEqual(query?.first { $0.name == "anchor" }?.value, prefix + "root")
                let items = [
                    numbered("root", 1), numbered("second", 2), numbered("side", 3),
                    numbered("hidden", 2, hidden: true), numbered("v2-only", 2)
                ]
                return (200, try JSONSerialization.data(withJSONObject: ["thread": items]))
            }
            let replies = ["side", "hidden", "second"].map { ["post": post($0)] }
            return (200, try JSONSerialization.data(withJSONObject: ["thread": ["post": post("root"), "replies": replies]]))
        }
        defer {
            StubURLProtocol.handler = nil
            session.invalidateAndCancel()
        }
        let service = ATProtoBlueskyService(defaults: .standard, session: session)
        let result = try await service.loadThread(uri: prefix + "root")
        XCTAssertEqual(result.posts.map(\.id), ["root", "side", "hidden", "second"].map { prefix + $0 })
        XCTAssertEqual(result.positions, [
            prefix + "root": ThreadPosition(index: 1, count: 2),
            prefix + "second": ThreadPosition(index: 2, count: 2)
        ].compactMapValues { $0 })
    }

    func testLoadPostResolvesHandleAuthorityButPreservesDIDAuthority() async throws {
        let configuration = URLSessionConfiguration.ephemeral
        configuration.protocolClasses = [StubURLProtocol.self]
        let session = URLSession(configuration: configuration)
        StubURLProtocol.clearRequests()
        let didURI = "at://did:plc:reader/app.bsky.feed.post/selected"
        let handleURI = "at://reader.bsky.social/app.bsky.feed.post/selected"
        let response = Data("{\"thread\":{}}".utf8)
        StubURLProtocol.handler = { request in
            if request.url?.path == "/xrpc/com.atproto.identity.resolveHandle" {
                return (200, Data("{\"did\":\"did:plc:reader\"}".utf8))
            }
            if request.url?.path == "/xrpc/app.bsky.feed.getPostThread" {
                let query = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)?.queryItems
                let requestedURI = query?.first(where: { $0.name == "uri" })?.value
                XCTAssertEqual(requestedURI, didURI)
                return (200, response)
            }
            return (404, Data("{\"error\":\"NotFound\"}".utf8))
        }
        defer {
            StubURLProtocol.handler = nil
            session.invalidateAndCancel()
        }

        let service = ATProtoBlueskyService(defaults: .standard, session: session)
        _ = try await service.loadPost(uri: handleURI)
        _ = try await service.loadPost(uri: didURI)
        XCTAssertEqual(
            StubURLProtocol.recordedRequests.filter { $0.url?.path == "/xrpc/com.atproto.identity.resolveHandle" }
                .count, 1)
    }

    func testPublicProfileRequestDoesNotUsePDSProxyOrAuthorization() async throws {
        let configuration = URLSessionConfiguration.ephemeral
        configuration.protocolClasses = [StubURLProtocol.self]
        let session = URLSession(configuration: configuration)
        StubURLProtocol.clearRequests()
        StubURLProtocol.handler = { request in
            XCTAssertEqual(request.url?.host, "public.api.bsky.app")
            XCTAssertNil(request.value(forHTTPHeaderField: "Authorization"))
            XCTAssertNil(request.value(forHTTPHeaderField: "atproto-proxy"))
            let profile: [String: Any] = [
                "did": "did:plc:public", "handle": "public.example",
                "links": [
                    [
                        "uri": "at://did:plc:public/app.bsky.actor.link/photos", "title": "My Photos!",
                        "url": "https://geesawra.github.io/crossgrain/did:plc:6ll5xi67lyuyovt6fiv4fnjo"
                    ],
                    [
                        "uri": "at://did:plc:public/app.bsky.actor.link/github", "title": "GitHub",
                        "url": "https://github.com/geesawra"
                    ],
                    ["uri": "empty-title", "title": "  ", "url": "https://example.com"],
                    ["uri": "unsafe", "url": "javascript:alert(1)"],
                    ["uri": "relative", "url": "/relative"],
                    [
                        "uri": "labelled", "title": "Labelled", "url": "https://example.org",
                        "labels": [["src": "did:plc:labeler", "val": "porn"]]
                    ]
                ]
            ]
            return (200, try JSONSerialization.data(withJSONObject: profile))
        }
        defer {
            StubURLProtocol.handler = nil
            session.invalidateAndCancel()
        }

        let service = ATProtoBlueskyService(defaults: .standard, session: session)
        let profile = try await service.loadProfile(actorID: "did:plc:public")
        XCTAssertEqual(profile?.author.id, "did:plc:public")
        XCTAssertEqual(profile?.links.map(\.title), ["My Photos!", "GitHub", "https://example.com", "Labelled"])
        XCTAssertEqual(profile?.links[1].url.absoluteString, "https://github.com/geesawra")
        XCTAssertEqual(profile?.links.last?.moderationLabels.first?.value, "porn")
    }

    func testProfileMapsBothFollowDirections() async throws {
        let configuration = URLSessionConfiguration.ephemeral
        configuration.protocolClasses = [StubURLProtocol.self]
        let session = URLSession(configuration: configuration)
        var viewer: [String: Any]?
        StubURLProtocol.handler = { request in
            XCTAssertEqual(request.url?.path, "/xrpc/app.bsky.actor.getProfile")
            var profile: [String: Any] = ["did": "did:plc:public", "handle": "public.example"]
            if let viewer { profile["viewer"] = viewer }
            return (200, try JSONSerialization.data(withJSONObject: profile))
        }
        defer {
            StubURLProtocol.handler = nil
            session.invalidateAndCancel()
        }

        let service = ATProtoBlueskyService(defaults: .standard, session: session)
        for following in [false, true] {
            for followedBy in [false, true] {
                viewer = [:]
                if following { viewer?["following"] = "at://did:plc:reader/app.bsky.graph.follow/one" }
                if followedBy { viewer?["followedBy"] = "at://did:plc:public/app.bsky.graph.follow/two" }
                let loadedProfile = try await service.loadProfile(actorID: "did:plc:public")
                let profile = try XCTUnwrap(loadedProfile)
                XCTAssertEqual(profile.isFollowing, following)
                XCTAssertEqual(profile.isFollowedBy, followedBy)
            }
        }
        viewer = nil
        let profile = try await service.loadProfile(actorID: "did:plc:public")
        XCTAssertEqual(profile?.isFollowedBy, false)
    }

    private func facetFixture(text: String) -> [[String: Any]] {
        let (linkStart, linkEnd) = byteRange(of: "https://example.com", in: text)
        let (mentionStart, mentionEnd) = byteRange(of: "@friend.example", in: text)
        let (tagStart, tagEnd) = byteRange(of: "#sky", in: text)
        let facets: [[String: Any]] = [
            [
                "index": ["byteStart": linkStart, "byteEnd": linkEnd],
                "features": [["$type": "app.bsky.richtext.facet#link", "uri": "https://example.com"]]
            ],
            [
                "index": ["byteStart": mentionStart, "byteEnd": mentionEnd],
                "features": [["$type": "app.bsky.richtext.facet#mention", "did": "did:plc:friend"]]
            ],
            [
                "index": ["byteStart": tagStart, "byteEnd": tagEnd],
                "features": [["$type": "app.bsky.richtext.facet#tag", "tag": "sky"]]
            ],
            [
                "index": ["byteStart": 1, "byteEnd": 2],
                "features": [["$type": "app.bsky.richtext.facet#tag", "tag": "invalid-boundary"]]
            ],
            [
                "index": ["byteStart": -1, "byteEnd": 2],
                "features": [["$type": "app.bsky.richtext.facet#tag", "tag": "negative"]]
            ],
            [
                "index": ["byteStart": 0, "byteEnd": 500],
                "features": [["$type": "app.bsky.richtext.facet#tag", "tag": "past-end"]]
            ]
        ]
        return facets
    }
}