Compare commits
No commits in common. "79e604eb963e5b7be897f068770db6295b998f45" and "aec5a01f2c681998097067ebf71f7d1536177736" have entirely different histories.
79e604eb96
...
aec5a01f2c
20 changed files with 264 additions and 203 deletions
|
@ -4,13 +4,12 @@
|
|||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/acrate-inbox/src" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/acrate-nodeinfo/src" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/acrate-nodeinfo/tests" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/acrate-webfinger/src" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/acrate_database/src" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/acrate_nodeinfo/src" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/acrate_nodeinfo/tests" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/acrate_rd/src" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/acrate_rd/tests" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/acrate_mime/src" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/acrate_rdserver/src" isTestSource="false" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/target" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
|
|
|
@ -1,3 +1,3 @@
|
|||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["acrate_database", "acrate_rd", "acrate_nodeinfo", "acrate_rdserver"]
|
||||
members = ["acrate_database", "acrate_rd", "acrate-nodeinfo", "acrate-webfinger"]
|
||||
|
|
|
@ -12,18 +12,13 @@ Federation database
|
|||
>
|
||||
> This software suite is in active development!
|
||||
|
||||
> [!Warning]
|
||||
>
|
||||
> **Monorepo!** Make sure to open the root directory in your IDE, or weird things might happen until the packages are published!
|
||||
|
||||
## Crates
|
||||
|
||||
### Libraries
|
||||
|
||||
- `acrate_database`: Database schema, migrations, and high level database-reliant structures
|
||||
- `acrate_nodeinfo`: Rust typing and utilities for the NodeInfo format
|
||||
- `acrate_database`: Database schema, migrations, and high level database-reliant structures for the [`acrate`] project
|
||||
- `acrate_rd`: Rust typing and utilities for the JSON and XML resource descriptior formats
|
||||
|
||||
### Binaries
|
||||
|
||||
- `acrate_rdserver`: Resource descriptor web server
|
||||
- `acrate-webfinger`: WebFinger server
|
||||
|
|
20
acrate-nodeinfo/Cargo.toml
Normal file
20
acrate-nodeinfo/Cargo.toml
Normal file
|
@ -0,0 +1,20 @@
|
|||
[package]
|
||||
name = "acrate-nodeinfo"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
acrate-hostmeta = { path = "../acrate-hostmeta" }
|
||||
log = "0.4.22"
|
||||
reqwest = { version = "0.12.9", features = ["json", "stream"] }
|
||||
serde = { version = "1.0.214", features = ["derive"] }
|
||||
serde_json = "1.0.132"
|
||||
thiserror = "2.0.3"
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_env_logger = "0.5.0"
|
||||
tokio = { version = "1.41.1", features = ["macros", "rt-multi-thread"] }
|
||||
tokio-test = "0.4.4"
|
||||
|
||||
[lints.clippy]
|
||||
tabs-in-doc-comments = "allow"
|
|
@ -1,4 +1,4 @@
|
|||
//! Rust typing and utilities for the NodeInfo format.
|
||||
//! Serde-based NodeInfo fetcher and loose parser.
|
||||
//!
|
||||
//! > NodeInfo is an effort to create a standardized way of exposing metadata about a server running one of the distributed social networks.
|
||||
//!
|
||||
|
@ -6,9 +6,7 @@
|
|||
//!
|
||||
//! - <https://github.com/jhass/nodeinfo/blob/main/PROTOCOL.md>
|
||||
//! - <https://codeberg.org/fediverse/fep/src/branch/main/fep/f1d5/fep-f1d5.md>
|
||||
//!
|
||||
|
||||
use mediatype::MediaTypeBuf;
|
||||
use serde::Deserialize;
|
||||
use thiserror::Error;
|
||||
|
||||
|
@ -17,7 +15,6 @@ use thiserror::Error;
|
|||
/// # Specification
|
||||
///
|
||||
/// - <https://github.com/jhass/nodeinfo/blob/main/PROTOCOL.md>
|
||||
///
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum NodeInfo {
|
||||
V1(NodeInfo1),
|
||||
|
@ -209,7 +206,7 @@ impl NodeInfo {
|
|||
base.set_path(Self::WELLKNOWN_NODEINFO_PATH);
|
||||
|
||||
log::trace!("Discovering NodeInfo document locations...");
|
||||
let discovery = acrate_rd::any::ResourceDescriptor::get(client, base)
|
||||
let discovery = acrate_hostmeta::any::ResourceDescriptor::get(client, base)
|
||||
.await
|
||||
.map_err(Get)?
|
||||
.jrd();
|
||||
|
@ -318,7 +315,7 @@ impl NodeInfo {
|
|||
pub enum NodeInfoGetWellknownError {
|
||||
/// The discovery of possible locations for NodeInfo documents failed.
|
||||
#[error("the discovery of possible locations for NodeInfo documents failed")]
|
||||
Get(acrate_rd::any::GetError),
|
||||
Get(acrate_hostmeta::any::GetError),
|
||||
/// No compatible NodeInfo documents were detected at the given URL.
|
||||
#[error("no compatible NodeInfo documents were detected at the given URL")]
|
||||
Unsupported,
|
||||
|
@ -356,21 +353,14 @@ impl NodeInfo1 {
|
|||
.get(reqwest::header::CONTENT_TYPE)
|
||||
.ok_or(ContentTypeMissing)?;
|
||||
|
||||
log::trace!("Extracting media type from the `Content-Type` header: {content_type:?}");
|
||||
let media_type: MediaTypeBuf = content_type
|
||||
.to_str()
|
||||
.map_err(ContentTypeUnprintable)?
|
||||
.parse()
|
||||
.map_err(ContentTypeInvalid)?;
|
||||
log::trace!("Extracting MIME type from the `Content-Type` header...");
|
||||
let mime_type = extract_mime_from_content_type(content_type)
|
||||
.ok_or(ContentTypeInvalid)?;
|
||||
|
||||
log::trace!("Checking if media type is supported: {media_type:?}");
|
||||
|
||||
let mime_is_json = media_type.essence().eq(&"application/json".parse::<MediaTypeBuf>().unwrap());
|
||||
log::trace!("Is media type `application/json`? {mime_is_json:?}");
|
||||
|
||||
if !mime_is_json {
|
||||
log::error!("Media type `{media_type}` is not acceptable for NodeInfo parsing.");
|
||||
return Err(ContentTypeUnsupported);
|
||||
log::trace!("Ensuring MIME type is acceptable for NodeInfo documents...");
|
||||
if mime_type != "application/json" {
|
||||
log::error!("MIME type `{mime_type}` is not acceptable for NodeInfo documents.");
|
||||
return Err(ContentTypeInvalid)
|
||||
}
|
||||
|
||||
log::trace!("Attempting to parse response as JSON...");
|
||||
|
@ -435,21 +425,14 @@ impl NodeInfo2 {
|
|||
.get(reqwest::header::CONTENT_TYPE)
|
||||
.ok_or(ContentTypeMissing)?;
|
||||
|
||||
log::trace!("Extracting media type from the `Content-Type` header: {content_type:?}");
|
||||
let media_type: MediaTypeBuf = content_type
|
||||
.to_str()
|
||||
.map_err(ContentTypeUnprintable)?
|
||||
.parse()
|
||||
.map_err(ContentTypeInvalid)?;
|
||||
log::trace!("Extracting MIME type from the `Content-Type` header...");
|
||||
let mime_type = extract_mime_from_content_type(content_type)
|
||||
.ok_or(ContentTypeInvalid)?;
|
||||
|
||||
log::trace!("Checking if media type is supported: {media_type:?}");
|
||||
|
||||
let mime_is_json = media_type.essence().eq(&"application/json".parse::<MediaTypeBuf>().unwrap());
|
||||
log::trace!("Is media type `application/json`? {mime_is_json:?}");
|
||||
|
||||
if !mime_is_json {
|
||||
log::error!("Media type `{media_type}` is not acceptable for NodeInfo parsing.");
|
||||
return Err(ContentTypeUnsupported);
|
||||
log::trace!("Ensuring MIME type is acceptable for NodeInfo documents...");
|
||||
if mime_type != "application/json" {
|
||||
log::error!("MIME type `{mime_type}` is not acceptable for NodeInfo documents.");
|
||||
return Err(ContentTypeInvalid)
|
||||
}
|
||||
|
||||
log::trace!("Attempting to parse response as JSON...");
|
||||
|
@ -477,17 +460,9 @@ pub enum NodeInfoGetError {
|
|||
#[error("the Content-Type header of the response is missing")]
|
||||
ContentTypeMissing,
|
||||
|
||||
/// The `Content-Type` header of the response can't be converted to a [`str`].
|
||||
#[error("the Content-Type header of the response cannot be converted to a &str")]
|
||||
ContentTypeUnprintable(reqwest::header::ToStrError),
|
||||
|
||||
/// The `Content-Type` header of the response is not a valid [`mime::Mime`] type.
|
||||
#[error("the Content-Type header of the response is not a valid media type")]
|
||||
ContentTypeInvalid(mediatype::MediaTypeError),
|
||||
|
||||
/// The `Content-Type` header of the response is not a supported [`mime::Mime`] type.
|
||||
#[error("the Content-Type header of the response is not a supported media type")]
|
||||
ContentTypeUnsupported,
|
||||
/// The `Content-Type` header of the response is invalid.
|
||||
#[error("the Content-Type header of the response is invalid")]
|
||||
ContentTypeInvalid,
|
||||
|
||||
/// The document failed to be parsed as JSON by [`reqwest`].
|
||||
#[error("the document failed to be parsed as JSON")]
|
||||
|
@ -497,3 +472,12 @@ pub enum NodeInfoGetError {
|
|||
#[error("the returned NodeInfo version would not match the version of the called method")]
|
||||
Version,
|
||||
}
|
||||
|
||||
/// Extract the MIME type from the value of the `Content-Type` header.
|
||||
fn extract_mime_from_content_type(value: &reqwest::header::HeaderValue) -> Option<String> {
|
||||
let value = value.to_str().ok()?;
|
||||
match value.split_once("; ") {
|
||||
None => Some(value.to_string()),
|
||||
Some((mime, _)) => Some(mime.to_string()),
|
||||
}
|
||||
}
|
|
@ -1,17 +1,11 @@
|
|||
[package]
|
||||
name = "acrate_rdserver"
|
||||
version = "0.3.0"
|
||||
authors = ["Stefano Pigozzi <me@steffo.eu>"]
|
||||
name = "acrate-webfinger"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
description = "Resource descriptor web server for the acrate project"
|
||||
repository = "https://forge.steffo.eu/unimore/tirocinio-canali-steffo-acrate"
|
||||
license = "EUPL-1.2"
|
||||
keywords = ["jrd", "xrd", "hostmeta", "webfinger", "resource-descriptor"]
|
||||
categories = ["web-programming"]
|
||||
|
||||
[dependencies]
|
||||
acrate_database = { path = "../acrate_database" }
|
||||
acrate_rd = { path = "../acrate_rd" }
|
||||
acrate-hostmeta = { path = "../acrate-hostmeta" }
|
||||
anyhow = "1.0.93"
|
||||
axum = { version = "0.7.7", features = ["macros"] }
|
||||
axum-extra = { version = "0.9.4", features = ["query"] }
|
||||
|
@ -23,7 +17,3 @@ quick-xml = { version = "0.37.0", features = ["serialize"] }
|
|||
serde = { version = "1.0.215", features = ["derive"] }
|
||||
serde_json = "1.0.132"
|
||||
tokio = { version = "1.41.1", features = ["macros", "net", "rt-multi-thread"] }
|
||||
mediatype = { version = "0.19.18", features = ["serde"] }
|
||||
|
||||
[lints.clippy]
|
||||
tabs-in-doc-comments = "allow"
|
|
@ -15,12 +15,12 @@ async fn main() -> anyhow::Result<std::convert::Infallible> {
|
|||
let mut mj = minijinja::Environment::<'static>::new();
|
||||
|
||||
log::trace!("Adding webfinger page to the Minijinja environment...");
|
||||
mj.add_template("rd.html.j2", include_str!("rd.html.j2"))
|
||||
.expect("rd.html.j2 to be a valid Minijinja template");
|
||||
mj.add_template("webfinger.html.j2", include_str!("webfinger.html.j2"))
|
||||
.expect("webfinger.html.j2 to be a valid Minijinja template");
|
||||
|
||||
log::trace!("Creating Axum router...");
|
||||
let app = axum::Router::new()
|
||||
.route("/*path", axum::routing::get(route::webfinger_handler))
|
||||
.route("/.well-known/webfinger", axum::routing::get(route::webfinger_handler))
|
||||
.layer(Extension(Arc::new(mj)));
|
||||
log::trace!("Axum router created successfully!");
|
||||
|
|
@ -1,16 +1,13 @@
|
|||
use std::iter::IntoIterator;
|
||||
use std::sync::Arc;
|
||||
use axum::Extension;
|
||||
use axum::extract::Path;
|
||||
use axum::http::{HeaderMap, Response, StatusCode};
|
||||
use axum_extra::extract::Query;
|
||||
use mediatype::{MediaTypeBuf, MediaTypeList};
|
||||
use serde::Deserialize;
|
||||
use acrate_database::diesel::GroupedBy;
|
||||
use acrate_database::diesel_async::{AsyncConnection, AsyncPgConnection};
|
||||
use acrate_database::meta::{MetaAlias, MetaLink, MetaLinkProperty, MetaLinkTitle, MetaProperty, MetaSubject};
|
||||
use acrate_rd::jrd::ResourceDescriptorLinkJRD;
|
||||
use acrate_rd::xrd::{ResourceDescriptorLinkXRD, ResourceDescriptorPropertyXRD, ResourceDescriptorTitleXRD};
|
||||
use acrate_hostmeta::jrd::ResourceDescriptorLinkJRD;
|
||||
use acrate_hostmeta::xrd::{ResourceDescriptorLinkXRD, ResourceDescriptorPropertyXRD, ResourceDescriptorTitleXRD};
|
||||
use crate::config;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
|
@ -21,8 +18,10 @@ pub struct WebfingerQuery {
|
|||
pub rel: Vec<String>,
|
||||
}
|
||||
|
||||
const WEBFINGER_DOC: &str = "/.well-known/webfinger";
|
||||
|
||||
#[axum::debug_handler]
|
||||
pub async fn webfinger_handler(
|
||||
Path(path): Path<String>,
|
||||
Query(WebfingerQuery {resource, rel}): Query<WebfingerQuery>,
|
||||
headers: HeaderMap,
|
||||
Extension(mj): Extension<Arc<minijinja::Environment<'static>>>,
|
||||
|
@ -32,18 +31,15 @@ pub async fn webfinger_handler(
|
|||
let resource = resource.unwrap_or_else(|| "".to_string());
|
||||
log::debug!("Resource is: {resource:#?}");
|
||||
|
||||
let path = format!("/{path}");
|
||||
log::debug!("Path is: {path:#?}");
|
||||
|
||||
log::debug!("Rel is: {rel:#?}");
|
||||
|
||||
let accept = headers.get("Accept");
|
||||
let accept = headers.get("Accept")
|
||||
.map(|v| v.to_str())
|
||||
.filter(Result::is_ok)
|
||||
.map(|v| v.unwrap())
|
||||
.unwrap_or("application/json")
|
||||
.to_string();
|
||||
log::debug!("Accept is: {accept:#?}");
|
||||
let accept = accept
|
||||
.map(|h| h.to_str())
|
||||
.unwrap_or(Ok("*/*"))
|
||||
.map(|h| MediaTypeList::new(h))
|
||||
.map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
|
||||
let mut response = Response::new("".to_string());
|
||||
|
||||
|
@ -51,7 +47,7 @@ pub async fn webfinger_handler(
|
|||
.await
|
||||
.map_err(|_| StatusCode::BAD_GATEWAY)?;
|
||||
|
||||
let subjects = MetaSubject::aquery_matching(&mut conn, &path, &resource)
|
||||
let subjects = MetaSubject::query_matching(&mut conn, WEBFINGER_DOC, &resource)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
|
@ -80,24 +76,24 @@ pub async fn webfinger_handler(
|
|||
|
||||
let subject = subject.subject.clone();
|
||||
|
||||
let aliases = MetaAlias::aquery_matching(&mut conn, &path, &resource)
|
||||
let aliases = MetaAlias::query_matching(&mut conn, WEBFINGER_DOC, &resource)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
let properties = MetaProperty::aquery_matching(&mut conn, &path, &resource)
|
||||
let properties = MetaProperty::query_matching(&mut conn, WEBFINGER_DOC, &resource)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
let links = MetaLink::aquery_matching(&mut conn, &path, &resource)
|
||||
let links = MetaLink::query_matching(&mut conn, WEBFINGER_DOC, &resource)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
let link_properties = MetaLinkProperty::aquery_by_link(&mut conn, &links)
|
||||
let link_properties = MetaLinkProperty::query_by_link(&mut conn, &links)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.grouped_by(&links);
|
||||
|
||||
let link_titles = MetaLinkTitle::aquery_by_link(&mut conn, &links)
|
||||
let link_titles = MetaLinkTitle::query_by_link(&mut conn, &links)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.grouped_by(&links);
|
||||
|
@ -117,26 +113,21 @@ pub async fn webfinger_handler(
|
|||
);
|
||||
}
|
||||
|
||||
for media_type in accept.into_iter() {
|
||||
let media_type = match media_type {
|
||||
Err(e) => {
|
||||
log::debug!("Skipping error while parsing media type: {e:?}");
|
||||
continue;
|
||||
},
|
||||
Ok(media_type) => media_type
|
||||
};
|
||||
|
||||
for mime in accept.split(",") {
|
||||
{
|
||||
let headers = response.headers_mut();
|
||||
headers.insert(
|
||||
"Content-Type",
|
||||
media_type.to_string()
|
||||
.parse()
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
mime.parse().map_err(|_| StatusCode::BAD_REQUEST)?
|
||||
);
|
||||
}
|
||||
|
||||
match media_type.essence().to_string().to_ascii_lowercase().as_str() {
|
||||
let (mime, _params) = match mime.trim().split_once(";") {
|
||||
Some((mime, params)) => (mime, Some(params)),
|
||||
None => (mime, None),
|
||||
};
|
||||
|
||||
match mime {
|
||||
"*/*" | "application/json" | "application/jrd+json" => {
|
||||
let aliases = aliases
|
||||
.into_iter()
|
||||
|
@ -152,7 +143,7 @@ pub async fn webfinger_handler(
|
|||
.into_iter()
|
||||
.map(|(link, properties, titles)| ResourceDescriptorLinkJRD {
|
||||
rel: link.rel,
|
||||
r#type: link.type_.map(|m| m.0),
|
||||
r#type: link.type_,
|
||||
href: link.href,
|
||||
template: link.template,
|
||||
properties: properties
|
||||
|
@ -166,7 +157,7 @@ pub async fn webfinger_handler(
|
|||
})
|
||||
.collect::<Vec<ResourceDescriptorLinkJRD>>();
|
||||
|
||||
let rd = acrate_rd::jrd::ResourceDescriptorJRD {
|
||||
let rd = acrate_hostmeta::jrd::ResourceDescriptorJRD {
|
||||
subject,
|
||||
aliases,
|
||||
properties,
|
||||
|
@ -201,7 +192,7 @@ pub async fn webfinger_handler(
|
|||
.into_iter()
|
||||
.map(|(link, properties, titles)| ResourceDescriptorLinkXRD {
|
||||
rel: link.rel,
|
||||
r#type: link.type_.map(|m| m.0),
|
||||
r#type: link.type_,
|
||||
href: link.href,
|
||||
template: link.template,
|
||||
properties: properties
|
||||
|
@ -221,7 +212,7 @@ pub async fn webfinger_handler(
|
|||
})
|
||||
.collect::<Vec<ResourceDescriptorLinkXRD>>();
|
||||
|
||||
let rd = acrate_rd::xrd::ResourceDescriptorXRD {
|
||||
let rd = acrate_hostmeta::xrd::ResourceDescriptorXRD {
|
||||
subject,
|
||||
aliases,
|
||||
properties,
|
||||
|
@ -250,12 +241,12 @@ pub async fn webfinger_handler(
|
|||
})
|
||||
.collect();
|
||||
|
||||
let links: Vec<(String, Option<MediaTypeBuf>, Option<String>, Option<String>, Vec<(String, Option<String>)>, Vec<(String, String)>)> = links_full
|
||||
let links: Vec<(String, Option<String>, Option<String>, Option<String>, Vec<(String, Option<String>)>, Vec<(String, String)>)> = links_full
|
||||
.into_iter()
|
||||
.map(|(link, properties, titles)| {
|
||||
(
|
||||
link.rel,
|
||||
link.type_.map(|m| m.0),
|
||||
link.type_,
|
||||
link.href,
|
||||
link.template,
|
||||
properties.into_iter()
|
||||
|
@ -268,11 +259,10 @@ pub async fn webfinger_handler(
|
|||
})
|
||||
.collect();
|
||||
|
||||
let html = mj.get_template("rd.html.j2")
|
||||
.expect("rd.html.j2 to exist")
|
||||
let html = mj.get_template("webfinger.html.j2")
|
||||
.expect("webfinger.html.j2 to exist")
|
||||
.render(
|
||||
minijinja::context!(
|
||||
path => path,
|
||||
subject => subject,
|
||||
aliases => aliases,
|
||||
properties => properties,
|
|
@ -1,7 +1,7 @@
|
|||
<!DOCTYPE html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>{{ subject }} · Acrate RDServer</title>
|
||||
<title>{{ subject }} · Acrate Webfinger</title>
|
||||
<style>
|
||||
:root {
|
||||
--wf-yellow: #e2bb03;
|
||||
|
@ -80,7 +80,7 @@
|
|||
<body>
|
||||
<header>
|
||||
<h1>
|
||||
<span id="path">{{ path }}</span>
|
||||
Acrate Webfinger
|
||||
</h1>
|
||||
</header>
|
||||
<main>
|
|
@ -14,7 +14,6 @@ diesel = { version = "2.2.4", features = ["postgres", "uuid"] }
|
|||
diesel-async = { version = "0.5.1", features = ["postgres"] }
|
||||
diesel_migrations = { version = "2.2.0", optional = true }
|
||||
log = "0.4.22"
|
||||
mediatype = "0.19.18"
|
||||
micronfig = { version = "0.3.0", optional = true }
|
||||
mime = "0.3.17"
|
||||
pretty_env_logger = { version = "0.5.0", optional = true }
|
||||
|
|
|
@ -26,12 +26,12 @@
|
|||
//! - [`acrate_rdserver`]
|
||||
//!
|
||||
|
||||
use std::str::FromStr;
|
||||
use diesel::deserialize::FromSql;
|
||||
use diesel::{AsExpression, Associations, FromSqlRow, Identifiable, Insertable, IntoSql, PgTextExpressionMethods, QueryResult, Queryable, QueryableByName, Selectable, SelectableHelper, ExpressionMethods, BelongingToDsl};
|
||||
use diesel::pg::{Pg, PgConnection};
|
||||
use diesel::serialize::{Output, ToSql};
|
||||
use diesel_async::AsyncPgConnection;
|
||||
use mediatype::MediaTypeBuf;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::schema;
|
||||
|
@ -40,7 +40,7 @@ use super::schema;
|
|||
/// Wrapper to use [`mime::Mime`] with [`diesel`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression)]
|
||||
#[diesel(sql_type = diesel::sql_types::Text)]
|
||||
pub struct MediaTypeDatabase(pub MediaTypeBuf);
|
||||
pub struct Mime(pub mime::Mime);
|
||||
|
||||
|
||||
/// A matchable record denoting the existence of a resource descriptor.
|
||||
|
@ -173,7 +173,7 @@ pub struct MetaLink {
|
|||
/// The media type of the value of the link.
|
||||
///
|
||||
/// Can be [`None`] if it shouldn't be specified.
|
||||
pub type_: Option<MediaTypeDatabase>,
|
||||
pub type_: Option<Mime>,
|
||||
|
||||
/// The URI to the document this property is linking the subject to.
|
||||
///
|
||||
|
@ -206,7 +206,7 @@ pub struct MetaLinkInsert {
|
|||
/// The media type of the value of the link.
|
||||
///
|
||||
/// Can be [`None`] if it shouldn't be specified.
|
||||
pub type_: Option<MediaTypeDatabase>,
|
||||
pub type_: Option<Mime>,
|
||||
|
||||
/// The URI to the document this property is linking the subject to.
|
||||
///
|
||||
|
@ -348,8 +348,8 @@ pub struct MetaPropertyInsert {
|
|||
pub value: Option<String>,
|
||||
}
|
||||
|
||||
/// Allow [`diesel::sql_types::Text`] values to be parsed as [`MediaTypeDatabase`].
|
||||
impl<DB> FromSql<diesel::sql_types::Text, DB> for MediaTypeDatabase
|
||||
/// Allow [`diesel::sql_types::Text`] values to be parsed as [`Mime`].
|
||||
impl<DB> FromSql<diesel::sql_types::Text, DB> for Mime
|
||||
where
|
||||
DB: diesel::backend::Backend,
|
||||
String: FromSql<diesel::sql_types::Text, DB>,
|
||||
|
@ -359,25 +359,25 @@ impl<DB> FromSql<diesel::sql_types::Text, DB> for MediaTypeDatabase
|
|||
let s = <String as FromSql<diesel::sql_types::Text, DB>>::from_sql(bytes)?;
|
||||
|
||||
log::trace!("Attempting to parse as a media type: {s:?}");
|
||||
let mt: MediaTypeBuf = s.parse()?;
|
||||
let mime = mime::Mime::from_str(&s)?;
|
||||
|
||||
log::trace!("Successfully parsed media type: {mt:?}");
|
||||
Ok(Self(mt))
|
||||
log::trace!("Successfully parsed media type: {mime:?}");
|
||||
Ok(Self(mime))
|
||||
}
|
||||
}
|
||||
|
||||
/// Allow [`diesel::sql_types::Text`] values to be written to with [`MediaTypeDatabase`].
|
||||
impl<DB> ToSql<diesel::sql_types::Text, DB> for MediaTypeDatabase
|
||||
/// Allow [`diesel::sql_types::Text`] values to be written to with [`Mime`].
|
||||
impl<DB> ToSql<diesel::sql_types::Text, DB> for Mime
|
||||
where
|
||||
DB: diesel::backend::Backend,
|
||||
str: ToSql<diesel::sql_types::Text, DB>,
|
||||
{
|
||||
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
|
||||
log::trace!("Getting the essence of a media type to prepare for serialization...");
|
||||
let mt = self.0.as_str();
|
||||
let mime = self.0.essence_str();
|
||||
|
||||
log::trace!("Serializing media type as TEXT: {mt:?}");
|
||||
<str as ToSql<diesel::sql_types::Text, DB>>::to_sql(mt, out)
|
||||
log::trace!("Serializing media type as TEXT: {mime:?}");
|
||||
<str as ToSql<diesel::sql_types::Text, DB>>::to_sql(mime, out)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,27 +0,0 @@
|
|||
[package]
|
||||
name = "acrate_nodeinfo"
|
||||
version = "0.3.0"
|
||||
authors = ["Stefano Pigozzi <me@steffo.eu>"]
|
||||
edition = "2021"
|
||||
description = "Rust typing and utilities for the NodeInfo format"
|
||||
repository = "https://forge.steffo.eu/unimore/tirocinio-canali-steffo-acrate"
|
||||
license = "EUPL-1.2"
|
||||
keywords = ["nodeinfo", "fediverse"]
|
||||
categories = ["web-programming"]
|
||||
|
||||
[dependencies]
|
||||
acrate_rd = { path = "../acrate_rd" }
|
||||
log = "0.4.22"
|
||||
mediatype = { version = "0.19.18", features = ["serde"] }
|
||||
reqwest = { version = "0.12.9", features = ["json", "stream"] }
|
||||
serde = { version = "1.0.214", features = ["derive"] }
|
||||
serde_json = "1.0.132"
|
||||
thiserror = "2.0.3"
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_env_logger = "0.5.0"
|
||||
tokio = { version = "1.41.1", features = ["macros", "rt-multi-thread"] }
|
||||
tokio-test = "0.4.4"
|
||||
|
||||
[lints.clippy]
|
||||
tabs-in-doc-comments = "allow"
|
|
@ -6,12 +6,12 @@ edition = "2021"
|
|||
description = "Rust typing and utilities for the JSON and XML resource descriptior formats"
|
||||
repository = "https://forge.steffo.eu/unimore/tirocinio-canali-steffo-acrate"
|
||||
license = "EUPL-1.2"
|
||||
keywords = ["jrd", "xrd", "host-meta", "webfinger", "resource-descriptor"]
|
||||
keywords = ["jrd", "xrd", "hostmeta", "webfinger", "resource-descriptor"]
|
||||
categories = ["web-programming"]
|
||||
|
||||
[dependencies]
|
||||
log = "0.4.22"
|
||||
mediatype = { version = "0.19.18", features = ["serde"] }
|
||||
mime = "0.3.17"
|
||||
quick-xml = { version = "0.37.0", features = ["overlapped-lists", "serialize"] }
|
||||
reqwest = { version = "0.12.9", features = ["json", "stream"] }
|
||||
serde = { version = "1.0.214", features = ["derive"] }
|
||||
|
|
|
@ -30,7 +30,7 @@ impl ResourceDescriptor {
|
|||
///
|
||||
/// ```
|
||||
/// # tokio_test::block_on(async {
|
||||
/// use acrate_rd::any::ResourceDescriptor;
|
||||
/// use acrate_hostmeta::any::ResourceDescriptor;
|
||||
///
|
||||
/// let client = reqwest::Client::new();
|
||||
/// let url: reqwest::Url = "https://junimo.party/.well-known/host-meta".parse()
|
||||
|
@ -185,7 +185,7 @@ impl ResourceDescriptor {
|
|||
///
|
||||
/// ```
|
||||
/// # tokio_test::block_on(async {
|
||||
/// use acrate_rd::any::ResourceDescriptor;
|
||||
/// use acrate_hostmeta::any::ResourceDescriptor;
|
||||
///
|
||||
/// let client = reqwest::Client::new();
|
||||
/// let base: reqwest::Url = "https://junimo.party".parse()
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
//! Definition and implementation of [`ResourceDescriptorJRD`].
|
||||
|
||||
use std::collections::HashMap;
|
||||
use mediatype::MediaTypeBuf;
|
||||
use std::str::FromStr;
|
||||
use serde::{Serialize, Deserialize};
|
||||
use thiserror::Error;
|
||||
use crate::xrd::{ResourceDescriptorLinkXRD, ResourceDescriptorPropertyXRD, ResourceDescriptorTitleXRD, ResourceDescriptorXRD};
|
||||
|
@ -76,7 +76,8 @@ pub struct ResourceDescriptorLinkJRD {
|
|||
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.2>
|
||||
///
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub r#type: Option<MediaTypeBuf>,
|
||||
#[serde(with = "crate::utils::serde_mime_opt")]
|
||||
pub r#type: Option<mime::Mime>,
|
||||
|
||||
/// URI to the resource put in relation.
|
||||
///
|
||||
|
@ -172,23 +173,24 @@ impl ResourceDescriptorJRD {
|
|||
.get(reqwest::header::CONTENT_TYPE)
|
||||
.ok_or(ContentTypeMissing)?;
|
||||
|
||||
log::trace!("Extracting media type from the `Content-Type` header: {content_type:?}");
|
||||
let media_type: MediaTypeBuf = content_type
|
||||
.to_str()
|
||||
.map_err(ContentTypeUnprintable)?
|
||||
.parse()
|
||||
log::trace!("Extracting media type from the `Content-Type` header...");
|
||||
let mime_type = content_type.to_str()
|
||||
.map_err(ContentTypeUnprintable)?;
|
||||
|
||||
log::trace!("Parsing media type: {mime_type:?}");
|
||||
let mime_type = mime::Mime::from_str(mime_type)
|
||||
.map_err(ContentTypeInvalid)?;
|
||||
|
||||
log::trace!("Checking if media type is supported: {media_type:?}");
|
||||
|
||||
let mime_is_json = media_type.essence().eq(&"application/json".parse::<MediaTypeBuf>().unwrap());
|
||||
log::trace!("Is media type `application/json`? {mime_is_json:?}");
|
||||
|
||||
let mime_is_jrd = media_type.essence().eq(&"application/jrd+json".parse::<MediaTypeBuf>().unwrap());
|
||||
log::trace!("Is media type `application/jrd+json`? {mime_is_jrd:?}");
|
||||
|
||||
log::trace!("Checking if media type is supported...");
|
||||
let mime_is_json = mime_type == mime::APPLICATION_JSON;
|
||||
log::trace!("Is media type application/json? {mime_is_json:?}");
|
||||
let mime_is_jrd =
|
||||
mime_type.type_() == mime::APPLICATION
|
||||
&& mime_type.subtype() == "jrd"
|
||||
&& mime_type.suffix() == Some(mime::JSON);
|
||||
log::trace!("Is media type application/jrd+json? {mime_is_jrd:?}");
|
||||
if !(mime_is_json || mime_is_jrd) {
|
||||
log::error!("Media type `{media_type}` is not acceptable for JRD parsing.");
|
||||
log::error!("MIME type `{mime_type}` is not acceptable for JRD parsing.");
|
||||
return Err(ContentTypeUnsupported);
|
||||
}
|
||||
|
||||
|
@ -265,7 +267,7 @@ pub enum GetJRDError {
|
|||
|
||||
/// The `Content-Type` header of the response is not a valid [`mime::Mime`] type.
|
||||
#[error("the Content-Type header of the response is not a valid media type")]
|
||||
ContentTypeInvalid(mediatype::MediaTypeError),
|
||||
ContentTypeInvalid(mime::FromStrError),
|
||||
|
||||
/// The `Content-Type` header of the response is not a supported [`mime::Mime`] type.
|
||||
#[error("the Content-Type header of the response is not a supported media type")]
|
||||
|
|
|
@ -8,3 +8,4 @@
|
|||
pub mod jrd;
|
||||
pub mod xrd;
|
||||
pub mod any;
|
||||
mod utils;
|
||||
|
|
105
acrate_rd/src/utils.rs
Normal file
105
acrate_rd/src/utils.rs
Normal file
|
@ -0,0 +1,105 @@
|
|||
//! Various utilities reused in the whole crate.
|
||||
|
||||
/// Module to use in `serde(with = ...)` to [`serde`] a [`mime::Mime`].
|
||||
#[allow(dead_code)]
|
||||
pub mod serde_mime {
|
||||
use std::fmt::Formatter;
|
||||
use std::str::FromStr;
|
||||
use serde::de::{Error, Visitor};
|
||||
use serde::{Deserializer, Serializer};
|
||||
|
||||
pub struct MimeVisitor;
|
||||
|
||||
impl<'de> Visitor<'de> for MimeVisitor {
|
||||
type Value = mime::Mime;
|
||||
|
||||
fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
|
||||
formatter.write_str("a media type (MIME type)")
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
mime::Mime::from_str(v)
|
||||
.map_err(|_| E::custom("failed to parse media type"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, De>(deserializer: De) -> Result<<MimeVisitor as Visitor<'de>>::Value, De::Error>
|
||||
where
|
||||
De: Deserializer<'de>
|
||||
{
|
||||
let s = deserializer.deserialize_str(MimeVisitor)?;
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
pub fn serialize<Ser>(data: mime::Mime, serializer: Ser) -> Result<Ser::Ok, Ser::Error>
|
||||
where
|
||||
Ser: Serializer
|
||||
{
|
||||
let s = data.essence_str();
|
||||
serializer.serialize_str(s)
|
||||
}
|
||||
}
|
||||
|
||||
/// Module to use in `serde(with = ...)` to [`serde`] an [`Option`] of [`mime::Mime`].
|
||||
#[allow(dead_code)]
|
||||
pub mod serde_mime_opt {
|
||||
use std::fmt::Formatter;
|
||||
use std::str::FromStr;
|
||||
use serde::de::{Error, Visitor};
|
||||
use serde::{Deserializer, Serializer};
|
||||
|
||||
pub struct MimeVisitor;
|
||||
|
||||
impl<'de> Visitor<'de> for MimeVisitor {
|
||||
type Value = Option<mime::Mime>;
|
||||
|
||||
fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
|
||||
formatter.write_str("optionally, a media type (MIME type)")
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
Ok(
|
||||
Some(
|
||||
mime::Mime::from_str(v)
|
||||
.map_err(|_| E::custom("failed to parse media type"))?
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
fn visit_none<E>(self) -> Result<Self::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, De>(deserializer: De) -> Result<<MimeVisitor as Visitor<'de>>::Value, De::Error>
|
||||
where
|
||||
De: Deserializer<'de>
|
||||
{
|
||||
let s = deserializer.deserialize_str(MimeVisitor)?;
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
pub fn serialize<Ser>(data: &Option<mime::Mime>, serializer: Ser) -> Result<Ser::Ok, Ser::Error>
|
||||
where
|
||||
Ser: Serializer
|
||||
{
|
||||
match data {
|
||||
None => {
|
||||
serializer.serialize_none()
|
||||
}
|
||||
Some(data) => {
|
||||
let s = data.essence_str();
|
||||
serializer.serialize_str(s)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,6 +1,6 @@
|
|||
//! Definition and implementation of [`ResourceDescriptorXRD`].
|
||||
|
||||
use mediatype::MediaTypeBuf;
|
||||
use std::str::FromStr;
|
||||
use serde::{Serialize, Deserialize};
|
||||
use thiserror::Error;
|
||||
use crate::jrd::{ResourceDescriptorJRD, ResourceDescriptorLinkJRD};
|
||||
|
@ -82,7 +82,8 @@ pub struct ResourceDescriptorLinkXRD {
|
|||
///
|
||||
#[serde(rename = "@type")]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub r#type: Option<MediaTypeBuf>,
|
||||
#[serde(with = "crate::utils::serde_mime_opt")]
|
||||
pub r#type: Option<mime::Mime>,
|
||||
|
||||
/// URI to the resource put in relation.
|
||||
///
|
||||
|
@ -208,20 +209,22 @@ impl ResourceDescriptorXRD {
|
|||
.get(reqwest::header::CONTENT_TYPE)
|
||||
.ok_or(ContentTypeMissing)?;
|
||||
|
||||
log::trace!("Extracting media type from the `Content-Type` header: {content_type:?}");
|
||||
let media_type: MediaTypeBuf = content_type
|
||||
.to_str()
|
||||
.map_err(ContentTypeUnprintable)?
|
||||
.parse()
|
||||
log::trace!("Extracting media type from the `Content-Type` header...");
|
||||
let mime_type = content_type.to_str()
|
||||
.map_err(ContentTypeUnprintable)?;
|
||||
|
||||
log::trace!("Parsing media type: {mime_type:?}");
|
||||
let mime_type = mime::Mime::from_str(mime_type)
|
||||
.map_err(ContentTypeInvalid)?;
|
||||
|
||||
log::trace!("Checking if media type is supported: {media_type:?}");
|
||||
|
||||
let mime_is_xrd = media_type.essence().eq(&"application/xrd+xml".parse::<MediaTypeBuf>().unwrap());
|
||||
log::trace!("Is media type `application/xrd+xml`? {mime_is_xrd:?}");
|
||||
|
||||
log::trace!("Checking if media type is supported...");
|
||||
let mime_is_xrd =
|
||||
mime_type.type_() == mime::APPLICATION
|
||||
&& mime_type.subtype() == "xrd"
|
||||
&& mime_type.suffix() == Some(mime::XML);
|
||||
log::trace!("Is media type application/xrd+xml? {mime_is_xrd:?}");
|
||||
if !mime_is_xrd {
|
||||
log::error!("MIME type `{media_type}` is not acceptable for XRD parsing.");
|
||||
log::error!("MIME type `{mime_type}` is not acceptable for XRD parsing.");
|
||||
return Err(ContentTypeUnsupported);
|
||||
}
|
||||
|
||||
|
@ -306,7 +309,7 @@ pub enum GetXRDError {
|
|||
|
||||
/// The `Content-Type` header of the response is not a valid [`mime::Mime`] type.
|
||||
#[error("the Content-Type header of the response is not a valid media type")]
|
||||
ContentTypeInvalid(mediatype::MediaTypeError),
|
||||
ContentTypeInvalid(mime::FromStrError),
|
||||
|
||||
/// The `Content-Type` header of the response is not a supported [`mime::Mime`] type.
|
||||
#[error("the Content-Type header of the response is not a supported media type")]
|
||||
|
|
Loading…
Reference in a new issue