Reviewed-on: #26
This commit was merged in pull request #26.
This commit is contained in:
253
crates/adapters/activitypub/tests/activity_ids.rs
Normal file
253
crates/adapters/activitypub/tests/activity_ids.rs
Normal file
@@ -0,0 +1,253 @@
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use activitypub::ActivityPubEventHandler;
|
||||
use async_trait::async_trait;
|
||||
use chrono::NaiveDate;
|
||||
use domain::{
|
||||
errors::DomainError,
|
||||
events::DomainEvent,
|
||||
models::{DiaryEntry, WatchlistWithMovie},
|
||||
ports::{
|
||||
EventHandler, FederationDeletionNotifier, LocalApContentQuery, MovieCommand, UserRepository,
|
||||
},
|
||||
testing::{
|
||||
InMemoryStore, PanicGoalQuery, PanicReviewRepository, PanicStatsRepository, test_movie,
|
||||
},
|
||||
value_objects::{InstanceIdentity, MovieId, UserId},
|
||||
};
|
||||
use k_ap::{
|
||||
ActivityPubService, ApUser, FederationEvent,
|
||||
testing::{MockActorRepoBuilder, MockFollowRepoBuilder, MockUserRepoBuilder},
|
||||
};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
struct NoContent;
|
||||
|
||||
#[async_trait]
|
||||
impl LocalApContentQuery for NoContent {
|
||||
async fn get_local_watchlist_for_user(
|
||||
&self,
|
||||
_: &UserId,
|
||||
) -> Result<Vec<WatchlistWithMovie>, DomainError> {
|
||||
Ok(vec![])
|
||||
}
|
||||
async fn get_local_reviews_for_movie(
|
||||
&self,
|
||||
_: &MovieId,
|
||||
) -> Result<Vec<DiaryEntry>, DomainError> {
|
||||
Ok(vec![])
|
||||
}
|
||||
async fn get_local_reviews_page(
|
||||
&self,
|
||||
_: &UserId,
|
||||
_: Option<chrono::NaiveDateTime>,
|
||||
_: usize,
|
||||
) -> Result<Vec<DiaryEntry>, DomainError> {
|
||||
Ok(vec![])
|
||||
}
|
||||
}
|
||||
|
||||
struct Capture(mpsc::UnboundedSender<serde_json::Value>);
|
||||
|
||||
#[async_trait]
|
||||
impl k_ap::EventPublisher for Capture {
|
||||
async fn publish(&self, event: FederationEvent) -> anyhow::Result<()> {
|
||||
if let FederationEvent::DeliveryRequested { activity, .. } = event {
|
||||
let _ = self.0.send(activity);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct Harness {
|
||||
handler: ActivityPubEventHandler,
|
||||
delivered: mpsc::UnboundedReceiver<serde_json::Value>,
|
||||
user: UserId,
|
||||
movie_id: MovieId,
|
||||
store: Arc<InMemoryStore>,
|
||||
service: Arc<ActivityPubService>,
|
||||
}
|
||||
|
||||
async fn harness() -> Harness {
|
||||
let user = UserId::from_uuid(uuid::Uuid::new_v4());
|
||||
let uid = user.value();
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
let service = ActivityPubService::builder("https://diary.example")
|
||||
.activity_repo(k_ap::testing::MockActivityRepoBuilder::new().build())
|
||||
.follow_repo(
|
||||
MockFollowRepoBuilder::new()
|
||||
.on_get_accepted_follower_inboxes(|_| {
|
||||
Ok(vec!["https://remote.example/inbox".to_string()])
|
||||
})
|
||||
.build(),
|
||||
)
|
||||
.actor_repo(MockActorRepoBuilder::new().build())
|
||||
.blocklist_repo(k_ap::testing::MockBlocklistRepoBuilder::new().build())
|
||||
.user_repo(
|
||||
MockUserRepoBuilder::new()
|
||||
.on_find_by_id(move |id| {
|
||||
Ok((id == uid).then(|| ApUser {
|
||||
id,
|
||||
username: "alice".into(),
|
||||
display_name: None,
|
||||
bio: None,
|
||||
avatar_url: None,
|
||||
banner_url: None,
|
||||
also_known_as: vec![],
|
||||
profile_url: None,
|
||||
attachment: vec![],
|
||||
manually_approves_followers: false,
|
||||
discoverable: true,
|
||||
actor_type: Default::default(),
|
||||
featured_url: None,
|
||||
}))
|
||||
})
|
||||
.build(),
|
||||
)
|
||||
.content_reader(k_ap::testing::MockContentReaderBuilder::new().build())
|
||||
.object_handler(k_ap::testing::MockObjectHandlerBuilder::new().build())
|
||||
.event_publisher(Arc::new(Capture(tx)))
|
||||
.build()
|
||||
.await
|
||||
.expect("service builds");
|
||||
|
||||
let store = InMemoryStore::new();
|
||||
let movie = test_movie("Heat");
|
||||
store.upsert_movie(&movie, &[]).await.unwrap();
|
||||
let service = Arc::new(service);
|
||||
store
|
||||
.save(&domain::testing::test_user_with_role(
|
||||
user.clone(),
|
||||
domain::models::UserRole::Standard,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
let handler = ActivityPubEventHandler::new(
|
||||
Arc::clone(&service),
|
||||
Arc::new(NoContent),
|
||||
Arc::new(PanicReviewRepository),
|
||||
store.clone(),
|
||||
Arc::new(PanicGoalQuery),
|
||||
Arc::new(PanicStatsRepository),
|
||||
store.clone(),
|
||||
store.clone(),
|
||||
InstanceIdentity::new("https://diary.example"),
|
||||
);
|
||||
Harness {
|
||||
handler,
|
||||
delivered: rx,
|
||||
user,
|
||||
movie_id: movie.id().clone(),
|
||||
store,
|
||||
service,
|
||||
}
|
||||
}
|
||||
|
||||
impl Harness {
|
||||
async fn next_activity_id(&mut self) -> String {
|
||||
let activity = tokio::time::timeout(Duration::from_secs(5), self.delivered.recv())
|
||||
.await
|
||||
.expect("an activity was delivered")
|
||||
.expect("channel open");
|
||||
activity["id"]
|
||||
.as_str()
|
||||
.expect("activity has an id")
|
||||
.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn activitypub_is_idempotent_when_run_twice() {
|
||||
let mut h = harness().await;
|
||||
let event = DomainEvent::WatchlistEntryAdded {
|
||||
user_id: h.user.clone(),
|
||||
movie_id: h.movie_id.clone(),
|
||||
movie_title: "Heat".into(),
|
||||
release_year: 1995,
|
||||
external_metadata_id: None,
|
||||
added_at: NaiveDate::from_ymd_opt(2026, 1, 1)
|
||||
.unwrap()
|
||||
.and_hms_opt(0, 0, 0)
|
||||
.unwrap(),
|
||||
};
|
||||
|
||||
h.handler.handle(&event).await.unwrap();
|
||||
let first = h.next_activity_id().await;
|
||||
h.handler.handle(&event).await.unwrap();
|
||||
let second = h.next_activity_id().await;
|
||||
|
||||
assert!(first.starts_with("https://diary.example/activities/create/"));
|
||||
assert_eq!(first, second, "a redelivered Create keeps its activity id");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn redelivered_delete_gets_a_fresh_activity_id_known_k_ap_limitation() {
|
||||
let mut h = harness().await;
|
||||
let event = DomainEvent::WatchlistEntryRemoved {
|
||||
user_id: h.user.clone(),
|
||||
movie_id: h.movie_id.clone(),
|
||||
};
|
||||
|
||||
h.handler.handle(&event).await.unwrap();
|
||||
let first = h.next_activity_id().await;
|
||||
h.handler.handle(&event).await.unwrap();
|
||||
let second = h.next_activity_id().await;
|
||||
|
||||
assert_ne!(first, second);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_deleted_account_sends_nothing_but_its_delete() {
|
||||
let mut h = harness().await;
|
||||
h.store.mark_deleted(&h.user, &[]).await.unwrap();
|
||||
let logged = DomainEvent::ReviewLogged {
|
||||
review_id: domain::value_objects::ReviewId::generate(),
|
||||
user_id: h.user.clone(),
|
||||
movie_id: h.movie_id.clone(),
|
||||
rating: domain::value_objects::Rating::new(4).unwrap(),
|
||||
watched_at: NaiveDate::from_ymd_opt(2026, 1, 1)
|
||||
.unwrap()
|
||||
.and_hms_opt(0, 0, 0)
|
||||
.unwrap(),
|
||||
};
|
||||
let added = DomainEvent::WatchlistEntryAdded {
|
||||
user_id: h.user.clone(),
|
||||
movie_id: h.movie_id.clone(),
|
||||
movie_title: "Heat".into(),
|
||||
release_year: 1995,
|
||||
external_metadata_id: None,
|
||||
added_at: NaiveDate::from_ymd_opt(2026, 1, 1)
|
||||
.unwrap()
|
||||
.and_hms_opt(0, 0, 0)
|
||||
.unwrap(),
|
||||
};
|
||||
let queued = DomainEvent::FederationDeliveryRequested {
|
||||
inbox_url: "https://remote.example/inbox".into(),
|
||||
activity_json: serde_json::json!({"type": "Create"}),
|
||||
signing_actor_id: h.user.value(),
|
||||
};
|
||||
|
||||
for event in [&logged, &added, &queued] {
|
||||
h.handler.handle(event).await.unwrap();
|
||||
}
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(300), h.delivered.recv())
|
||||
.await
|
||||
.is_err(),
|
||||
"nothing is delivered for a deleted account"
|
||||
);
|
||||
|
||||
activitypub::ApDeletionNotifier::new(
|
||||
Arc::clone(&h.service),
|
||||
InstanceIdentity::new("https://diary.example"),
|
||||
)
|
||||
.notify_deleted(&h.user)
|
||||
.await
|
||||
.unwrap();
|
||||
let delete = tokio::time::timeout(Duration::from_secs(5), h.delivered.recv())
|
||||
.await
|
||||
.expect("the Delete is delivered")
|
||||
.unwrap();
|
||||
assert_eq!(delete["type"], "Delete");
|
||||
}
|
||||
4
crates/adapters/activitypub/tests/objects.rs
Normal file
4
crates/adapters/activitypub/tests/objects.rs
Normal file
@@ -0,0 +1,4 @@
|
||||
#[path = "objects/review_object_test.rs"]
|
||||
mod review_object_test;
|
||||
#[path = "objects/watchlist_object_test.rs"]
|
||||
mod watchlist_object_test;
|
||||
112
crates/adapters/activitypub/tests/objects/review_object_test.rs
Normal file
112
crates/adapters/activitypub/tests/objects/review_object_test.rs
Normal file
@@ -0,0 +1,112 @@
|
||||
use activitypub::objects::{ReviewApInput, review_to_ap_object};
|
||||
use chrono::NaiveDateTime;
|
||||
use domain::models::{PersistedReview, Review, ReviewSource};
|
||||
use domain::value_objects::{Comment, MovieId, Rating, ReviewId, UserId};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const PUBLIC: &str = "https://www.w3.org/ns/activitystreams#Public";
|
||||
|
||||
fn timestamp() -> NaiveDateTime {
|
||||
NaiveDateTime::parse_from_str("2024-06-01 00:00:00", "%Y-%m-%d %H:%M:%S").unwrap()
|
||||
}
|
||||
|
||||
fn review(rating: u8, comment: Option<&str>, spoilers: bool) -> Review {
|
||||
Review::from_persistence(PersistedReview {
|
||||
id: ReviewId::generate(),
|
||||
movie_id: MovieId::from_uuid(uuid::Uuid::new_v4()),
|
||||
user_id: UserId::from_uuid(uuid::Uuid::new_v4()),
|
||||
rating: Rating::new(rating).unwrap(),
|
||||
comment: comment.map(|c| Comment::new(c.into()).unwrap()),
|
||||
watched_at: timestamp(),
|
||||
created_at: timestamp(),
|
||||
source: ReviewSource::Local,
|
||||
watch_medium: None,
|
||||
spoilers,
|
||||
})
|
||||
}
|
||||
|
||||
fn input(movie_title: &str, actor_url: &str) -> ReviewApInput {
|
||||
ReviewApInput {
|
||||
ap_id: "https://example.com/reviews/1".parse().unwrap(),
|
||||
actor_url: actor_url.parse().unwrap(),
|
||||
movie_title: movie_title.to_string(),
|
||||
release_year: 2021,
|
||||
external_metadata_id: None,
|
||||
poster_url: None,
|
||||
base_url: "https://example.com".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn render(review: &Review, input: ReviewApInput) -> Value {
|
||||
serde_json::to_value(review_to_ap_object(review, input)).unwrap()
|
||||
}
|
||||
|
||||
fn tag_names(json: &Value) -> Vec<&str> {
|
||||
json["tag"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|t| t["name"].as_str().unwrap())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn review_object_tags_movie_title_with_non_alphanumerics_stripped() {
|
||||
for (title, hashtag) in [
|
||||
("The Dark Knight", "#TheDarkKnight"),
|
||||
("Schindler's List", "#SchindlersList"),
|
||||
("2001: A Space Odyssey", "#2001ASpaceOdyssey"),
|
||||
] {
|
||||
let json = render(
|
||||
&review(4, None, false),
|
||||
input(title, "https://example.com/users/1"),
|
||||
);
|
||||
assert!(
|
||||
tag_names(&json).contains(&hashtag),
|
||||
"{title}: {:?}",
|
||||
tag_names(&json)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn review_object_includes_two_hashtags() {
|
||||
let json = render(
|
||||
&review(4, None, false),
|
||||
input("Dune", "https://example.com/users/1"),
|
||||
);
|
||||
|
||||
assert_eq!(tag_names(&json), vec!["#MoviesDiary", "#Dune"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn review_object_is_publicly_addressed_with_followers_in_cc() {
|
||||
let json = render(
|
||||
&review(3, None, false),
|
||||
input("Dune", "https://example.com/users/abc"),
|
||||
);
|
||||
|
||||
assert_eq!(json["to"], json!([PUBLIC]));
|
||||
assert_eq!(
|
||||
json["cc"],
|
||||
json!(["https://example.com/users/abc/followers"])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn review_object_carries_spoiler_flag_and_summary_only_with_a_comment() {
|
||||
let json = render(
|
||||
&review(4, Some("the mentor is the villain"), true),
|
||||
input("Dune", "https://example.com/users/1"),
|
||||
);
|
||||
assert_eq!(json["containsSpoilers"], Value::Bool(true));
|
||||
assert_eq!(json["summary"], "Contains spoilers");
|
||||
|
||||
// A flag without a comment never travels: there is nothing to veil.
|
||||
let json = render(
|
||||
&review(4, None, true),
|
||||
input("Dune", "https://example.com/users/1"),
|
||||
);
|
||||
assert!(json.get("containsSpoilers").is_none());
|
||||
assert!(json.get("summary").is_none());
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
use activitypub::objects::{WatchlistApInput, watchlist_to_ap_object};
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn watchlist_object_is_publicly_addressed_with_followers_in_cc() {
|
||||
let obj = watchlist_to_ap_object(WatchlistApInput {
|
||||
ap_id: "https://example.com/watchlist/1".parse().unwrap(),
|
||||
actor_url: "https://example.com/users/abc".parse().unwrap(),
|
||||
movie_title: "Alien".to_string(),
|
||||
release_year: 1979,
|
||||
external_metadata_id: None,
|
||||
poster_url: None,
|
||||
added_at: chrono::Utc::now(),
|
||||
base_url: "https://example.com".to_string(),
|
||||
});
|
||||
let json = serde_json::to_value(&obj).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
json["to"],
|
||||
json!(["https://www.w3.org/ns/activitystreams#Public"])
|
||||
);
|
||||
assert_eq!(
|
||||
json["cc"],
|
||||
json!(["https://example.com/users/abc/followers"])
|
||||
);
|
||||
}
|
||||
67
crates/adapters/activitypub/tests/user_adapter.rs
Normal file
67
crates/adapters/activitypub/tests/user_adapter.rs
Normal file
@@ -0,0 +1,67 @@
|
||||
use domain::{
|
||||
ports::UserRepository,
|
||||
testing::{InMemoryStore, test_user},
|
||||
value_objects::InstanceIdentity,
|
||||
};
|
||||
use k_ap::ApUserRepository;
|
||||
|
||||
use activitypub::DomainUserRepoAdapter;
|
||||
|
||||
async fn adapter_with_deleted_alice() -> (DomainUserRepoAdapter, uuid::Uuid) {
|
||||
let store = InMemoryStore::new();
|
||||
let alice = test_user("alice");
|
||||
store.save(&alice).await.unwrap();
|
||||
store.mark_deleted(alice.id(), &[]).await.unwrap();
|
||||
let adapter = DomainUserRepoAdapter::new(store, InstanceIdentity::new("https://md.example"));
|
||||
(adapter, alice.id().value())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tombstoned_actor_can_still_sign() {
|
||||
let (adapter, id) = adapter_with_deleted_alice().await;
|
||||
|
||||
let user = adapter.find_by_id(id).await.unwrap();
|
||||
|
||||
assert_eq!(user.expect("k-ap resolves the tombstone").username, "alice");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_tombstone_is_not_found_by_username() {
|
||||
let (adapter, _) = adapter_with_deleted_alice().await;
|
||||
|
||||
assert!(adapter.find_by_username("alice").await.unwrap().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_unknown_user_is_none() {
|
||||
let (adapter, _) = adapter_with_deleted_alice().await;
|
||||
|
||||
assert!(
|
||||
adapter
|
||||
.find_by_id(uuid::Uuid::new_v4())
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_per_user_path_is_gated() {
|
||||
use activitypub::tombstone_gate::gated_user;
|
||||
let id = uuid::Uuid::new_v4();
|
||||
let rid = uuid::Uuid::new_v4();
|
||||
for endpoint in [
|
||||
"outbox",
|
||||
"featured",
|
||||
"inbox",
|
||||
"followers",
|
||||
"following",
|
||||
&format!("reviews/{rid}"),
|
||||
] {
|
||||
assert_eq!(gated_user(&format!("/users/{id}/{endpoint}")), Some(id));
|
||||
}
|
||||
assert_eq!(gated_user(&format!("/users/{id}")), None);
|
||||
assert_eq!(gated_user(&format!("/users/{id}/")), None);
|
||||
assert_eq!(gated_user("/inbox"), None);
|
||||
assert_eq!(gated_user("/users/not-a-uuid/outbox"), None);
|
||||
}
|
||||
Reference in New Issue
Block a user