Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add helpers to deserialise JSON-LD in a more robust way #492

Merged
merged 6 commits into from
Mar 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions crates/kitsune-activitypub/src/deliverer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use kitsune_db::{
PgPool,
};
use kitsune_service::attachment::AttachmentService;
use kitsune_type::ap::{ap_context, helper::StringOrObject, Activity, ActivityType, ObjectField};
use kitsune_type::ap::{ap_context, Activity, ActivityType, ObjectField};
use kitsune_url::UrlService;
use kitsune_util::try_join;
use scoped_futures::ScopedFutureExt;
Expand Down Expand Up @@ -93,7 +93,7 @@ impl Deliverer {
context: ap_context(),
id: format!("{}#accept", follow.url),
r#type: ActivityType::Accept,
actor: StringOrObject::String(followed_account_url),
actor: followed_account_url,
object: ObjectField::Url(follow.url),
published: Timestamp::now_utc(),
};
Expand Down Expand Up @@ -280,7 +280,7 @@ impl Deliverer {
context: ap_context(),
id: format!("{}#reject", follow.url),
r#type: ActivityType::Reject,
actor: StringOrObject::String(followed_account_url),
actor: followed_account_url,
object: ObjectField::Url(follow.url),
published: Timestamp::now_utc(),
};
Expand Down
7 changes: 4 additions & 3 deletions crates/kitsune-activitypub/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,16 +201,17 @@ async fn preprocess_object(
language_detection_config,
}: ProcessNewObject<'_>,
) -> Result<PreprocessedObject<'_>> {
let attributed_to = object.attributed_to().ok_or(Error::InvalidDocument)?;
let user = if let Some(author) = author {
CowBox::borrowed(author)
} else {
if Uri::try_from(attributed_to)?.authority() != Uri::try_from(&object.id)?.authority() {
if Uri::try_from(&object.attributed_to)?.authority()
!= Uri::try_from(&object.id)?.authority()
{
return Err(Error::InvalidDocument);
}

let Some(author) = fetcher
.fetch_account(attributed_to.into())
.fetch_account(object.attributed_to.as_str().into())
.await
.map_err(Error::FetchAccount)?
else {
Expand Down
20 changes: 10 additions & 10 deletions crates/kitsune-activitypub/src/mapping/activity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use kitsune_db::{
model::{account::Account, favourite::Favourite, follower::Follow, post::Post},
schema::{accounts, posts},
};
use kitsune_type::ap::{ap_context, helper::StringOrObject, Activity, ActivityType, ObjectField};
use kitsune_type::ap::{ap_context, Activity, ActivityType, ObjectField};
use kitsune_util::try_join;
use scoped_futures::ScopedFutureExt;
use std::future::Future;
Expand All @@ -34,7 +34,7 @@ impl IntoActivity for Account {
context: ap_context(),
id: format!("{account_url}#update"),
r#type: ActivityType::Update,
actor: StringOrObject::String(account_url),
actor: account_url,
object: ObjectField::Actor(self.into_object(state).await?),
published: Timestamp::now_utc(),
})
Expand Down Expand Up @@ -74,7 +74,7 @@ impl IntoActivity for Favourite {
context: ap_context(),
id: self.url,
r#type: ActivityType::Like,
actor: StringOrObject::String(account_url),
actor: account_url,
object: ObjectField::Url(post_url),
published: self.created_at,
})
Expand All @@ -96,7 +96,7 @@ impl IntoActivity for Favourite {
context: ap_context(),
id: format!("{}#undo", self.url),
r#type: ActivityType::Undo,
actor: StringOrObject::String(account_url.clone()),
actor: account_url.clone(),
object: ObjectField::Activity(self.into_activity(state).await?.into()),
published: Timestamp::now_utc(),
})
Expand Down Expand Up @@ -131,7 +131,7 @@ impl IntoActivity for Follow {
Ok(Activity {
context: ap_context(),
id: self.url,
actor: StringOrObject::String(attributed_to),
actor: attributed_to,
r#type: ActivityType::Follow,
object: ObjectField::Url(object),
published: self.created_at,
Expand All @@ -154,7 +154,7 @@ impl IntoActivity for Follow {
context: ap_context(),
id: format!("{}#undo", self.url),
r#type: ActivityType::Undo,
actor: StringOrObject::String(attributed_to),
actor: attributed_to,
published: self.created_at,
object: ObjectField::Activity(self.into_activity(state).await?.into()),
})
Expand Down Expand Up @@ -184,7 +184,7 @@ impl IntoActivity for Post {
context: ap_context(),
id: format!("{}/activity", self.url),
r#type: ActivityType::Announce,
actor: StringOrObject::String(account_url),
actor: account_url,
object: ObjectField::Url(reposted_post_url),
published: self.created_at,
})
Expand All @@ -196,7 +196,7 @@ impl IntoActivity for Post {
context: ap_context(),
id: format!("{}/activity", object.id),
r#type: ActivityType::Create,
actor: StringOrObject::String(account_url),
actor: account_url,
published: created_at,
object: ObjectField::Object(object),
})
Expand All @@ -211,7 +211,7 @@ impl IntoActivity for Post {
context: ap_context(),
id: format!("{}#undo", self.url),
r#type: ActivityType::Undo,
actor: StringOrObject::String(account_url),
actor: account_url,
object: ObjectField::Url(self.url),
published: Timestamp::now_utc(),
}
Expand All @@ -222,7 +222,7 @@ impl IntoActivity for Post {
context: ap_context(),
id: format!("{}#delete", object.id),
r#type: ActivityType::Delete,
actor: StringOrObject::String(account_url),
actor: account_url,
published: Timestamp::now_utc(),
object: ObjectField::Object(object),
}
Expand Down
4 changes: 2 additions & 2 deletions crates/kitsune-activitypub/src/mapping/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use kitsune_type::ap::{
ap_context,
emoji::Emoji,
object::{MediaAttachment, MediaAttachmentType},
AttributedToField, Object, ObjectType, Tag, TagType,
Object, ObjectType, Tag, TagType,
};
use kitsune_util::try_join;
use mime::Mime;
Expand Down Expand Up @@ -177,7 +177,7 @@ impl IntoObject for Post {
context: ap_context(),
id: self.url,
r#type: ObjectType::Note,
attributed_to: AttributedToField::Url(account_url),
attributed_to: account_url,
in_reply_to,
sensitive: self.is_sensitive,
name: None,
Expand Down
4 changes: 2 additions & 2 deletions crates/kitsune-activitypub/tests/fetcher/infinite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use kitsune_search::NoopSearchService;
use kitsune_test::{build_ap_response, database_test, language_detection_config};
use kitsune_type::ap::{
actor::{Actor, ActorType, PublicKey},
ap_context, AttributedToField, Object, ObjectType, PUBLIC_IDENTIFIER,
ap_context, Object, ObjectType, PUBLIC_IDENTIFIER,
};
use kitsune_webfinger::Webfinger;
use std::{
Expand Down Expand Up @@ -65,7 +65,7 @@ async fn fetch_infinitely_long_reply_chain() {
context: ap_context(),
id: format!("https://example.com/notes/{note_id}"),
r#type: ObjectType::Note,
attributed_to: AttributedToField::Url(author.id.clone()),
attributed_to: author.id.clone(),
in_reply_to: Some(format!("https://example.com/notes/{}", note_id + 1)),
name: None,
summary: None,
Expand Down
1 change: 1 addition & 0 deletions crates/kitsune-type/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ utoipa = { version = "4.2.0", features = ["chrono", "uuid"] }

[dev-dependencies]
pretty_assertions = "1.4.0"
serde_test = "1"

[lints]
workspace = true
39 changes: 38 additions & 1 deletion crates/kitsune-type/src/ap/actor.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::object::MediaAttachment;
use crate::jsonld::RdfNode;
use crate::jsonld::{self, RdfNode};
use iso8601_timestamp::Timestamp;
use serde::{Deserialize, Serialize};
use simd_json::OwnedValue;
Expand Down Expand Up @@ -29,20 +29,51 @@ pub struct Actor {
#[serde(default, rename = "@context")]
pub context: OwnedValue,
pub id: String,
#[serde(deserialize_with = "jsonld::serde::FirstOk::deserialize")]
pub r#type: ActorType,
#[serde(default)]
#[serde(deserialize_with = "jsonld::serde::Optional::<jsonld::serde::First<_>>::deserialize")]
pub name: Option<String>,
#[serde(deserialize_with = "jsonld::serde::First::deserialize")]
pub preferred_username: String,
#[serde(default)]
#[serde(deserialize_with = "jsonld::serde::Optional::<jsonld::serde::First<_>>::deserialize")]
pub subject: Option<String>,
#[serde(default)]
#[serde(deserialize_with = "jsonld::serde::Optional::<jsonld::serde::First<_>>::deserialize")]
pub icon: Option<MediaAttachment>,
#[serde(default)]
#[serde(deserialize_with = "jsonld::serde::Optional::<jsonld::serde::First<_>>::deserialize")]
pub image: Option<MediaAttachment>,
#[serde(default)]
#[serde(deserialize_with = "jsonld::serde::First::deserialize")]
pub manually_approves_followers: bool,
#[serde(deserialize_with = "jsonld::serde::First::deserialize")]
pub public_key: PublicKey,
#[serde(default)]
#[serde(deserialize_with = "jsonld::serde::Optional::<jsonld::serde::First<_>>::deserialize")]
pub endpoints: Option<Endpoints>,
#[serde(default)]
#[serde(
deserialize_with = "jsonld::serde::Optional::<jsonld::serde::FirstId<_>>::deserialize"
)]
pub featured: Option<String>,
#[serde(deserialize_with = "jsonld::serde::FirstId::deserialize")]
pub inbox: String,
#[serde(default)]
#[serde(
deserialize_with = "jsonld::serde::Optional::<jsonld::serde::FirstId<_>>::deserialize"
)]
pub outbox: Option<String>,
#[serde(default)]
#[serde(
deserialize_with = "jsonld::serde::Optional::<jsonld::serde::FirstId<_>>::deserialize"
)]
pub followers: Option<String>,
#[serde(default)]
#[serde(
deserialize_with = "jsonld::serde::Optional::<jsonld::serde::FirstId<_>>::deserialize"
)]
pub following: Option<String>,
#[serde(default = "Timestamp::now_utc")]
pub published: Timestamp,
Expand All @@ -57,13 +88,19 @@ impl RdfNode for Actor {
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Endpoints {
#[serde(default)]
#[serde(
deserialize_with = "jsonld::serde::Optional::<jsonld::serde::FirstId<_>>::deserialize"
)]
pub shared_inbox: Option<String>,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PublicKey {
pub id: String,
#[serde(deserialize_with = "jsonld::serde::FirstId::deserialize")]
pub owner: String,
#[serde(deserialize_with = "jsonld::serde::First::deserialize")]
pub public_key_pem: String,
}
3 changes: 3 additions & 0 deletions crates/kitsune-type/src/ap/collection.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::jsonld;
use serde::{Deserialize, Serialize};
use simd_json::OwnedValue;

