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

feat: block instances and actors #67

Merged
merged 16 commits into from
Sep 26, 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
1 change: 1 addition & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions crates/api_admin/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,6 @@ activitypub_federation = { workspace = true }
axum = { workspace = true }
sea-orm = { workspace = true }
serde = { workspace = true }
url = { workspace = true }
utoipa = { workspace = true }
utoipa-axum = { workspace = true }
14 changes: 14 additions & 0 deletions crates/api_admin/src/entities/block_url_or_acct.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
use serde::{Deserialize, Serialize};
use url::Url;
use utoipa::{IntoParams, ToSchema};

#[derive(Deserialize, IntoParams)]
pub struct BlockUrlQuery {
pub url: Url,
}

#[derive(Serialize, ToSchema)]
pub struct BlockUrlResult {
pub url: Url,
pub message: String,
}
2 changes: 2 additions & 0 deletions crates/api_admin/src/entities/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
mod block_url_or_acct;
mod create_remove_account;

pub use block_url_or_acct::{BlockUrlQuery, BlockUrlResult};
pub use create_remove_account::{CreateRemoveAccount, CreateRemoveAccountResult};
68 changes: 68 additions & 0 deletions crates/api_admin/src/routes/block_url.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
use activitypub_federation::config::Data;
use axum::{debug_handler, extract::Query, http::StatusCode, Json};
use hatsu_db_schema::{blocked_url, prelude::BlockedUrl};
use hatsu_utils::{AppData, AppError};
use sea_orm::{ActiveModelTrait, EntityTrait, Set};

use crate::{
entities::{BlockUrlQuery, BlockUrlResult},
TAG,
};

/// Block URL
#[utoipa::path(
post,
tag = TAG,
path = "/api/v0/admin/block-url",
params(BlockUrlQuery),
responses(
(status = OK, description = "block successfully", body = BlockUrlResult),
(status = BAD_REQUEST, description = "error", body = AppError)
),
security(("api_key" = ["token"]))
)]
#[debug_handler]
pub async fn block_url(
data: Data<AppData>,
query: Query<BlockUrlQuery>,
) -> Result<(StatusCode, Json<BlockUrlResult>), AppError> {
match &query.url {
url if url.query().is_some() => Err(AppError::new(
format!(
"wrong url: {} (can't contain search params)",
url.to_string()
),
None,
Some(StatusCode::BAD_REQUEST),
)),
_ => match BlockedUrl::find_by_id(&query.url.to_string())
.one(&data.conn)
.await?
{
Some(url) => Err(AppError::new(
format!("The url already blocked: {}", url.id),
None,
Some(StatusCode::BAD_REQUEST),
)),
None => {
blocked_url::ActiveModel {
id: Set(query.url.to_string()),
is_instance: Set(query.url.path().eq("/")),
kwaa marked this conversation as resolved.
Show resolved Hide resolved
}
.insert(&data.conn)
.await?;

Ok((
StatusCode::OK,
Json(BlockUrlResult {
url: query.url.clone(),
message: format!(
"The url was successfully blocked: {}",
&query.url.to_string()
),
}),
))
},
},
}
}
21 changes: 16 additions & 5 deletions crates/api_admin/src/routes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,22 @@ use utoipa::{
};
use utoipa_axum::{router::OpenApiRouter, routes};

use crate::entities::{CreateRemoveAccount, CreateRemoveAccountResult};
use crate::entities::{BlockUrlResult, CreateRemoveAccount, CreateRemoveAccountResult};

mod block_url;
mod create_account;
mod remove_account;
mod unblock_url;

pub const TAG: &str = "hatsu::admin";

