//// End-to-end wiring tests for the graph.followUser/unfollowUser handlers, //// plus the pure `graph_follows.find` lookup. import atproto/xrpc import atproto_core/xrpc as core_xrpc import crate/gen/graph/follow.{type GraphFollow, GraphFollow} import crate/storage.{type StoredItem, StoredItem} import crate_server/context.{type Context, Context} import crate_server/follow_index import crate_server/graph_follows import crate_server/handlers/graph import crate_server/oauth/config import crate_server/oauth/session_store import crate_server/oauth/sessions import gleam/bit_array import gleam/erlang/process import gleam/http import gleam/http/response import gleam/int import gleam/json import gleam/list import gleam/option.{None, Some} import gleam/string import support import wisp import wisp/simulate const target_did = "did:plc:target" const viewer_did = "did:plc:x" const session_cookie = "ar_oauth_sid" fn a_session() -> sessions.OauthSession { support.stub_session_with( access_token: "at", refresh_token: "rt", expires_at: 9_999_999_999, ) } fn follow_uri(rkey: String) -> String { "at://" <> viewer_did <> "/dev.mokkenstorm.crate.graph.follow/" <> rkey } fn stored_follow(rkey: String, subject: String) -> StoredItem(GraphFollow) { StoredItem( uri: follow_uri(rkey), cid: "bafy" <> rkey, rkey:, value: GraphFollow(created_at: "2026-01-01T00:00:00Z", subject:), ) } fn follow_record_json(rkey: String, subject: String) -> json.Json { json.object([ #("uri", json.string(follow_uri(rkey))), #("cid", json.string("bafy" <> rkey)), #( "value", json.object([ #("createdAt", json.string("2026-01-01T00:00:00Z")), #("subject", json.string(subject)), ]), ), ]) } fn list_records_body(records: List(json.Json)) -> String { json.object([#("records", json.preprocessed_array(records))]) |> json.to_string } fn create_record_response(rkey: String) -> String { json.object([ #("uri", json.string(follow_uri(rkey))), #("cid", json.string("bafy" <> rkey)), ]) |> json.to_string } fn ok_response( body: String, ) -> Result(response.Response(BitArray), xrpc.TransportError) { Ok(response.Response(200, [], bit_array.from_string(body))) } fn network_client(list_body: String, create_body: String) -> xrpc.Client { xrpc.Client(send: fn(req) { case req.path { "/xrpc/com.atproto.repo.listRecords" -> ok_response(list_body) "/xrpc/com.atproto.repo.putRecord" -> ok_response(create_body) "/xrpc/com.atproto.repo.deleteRecord" -> ok_response("{}") _ -> panic as { "unexpected path: " <> req.path } } }) } fn forbidden_client(error_code: String) -> xrpc.Client { xrpc.Client(send: fn(req) { case req.path { "/xrpc/com.atproto.repo.listRecords" -> ok_response(list_records_body([])) "/xrpc/com.atproto.repo.putRecord" -> Ok(response.Response( 403, [], bit_array.from_string("{\"error\":\"" <> error_code <> "\"}"), )) _ -> panic as { "unexpected path: " <> req.path } } }) } fn missing_scope_client() -> xrpc.Client { xrpc.Client(send: fn(req) { case req.path { "/xrpc/com.atproto.repo.listRecords" -> ok_response(list_records_body([])) "/xrpc/com.atproto.repo.putRecord" -> Ok(response.Response( 403, [], bit_array.from_string("{\"error\":\"InsufficientScope\"}"), )) _ -> panic as { "unexpected path: " <> req.path } } }) } // Panics on listRecords, so any lookup that reaches it failed to use the index. fn no_list_client() -> xrpc.Client { xrpc.Client(send: fn(req) { case req.path { "/xrpc/com.atproto.repo.deleteRecord" -> ok_response("{}") "/xrpc/com.atproto.repo.putRecord" -> ok_response(create_record_response("3ccc")) _ -> panic as { "unexpected PDS call: " <> req.path } } }) } fn no_create_client(list_body: String) -> xrpc.Client { xrpc.Client(send: fn(req) { case req.path { "/xrpc/com.atproto.repo.listRecords" -> ok_response(list_body) "/xrpc/com.atproto.repo.deleteRecord" -> ok_response("{}") "/xrpc/com.atproto.repo.createRecord" -> panic as "idempotent follow attempted a create" _ -> panic as { "unexpected PDS call: " <> req.path } } }) } fn partial_delete_failure_client() -> xrpc.Client { xrpc.Client(send: fn(req) { case req.path { "/xrpc/com.atproto.repo.deleteRecord" -> case bit_array.to_string(req.body) { Ok(body) -> case string.contains(body, "3bbb") { True -> Error(core_xrpc.ConnectionFailed("PDS unreachable for 3bbb")) False -> ok_response("{}") } Error(_) -> panic as "expected a decodable delete body" } _ -> panic as { "unexpected PDS call: " <> req.path } } }) } fn test_context( client: xrpc.Client, follows: follow_index.Store, ) -> #(Context, config.Config) { let cfg = support.stub_config(client) let ctx = Context( ..support.stub_context_with( cfg, support.unreachable_catalog_deps(), fn(_req) { Error("unused") }, [], ), follow_index: follows, ) #(ctx, cfg) } fn authed_post(path: String, cfg: config.Config) -> wisp.Request { let assert Ok(id) = session_store.create(cfg.sessions, a_session()) simulate.request(http.Post, support.xrpc(path)) |> simulate.json_body(json.object([#("subject", json.string(target_did))])) |> simulate.cookie(session_cookie, id, wisp.Signed) } fn call( handler: fn(wisp.Request, Context) -> wisp.Response, path: String, client: xrpc.Client, follows: follow_index.Store, ) -> wisp.Response { let #(ctx, cfg) = test_context(client, follows) handler(authed_post(path, cfg), ctx) } fn seeded_index(edges: List(#(String, String))) -> follow_index.Store { let follows = support.fresh_follow_index() list.each(edges, fn(edge) { let #(rkey, created_at) = edge follows.edges.upsert(follow_index.Follow( follow_uri: follow_uri(rkey), did: viewer_did, subject: target_did, created_at:, )) }) follows.seen.mark_seen(viewer_did) follows } pub fn find_locates_the_stored_follow_or_returns_none_test() { let stored = [ stored_follow("3aaa", "did:plc:other"), stored_follow("3bbb", target_did), ] let assert Some(found) = graph_follows.find(stored, target_did) assert found.rkey == "3bbb" assert graph_follows.find( [stored_follow("3aaa", "did:plc:other")], target_did, ) == None } pub fn follow_requires_authentication_test() { let #(ctx, _cfg) = test_context( network_client(list_records_body([]), ""), support.fresh_follow_index(), ) let req = simulate.request(http.Post, support.xrpc("graph.followUser")) |> simulate.json_body(json.object([#("subject", json.string(target_did))])) assert graph.follow(req, ctx).status == 401 } // A fresh follow writes a record; an existing one reuses the lowest-sorting // legacy rkey instead of creating a second. pub fn follow_returns_a_stable_record_uri_test() { [ #( network_client(list_records_body([]), create_record_response("3ccc")), "3ccc", ), #( no_create_client( list_records_body([ follow_record_json("3bbb", target_did), follow_record_json("3aaa", target_did), ]), ), "3aaa", ), ] |> list.each(fn(row) { let #(client, rkey) = row let resp = call( graph.follow, "graph.followUser", client, support.fresh_follow_index(), ) assert resp.status == 200 assert support.field_string(simulate.read_body(resp), ["uri"]) == Ok(follow_uri(rkey)) }) } pub fn follow_scope_failure_is_exposed_as_a_reauthorization_signal_test() { let resp = call( graph.follow, "graph.followUser", missing_scope_client(), support.fresh_follow_index(), ) assert resp.status == 403 let body = simulate.read_body(resp) assert support.field_string(body, ["error"]) == Ok("InsufficientScope") assert support.field_string(body, ["message"]) == Ok( "your session needs permission to follow collectors; sign in again to approve it", ) } /// A suspended or taken-down account is a PDS 403 too. Answering it with the /// reauthorization prompt sends the user round a loop that cannot help them. pub fn a_non_scope_pds_403_is_an_upstream_failure_not_a_scope_prompt_test() { ["AccountTakedown", "AccountDeactivated", "Forbidden"] |> list.each(fn(code) { let resp = call( graph.follow, "graph.followUser", forbidden_client(code), support.fresh_follow_index(), ) assert resp.status == 502 assert support.field_string(simulate.read_body(resp), ["error"]) == Ok("UpstreamFailure") }) } pub fn follow_mirrors_the_written_record_into_the_index_test() { let follows = seeded_index([]) assert call(graph.follow, "graph.followUser", no_list_client(), follows).status == 200 assert follows.edges.following(viewer_did) == [target_did] let assert Some(edge) = follows.edges.find(viewer_did, target_did) assert edge.follow_uri == follow_uri("3ccc") } // Unfollow resolves the rkey from the index rather than listing the PDS, and // takes every duplicate legacy edge for the subject with it. pub fn unfollow_clears_index_edges_without_a_pds_list_test() { [ #([#("3ddd", "2026-01-01T00:00:00Z")], 200), #( [#("3aaa", "2026-01-01T00:00:00Z"), #("3bbb", "2026-01-02T00:00:00Z")], 200, ), #([], 404), ] |> list.each(fn(row) { let #(edges, status) = row let follows = seeded_index(edges) let resp = call(graph.unfollow, "graph.unfollowUser", no_list_client(), follows) assert resp.status == status assert follows.edges.following(viewer_did) == [] }) } pub fn unfollow_without_the_index_falls_back_to_the_pds_test() { [ #(list_records_body([follow_record_json("3ddd", target_did)]), 200), #(list_records_body([]), 404), ] |> list.each(fn(row) { let #(list_body, status) = row let resp = call( graph.unfollow, "graph.unfollowUser", network_client(list_body, ""), support.fresh_follow_index(), ) assert resp.status == status }) } pub fn unfollow_index_keeps_only_edges_the_pds_delete_failed_on_test() { let follows = seeded_index([ #("3aaa", "2026-01-01T00:00:00Z"), #("3bbb", "2026-01-02T00:00:00Z"), ]) let resp = call( graph.unfollow, "graph.unfollowUser", partial_delete_failure_client(), follows, ) assert resp.status == 502 let assert Some(edge) = follows.edges.find(viewer_did, target_did) assert edge.follow_uri == follow_uri("3bbb") } pub fn deterministic_rkey_is_stable_and_atproto_safe_test() { let first = graph_follows.rkey_for_subject(target_did) assert first == graph_follows.rkey_for_subject(target_did) assert string.starts_with(first, "f_") assert string.contains(first, ":") == False } pub fn concurrent_follows_converge_on_the_same_put_rkey_test() { let expected_rkey = graph_follows.rkey_for_subject(target_did) let client = xrpc.Client(send: fn(req) { case req.path { "/xrpc/com.atproto.repo.listRecords" -> ok_response(list_records_body([])) "/xrpc/com.atproto.repo.putRecord" -> case bit_array.to_string(req.body) { Ok(body) -> case string.contains(body, expected_rkey) { True -> ok_response(create_record_response(expected_rkey)) False -> Error(core_xrpc.ConnectionFailed( "non-deterministic follow rkey", )) } _ -> Error(core_xrpc.ConnectionFailed("non-deterministic follow rkey")) } _ -> panic as { "unexpected PDS call: " <> req.path } } }) let #(ctx, cfg) = test_context(client, support.fresh_follow_index()) let replies = process.new_subject() let requests = [ authed_post("graph.followUser", cfg), authed_post("graph.followUser", cfg), ] list.each(requests, fn(req) { process.spawn_unlinked(fn() { process.send(replies, graph.follow(req, ctx).status) }) }) let assert Ok(a) = process.receive(replies, 1000) let assert Ok(b) = process.receive(replies, 1000) assert list.sort([a, b], int.compare) == [200, 200] }