Expand All @@ -12,6 +13,7 @@ pub struct Collection {
#[serde(default, rename = "@context")]
pub context: OwnedValue,
pub id: String,
#[serde(deserialize_with = "jsonld::serde::FirstOk::deserialize")]
pub r#type: CollectionType,
pub total_items: u64,
pub first: Option<String>,
Expand All @@ -29,6 +31,7 @@ pub struct CollectionPage<T> {
#[serde(default, rename = "@context")]
pub context: OwnedValue,
pub id: String,
#[serde(deserialize_with = "jsonld::serde::FirstOk::deserialize")]
pub r#type: PageType,
pub next: String,
pub prev: String,
Expand Down
5 changes: 4 additions & 1 deletion crates/kitsune-type/src/ap/emoji.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::object::MediaAttachment;
use crate::jsonld::RdfNode;
use crate::jsonld::{self, RdfNode};
use iso8601_timestamp::Timestamp;
use serde::{Deserialize, Serialize};
use simd_json::OwnedValue;
Expand All @@ -10,8 +10,11 @@ pub struct Emoji {
#[serde(default, rename = "@context")]
pub context: OwnedValue,
pub id: String,
#[serde(deserialize_with = "jsonld::serde::FirstOk::deserialize")]
pub r#type: String,
#[serde(deserialize_with = "jsonld::serde::First::deserialize")]
pub name: String,
#[serde(deserialize_with = "jsonld::serde::First::deserialize")]
pub icon: MediaAttachment,
#[serde(default = "Timestamp::now_utc")]
pub updated: Timestamp,
Expand Down
30 changes: 0 additions & 30 deletions crates/kitsune-type/src/ap/helper.rs
Original file line number Diff line number Diff line change
@@ -1,34 +1,4 @@
use super::{Object, PUBLIC_IDENTIFIER};
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum StringOrObject<T> {
String(String),
Object(T),
}

impl<T> StringOrObject<T> {
pub fn into_string(self) -> Option<String> {
match self {
Self::String(str) => Some(str),
Self::Object(..) => None,
}
}

pub fn into_object(self) -> Option<T> {
match self {
Self::String(..) => None,
Self::Object(obj) => Some(obj),
}
}
}

impl<T> Default for StringOrObject<T> {
fn default() -> Self {
Self::String(String::new())
}
}

pub trait CcTo {
fn cc(&self) -> &[String];
Expand Down
Loading
Loading