#[derive(OpenApi)]
#[openapi(
components(schemas(CreateRemoveAccount, CreateRemoveAccountResult)),
components(schemas(
BlockUrlResult,
CreateRemoveAccount,
CreateRemoveAccountResult
)),
modifiers(&SecurityAddon),
tags(
(name = TAG, description = "Hatsu Admin API (/api/v0/admin/)"),
Expand All @@ -45,8 +51,10 @@ impl Modify for SecurityAddon {

pub fn routes() -> OpenApiRouter {
OpenApiRouter::with_openapi(HatsuAdminApi::openapi())
.routes(routes!(block_url::block_url))
.routes(routes!(create_account::create_account))
.routes(routes!(remove_account::remove_account))
.routes(routes!(unblock_url::unblock_url))
.layer(middleware::from_fn(auth))
}

Expand All @@ -57,9 +65,12 @@ async fn auth(
) -> Result<Response, StatusCode> {
match &data.env.hatsu_access_token {
Some(token) => match request.uri().query() {
Some(query) if query == format!("token={token}") => Ok(next.run(request).await),
Some(query) if query != format!("token={token}") => Err(StatusCode::UNAUTHORIZED),
_ => Err(StatusCode::BAD_REQUEST),
Some(queries)
if queries
.split('&')
.any(|query| query.eq(&format!("token={token}"))) =>
Ok(next.run(request).await),
_ => Err(StatusCode::UNAUTHORIZED),
kwaa marked this conversation as resolved.
Show resolved Hide resolved
},
None => Err(StatusCode::UNAUTHORIZED),
}
Expand Down
53 changes: 53 additions & 0 deletions crates/api_admin/src/routes/unblock_url.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
use activitypub_federation::config::Data;
use axum::{debug_handler, extract::Query, http::StatusCode, Json};
use hatsu_db_schema::prelude::BlockedUrl;
use hatsu_utils::{AppData, AppError};
use sea_orm::{EntityTrait, ModelTrait};

use crate::{
entities::{BlockUrlQuery, BlockUrlResult},
TAG,
};

/// Unblock URL
#[utoipa::path(
post,
tag = TAG,
path = "/api/v0/admin/unblock-url",
params(BlockUrlQuery),
responses(
(status = OK, description = "unblock successfully", body = BlockUrlResult),
(status = BAD_REQUEST, description = "error", body = AppError)
),
security(("api_key" = ["token"]))
)]
#[debug_handler]
pub async fn unblock_url(
data: Data<AppData>,
query: Query<BlockUrlQuery>,
) -> Result<(StatusCode, Json<BlockUrlResult>), AppError> {
match BlockedUrl::find_by_id(&query.url.to_string())
.one(&data.conn)
.await?
{
Some(url) => {
url.delete(&data.conn).await?;

Ok((
StatusCode::OK,
Json(BlockUrlResult {
url: query.url.clone(),
message: format!(
"The url was successfully unblocked: {}",
&query.url.to_string()
),
}),
))
},
None => Err(AppError::new(
format!("The url doesn't exist: {}", query.url.to_string()),
None,
Some(StatusCode::BAD_REQUEST),
)),
}
}
4 changes: 3 additions & 1 deletion crates/apub/src/activities/create_or_update/note.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use crate::{
activities::CreateOrUpdateType,
actors::ApubUser,
objects::{ApubPost, Note},
utils::verify_blocked,
};

#[derive(Deserialize, Serialize, Debug)]
Expand Down Expand Up @@ -53,7 +54,7 @@ impl CreateOrUpdateNote {
kind: activity.kind.to_string(),
published: Some(activity.published.clone()),
actor: activity.actor().to_string(),
activity: serde_json::to_string(&activity)?,
activity: serde_json::to_value(&activity)?,
kwaa marked this conversation as resolved.
Show resolved Hide resolved
}
.into_active_model()
.insert(&data.conn)
Expand Down Expand Up @@ -97,6 +98,7 @@ impl ActivityHandler for CreateOrUpdateNote {
async fn verify(&self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
// TODO
ApubPost::verify(&self.object, &self.id, data).await?;
verify_blocked(&self.id, data).await?;
Ok(())
}

Expand Down
2 changes: 1 addition & 1 deletion crates/apub/src/activities/db_activity_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ use super::ApubActivity;
impl ApubActivity {
// 转换为 JSON
pub fn into_json(self) -> Result<Value, AppError> {
Ok(serde_json::from_str(&self.activity)?)
Ok(serde_json::from_value(self.activity.clone())?)
}
}
4 changes: 2 additions & 2 deletions crates/apub/src/activities/following/accept_follow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ impl AcceptFollow {

let _insert_activity = DbActivity {
id: activity.id().to_string(),
activity: serde_json::to_string(&activity)?,
activity: serde_json::to_value(&activity)?,
actor: activity.actor().to_string(),
kind: activity.kind.to_string(),
published: Some(hatsu_utils::date::now()),
Expand Down Expand Up @@ -78,7 +78,7 @@ impl ActivityHandler for AcceptFollow {
}

async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
// TODO
// TODO: just throw error
kwaa marked this conversation as resolved.
Show resolved Hide resolved
Ok(())
}

Expand Down
4 changes: 3 additions & 1 deletion crates/apub/src/activities/following/follow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ use url::Url;
use crate::{
activities::{AcceptFollow, ApubReceivedFollow},
actors::ApubUser,
utils::verify_blocked,
};

/// <https://github.com/LemmyNet/lemmy/blob/963d04b3526f8a5e9ff762960bfb5215e353bb27/crates/apub/src/protocol/activities/following/follow.rs>
Expand Down Expand Up @@ -58,8 +59,9 @@ impl ActivityHandler for Follow {
self.actor.inner()
}

async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
async fn verify(&self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
// TODO
verify_blocked(&self.id, data).await?;
Ok(())
}

Expand Down
5 changes: 3 additions & 2 deletions crates/apub/src/activities/following/undo_follow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use sea_orm::EntityTrait;
use serde::{Deserialize, Serialize};
use url::Url;

use crate::{activities::Follow, actors::ApubUser};
use crate::{activities::Follow, actors::ApubUser, utils::verify_blocked};

// https://github.com/LemmyNet/lemmy/blob/963d04b3526f8a5e9ff762960bfb5215e353bb27/crates/apub/src/protocol/activities/following/undo_follow.rs
#[derive(Clone, Debug, Deserialize, Serialize)]
Expand Down Expand Up @@ -44,8 +44,9 @@ impl ActivityHandler for UndoFollow {
self.actor.inner()
}

async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
async fn verify(&self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
// TODO
verify_blocked(&self.id, data).await?;
Ok(())
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ use crate::{
activities::{ApubReceivedAnnounce, ApubReceivedLike, LikeOrAnnounceType},
actors::ApubUser,
objects::ApubPost,
utils::verify_blocked,
};

#[derive(Clone, Debug, Deserialize, Serialize)]
Expand All @@ -48,8 +49,9 @@ impl ActivityHandler for LikeOrAnnounce {
self.actor.inner()
}

async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
async fn verify(&self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
// TODO
verify_blocked(&self.id, data).await?;
Ok(())
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use serde::{Deserialize, Serialize};
use url::Url;

use super::LikeOrAnnounceType;
use crate::{activities::LikeOrAnnounce, actors::ApubUser};
use crate::{activities::LikeOrAnnounce, actors::ApubUser, utils::verify_blocked};

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
Expand All @@ -37,8 +37,9 @@ impl ActivityHandler for UndoLikeOrAnnounce {
self.actor.inner()
}

async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
async fn verify(&self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
// TODO
verify_blocked(&self.id, data).await?;
kwaa marked this conversation as resolved.
Show resolved Hide resolved
Ok(())
}

Expand Down
1 change: 1 addition & 0 deletions crates/apub/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ pub mod actors;
pub mod collections;
pub mod links;
pub mod objects;
mod utils;

// #[cfg(test)]
pub mod tests {
Expand Down
3 changes: 3 additions & 0 deletions crates/apub/src/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
mod verify_blocked;

pub use verify_blocked::verify_blocked;
37 changes: 37 additions & 0 deletions crates/apub/src/utils/verify_blocked.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
use activitypub_federation::config::Data;
use axum::http::StatusCode;
use hatsu_db_schema::prelude::BlockedUrl;
use hatsu_utils::{AppData, AppError};
use sea_orm::EntityTrait;
use url::Url;

pub async fn verify_blocked(url: &Url, data: &Data<AppData>) -> Result<(), AppError> {
let blocked_url = BlockedUrl::find().all(&data.conn).await?;

if blocked_url
.iter()
.filter(|url| url.is_instance)
.filter_map(|url| Url::parse(&url.id).ok())
.map(|url| url.origin())
.any(|instance| url.origin().eq(&instance))
{
Err(AppError::new(
format!("blocked instance: {:?}", url.host_str()),
None,
Some(StatusCode::BAD_REQUEST),
))
} else if blocked_url
.iter()
.filter(|url| !url.is_instance)
.filter_map(|url| Url::parse(&url.id).ok())
.any(|actor| url.eq(&actor))
{
Err(AppError::new(
format!("blocked actor: {}", url),
None,
Some(StatusCode::BAD_REQUEST),
))
} else {
Ok(())
}
}
Loading