Skip to content

Commit

Permalink
progress
Browse files Browse the repository at this point in the history
  • Loading branch information
aumetra committed Apr 6, 2024
1 parent a922ff7 commit f1bcd13
Show file tree
Hide file tree
Showing 12 changed files with 55 additions and 42 deletions.
1 change: 0 additions & 1 deletion Cargo.lock

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

1 change: 0 additions & 1 deletion crates/kitsune-activitypub/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ autometrics = { version = "1.0.1", default-features = false }
base64-simd = "0.8.0"
diesel = "2.1.5"
diesel-async = "0.4.1"
eyre = "0.6.12"
futures-util = "0.3.30"
headers = "0.4.0"
http = "1.1.0"
Expand Down
3 changes: 1 addition & 2 deletions crates/kitsune-activitypub/src/fetcher/actor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,7 @@ impl Fetcher {
match self
.resolver
.resolve_account(&actor.preferred_username, domain)
.await
.map_err(Error::Resolver)?
.await?
{
Some(resource) if resource.uri == actor.id => {
actor.preferred_username = resource.username;
Expand Down
6 changes: 3 additions & 3 deletions crates/kitsune-activitypub/src/fetcher/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,15 +123,15 @@ impl FetcherTrait for Fetcher {
Arc::new(self.resolver.clone())
}

async fn fetch_account(&self, opts: AccountFetchOptions<'_>) -> eyre::Result<Option<Account>> {
async fn fetch_account(&self, opts: AccountFetchOptions<'_>) -> Result<Option<Account>> {
Ok(self.fetch_actor(opts).await?)
}

async fn fetch_emoji(&self, url: &str) -> eyre::Result<Option<CustomEmoji>> {
async fn fetch_emoji(&self, url: &str) -> Result<Option<CustomEmoji>> {
Ok(self.fetch_emoji(url).await?)
}

async fn fetch_post(&self, opts: PostFetchOptions<'_>) -> eyre::Result<Option<Post>> {
async fn fetch_post(&self, opts: PostFetchOptions<'_>) -> Result<Option<Post>> {
Ok(self.fetch_object(opts.url, opts.call_depth).await?)
}
}
15 changes: 6 additions & 9 deletions crates/kitsune-activitypub/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use kitsune_db::{
with_transaction, PgPool,
};
use kitsune_embed::Client as EmbedClient;
use kitsune_error::{Error, Result};
use kitsune_error::{kitsune_error, Error, Result};
use kitsune_language::Language;
use kitsune_search::{AnySearchBackend, SearchBackend};
use kitsune_type::ap::{object::MediaAttachment, Object, Tag, TagType};
Expand Down Expand Up @@ -103,8 +103,7 @@ async fn handle_custom_emojis(
emoji_text: emoji_tag.name.clone(),
})
.try_collect::<Vec<PostCustomEmoji>>()
.await
.map_err(Error::FetchEmoji)?;
.await?;

diesel::insert_into(posts_custom_emojis::table)
.values(emojis)
Expand Down Expand Up @@ -205,15 +204,14 @@ async fn preprocess_object(
if Uri::try_from(&object.attributed_to)?.authority()
!= Uri::try_from(&object.id)?.authority()
{
return Err(Error::InvalidDocument);
return Err(kitsune_error!("invalid document"));
}

let Some(author) = fetcher
.fetch_account(object.attributed_to.as_str().into())
.await
.map_err(Error::FetchAccount)?
.await?
else {
return Err(Error::NotFound);
return Err(kitsune_error!("account not found"));
};

CowBox::boxed(author)
Expand All @@ -228,8 +226,7 @@ async fn preprocess_object(
.call_depth(call_depth + 1)
.build(),
)
.await
.map_err(Error::FetchPost)?
.await?
.map(|post| post.id)
} else {
None
Expand Down
17 changes: 12 additions & 5 deletions crates/kitsune-activitypub/src/mapping/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use kitsune_db::{
schema::{accounts, custom_emojis, media_attachments, posts, posts_custom_emojis},
with_connection,
};
use kitsune_error::{Error, Result};
use kitsune_error::{bail, kitsune_error, Error, ErrorType, Result};
use kitsune_type::ap::{
actor::{Actor, PublicKey},
ap_context,
Expand All @@ -35,12 +35,19 @@ impl IntoObject for DbMediaAttachment {
type Output = MediaAttachment;

async fn into_object(self, state: State<'_>) -> Result<Self::Output> {
let mime = Mime::from_str(&self.content_type).map_err(|_| Error::UnsupportedMediaType)?;
let mime = Mime::from_str(&self.content_type).map_err(
|_| kitsune_error!(type = ErrorType::UnsupportedMediaType, "unsupported media type"),
)?;

let r#type = match mime.type_() {
mime::AUDIO => MediaAttachmentType::Audio,
mime::IMAGE => MediaAttachmentType::Image,
mime::VIDEO => MediaAttachmentType::Video,
_ => return Err(Error::UnsupportedMediaType),
_ => {
return Err(
kitsune_error!(type = ErrorType::UnsupportedMediaType, "unsupported media type"),
)
}
};
let url = state.service.attachment.get_url(self.id).await?;

Expand Down Expand Up @@ -98,7 +105,7 @@ impl IntoObject for Post {
// Therefore it's also not an object
// We just return en error here
if self.reposted_post_id.is_some() {
return Err(Error::NotFound);
bail!("post not found");
}

let (account, in_reply_to, mentions, emojis, attachment_stream) =
Expand Down Expand Up @@ -255,7 +262,7 @@ impl IntoObject for CustomEmoji {
// Let's pretend we're not home and do not answer
let name = match self.domain {
None => Ok(format!(":{}:", self.shortcode)),
Some(_) => Err(Error::NotFound),
Some(_) => Err(kitsune_error!("custom emoji not found")),
}?;

let icon = with_connection!(state.db_pool, |db_conn| {
Expand Down
1 change: 1 addition & 0 deletions crates/kitsune-error/src/axum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ impl IntoResponse for Error {
ErrorType::Forbidden(maybe_body) => to_response(StatusCode::FORBIDDEN, maybe_body),
ErrorType::NotFound => StatusCode::NOT_FOUND.into_response(),
ErrorType::Unauthorized => StatusCode::UNAUTHORIZED.into_response(),
ErrorType::UnsupportedMediaType => StatusCode::UNSUPPORTED_MEDIA_TYPE.into_response(),
ErrorType::Other(maybe_body) => {
to_response(StatusCode::INTERNAL_SERVER_ERROR, maybe_body)
}
Expand Down
18 changes: 18 additions & 0 deletions crates/kitsune-error/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,30 @@ mod ext;
pub type BoxError = Box<dyn std::error::Error + Send + Sync>;
pub type Result<T, E = Error> = std::result::Result<T, E>;

#[macro_export]
macro_rules! bail {
($(type = $type:expr,)? $msg:expr) => {
return Err($crate::kitsune_error!($(type = $type,)? $msg));
};
}

#[macro_export]
macro_rules! kitsune_error {
(type = $type:expr, $msg:expr) => {
$crate::Error::msg($msg).with_error_type($type)
};
($msg:expr) => {
$crate::kitsune_error!(type = $crate::ErrorType::Other(None), $msg)
};
}

#[derive(Clone, Debug)]
pub enum ErrorType {
BadRequest(Option<String>),
Forbidden(Option<String>),
NotFound,
Unauthorized,
UnsupportedMediaType,
Other(Option<String>),
}

Expand Down
10 changes: 5 additions & 5 deletions crates/kitsune-s3/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use http::{
header::{CONTENT_LENGTH, ETAG},
Request,
};
use kitsune_error::{Error, Result};
use kitsune_error::{bail, Error, Result};
use kitsune_http_client::{Body, Client as HttpClient, Response};
use rusty_s3::{actions::CreateMultipartUpload, Bucket, Credentials, S3Action};
use serde::Serialize;
Expand Down Expand Up @@ -47,7 +47,7 @@ async fn execute_request(client: &HttpClient, req: Request<Body>) -> Result<Resp
err_msg.push_str("\nbody: ");
err_msg.push_str(&body);

return Err(Error::msg(err_msg));
bail!(err_msg);
}

Ok(response)
Expand Down Expand Up @@ -169,7 +169,7 @@ impl Client {

let response = execute_request(&self.http_client, request).await?;
let Some(etag_header) = response.headers().get(ETAG) else {
return Err(Error::msg("missing etag header"));
bail!("missing etag header");
};

etags.push(etag_header.to_str()?.to_string());
Expand Down Expand Up @@ -228,7 +228,7 @@ impl Client {
mod test {
use crate::CreateBucketConfiguration;
use futures_util::{future, stream, TryStreamExt};
use kitsune_error::Error;
use kitsune_error::{kitsune_error, Error};
use kitsune_test::minio_test;

const TEST_DATA: &[u8] = b"https://open.spotify.com/track/6VNNakpjSH8LNBX7fSGhUv";
Expand Down Expand Up @@ -286,7 +286,7 @@ mod test {
let result = client
.put_object(
"this will break horribly",
stream::once(future::err(Error::msg("hehe"))),
stream::once(future::err(kitsune_error!("hehe"))),
)
.await;

Expand Down
4 changes: 2 additions & 2 deletions crates/kitsune-service/src/attachment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use kitsune_db::{
schema::media_attachments,
with_connection, PgPool,
};
use kitsune_error::{Error, ErrorType, Result};
use kitsune_error::{kitsune_error, Error, ErrorType, Result};
use kitsune_http_client::Client;
use kitsune_storage::{AnyStorageBackend, StorageBackend};
use kitsune_url::UrlService;
Expand Down Expand Up @@ -137,7 +137,7 @@ impl AttachmentService {
.map_err(Into::into)
.boxed())
} else {
Err(Error::msg("attachment not found").with_error_type(ErrorType::NotFound))
Err(kitsune_error!(type = ErrorType::NotFound, "attachment not found"))
}
}

Expand Down
11 changes: 4 additions & 7 deletions crates/kitsune-service/src/post/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ use kitsune_db::{
with_connection, with_transaction, PgPool,
};
use kitsune_embed::Client as EmbedClient;
use kitsune_error::{Error, ErrorType, Result};
use kitsune_error::{bail, Error, ErrorType, Result};
use kitsune_jobs::deliver::{
create::DeliverCreate,
delete::DeliverDelete,
Expand Down Expand Up @@ -323,8 +323,7 @@ impl PostService {
.await?
!= media_attachment_ids.len() as i64
{
return Err(Error::msg("tried to attach unknown attachment ids")
.with_error_type(ErrorType::BadRequest(None)));
bail!(type = ErrorType::BadRequest(None), "tried to attach unknown attachment ids");
}

diesel::insert_into(posts_media_attachments::table)
Expand Down Expand Up @@ -1134,12 +1133,10 @@ impl PostService {
})?;

if admin_role_count == 0 {
return Err(Error::msg("unauthorised (not an admin)")
.with_error_type(ErrorType::Unauthorized));
bail!(type = ErrorType::Unauthorized, "unauthorised (not an admin)");
}
} else {
return Err(Error::msg("unauthorised (not logged in)")
.with_error_type(ErrorType::Unauthorized));
bail!(type = ErrorType::Unauthorized, "unauthorised (not logged in)");
}
}

Expand Down
10 changes: 3 additions & 7 deletions crates/kitsune-service/src/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use kitsune_db::{
schema::{accounts, accounts_preferences, users},
with_transaction, PgPool,
};
use kitsune_error::{Error, ErrorType, Result};
use kitsune_error::{bail, kitsune_error, Error, ErrorType, Result};
use kitsune_jobs::mailing::confirmation::SendConfirmationMail;
use kitsune_url::UrlService;
use kitsune_util::{generate_secret, try_join};
Expand Down Expand Up @@ -126,19 +126,15 @@ impl UserService {
#[allow(clippy::too_many_lines)] // TODO: Refactor to get under the limit
pub async fn register(&self, register: Register) -> Result<User> {
if !self.registrations_open && !register.force_registration {
return Err(Error::msg("registrations closed")
.with_error_type(ErrorType::Forbidden(Some("registrations closed".into()))));
bail!(type = ErrorType::Forbidden(Some("registrations closed".into())), "registrations closed");
}

register.validate(&RegisterContext {
allow_non_ascii: self.allow_non_ascii_usernames,
})?;

if self.captcha_service.enabled() {
let invalid_captcha = || {
Error::msg("invalid captcha")
.with_error_type(ErrorType::BadRequest(Some("invalid captcha".into())))
};
let invalid_captcha = || kitsune_error!(type = ErrorType::BadRequest(Some("invalid captcha".into())), "invalid captcha");

let token = register.captcha_token.ok_or_else(invalid_captcha)?;
let result = self.captcha_service.verify_token(&token).await?;
Expand Down

0 comments on commit f1bcd13

Please sign in to comment.